diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 04ffaeeeeb..b9e745c7a0 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -43,6 +43,8 @@ import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem" import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner"; import { ObservabilityLive } from "./observability/Layers/Observability"; +import { TerminalProcessInspectorLive } from "./terminalProcessInspector/Layers/TerminalProcessInspector"; +import { WebPortInspectorLive } from "./terminalProcessInspector/Layers/WebPortInspector"; const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -168,7 +170,11 @@ const GitLayerLive = Layer.empty.pipe( Layer.provideMerge(GitCoreLive), ); -const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive)); +const TerminalLayerLive = TerminalManagerLive.pipe( + Layer.provideMerge(WebPortInspectorLive), + Layer.provideMerge(TerminalProcessInspectorLive), + Layer.provide(PtyAdapterLive), +); const WorkspaceLayerLive = Layer.mergeAll( WorkspacePathsLive, diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index c059c97983..aff699ed96 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -1,5 +1,6 @@ import path from "node:path"; +import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { @@ -15,6 +16,7 @@ import { Exit, Fiber, FileSystem, + Layer, Option, PlatformError, Ref, @@ -24,6 +26,10 @@ import { import { TestClock } from "effect/testing"; import { expect } from "vitest"; +import { TerminalProcessInspectorLive } from "../../terminalProcessInspector/Layers/TerminalProcessInspector"; +import { WebPortInspectorLive } from "../../terminalProcessInspector/Layers/WebPortInspector"; +import { TerminalProcessInspector } from "../../terminalProcessInspector/Services/TerminalProcessInspector"; +import { WebPortInspector } from "../../terminalProcessInspector/Services/WebPortInspector"; import type { TerminalManagerShape } from "../Services/Manager"; import { type PtyAdapterShape, @@ -213,7 +219,7 @@ const createManager = ( ): Effect.Effect< ManagerFixture, PlatformError.PlatformError, - FileSystem.FileSystem | Scope.Scope + FileSystem.FileSystem | Scope.Scope | TerminalProcessInspector | WebPortInspector > => Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => Effect.gen(function* () { @@ -262,7 +268,16 @@ const createManager = ( }), ); -it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => { +const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer)); + +it.layer( + Layer.mergeAll( + NodeServices.layer, + WebPortInspectorLive, + TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer)), + ), + { excludeTestServices: true }, +)("TerminalManager", (it) => { it.effect("spawns lazily and reuses running terminal per thread", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 930e764e36..72963196d4 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -30,10 +30,15 @@ import { } from "../../observability/Metrics"; import { arePortListsEqual, - defaultSubprocessInspector, normalizeRunningPorts, + subprocessCheckerToInspector, + TerminalProcessInspector, + type TerminalSubprocessActivity, + type TerminalSubprocessChecker, + type TerminalSubprocessInspector, + type TerminalWebPortInspector, } from "../../terminalProcessInspector"; -import { DEFAULT_WEB_PORT_PROBE_TTL_MS, defaultWebPortInspector } from "../../webPortInspector"; +import { DEFAULT_WEB_PORT_PROBE_TTL_MS, WebPortInspector } from "../../webPortInspector"; import { TerminalCwdError, TerminalHistoryError, @@ -59,25 +64,6 @@ const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); -type TerminalSubprocessChecker = ( - terminalPid: number, -) => Effect.Effect; -type TerminalSubprocessActivity = { - hasRunningSubprocess: boolean; - runningPorts: number[]; -}; -type TerminalSubprocessInspector = ( - terminalPid: number, -) => Effect.Effect; -type TerminalWebPortInspector = (port: number) => Effect.Effect; - -class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{ - readonly message: string; - readonly cause?: unknown; - readonly terminalPid: number; - readonly command: "powershell" | "pgrep" | "ps"; -}> {} - class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{ readonly message: string; readonly cause?: unknown; @@ -588,29 +574,9 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const subprocessInspector = options.subprocessInspector ?? (options.subprocessChecker - ? (terminalPid: number) => - Effect.map(options.subprocessChecker!(terminalPid), (hasRunningSubprocess) => ({ - hasRunningSubprocess, - runningPorts: [], - })) - : (terminalPid: number) => - Effect.tryPromise({ - try: () => defaultSubprocessInspector(terminalPid), - catch: (cause) => - new TerminalSubprocessCheckError({ - message: "Failed to inspect terminal subprocess activity", - cause, - terminalPid, - command: process.platform === "win32" ? "powershell" : "ps", - }), - })); - const webPortInspector = - options.webPortInspector ?? - ((port: number) => - Effect.tryPromise({ - try: () => defaultWebPortInspector(port), - catch: () => false, - })); + ? subprocessCheckerToInspector(options.subprocessChecker) + : (yield* TerminalProcessInspector).inspect); + const webPortInspector = options.webPortInspector ?? (yield* WebPortInspector).inspect; const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS; const subprocessPollIntervalMs = options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; diff --git a/apps/server/src/terminalProcessInspector/Errors.ts b/apps/server/src/terminalProcessInspector/Errors.ts new file mode 100644 index 0000000000..77ed38e08b --- /dev/null +++ b/apps/server/src/terminalProcessInspector/Errors.ts @@ -0,0 +1,32 @@ +import { Schema } from "effect"; + +export class TerminalProcessInspectionError extends Schema.TaggedErrorClass()( + "TerminalProcessInspectionError", + { + operation: Schema.String, + terminalPid: Schema.Int, + command: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `${this.operation} failed for terminal pid ${this.terminalPid}: ${this.detail}`; + } +} + +export class WebPortInspectionError extends Schema.TaggedErrorClass()( + "WebPortInspectionError", + { + port: Schema.Int, + host: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Web port probe failed for ${this.host}:${this.port}: ${this.detail}`; + } +} + +export type TerminalInspectorError = TerminalProcessInspectionError | WebPortInspectionError; diff --git a/apps/server/src/terminalProcessInspector/Layers/TerminalProcessInspector.ts b/apps/server/src/terminalProcessInspector/Layers/TerminalProcessInspector.ts new file mode 100644 index 0000000000..11c08c48fc --- /dev/null +++ b/apps/server/src/terminalProcessInspector/Layers/TerminalProcessInspector.ts @@ -0,0 +1,241 @@ +import { Buffer } from "node:buffer"; + +import { Effect, Layer, Option, PlatformError, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { TerminalProcessInspectionError } from "../Errors"; +import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "../posix"; +import type { TerminalProcessInspectorShape } from "../Services/TerminalProcessInspector"; +import { TerminalProcessInspector } from "../Services/TerminalProcessInspector"; +import { + type TerminalSubprocessActivity, + type TerminalSubprocessChecker, + type TerminalSubprocessInspector, +} from "../types"; +import { checkWindowsListeningPorts, collectWindowsChildPids } from "../win32"; + +const DEFAULT_COMMAND_KILL_GRACE_MS = 1_000; + +interface InspectorCommandResult { + readonly stdout: string; + readonly stderr: string; + readonly exitCode: number; +} + +interface CollectOutputResult { + readonly text: string; + readonly truncated: boolean; +} + +interface RunInspectorCommandInput { + readonly operation: string; + readonly terminalPid: number; + readonly command: string; + readonly args: ReadonlyArray; + readonly timeoutMs: number; + readonly maxOutputBytes: number; +} + +function commandLabel(command: string, args: ReadonlyArray): string { + return [command, ...args].join(" "); +} + +const collectOutput = Effect.fn("terminalProcessInspector.collectOutput")(function* ( + stream: Stream.Stream, + maxOutputBytes: number, +): Effect.fn.Return { + return yield* stream.pipe( + Stream.decodeText(), + Stream.runFold( + () => ({ + text: "", + bytes: 0, + truncated: false, + }), + (state, chunk) => { + if (state.bytes >= maxOutputBytes) { + return { + ...state, + truncated: true, + }; + } + + const chunkBytes = Buffer.byteLength(chunk); + const remainingBytes = maxOutputBytes - state.bytes; + if (chunkBytes <= remainingBytes) { + return { + text: `${state.text}${chunk}`, + bytes: state.bytes + chunkBytes, + truncated: state.truncated, + }; + } + + const truncatedChunk = Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8"); + return { + text: `${state.text}${truncatedChunk}`, + bytes: state.bytes + remainingBytes, + truncated: true, + }; + }, + ), + Effect.map(({ text, truncated }) => ({ text, truncated })), + ); +}); + +const makeTerminalProcessInspector = Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + const runInspectorCommand = Effect.fn("terminalProcessInspector.runInspectorCommand")(function* ( + input: RunInspectorCommandInput, + ) { + const command = ChildProcess.make(input.command, [...input.args], { + killSignal: "SIGTERM", + forceKillAfter: DEFAULT_COMMAND_KILL_GRACE_MS, + }); + + return yield* Effect.gen(function* () { + const child = yield* spawner.spawn(command).pipe( + Effect.mapError( + (cause) => + new TerminalProcessInspectionError({ + operation: input.operation, + terminalPid: input.terminalPid, + command: commandLabel(input.command, input.args), + detail: "Failed to spawn inspector command.", + cause, + }), + ), + ); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectOutput(child.stdout, input.maxOutputBytes).pipe( + Effect.mapError( + (cause) => + new TerminalProcessInspectionError({ + operation: input.operation, + terminalPid: input.terminalPid, + command: commandLabel(input.command, input.args), + detail: "Failed to read stdout from inspector command.", + cause, + }), + ), + ), + collectOutput(child.stderr, input.maxOutputBytes).pipe( + Effect.mapError( + (cause) => + new TerminalProcessInspectionError({ + operation: input.operation, + terminalPid: input.terminalPid, + command: commandLabel(input.command, input.args), + detail: "Failed to read stderr from inspector command.", + cause, + }), + ), + ), + child.exitCode.pipe( + Effect.map(Number), + Effect.mapError( + (cause) => + new TerminalProcessInspectionError({ + operation: input.operation, + terminalPid: input.terminalPid, + command: commandLabel(input.command, input.args), + detail: "Failed to read inspector command exit code.", + cause, + }), + ), + ), + ], + { concurrency: "unbounded" }, + ); + + return { + stdout: stdout.text, + stderr: stderr.text, + exitCode, + } satisfies InspectorCommandResult; + }).pipe( + Effect.scoped, + Effect.timeoutOption(input.timeoutMs), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new TerminalProcessInspectionError({ + operation: input.operation, + terminalPid: input.terminalPid, + command: commandLabel(input.command, input.args), + detail: "Inspector command timed out.", + }), + ), + onSome: Effect.succeed, + }), + ), + ); + }); + + const inspect: TerminalProcessInspectorShape["inspect"] = Effect.fn( + "terminalProcessInspector.inspect", + )(function* (terminalPid) { + if (!Number.isInteger(terminalPid) || terminalPid <= 0) { + return { + hasRunningSubprocess: false, + runningPorts: [], + } satisfies TerminalSubprocessActivity; + } + + if (process.platform === "win32") { + const childPids = yield* collectWindowsChildPids(terminalPid, runInspectorCommand); + const processPidsForPortScan = [terminalPid, ...childPids]; + const runningPorts = yield* checkWindowsListeningPorts(processPidsForPortScan, { + terminalPid, + runCommand: runInspectorCommand, + }); + return { + hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0, + runningPorts, + } satisfies TerminalSubprocessActivity; + } + + const processFamilyPids = yield* collectPosixProcessFamilyPids( + terminalPid, + runInspectorCommand, + ); + if (processFamilyPids.length === 0) { + return { + hasRunningSubprocess: false, + runningPorts: [], + } satisfies TerminalSubprocessActivity; + } + + const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid); + const runningPorts = yield* checkPosixListeningPorts(processFamilyPids, { + terminalPid, + runCommand: runInspectorCommand, + }); + return { + hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0, + runningPorts, + } satisfies TerminalSubprocessActivity; + }); + + return { + inspect, + } satisfies TerminalProcessInspectorShape; +}); + +export const subprocessCheckerToInspector = ( + subprocessChecker: TerminalSubprocessChecker, +): TerminalSubprocessInspector => + Effect.fn("terminalProcessInspector.subprocessCheckerToInspector")(function* (terminalPid) { + return { + hasRunningSubprocess: yield* subprocessChecker(terminalPid), + runningPorts: [], + }; + }); + +export const TerminalProcessInspectorLive = Layer.effect( + TerminalProcessInspector, + makeTerminalProcessInspector, +); diff --git a/apps/server/src/terminalProcessInspector/Layers/WebPortInspector.ts b/apps/server/src/terminalProcessInspector/Layers/WebPortInspector.ts new file mode 100644 index 0000000000..8484edb7d1 --- /dev/null +++ b/apps/server/src/terminalProcessInspector/Layers/WebPortInspector.ts @@ -0,0 +1,217 @@ +import { request as httpRequest } from "node:http"; +import type { IncomingMessage } from "node:http"; + +import { Effect, Layer } from "effect"; + +import { WebPortInspectionError } from "../Errors"; +import type { WebPortInspectorShape } from "../Services/WebPortInspector"; +import { WebPortInspector } from "../Services/WebPortInspector"; + +const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000; +const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192; + +interface WebProbeResult { + readonly status: number; + readonly contentType: string; + readonly body: string; + readonly location: string; +} + +function normalizeHeaderValue(value: string | string[] | undefined): string { + if (typeof value === "string") return value; + if (Array.isArray(value)) return value[0] ?? ""; + return ""; +} + +function isLikelyWebProbe(result: WebProbeResult | null): boolean { + if (!result) return false; + if (result.status === 404) return false; + if (result.status >= 300 && result.status < 400 && result.location.length > 0) { + return true; + } + const contentType = result.contentType.toLowerCase(); + if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) { + return true; + } + const body = result.body.toLowerCase(); + return body.includes(" { + return yield* Effect.callback((resume) => { + let response: IncomingMessage | null = null; + let timer: ReturnType | null = null; + let settled = false; + + const settle = (effect: Effect.Effect) => { + if (settled) return; + settled = true; + cleanup(); + resume(effect); + }; + + const cleanup = () => { + if (timer) { + clearTimeout(timer); + timer = null; + } + response?.removeAllListeners(); + request.removeAllListeners(); + response?.destroy(); + request.destroy(); + }; + + const request = httpRequest( + { + host, + port, + method: "GET", + path: "/", + timeout: DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS, + }, + (res) => { + response = res; + const status = res.statusCode ?? 0; + const contentType = normalizeHeaderValue(res.headers["content-type"]); + const location = normalizeHeaderValue(res.headers.location); + + if ( + (status >= 300 && status < 400 && location.length > 0) || + contentType.toLowerCase().includes("text/html") || + contentType.toLowerCase().includes("application/xhtml+xml") + ) { + settle( + Effect.succeed({ + status, + contentType, + location, + body: "", + } satisfies WebProbeResult), + ); + return; + } + + const chunks: string[] = []; + let received = 0; + + res.setEncoding("utf8"); + res.on("data", (chunk: string) => { + if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) return; + const remaining = WEB_PORT_PROBE_MAX_BODY_BYTES - received; + const fragment = chunk.slice(0, remaining); + received += fragment.length; + chunks.push(fragment); + if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) { + settle( + Effect.succeed({ + status, + contentType, + location, + body: chunks.join(""), + } satisfies WebProbeResult), + ); + } + }); + res.on("end", () => { + settle( + Effect.succeed({ + status, + contentType, + location, + body: chunks.join(""), + } satisfies WebProbeResult), + ); + }); + res.on("error", (cause) => { + settle( + Effect.fail( + new WebPortInspectionError({ + port, + host, + detail: "Failed to read HTTP probe response.", + cause, + }), + ), + ); + }); + }, + ); + + request.on("timeout", () => { + settle( + Effect.fail( + new WebPortInspectionError({ + port, + host, + detail: "HTTP probe timed out.", + }), + ), + ); + }); + request.on("error", (cause) => { + settle( + Effect.fail( + new WebPortInspectionError({ + port, + host, + detail: "Failed to open HTTP probe request.", + cause, + }), + ), + ); + }); + + timer = setTimeout(() => { + settle( + Effect.fail( + new WebPortInspectionError({ + port, + host, + detail: "HTTP probe timed out.", + }), + ), + ); + }, DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS + 50); + + request.end(); + + return Effect.sync(cleanup); + }); +}); + +const makeWebPortInspector = Effect.succeed({ + inspect: Effect.fn("webPortInspector.inspect")(function* (port) { + if (!Number.isInteger(port) || port <= 0 || port > 65_535) { + return yield* new WebPortInspectionError({ + port, + host: "127.0.0.1", + detail: "Port must be an integer between 1 and 65535.", + }); + } + + const ipv4Result = yield* probeWebPortOnHost(port, "127.0.0.1").pipe(Effect.exit); + if (ipv4Result._tag === "Success" && isLikelyWebProbe(ipv4Result.value)) { + return true; + } + + const ipv6Result = yield* probeWebPortOnHost(port, "::1").pipe(Effect.exit); + if (ipv6Result._tag === "Success" && isLikelyWebProbe(ipv6Result.value)) { + return true; + } + + if (ipv4Result._tag === "Success" || ipv6Result._tag === "Success") { + return false; + } + + if (ipv6Result._tag === "Failure") { + return yield* Effect.failCause(ipv6Result.cause); + } + + return yield* Effect.failCause(ipv4Result.cause); + }), +} satisfies WebPortInspectorShape); + +export const WebPortInspectorLive = Layer.effect(WebPortInspector, makeWebPortInspector); diff --git a/apps/server/src/terminalProcessInspector/Services/TerminalProcessInspector.ts b/apps/server/src/terminalProcessInspector/Services/TerminalProcessInspector.ts new file mode 100644 index 0000000000..bdb72daf50 --- /dev/null +++ b/apps/server/src/terminalProcessInspector/Services/TerminalProcessInspector.ts @@ -0,0 +1,16 @@ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { TerminalProcessInspectionError } from "../Errors"; +import type { TerminalSubprocessActivity } from "../types"; + +export interface TerminalProcessInspectorShape { + readonly inspect: ( + terminalPid: number, + ) => Effect.Effect; +} + +export class TerminalProcessInspector extends ServiceMap.Service< + TerminalProcessInspector, + TerminalProcessInspectorShape +>()("t3/terminalProcessInspector/Services/TerminalProcessInspector") {} diff --git a/apps/server/src/terminalProcessInspector/Services/WebPortInspector.ts b/apps/server/src/terminalProcessInspector/Services/WebPortInspector.ts new file mode 100644 index 0000000000..35b1508156 --- /dev/null +++ b/apps/server/src/terminalProcessInspector/Services/WebPortInspector.ts @@ -0,0 +1,14 @@ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { WebPortInspectionError } from "../Errors"; + +export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000; + +export interface WebPortInspectorShape { + readonly inspect: (port: number) => Effect.Effect; +} + +export class WebPortInspector extends ServiceMap.Service()( + "t3/terminalProcessInspector/Services/WebPortInspector", +) {} diff --git a/apps/server/src/terminalProcessInspector/index.test.ts b/apps/server/src/terminalProcessInspector/index.test.ts index 248b8bd2bf..532a2c6f97 100644 --- a/apps/server/src/terminalProcessInspector/index.test.ts +++ b/apps/server/src/terminalProcessInspector/index.test.ts @@ -1,22 +1,47 @@ import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process"; import type { Readable } from "node:stream"; -import { afterEach, describe, expect, it } from "vitest"; +import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; -import { defaultSubprocessInspector } from "./index"; +import { TerminalProcessInspectorLive } from "./Layers/TerminalProcessInspector"; +import { TerminalProcessInspector } from "./Services/TerminalProcessInspector"; type ListenerProcess = ChildProcessByStdio; interface StartedProcess { - process: ListenerProcess; - port: number; + readonly process: ListenerProcess; + readonly port: number; } -async function waitForPort(child: ListenerProcess): Promise { - return new Promise((resolve, reject) => { +const stopProcess = (child: ChildProcess) => + Effect.callback((resume) => { + if (child.exitCode !== null || child.signalCode !== null) { + resume(Effect.void); + return; + } + + child.kill("SIGTERM"); + + const timeout = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) { + child.kill("SIGKILL"); + } + }, 1_000); + + child.once("exit", () => { + clearTimeout(timeout); + resume(Effect.void); + }); + }); + +const waitForPort = (child: ListenerProcess) => + Effect.callback((resume) => { const timeout = setTimeout(() => { cleanup(); - reject(new Error("Timed out waiting for listener port")); + resume(Effect.fail(new Error("Timed out waiting for listener port"))); }, 3_000); let stdout = ""; @@ -36,7 +61,7 @@ async function waitForPort(child: ListenerProcess): Promise { const port = Number(match[1]); if (!Number.isInteger(port) || port <= 0) return; cleanup(); - resolve(port); + resume(Effect.succeed(port)); }; const onStderr = (chunk: Buffer) => { @@ -45,9 +70,11 @@ async function waitForPort(child: ListenerProcess): Promise { const onExit = (code: number | null) => { cleanup(); - reject( - new Error( - `Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`, + resume( + Effect.fail( + new Error( + `Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`, + ), ), ); }; @@ -55,10 +82,11 @@ async function waitForPort(child: ListenerProcess): Promise { child.stdout.on("data", onStdout); child.stderr.on("data", onStderr); child.on("exit", onExit); - }); -} -async function startListenerProcess(): Promise { + return Effect.sync(cleanup); + }); + +const startListenerProcess = Effect.gen(function* () { const script = [ "const { createServer } = require('node:http');", "const server = createServer((_req, res) => {", @@ -79,63 +107,56 @@ async function startListenerProcess(): Promise { const process = spawn("node", ["-e", script], { stdio: ["ignore", "pipe", "pipe"], }); - const port = await waitForPort(process); - return { process, port }; -} - -async function stopProcess(child: ChildProcess): Promise { - if (child.exitCode !== null || child.signalCode !== null) { - return; - } - - child.kill("SIGTERM"); - await new Promise((resolve) => { - const timeout = setTimeout(() => { - if (child.exitCode === null && child.signalCode === null) { - child.kill("SIGKILL"); - } - }, 1_000); - child.once("exit", () => { - clearTimeout(timeout); - resolve(); - }); - }); -} - -describe("defaultSubprocessInspector", () => { - const spawned: ChildProcess[] = []; - - afterEach(async () => { - await Promise.all(spawned.splice(0, spawned.length).map((child) => stopProcess(child))); - }); - - it("detects listening ports when the terminal root PID is the listener", async () => { - const listener = await startListenerProcess(); - spawned.push(listener.process); - const listenerPid = listener.process.pid; - if (!listenerPid) { - throw new Error("Listener process pid missing"); - } - - const activity = await defaultSubprocessInspector(listenerPid); - - expect(activity.hasRunningSubprocess).toBe(true); - expect(activity.runningPorts).toContain(listener.port); - }); - - it("returns idle activity when root process has no children and no listening ports", async () => { - const idle = spawn("node", ["-e", "setInterval(() => {}, 10_000)"], { - stdio: ["ignore", "ignore", "ignore"], - }); - spawned.push(idle); - const idlePid = idle.pid; - if (!idlePid) { - throw new Error("Idle process pid missing"); - } - - const activity = await defaultSubprocessInspector(idlePid); - - expect(activity.hasRunningSubprocess).toBe(false); - expect(activity.runningPorts).toEqual([]); - }); + const port = yield* waitForPort(process); + return { process, port } satisfies StartedProcess; +}); + +const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer)); + +const testLayer = TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer)); + +it.layer(testLayer)("TerminalProcessInspectorLive", (it) => { + it.effect("detects listening ports when the terminal root pid is the listener", () => + Effect.acquireUseRelease( + startListenerProcess, + ({ process, port }) => + Effect.gen(function* () { + const listenerPid = process.pid; + if (!listenerPid) { + return yield* Effect.fail(new Error("Listener process pid missing")); + } + + const inspector = yield* TerminalProcessInspector; + const activity = yield* inspector.inspect(listenerPid); + + assert.equal(activity.hasRunningSubprocess, true); + assert.deepStrictEqual(activity.runningPorts.includes(port), true); + }), + ({ process }) => stopProcess(process), + ), + ); + + it.effect("returns idle activity when root process has no children and no listening ports", () => + Effect.acquireUseRelease( + Effect.sync(() => + spawn("node", ["-e", "setInterval(() => {}, 10_000)"], { + stdio: ["ignore", "ignore", "ignore"], + }), + ), + (process) => + Effect.gen(function* () { + const idlePid = process.pid; + if (!idlePid) { + return yield* Effect.fail(new Error("Idle process pid missing")); + } + + const inspector = yield* TerminalProcessInspector; + const activity = yield* inspector.inspect(idlePid); + + assert.equal(activity.hasRunningSubprocess, false); + assert.deepStrictEqual(activity.runningPorts, []); + }), + stopProcess, + ), + ); }); diff --git a/apps/server/src/terminalProcessInspector/index.ts b/apps/server/src/terminalProcessInspector/index.ts index 21871d5b8a..a9104a430f 100644 --- a/apps/server/src/terminalProcessInspector/index.ts +++ b/apps/server/src/terminalProcessInspector/index.ts @@ -1,11 +1,11 @@ -import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "./posix"; -import { - type TerminalSubprocessActivity, - type TerminalSubprocessChecker, - type TerminalSubprocessInspector, - type TerminalWebPortInspector, -} from "./types"; -import { checkWindowsListeningPorts, collectWindowsChildPids } from "./win32"; +export { TerminalProcessInspectionError, WebPortInspectionError } from "./Errors"; +export { + TerminalProcessInspectorLive, + subprocessCheckerToInspector, +} from "./Layers/TerminalProcessInspector"; +export { WebPortInspectorLive } from "./Layers/WebPortInspector"; +export { TerminalProcessInspector } from "./Services/TerminalProcessInspector"; +export { WebPortInspector } from "./Services/WebPortInspector"; export { arePortListsEqual, normalizeRunningPorts } from "./utils"; @@ -15,42 +15,3 @@ export type { TerminalSubprocessInspector, TerminalWebPortInspector, } from "./types"; - -export async function defaultSubprocessInspector( - terminalPid: number, -): Promise { - if (!Number.isInteger(terminalPid) || terminalPid <= 0) { - return { hasRunningSubprocess: false, runningPorts: [] }; - } - - if (process.platform === "win32") { - const childPids = await collectWindowsChildPids(terminalPid); - const processPidsForPortScan = [terminalPid, ...childPids]; - const runningPorts = await checkWindowsListeningPorts(processPidsForPortScan); - return { - hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0, - runningPorts, - }; - } - - const processFamilyPids = await collectPosixProcessFamilyPids(terminalPid); - if (processFamilyPids.length === 0) { - return { hasRunningSubprocess: false, runningPorts: [] }; - } - - const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid); - const runningPorts = await checkPosixListeningPorts(processFamilyPids); - return { - hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0, - runningPorts, - }; -} - -export function subprocessCheckerToInspector( - subprocessChecker: TerminalSubprocessChecker, -): TerminalSubprocessInspector { - return async (terminalPid: number) => ({ - hasRunningSubprocess: await subprocessChecker(terminalPid), - runningPorts: [], - }); -} diff --git a/apps/server/src/terminalProcessInspector/posix.ts b/apps/server/src/terminalProcessInspector/posix.ts index 06280190e6..0b3c360eca 100644 --- a/apps/server/src/terminalProcessInspector/posix.ts +++ b/apps/server/src/terminalProcessInspector/posix.ts @@ -1,119 +1,147 @@ -import { runProcess } from "../processRunner"; +import { Effect } from "effect"; + +import type { TerminalProcessInspectionError } from "./Errors"; import { MAX_PORT_NUMBER, portFromAddress } from "./utils"; -export async function collectPosixProcessFamilyPids(terminalPid: number): Promise { - try { - const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], { - timeoutMs: 1_000, - allowNonZeroExit: true, - maxBufferBytes: 262_144, - outputMode: "truncate", - }); - if (psResult.code !== 0) { - return []; - } - - const childrenByParentPid = new Map(); - for (const line of psResult.stdout.split(/\r?\n/g)) { - const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; - const children = childrenByParentPid.get(ppid); - if (children) { - children.push(pid); - } else { - childrenByParentPid.set(ppid, [pid]); - } - } - - const processFamily = new Set([terminalPid]); - const pendingParents = [terminalPid]; - while (pendingParents.length > 0) { - const parentPid = pendingParents.shift(); - if (!parentPid) continue; - const childPids = childrenByParentPid.get(parentPid); - if (!childPids || childPids.length === 0) continue; - for (const childPid of childPids) { - if (processFamily.has(childPid)) continue; - processFamily.add(childPid); - pendingParents.push(childPid); - } - } - - return [...processFamily]; - } catch { - return []; - } +interface InspectorCommandResult { + readonly stdout: string; + readonly stderr: string; + readonly exitCode: number; } -export async function checkPosixListeningPorts(processIds: number[]): Promise { +interface PosixRunCommand { + ( + input: Readonly<{ + operation: string; + terminalPid: number; + command: string; + args: ReadonlyArray; + timeoutMs: number; + maxOutputBytes: number; + }>, + ): Effect.Effect; +} + +export const collectPosixProcessFamilyPids = Effect.fn( + "terminalProcessInspector.collectPosixProcessFamilyPids", +)(function* ( + terminalPid: number, + runCommand: PosixRunCommand, +): Effect.fn.Return { + const psResult = yield* runCommand({ + operation: "TerminalProcessInspector.collectPosixProcessFamilyPids", + terminalPid, + command: "ps", + args: ["-eo", "pid=,ppid="], + timeoutMs: 1_000, + maxOutputBytes: 262_144, + }); + if (psResult.exitCode !== 0) { + return []; + } + + const childrenByParentPid = new Map(); + for (const line of psResult.stdout.split(/\r?\n/g)) { + const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); + const pid = Number(pidRaw); + const ppid = Number(ppidRaw); + if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; + const children = childrenByParentPid.get(ppid); + if (children) { + children.push(pid); + } else { + childrenByParentPid.set(ppid, [pid]); + } + } + + const processFamily = new Set([terminalPid]); + const pendingParents = [terminalPid]; + while (pendingParents.length > 0) { + const parentPid = pendingParents.shift(); + if (!parentPid) continue; + const childPids = childrenByParentPid.get(parentPid); + if (!childPids || childPids.length === 0) continue; + for (const childPid of childPids) { + if (processFamily.has(childPid)) continue; + processFamily.add(childPid); + pendingParents.push(childPid); + } + } + + return [...processFamily]; +}); + +export const checkPosixListeningPorts = Effect.fn( + "terminalProcessInspector.checkPosixListeningPorts", +)(function* ( + processIds: number[], + input: { + terminalPid: number; + runCommand: PosixRunCommand; + }, +): Effect.fn.Return { if (processIds.length === 0) return []; const ports = new Set(); const pidFilter = new Set(processIds); - try { - const result = await runProcess( - "lsof", - ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")], - { - timeoutMs: 1_500, - allowNonZeroExit: true, - maxBufferBytes: 262_144, - outputMode: "truncate", - }, - ); - if (result.code !== 0) { - // `lsof` returns 1 when there are no matching files/sockets. - // This is a valid "no results" outcome; avoid falling back to `ss`. + const lsofResult = yield* input + .runCommand({ + operation: "TerminalProcessInspector.checkPosixListeningPorts.lsof", + terminalPid: input.terminalPid, + command: "lsof", + args: ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")], + timeoutMs: 1_500, + maxOutputBytes: 262_144, + }) + .pipe(Effect.exit); + + if (lsofResult._tag === "Success") { + if (lsofResult.value.exitCode === 1) { return []; } - - for (const line of result.stdout.split(/\r?\n/g)) { - const match = line.match(/:(\d+)\s+\(LISTEN\)$/); - if (!match?.[1]) continue; - const port = Number(match[1]); - if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) { - ports.add(port); + if (lsofResult.value.exitCode === 0) { + for (const line of lsofResult.value.stdout.split(/\r?\n/g)) { + const match = line.match(/:(\d+)\s+\(LISTEN\)$/); + if (!match?.[1]) continue; + const port = Number(match[1]); + if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) { + ports.add(port); + } } + return [...ports].toSorted((left, right) => left - right); } - return [...ports].toSorted((left, right) => left - right); - } catch { - // Fall back to ss if lsof is unavailable. } - try { - const result = await runProcess("ss", ["-ltnp"], { - timeoutMs: 1_500, - allowNonZeroExit: true, - maxBufferBytes: 524_288, - outputMode: "truncate", - }); - if (result.code !== 0) { - return []; - } - - for (const line of result.stdout.split(/\r?\n/g)) { - if (!line.includes("pid=")) continue; - const localAddress = line.trim().split(/\s+/g)[3]; - if (!localAddress) continue; - const port = portFromAddress(localAddress); - if (port === null) continue; - - const pidMatches = [...line.matchAll(/pid=(\d+)/g)]; - if (pidMatches.length === 0) continue; - if ( - pidMatches.some((match) => { - const pid = Number(match[1]); - return Number.isInteger(pid) && pidFilter.has(pid); - }) - ) { - ports.add(port); - } - } - return [...ports].toSorted((left, right) => left - right); - } catch { + const ssResult = yield* input.runCommand({ + operation: "TerminalProcessInspector.checkPosixListeningPorts.ss", + terminalPid: input.terminalPid, + command: "ss", + args: ["-ltnp"], + timeoutMs: 1_500, + maxOutputBytes: 524_288, + }); + if (ssResult.exitCode !== 0) { return []; } -} + + for (const line of ssResult.stdout.split(/\r?\n/g)) { + if (!line.includes("pid=")) continue; + const localAddress = line.trim().split(/\s+/g)[3]; + if (!localAddress) continue; + const port = portFromAddress(localAddress); + if (port === null) continue; + + const pidMatches = [...line.matchAll(/pid=(\d+)/g)]; + if (pidMatches.length === 0) continue; + if ( + pidMatches.some((match) => { + const pid = Number(match[1]); + return Number.isInteger(pid) && pidFilter.has(pid); + }) + ) { + ports.add(port); + } + } + return [...ports].toSorted((left, right) => left - right); +}); diff --git a/apps/server/src/terminalProcessInspector/types.ts b/apps/server/src/terminalProcessInspector/types.ts index 4d80fd38a9..caf488d242 100644 --- a/apps/server/src/terminalProcessInspector/types.ts +++ b/apps/server/src/terminalProcessInspector/types.ts @@ -1,6 +1,14 @@ -export type TerminalSubprocessChecker = (terminalPid: number) => Promise; +import type { Effect } from "effect"; -export type TerminalWebPortInspector = (port: number) => Promise; +import type { TerminalProcessInspectionError, WebPortInspectionError } from "./Errors"; + +export type TerminalSubprocessChecker = ( + terminalPid: number, +) => Effect.Effect; + +export type TerminalWebPortInspector = ( + port: number, +) => Effect.Effect; export interface TerminalSubprocessActivity { hasRunningSubprocess: boolean; @@ -9,4 +17,4 @@ export interface TerminalSubprocessActivity { export type TerminalSubprocessInspector = ( terminalPid: number, -) => Promise; +) => Effect.Effect; diff --git a/apps/server/src/terminalProcessInspector/win32.ts b/apps/server/src/terminalProcessInspector/win32.ts index a0f5b99110..65435bb834 100644 --- a/apps/server/src/terminalProcessInspector/win32.ts +++ b/apps/server/src/terminalProcessInspector/win32.ts @@ -1,33 +1,61 @@ -import { runProcess } from "../processRunner"; +import { Effect } from "effect"; + +import type { TerminalProcessInspectionError } from "./Errors"; import { parsePidList, parsePortList } from "./utils"; -export async function collectWindowsChildPids(terminalPid: number): Promise { +interface InspectorCommandResult { + readonly stdout: string; + readonly stderr: string; + readonly exitCode: number; +} + +interface WindowsRunCommand { + ( + input: Readonly<{ + operation: string; + terminalPid: number; + command: string; + args: ReadonlyArray; + timeoutMs: number; + maxOutputBytes: number; + }>, + ): Effect.Effect; +} + +export const collectWindowsChildPids = Effect.fn( + "terminalProcessInspector.collectWindowsChildPids", +)(function* ( + terminalPid: number, + runCommand: WindowsRunCommand, +): Effect.fn.Return { const command = [ `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`, "if (-not $children) { exit 0 }", "$children | Select-Object -ExpandProperty ProcessId", ].join("; "); - try { - const result = await runProcess( - "powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", command], - { - timeoutMs: 1_500, - allowNonZeroExit: true, - maxBufferBytes: 32_768, - outputMode: "truncate", - }, - ); - if (result.code !== 0) { - return []; - } - return parsePidList(result.stdout); - } catch { + const result = yield* runCommand({ + operation: "TerminalProcessInspector.collectWindowsChildPids", + terminalPid, + command: "powershell.exe", + args: ["-NoProfile", "-NonInteractive", "-Command", command], + timeoutMs: 1_500, + maxOutputBytes: 32_768, + }); + if (result.exitCode !== 0) { return []; } -} + return parsePidList(result.stdout); +}); -export async function checkWindowsListeningPorts(processIds: number[]): Promise { +export const checkWindowsListeningPorts = Effect.fn( + "terminalProcessInspector.checkWindowsListeningPorts", +)(function* ( + processIds: number[], + input: { + terminalPid: number; + runCommand: WindowsRunCommand; + }, +): Effect.fn.Return { if (processIds.length === 0) return []; const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or "); @@ -37,22 +65,16 @@ export async function checkWindowsListeningPorts(processIds: number[]): Promise< "if (-not $matching) { exit 0 }", "$matching | Select-Object -ExpandProperty LocalPort -Unique", ].join("; "); - try { - const result = await runProcess( - "powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", command], - { - timeoutMs: 1_500, - allowNonZeroExit: true, - maxBufferBytes: 65_536, - outputMode: "truncate", - }, - ); - if (result.code !== 0) { - return []; - } - return parsePortList(result.stdout); - } catch { + const result = yield* input.runCommand({ + operation: "TerminalProcessInspector.checkWindowsListeningPorts", + terminalPid: input.terminalPid, + command: "powershell.exe", + args: ["-NoProfile", "-NonInteractive", "-Command", command], + timeoutMs: 1_500, + maxOutputBytes: 65_536, + }); + if (result.exitCode !== 0) { return []; } -} + return parsePortList(result.stdout); +}); diff --git a/apps/server/src/webPortInspector.test.ts b/apps/server/src/webPortInspector.test.ts index 791a6bbf71..7211ba8c0e 100644 --- a/apps/server/src/webPortInspector.test.ts +++ b/apps/server/src/webPortInspector.test.ts @@ -1,81 +1,109 @@ -import { createServer, type Server } from "node:http"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; -import { afterEach, describe, expect, it } from "vitest"; +import { assert, it } from "@effect/vitest"; +import { Effect } from "effect"; -import { defaultWebPortInspector } from "./webPortInspector"; +import { WebPortInspectorLive } from "./webPortInspector"; +import { WebPortInspector } from "./terminalProcessInspector/Services/WebPortInspector"; -async function listenServer(server: Server): Promise { - await new Promise((resolve, reject) => { +const closeServer = (server: Server) => + Effect.callback((resume) => { + server.close(() => { + resume(Effect.void); + }); + + return Effect.sync(() => { + try { + server.close(); + } catch { + // Ignore cleanup failures in tests. + } + }); + }); + +const listenServer = (server: Server) => + Effect.callback((resume) => { server.listen(0, "127.0.0.1", (error?: Error) => { if (error) { - reject(error); + resume(Effect.fail(error)); return; } - resolve(); - }); - }); - const address = server.address(); - if (!address || typeof address !== "object") { - throw new Error("Server did not provide a valid listening address."); - } - return address.port; -} -async function closeServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.close((error?: Error) => { - if (error) { - reject(error); + const address = server.address(); + if (!address || typeof address !== "object") { + resume(Effect.fail(new Error("Server did not provide a valid listening address."))); return; } - resolve(); + + resume(Effect.succeed(address.port)); }); - }); -} -describe("defaultWebPortInspector", () => { - const servers: Server[] = []; - - afterEach(async () => { - await Promise.all(servers.splice(0, servers.length).map((server) => closeServer(server))); + return closeServer(server); }); - it("treats slow HTML responses as web ports", async () => { - const server = createServer((_req, res) => { - setTimeout(() => { - res.statusCode = 200; - res.setHeader("content-type", "text/html; charset=utf-8"); - res.end("okhello"); - }, 800); - }); - servers.push(server); - const port = await listenServer(server); - - await expect(defaultWebPortInspector(port)).resolves.toBe(true); +const startServer = ( + handler: (request: IncomingMessage, response: ServerResponse) => void, +): Effect.Effect<{ server: Server; port: number }, Error> => + Effect.gen(function* () { + const server = createServer(handler); + const port = yield* listenServer(server); + return { server, port }; }); - it("treats HTML responses with large bodies as web ports", async () => { - const server = createServer((_req, res) => { - res.statusCode = 200; - res.setHeader("content-type", "text/html; charset=utf-8"); - res.end( - `x${"x".repeat(20_000)}`, - ); - }); - servers.push(server); - const port = await listenServer(server); +it.layer(WebPortInspectorLive)("WebPortInspectorLive", (it) => { + it.effect("treats slow HTML responses as web ports", () => + Effect.acquireUseRelease( + startServer((_request, response) => { + setTimeout(() => { + response.statusCode = 200; + response.setHeader("content-type", "text/html; charset=utf-8"); + response.end( + "okhello", + ); + }, 800); + }), + ({ port }) => + Effect.gen(function* () { + const inspector = yield* WebPortInspector; + const isWeb = yield* inspector.inspect(port); + assert.equal(isWeb, true); + }), + ({ server }) => closeServer(server), + ), + ); - await expect(defaultWebPortInspector(port)).resolves.toBe(true); - }); + it.effect("treats HTML responses with large bodies as web ports", () => + Effect.acquireUseRelease( + startServer((_request, response) => { + response.statusCode = 200; + response.setHeader("content-type", "text/html; charset=utf-8"); + response.end( + `x${"x".repeat(20_000)}`, + ); + }), + ({ port }) => + Effect.gen(function* () { + const inspector = yield* WebPortInspector; + const isWeb = yield* inspector.inspect(port); + assert.equal(isWeb, true); + }), + ({ server }) => closeServer(server), + ), + ); - it("ignores HTTP 404 responses", async () => { - const server = createServer((_req, res) => { - res.statusCode = 404; - res.end(); - }); - servers.push(server); - const port = await listenServer(server); - - await expect(defaultWebPortInspector(port)).resolves.toBe(false); - }); + it.effect("ignores HTTP 404 responses", () => + Effect.acquireUseRelease( + startServer((_request, response) => { + response.statusCode = 404; + response.end(); + }), + ({ port }) => + Effect.gen(function* () { + const inspector = yield* WebPortInspector; + const isWeb = yield* inspector.inspect(port); + assert.equal(isWeb, false); + }), + ({ server }) => closeServer(server), + ), + ); }); diff --git a/apps/server/src/webPortInspector.ts b/apps/server/src/webPortInspector.ts index 80bc034b4f..9a0fb2b748 100644 --- a/apps/server/src/webPortInspector.ts +++ b/apps/server/src/webPortInspector.ts @@ -1,132 +1,7 @@ -import { request as httpRequest } from "node:http"; - -export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000; -const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000; -const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192; - -interface WebProbeResult { - status: number; - contentType: string; - body: string; - location: string; -} - -function normalizeHeaderValue(value: string | string[] | undefined): string { - if (typeof value === "string") return value; - if (Array.isArray(value)) return value[0] ?? ""; - return ""; -} - -function isLikelyWebProbe(result: WebProbeResult | null): boolean { - if (!result) return false; - if (result.status === 404) return false; - if (result.status >= 300 && result.status < 400 && result.location.length > 0) { - return true; - } - const contentType = result.contentType.toLowerCase(); - if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) { - return true; - } - const body = result.body.toLowerCase(); - return body.includes(" { - return new Promise((resolve) => { - let timer: ReturnType | null = null; - let settled = false; - const settle = (result: WebProbeResult | null) => { - if (settled) return; - settled = true; - if (timer) { - clearTimeout(timer); - } - resolve(result); - }; - - const req = httpRequest( - { - host, - port, - method: "GET", - path: "/", - timeout: DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS, - }, - (res) => { - const status = res.statusCode ?? 0; - const contentType = normalizeHeaderValue(res.headers["content-type"]); - const location = normalizeHeaderValue(res.headers.location); - - const settleFromChunks = (chunks: string[]) => { - settle({ - status, - contentType, - location, - body: chunks.join(""), - }); - }; - - // Resolve immediately for clear web responses based on status/headers. - if ( - (status >= 300 && status < 400 && location.length > 0) || - contentType.toLowerCase().includes("text/html") || - contentType.toLowerCase().includes("application/xhtml+xml") - ) { - settle({ - status, - contentType, - location, - body: "", - }); - req.destroy(); - return; - } - - const chunks: string[] = []; - let received = 0; - res.setEncoding("utf8"); - res.on("data", (chunk: string) => { - if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) return; - const remaining = WEB_PORT_PROBE_MAX_BODY_BYTES - received; - const fragment = chunk.slice(0, remaining); - received += fragment.length; - chunks.push(fragment); - if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) { - settleFromChunks(chunks); - res.destroy(); - } - }); - res.on("end", () => { - settleFromChunks(chunks); - }); - res.on("error", () => { - settle(null); - }); - }, - ); - - req.on("timeout", () => { - req.destroy(); - settle(null); - }); - req.on("error", () => { - settle(null); - }); - - timer = setTimeout(() => { - req.destroy(); - settle(null); - }, DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS + 50); - - req.end(); - }); -} - -export async function defaultWebPortInspector(port: number): Promise { - const ipv4Result = await probeWebPortOnHost(port, "127.0.0.1"); - if (isLikelyWebProbe(ipv4Result)) { - return true; - } - const ipv6Result = await probeWebPortOnHost(port, "::1"); - return isLikelyWebProbe(ipv6Result); -} +export { WebPortInspectionError } from "./terminalProcessInspector/Errors"; +export { WebPortInspectorLive } from "./terminalProcessInspector/Layers/WebPortInspector"; +export { + DEFAULT_WEB_PORT_PROBE_TTL_MS, + WebPortInspector, + type WebPortInspectorShape, +} from "./terminalProcessInspector/Services/WebPortInspector";