|
| 1 | +import type { |
| 2 | + LocalProcessProbePortsInput, |
| 3 | + LocalProcessProbePortsResult, |
| 4 | + LocalProcessStopPortsInput, |
| 5 | + LocalProcessStopPortsResult, |
| 6 | +} from "@t3tools/contracts"; |
| 7 | + |
| 8 | +import { runProcess } from "./processRunner.ts"; |
| 9 | + |
| 10 | +const PORT_LOOKUP_TIMEOUT_MS = 2_000; |
| 11 | +const PORT_LOOKUP_MAX_BUFFER_BYTES = 64 * 1024; |
| 12 | + |
| 13 | +export interface LocalProcessControls { |
| 14 | + readonly listListeningPids: (port: number) => Promise<readonly number[]>; |
| 15 | + readonly killPid: (pid: number) => Promise<void> | void; |
| 16 | + readonly currentPid: number; |
| 17 | +} |
| 18 | + |
| 19 | +export function parseListeningPidList(text: string): number[] { |
| 20 | + const seen = new Set<number>(); |
| 21 | + for (const token of text.split(/\s+/u)) { |
| 22 | + if (!/^\d+$/u.test(token)) { |
| 23 | + continue; |
| 24 | + } |
| 25 | + const pid = Number(token); |
| 26 | + if (Number.isSafeInteger(pid) && pid > 0) { |
| 27 | + seen.add(pid); |
| 28 | + } |
| 29 | + } |
| 30 | + return [...seen]; |
| 31 | +} |
| 32 | + |
| 33 | +function normalizePorts(input: LocalProcessStopPortsInput): number[] { |
| 34 | + const seen = new Set<number>(); |
| 35 | + for (const port of input.ports) { |
| 36 | + if (Number.isInteger(port) && port >= 1 && port <= 65_535) { |
| 37 | + seen.add(port); |
| 38 | + } |
| 39 | + } |
| 40 | + return [...seen].slice(0, 16); |
| 41 | +} |
| 42 | + |
| 43 | +function normalizeProbePorts(input: LocalProcessProbePortsInput): number[] { |
| 44 | + const seen = new Set<number>(); |
| 45 | + for (const port of input.ports) { |
| 46 | + if (Number.isInteger(port) && port >= 1 && port <= 65_535) { |
| 47 | + seen.add(port); |
| 48 | + } |
| 49 | + } |
| 50 | + return [...seen].slice(0, 32); |
| 51 | +} |
| 52 | + |
| 53 | +async function listListeningPidsWithLsof(port: number): Promise<number[]> { |
| 54 | + const result = await runProcess("lsof", ["-nP", "-ti", `TCP:${port}`, "-sTCP:LISTEN"], { |
| 55 | + allowNonZeroExit: true, |
| 56 | + maxBufferBytes: PORT_LOOKUP_MAX_BUFFER_BYTES, |
| 57 | + outputMode: "truncate", |
| 58 | + timeoutMs: PORT_LOOKUP_TIMEOUT_MS, |
| 59 | + }); |
| 60 | + return parseListeningPidList(result.stdout); |
| 61 | +} |
| 62 | + |
| 63 | +async function listListeningPidsWithPowerShell(port: number): Promise<number[]> { |
| 64 | + const command = [ |
| 65 | + "Get-NetTCPConnection", |
| 66 | + `-LocalPort ${port}`, |
| 67 | + "-State Listen", |
| 68 | + "-ErrorAction SilentlyContinue", |
| 69 | + "| Select-Object -ExpandProperty OwningProcess -Unique", |
| 70 | + ].join(" "); |
| 71 | + const result = await runProcess( |
| 72 | + "powershell.exe", |
| 73 | + ["-NoProfile", "-NonInteractive", "-Command", command], |
| 74 | + { |
| 75 | + allowNonZeroExit: true, |
| 76 | + maxBufferBytes: PORT_LOOKUP_MAX_BUFFER_BYTES, |
| 77 | + outputMode: "truncate", |
| 78 | + timeoutMs: PORT_LOOKUP_TIMEOUT_MS, |
| 79 | + }, |
| 80 | + ); |
| 81 | + return parseListeningPidList(result.stdout); |
| 82 | +} |
| 83 | + |
| 84 | +async function listListeningPids(port: number): Promise<number[]> { |
| 85 | + if (process.platform === "win32") { |
| 86 | + return listListeningPidsWithPowerShell(port); |
| 87 | + } |
| 88 | + return listListeningPidsWithLsof(port); |
| 89 | +} |
| 90 | + |
| 91 | +function killPid(pid: number): void { |
| 92 | + process.kill(pid, "SIGTERM"); |
| 93 | +} |
| 94 | + |
| 95 | +export const defaultLocalProcessControls: LocalProcessControls = { |
| 96 | + currentPid: process.pid, |
| 97 | + listListeningPids, |
| 98 | + killPid, |
| 99 | +}; |
| 100 | + |
| 101 | +function errorMessage(error: unknown): string { |
| 102 | + return error instanceof Error ? error.message : String(error); |
| 103 | +} |
| 104 | + |
| 105 | +export async function probeLocalPorts( |
| 106 | + input: LocalProcessProbePortsInput, |
| 107 | + controls: LocalProcessControls = defaultLocalProcessControls, |
| 108 | +): Promise<LocalProcessProbePortsResult> { |
| 109 | + const ports = normalizeProbePorts(input); |
| 110 | + const results = await Promise.all( |
| 111 | + ports.map(async (port) => { |
| 112 | + try { |
| 113 | + const pids = await controls.listListeningPids(port); |
| 114 | + const filteredPids = [...new Set(pids)].filter( |
| 115 | + (pid) => Number.isSafeInteger(pid) && pid > 0 && pid !== controls.currentPid, |
| 116 | + ); |
| 117 | + return { |
| 118 | + port, |
| 119 | + isListening: filteredPids.length > 0, |
| 120 | + pids: filteredPids, |
| 121 | + error: null, |
| 122 | + }; |
| 123 | + } catch (error) { |
| 124 | + return { |
| 125 | + port, |
| 126 | + isListening: false, |
| 127 | + pids: [] as number[], |
| 128 | + error: errorMessage(error), |
| 129 | + }; |
| 130 | + } |
| 131 | + }), |
| 132 | + ); |
| 133 | + return { results }; |
| 134 | +} |
| 135 | + |
| 136 | +export async function stopLocalPorts( |
| 137 | + input: LocalProcessStopPortsInput, |
| 138 | + controls: LocalProcessControls = defaultLocalProcessControls, |
| 139 | +): Promise<LocalProcessStopPortsResult> { |
| 140 | + const results: Array<{ port: number; killedPids: number[]; errors: string[] }> = []; |
| 141 | + |
| 142 | + for (const port of normalizePorts(input)) { |
| 143 | + const errors: string[] = []; |
| 144 | + let pids: readonly number[] = []; |
| 145 | + |
| 146 | + try { |
| 147 | + pids = await controls.listListeningPids(port); |
| 148 | + } catch (error) { |
| 149 | + errors.push(`Failed to inspect port ${port}: ${errorMessage(error)}`); |
| 150 | + } |
| 151 | + |
| 152 | + const killedPids: number[] = []; |
| 153 | + for (const pid of new Set(pids)) { |
| 154 | + if (!Number.isSafeInteger(pid) || pid <= 0) { |
| 155 | + continue; |
| 156 | + } |
| 157 | + if (pid === controls.currentPid) { |
| 158 | + errors.push(`Refusing to stop the current T3 Code process on port ${port}.`); |
| 159 | + continue; |
| 160 | + } |
| 161 | + try { |
| 162 | + await controls.killPid(pid); |
| 163 | + killedPids.push(pid); |
| 164 | + } catch (error) { |
| 165 | + const code = |
| 166 | + error && typeof error === "object" ? (error as NodeJS.ErrnoException).code : ""; |
| 167 | + if (code !== "ESRCH") { |
| 168 | + errors.push(`Failed to stop process ${pid} on port ${port}: ${errorMessage(error)}`); |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + results.push({ port, killedPids, errors }); |
| 174 | + } |
| 175 | + |
| 176 | + return { results }; |
| 177 | +} |
0 commit comments