The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- the stop test drives real server processes. |
| 2 | import * as NodeChildProcess from "node:child_process"; |
| 3 | |
| 4 | import { it as effectIt } from "@effect/vitest"; |
| 5 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 6 | import { |
| 7 | CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS, |
| 8 | PREVIEW_URL_MAX_LENGTH, |
| 9 | type DiscoveredLocalServer, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import * as ProcessGroup from "@t3tools/provider-core/server/processGroup"; |
| 12 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 13 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 14 | import * as Duration from "effect/Duration"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Exit from "effect/Exit"; |
| 17 | import * as FileSystem from "effect/FileSystem"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as PlatformError from "effect/PlatformError"; |
| 20 | import * as Scope from "effect/Scope"; |
| 21 | import * as TestClock from "effect/testing/TestClock"; |
| 22 | import { expect, vi } from "vite-plus/test"; |
| 23 | import { FetchHttpClient } from "effect/http"; |
| 24 | |
| 25 | import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; |
| 26 | import * as ProcessRunner from "../processRunner.ts"; |
| 27 | import * as PortScanner from "./PortScanner.ts"; |
| 28 | |
| 29 | vi.mock("@t3tools/provider-core/server/processGroup", { spy: true }); |
| 30 | |
| 31 | const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) => |
| 32 | Effect.fail( |
| 33 | new ProcessRunner.ProcessSpawnError({ |
| 34 | command: input.command, |
| 35 | argumentCount: input.args.length, |
| 36 | cwd: input.cwd, |
| 37 | cause: PlatformError.systemError({ |
| 38 | _tag: "NotFound", |
| 39 | module: "ChildProcess", |
| 40 | method: "spawn", |
| 41 | description: "PowerShell is not installed in the test environment", |
| 42 | }), |
| 43 | }), |
| 44 | ); |
| 45 | |
| 46 | const layerNoProc = FileSystem.layerNoop({}); |
| 47 | |
| 48 | const layerForeground = Layer.mock(BackgroundPolicy.BackgroundPolicy)({ |
| 49 | shouldRunOpportunisticWork: Effect.succeed(true), |
| 50 | }); |
| 51 | |
| 52 | const layerScanner = PortScanner.layer.pipe(Layer.provide(layerForeground)); |
| 53 | |
| 54 | const layerProbeFailure = ( |
| 55 | run: ProcessRunner.ProcessRunner["Service"]["run"], |
| 56 | fetch: typeof globalThis.fetch = globalThis.fetch, |
| 57 | fileSystem: Layer.Layer<FileSystem.FileSystem> = layerNoProc, |
| 58 | ) => |
| 59 | layerScanner.pipe( |
| 60 | Layer.provide( |
| 61 | Layer.mergeAll( |
| 62 | fileSystem, |
| 63 | Layer.succeed(ProcessRunner.ProcessRunner, { run }), |
| 64 | Layer.succeed(HostProcess.Platform, "linux"), |
| 65 | FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))), |
| 66 | ), |
| 67 | ), |
| 68 | ); |
| 69 | |
| 70 | const LSOF_TEST_PORT = 43_123; |
| 71 | |
| 72 | const processOutput = (stdout: string): ProcessRunner.ProcessRunOutput => ({ |
| 73 | stdout, |
| 74 | stderr: "", |
| 75 | code: ChildProcessSpawner.ExitCode(0), |
| 76 | timedOut: false, |
| 77 | stdoutTruncated: false, |
| 78 | stderrTruncated: false, |
| 79 | stdoutInvalidUtf8: false, |
| 80 | stderrInvalidUtf8: false, |
| 81 | }); |
| 82 | |
| 83 | const ownedScanner = (processIds: ReadonlyArray<number> = [1234]) => |
| 84 | Effect.tap(PortScanner.PortDiscovery, (scanner) => |
| 85 | scanner.registerTerminalProcesses({ |
| 86 | threadId: "scanner-thread", |
| 87 | terminalId: "scanner-terminal", |
| 88 | processIds, |
| 89 | }), |
| 90 | ); |
| 91 | |
| 92 | const layerLsofScanner = (input: { |
| 93 | readonly pid: () => number; |
| 94 | readonly fetch: typeof globalThis.fetch; |
| 95 | readonly stdout?: () => string; |
| 96 | readonly backgroundPolicy?: Layer.Layer<BackgroundPolicy.BackgroundPolicy>; |
| 97 | }) => |
| 98 | PortScanner.layer.pipe( |
| 99 | Layer.provide( |
| 100 | Layer.mergeAll( |
| 101 | input.backgroundPolicy ?? layerForeground, |
| 102 | layerNoProc, |
| 103 | Layer.succeed(ProcessRunner.ProcessRunner, { |
| 104 | run: () => |
| 105 | Effect.succeed({ |
| 106 | stdout: input.stdout?.() ?? `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`, |
| 107 | stderr: "", |
| 108 | code: null, |
| 109 | timedOut: false, |
| 110 | stdoutTruncated: false, |
| 111 | stderrTruncated: false, |
| 112 | stdoutInvalidUtf8: false, |
| 113 | stderrInvalidUtf8: false, |
| 114 | }), |
| 115 | }), |
| 116 | Layer.succeed(HostProcess.Platform, "linux"), |
| 117 | FetchHttpClient.layer.pipe( |
| 118 | Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)), |
| 119 | ), |
| 120 | ), |
| 121 | ), |
| 122 | ); |
| 123 | |
| 124 | effectIt.effect("keeps a full configured URL when the discovered server root fails", () => { |
| 125 | const requests: string[] = []; |
| 126 | const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`; |
| 127 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 128 | const url = String(input); |
| 129 | requests.push(url); |
| 130 | return Promise.resolve( |
| 131 | url === configuredUrl |
| 132 | ? new Response("docs", { headers: { "content-type": "text/html" } }) |
| 133 | : new Response("not found", { |
| 134 | status: 404, |
| 135 | headers: { "content-type": "text/html" }, |
| 136 | }), |
| 137 | ); |
| 138 | }) as typeof globalThis.fetch; |
| 139 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn }); |
| 140 | |
| 141 | return Effect.gen(function* () { |
| 142 | const scanner = yield* PortScanner.PortDiscovery; |
| 143 | const servers = yield* scanner.scan([configuredUrl]); |
| 144 | expect(servers).toHaveLength(1); |
| 145 | expect(servers[0]?.url).toBe(configuredUrl); |
| 146 | expect(requests).toContain(configuredUrl); |
| 147 | }).pipe(Effect.provide(layer)); |
| 148 | }); |
| 149 | |
| 150 | effectIt.effect("probes configured custom ports through a canonical loopback host", () => { |
| 151 | const customPort = 43_124; |
| 152 | const configuredUrl = `http://0.0.0.0:${customPort}/docs`; |
| 153 | const expectedUrl = `http://localhost:${customPort}/docs`; |
| 154 | const requests: string[] = []; |
| 155 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 156 | requests.push(String(input)); |
| 157 | return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } })); |
| 158 | }) as typeof globalThis.fetch; |
| 159 | const layer = layerProbeFailure(processProbeFailure, fetchFn); |
| 160 | |
| 161 | return Effect.gen(function* () { |
| 162 | const scanner = yield* PortScanner.PortDiscovery; |
| 163 | const servers = yield* scanner.scan([configuredUrl]); |
| 164 | expect(servers).toHaveLength(1); |
| 165 | expect(servers[0]?.host).toBe("localhost"); |
| 166 | expect(servers[0]?.port).toBe(customPort); |
| 167 | expect(servers[0]?.url).toBe(expectedUrl); |
| 168 | expect(requests).toEqual([expectedUrl]); |
| 169 | }).pipe(Effect.provide(layer)); |
| 170 | }); |
| 171 | |
| 172 | effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => { |
| 173 | const ipv4Url = "https://127.0.0.1:43125/docs"; |
| 174 | const ipv6Url = "http://[::1]:43126/docs"; |
| 175 | const wildcardPrefix = "http://0.0.0.0/"; |
| 176 | const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat( |
| 177 | PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length, |
| 178 | )}`; |
| 179 | const requests: string[] = []; |
| 180 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 181 | requests.push(String(input)); |
| 182 | return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } })); |
| 183 | }) as typeof globalThis.fetch; |
| 184 | const layer = layerProbeFailure(processProbeFailure, fetchFn); |
| 185 | |
| 186 | return Effect.gen(function* () { |
| 187 | const scanner = yield* PortScanner.PortDiscovery; |
| 188 | const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]); |
| 189 | expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]); |
| 190 | expect(requests).toEqual([ipv4Url, ipv6Url]); |
| 191 | }).pipe(Effect.provide(layer)); |
| 192 | }); |
| 193 | |
| 194 | effectIt.effect("projects configured paths independently for simultaneous subscribers", () => { |
| 195 | const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`; |
| 196 | const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`; |
| 197 | let ready = true; |
| 198 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 199 | const url = String(input); |
| 200 | return Promise.resolve( |
| 201 | ready && (url === docsUrl || url === adminUrl) |
| 202 | ? new Response("app", { headers: { "content-type": "text/html" } }) |
| 203 | : new Response("not found", { status: 404 }), |
| 204 | ); |
| 205 | }) as typeof globalThis.fetch; |
| 206 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn }); |
| 207 | |
| 208 | return Effect.gen(function* () { |
| 209 | const scanner = yield* ownedScanner(); |
| 210 | const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = []; |
| 211 | const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = []; |
| 212 | yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) => |
| 213 | Effect.sync(() => docsSnapshots.push(servers)), |
| 214 | ); |
| 215 | yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) => |
| 216 | Effect.sync(() => adminSnapshots.push(servers)), |
| 217 | ); |
| 218 | yield* scanner.retain; |
| 219 | |
| 220 | expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl); |
| 221 | expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl); |
| 222 | |
| 223 | ready = false; |
| 224 | yield* TestClock.adjust(Duration.seconds(15)); |
| 225 | expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl); |
| 226 | expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl); |
| 227 | }).pipe(Effect.scoped, Effect.provide(layer)); |
| 228 | }); |
| 229 | |
| 230 | effectIt.effect( |
| 231 | "keeps each subscriber's candidates when their combined union exceeds the per-client cap", |
| 232 | () => { |
| 233 | const firstSubscriberUrls = Array.from( |
| 234 | { length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS }, |
| 235 | (_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`, |
| 236 | ); |
| 237 | const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`; |
| 238 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => |
| 239 | Promise.resolve( |
| 240 | String(input) === secondSubscriberUrl |
| 241 | ? new Response("app", { headers: { "content-type": "text/html" } }) |
| 242 | : new Response("not found", { status: 404 }), |
| 243 | )) as typeof globalThis.fetch; |
| 244 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn }); |
| 245 | |
| 246 | return Effect.gen(function* () { |
| 247 | const scanner = yield* PortScanner.PortDiscovery; |
| 248 | const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = []; |
| 249 | yield* scanner.subscribe( |
| 250 | { configuredUrls: firstSubscriberUrls, initialSnapshot: [] }, |
| 251 | () => Effect.void, |
| 252 | ); |
| 253 | yield* scanner.subscribe( |
| 254 | { configuredUrls: [secondSubscriberUrl], initialSnapshot: [] }, |
| 255 | (servers) => Effect.sync(() => secondSnapshots.push(servers)), |
| 256 | ); |
| 257 | yield* scanner.retain; |
| 258 | |
| 259 | expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl); |
| 260 | }).pipe(Effect.scoped, Effect.provide(layer)); |
| 261 | }, |
| 262 | ); |
| 263 | |
| 264 | effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => { |
| 265 | const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`; |
| 266 | const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`; |
| 267 | const requests: string[] = []; |
| 268 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 269 | const url = String(input); |
| 270 | requests.push(url); |
| 271 | return Promise.resolve( |
| 272 | url === docsUrl || url === adminUrl |
| 273 | ? new Response("app", { headers: { "content-type": "text/html" } }) |
| 274 | : new Response("not found", { status: 404 }), |
| 275 | ); |
| 276 | }) as typeof globalThis.fetch; |
| 277 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn }); |
| 278 | |
| 279 | return Effect.gen(function* () { |
| 280 | const scanner = yield* PortScanner.PortDiscovery; |
| 281 | const docsScope = yield* Scope.make(); |
| 282 | yield* scanner |
| 283 | .subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void) |
| 284 | .pipe(Effect.provideService(Scope.Scope, docsScope)); |
| 285 | yield* scanner.subscribe( |
| 286 | { configuredUrls: [adminUrl], initialSnapshot: [] }, |
| 287 | () => Effect.void, |
| 288 | ); |
| 289 | yield* scanner.retain; |
| 290 | yield* Scope.close(docsScope, Exit.void); |
| 291 | |
| 292 | requests.length = 0; |
| 293 | yield* TestClock.adjust(Duration.seconds(15)); |
| 294 | expect(requests).toContain(adminUrl); |
| 295 | expect(requests).not.toContain(docsUrl); |
| 296 | }).pipe(Effect.scoped, Effect.provide(layer)); |
| 297 | }); |
| 298 | |
| 299 | effectIt.effect("skips scheduled scans while no client is in the foreground", () => { |
| 300 | let lsofRuns = 0; |
| 301 | let foreground = true; |
| 302 | const layer = layerLsofScanner({ |
| 303 | pid: () => 1234, |
| 304 | fetch: (() => Promise.resolve(new Response("not found", { status: 404 }))) as typeof fetch, |
| 305 | stdout: () => { |
| 306 | lsofRuns += 1; |
| 307 | return `p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`; |
| 308 | }, |
| 309 | backgroundPolicy: Layer.mock(BackgroundPolicy.BackgroundPolicy)({ |
| 310 | shouldRunOpportunisticWork: Effect.sync(() => foreground), |
| 311 | }), |
| 312 | }); |
| 313 | |
| 314 | return Effect.gen(function* () { |
| 315 | const scanner = yield* PortScanner.PortDiscovery; |
| 316 | yield* scanner.subscribe( |
| 317 | { configuredUrls: [`http://localhost:${LSOF_TEST_PORT}/`], initialSnapshot: [] }, |
| 318 | () => Effect.void, |
| 319 | ); |
| 320 | yield* scanner.retain; |
| 321 | const afterInitialScan = lsofRuns; |
| 322 | expect(afterInitialScan).toBeGreaterThan(0); |
| 323 | |
| 324 | foreground = false; |
| 325 | yield* TestClock.adjust(Duration.seconds(15)); |
| 326 | expect(lsofRuns).toBe(afterInitialScan); |
| 327 | |
| 328 | foreground = true; |
| 329 | yield* TestClock.adjust(Duration.seconds(3)); |
| 330 | expect(lsofRuns).toBeGreaterThan(afterInitialScan); |
| 331 | }).pipe(Effect.scoped, Effect.provide(layer)); |
| 332 | }); |
| 333 | |
| 334 | effectIt.effect("uses the current configured fragment when readiness comes from cache", () => { |
| 335 | const requests: string[] = []; |
| 336 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 337 | requests.push(String(input)); |
| 338 | return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } })); |
| 339 | }) as typeof globalThis.fetch; |
| 340 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn }); |
| 341 | const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`; |
| 342 | const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`; |
| 343 | |
| 344 | return Effect.gen(function* () { |
| 345 | const scanner = yield* PortScanner.PortDiscovery; |
| 346 | expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl); |
| 347 | const requestCount = requests.length; |
| 348 | expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl); |
| 349 | expect(requests).toHaveLength(requestCount); |
| 350 | }).pipe(Effect.provide(layer)); |
| 351 | }); |
| 352 | |
| 353 | effectIt.effect( |
| 354 | "probes only a configured HTTPS URL, keeps it for an owned listener when the check fails, and does not follow redirects", |
| 355 | () => { |
| 356 | const configuredUrl = `https://localhost:${LSOF_TEST_PORT}/app`; |
| 357 | const requests: Array<readonly [string, string | undefined]> = []; |
| 358 | let respond = async () => |
| 359 | new Response(null, { status: 302, headers: { location: "https://example.com" } }); |
| 360 | const fetchFn = (async ( |
| 361 | input: Parameters<typeof globalThis.fetch>[0], |
| 362 | init?: Parameters<typeof globalThis.fetch>[1], |
| 363 | ) => { |
| 364 | requests.push([String(input), init?.redirect]); |
| 365 | return respond(); |
| 366 | }) as typeof globalThis.fetch; |
| 367 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn }); |
| 368 | |
| 369 | return Effect.gen(function* () { |
| 370 | const scanner = yield* ownedScanner(); |
| 371 | expect(yield* scanner.scan([configuredUrl])).toMatchObject([ |
| 372 | { pid: 1234, url: configuredUrl }, |
| 373 | ]); |
| 374 | |
| 375 | respond = async () => new Response("unavailable", { status: 503 }); |
| 376 | yield* TestClock.adjust(Duration.seconds(15)); |
| 377 | expect(yield* scanner.scan([configuredUrl])).toMatchObject([ |
| 378 | { pid: 1234, url: configuredUrl }, |
| 379 | ]); |
| 380 | |
| 381 | respond = () => Promise.reject(new TypeError("fetch failed")); |
| 382 | yield* TestClock.adjust(Duration.seconds(15)); |
| 383 | expect(yield* scanner.scan([configuredUrl])).toMatchObject([ |
| 384 | { pid: 1234, url: configuredUrl }, |
| 385 | ]); |
| 386 | expect(requests).toEqual(Array.from({ length: 3 }, () => [configuredUrl, "manual"])); |
| 387 | }).pipe(Effect.provide(layer)); |
| 388 | }, |
| 389 | ); |
| 390 | |
| 391 | effectIt.effect("discovers owned listeners without sending HTTP or TLS probes", () => { |
| 392 | const owned = `p1234\ncnode\nn[::1]:${LSOF_TEST_PORT}\n`; |
| 393 | const unowned = `p5678\ncrpc\nn127.0.0.1:${LSOF_TEST_PORT}\n`; |
| 394 | let stdout = unowned; |
| 395 | const requests: string[] = []; |
| 396 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 397 | requests.push(String(input)); |
| 398 | return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } })); |
| 399 | }) as typeof globalThis.fetch; |
| 400 | const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn, stdout: () => stdout }); |
| 401 | |
| 402 | return Effect.gen(function* () { |
| 403 | const scanner = yield* ownedScanner(); |
| 404 | expect(yield* scanner.scan()).toHaveLength(0); |
| 405 | stdout = `${owned}${unowned}`; |
| 406 | expect(yield* scanner.scan()).toHaveLength(0); |
| 407 | expect(requests).toEqual([]); |
| 408 | |
| 409 | stdout = owned; |
| 410 | expect(yield* scanner.scan()).toHaveLength(1); |
| 411 | expect(requests).toEqual([]); |
| 412 | |
| 413 | yield* scanner.unregisterTerminal({ |
| 414 | threadId: "scanner-thread", |
| 415 | terminalId: "scanner-terminal", |
| 416 | }); |
| 417 | expect(yield* scanner.scan()).toHaveLength(0); |
| 418 | expect(requests).toEqual([]); |
| 419 | }).pipe(Effect.provide(layer)); |
| 420 | }); |
| 421 | |
| 422 | effectIt.effect( |
| 423 | "excludes configured URLs answering with HTTP errors, non-navigation responses, or non-documents", |
| 424 | () => { |
| 425 | let pid = 1; |
| 426 | let makeResponse = () => |
| 427 | new Response("not found", { status: 404, headers: { "content-type": "text/html" } }); |
| 428 | const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) => |
| 429 | Promise.resolve(makeResponse())) as typeof globalThis.fetch; |
| 430 | const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn }); |
| 431 | const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/`; |
| 432 | |
| 433 | return Effect.gen(function* () { |
| 434 | const scanner = yield* PortScanner.PortDiscovery; |
| 435 | const scan = () => scanner.scan([configuredUrl]); |
| 436 | expect(yield* scan()).toHaveLength(0); |
| 437 | |
| 438 | pid += 1; |
| 439 | makeResponse = () => |
| 440 | new Response("{}", { status: 200, headers: { "content-type": "application/json" } }); |
| 441 | expect(yield* scan()).toHaveLength(0); |
| 442 | |
| 443 | pid += 1; |
| 444 | makeResponse = () => |
| 445 | new Response("ready", { status: 200, headers: { "content-type": "text/plain" } }); |
| 446 | expect(yield* scan()).toHaveLength(0); |
| 447 | |
| 448 | pid += 1; |
| 449 | makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } }); |
| 450 | expect(yield* scan()).toHaveLength(0); |
| 451 | |
| 452 | pid += 1; |
| 453 | makeResponse = () => |
| 454 | new Response(null, { status: 204, headers: { "content-type": "text/html" } }); |
| 455 | expect(yield* scan()).toHaveLength(0); |
| 456 | |
| 457 | pid += 1; |
| 458 | makeResponse = () => new Response(null, { status: 302 }); |
| 459 | expect(yield* scan()).toHaveLength(0); |
| 460 | |
| 461 | pid += 1; |
| 462 | makeResponse = () => |
| 463 | new Response("<html />", { |
| 464 | status: 200, |
| 465 | headers: { "content-type": "application/xhtml+xml; charset=utf-8" }, |
| 466 | }); |
| 467 | expect(yield* scan()).toHaveLength(1); |
| 468 | }).pipe(Effect.provide(layer)); |
| 469 | }, |
| 470 | ); |
| 471 | |
| 472 | const PROC_NET_TCP = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode |
| 473 | 0: 0100007F:223D 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5001 1 0000000000000000 100 0 0 10 0 |
| 474 | 1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5002 1 0000000000000000 100 0 0 10 0 |
| 475 | 2: 0100007F:223D 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 5003 1 0000000000000000 20 4 30 10 -1 |
| 476 | 3: 0A00000F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5005 1 0000000000000000 100 0 0 10 0 |
| 477 | `; |
| 478 | const PROC_NET_TCP6 = ` sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode |
| 479 | 0: 00000000000000000000000000000000:0BB9 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5004 1 0000000000000000 100 0 0 10 0 |
| 480 | `; |
| 481 | |
| 482 | effectIt.effect( |
| 483 | "prefers Linux /proc over installed lsof, and bounds repeated socket owner lookups", |
| 484 | () => { |
| 485 | let lsofSpawns = 0; |
| 486 | const fdWalks: string[] = []; |
| 487 | const procFiles: Record<string, string> = { |
| 488 | "/proc/net/tcp": |
| 489 | PROC_NET_TCP + |
| 490 | PROC_NET_TCP.split("\n")[1]! |
| 491 | .replace("0100007F:223D", "0101007F:1388") |
| 492 | .replace("5001", "5007"), |
| 493 | "/proc/net/tcp6": PROC_NET_TCP6, |
| 494 | "/proc/4242/comm": "python3\n", |
| 495 | }; |
| 496 | const procFds: Record<string, Record<string, string>> = { |
| 497 | "4242": { |
| 498 | "0": "/dev/null", |
| 499 | "3": "socket:[5001]", |
| 500 | "4": "socket:[5004]", |
| 501 | "5": "socket:[5007]", |
| 502 | }, |
| 503 | "77": { "5": "socket:[9999]" }, |
| 504 | }; |
| 505 | const missing = FileSystem.makeNoop({}); |
| 506 | const fileSystem = FileSystem.layerNoop({ |
| 507 | readFileString: (path) => { |
| 508 | const content = procFiles[path]; |
| 509 | return content === undefined ? missing.readFileString(path) : Effect.succeed(content); |
| 510 | }, |
| 511 | readDirectory: (path) => { |
| 512 | if (path === "/proc") return Effect.succeed(["self", "77", "4242"]); |
| 513 | const pid = /^\/proc\/(\d+)\/fd$/.exec(path)?.[1]; |
| 514 | const fds = pid === undefined ? undefined : procFds[pid]; |
| 515 | if (pid === undefined || fds === undefined) return missing.readDirectory(path); |
| 516 | fdWalks.push(pid); |
| 517 | return Effect.succeed(Object.keys(fds)); |
| 518 | }, |
| 519 | readLink: (path) => { |
| 520 | const [, pid, fd] = /^\/proc\/(\d+)\/fd\/(\d+)$/.exec(path) ?? []; |
| 521 | const target = pid && fd ? procFds[pid]?.[fd] : undefined; |
| 522 | return target === undefined ? missing.readLink(path) : Effect.succeed(target); |
| 523 | }, |
| 524 | }); |
| 525 | const requests: string[] = []; |
| 526 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 527 | requests.push(String(input)); |
| 528 | return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } })); |
| 529 | }) as typeof globalThis.fetch; |
| 530 | const layer = layerProbeFailure( |
| 531 | () => { |
| 532 | lsofSpawns += 1; |
| 533 | return Effect.succeed(processOutput("p4242\ncpython3\nn*:3001\nn*:8765\n")); |
| 534 | }, |
| 535 | fetchFn, |
| 536 | fileSystem, |
| 537 | ); |
| 538 | |
| 539 | return Effect.gen(function* () { |
| 540 | const scanner = yield* ownedScanner([4242]); |
| 541 | const first = yield* scanner.scan(); |
| 542 | expect( |
| 543 | first.map(({ port, pid, processName, url }) => ({ port, pid, processName, url })), |
| 544 | ).toEqual([ |
| 545 | { port: 3001, pid: 4242, processName: "python3", url: "http://localhost:3001" }, |
| 546 | { port: 8765, pid: 4242, processName: "python3", url: "http://localhost:8765" }, |
| 547 | ]); |
| 548 | yield* scanner.scan(); |
| 549 | expect(lsofSpawns).toBe(0); |
| 550 | expect(fdWalks).toEqual(["77", "4242", "77", "4242"]); |
| 551 | yield* scanner.scan(); |
| 552 | yield* scanner.scan(); |
| 553 | expect(fdWalks).toEqual(["77", "4242", "77", "4242", "77", "4242"]); |
| 554 | procFds["77"]!["6"] = "socket:[5006]"; |
| 555 | procFiles["/proc/net/tcp6"] = |
| 556 | PROC_NET_TCP6 + PROC_NET_TCP.split("\n")[1]!.replace("5001", "5006"); |
| 557 | expect((yield* scanner.scan()).map(({ port }) => port)).toEqual([3001]); |
| 558 | const walksAfterCollision = fdWalks.length; |
| 559 | procFiles["/proc/net/tcp"] = PROC_NET_TCP.split("\n")[0]!; |
| 560 | procFiles["/proc/net/tcp6"] = PROC_NET_TCP6.split("\n")[0]!; |
| 561 | expect(yield* scanner.scan()).toEqual([]); |
| 562 | expect(lsofSpawns).toBe(0); |
| 563 | expect(fdWalks).toHaveLength(walksAfterCollision); |
| 564 | expect(requests).toEqual([]); |
| 565 | |
| 566 | procFiles["/proc/net/tcp"] = PROC_NET_TCP; |
| 567 | procFiles["/proc/net/tcp6"] = PROC_NET_TCP6; |
| 568 | expect((yield* scanner.scan()).map(({ pid }) => pid)).toEqual([4242, 4242]); |
| 569 | yield* scanner.retain.pipe(Effect.scoped); |
| 570 | procFds["77"] = procFds["4242"]!; |
| 571 | delete procFds["4242"]; |
| 572 | procFiles["/proc/77/comm"] = "python3\n"; |
| 573 | yield* scanner.registerTerminalProcesses({ |
| 574 | threadId: "scanner-thread", |
| 575 | terminalId: "scanner-terminal", |
| 576 | processIds: [77], |
| 577 | }); |
| 578 | expect((yield* scanner.scan()).map(({ port, pid }) => ({ port, pid }))).toEqual([ |
| 579 | { port: 3001, pid: 77 }, |
| 580 | { port: 8765, pid: 77 }, |
| 581 | ]); |
| 582 | }).pipe(Effect.provide(layer)); |
| 583 | }, |
| 584 | ); |
| 585 | |
| 586 | effectIt.effect.each([ |
| 587 | { mode: "missing", fallback: true }, |
| 588 | { mode: "denied", fallback: true }, |
| 589 | { mode: "invalid", fallback: true }, |
| 590 | { mode: "fd-unavailable", fallback: true }, |
| 591 | { mode: "fd-budget", fallback: true }, |
| 592 | { mode: "fd-budget-no-lsof", fallback: true }, |
| 593 | { mode: "ipv6-denied", fallback: true }, |
| 594 | { mode: "ipv6-absent", fallback: false }, |
| 595 | { mode: "empty", fallback: false }, |
| 596 | { mode: "darwin", fallback: true }, |
| 597 | ] as const)("uses lsof only if Linux /proc is unusable: $mode", ({ mode, fallback }) => { |
| 598 | let lsofSpawns = 0; |
| 599 | let procWalks = 0; |
| 600 | const missing = FileSystem.makeNoop({}); |
| 601 | const layer = layerScanner.pipe( |
| 602 | Layer.provide( |
| 603 | Layer.mergeAll( |
| 604 | FileSystem.layerNoop({ |
| 605 | readFileString: (path) => { |
| 606 | if (!path.startsWith("/proc/net/tcp") || mode === "missing") { |
| 607 | return missing.readFileString(path); |
| 608 | } |
| 609 | if (mode === "denied" || (mode === "ipv6-denied" && path.endsWith("tcp6"))) { |
| 610 | return Effect.fail( |
| 611 | PlatformError.systemError({ |
| 612 | _tag: "PermissionDenied", |
| 613 | module: "FileSystem", |
| 614 | method: "readFileString", |
| 615 | }), |
| 616 | ); |
| 617 | } |
| 618 | if (mode === "ipv6-absent" && path.endsWith("tcp6")) { |
| 619 | return missing.readFileString(path); |
| 620 | } |
| 621 | if (mode === "invalid") return Effect.succeed("unusable table"); |
| 622 | return Effect.succeed( |
| 623 | mode === "fd-unavailable" || mode.startsWith("fd-budget") |
| 624 | ? PROC_NET_TCP |
| 625 | : PROC_NET_TCP.split("\n")[0]!, |
| 626 | ); |
| 627 | }, |
| 628 | readDirectory: (path) => { |
| 629 | if (!mode.startsWith("fd-budget")) return missing.readDirectory(path); |
| 630 | if (path === "/proc") procWalks += 1; |
| 631 | if (mode === "fd-budget-no-lsof") { |
| 632 | if (path === "/proc") return Effect.succeed(["1234", "9999"]); |
| 633 | if (path === "/proc/1234/fd") return Effect.succeed(["3"]); |
| 634 | } |
| 635 | return Effect.succeed( |
| 636 | path === "/proc" |
| 637 | ? ["1", "1234"] |
| 638 | : Array.from({ length: 50_000 }, (_, i) => String(i)), |
| 639 | ); |
| 640 | }, |
| 641 | readLink: (path) => |
| 642 | mode === "fd-budget-no-lsof" && path === "/proc/1234/fd/3" |
| 643 | ? Effect.succeed("socket:[5001]") |
| 644 | : mode.startsWith("fd-budget") |
| 645 | ? Effect.succeed("/dev/null") |
| 646 | : missing.readLink(path), |
| 647 | }), |
| 648 | Layer.succeed(ProcessRunner.ProcessRunner, { |
| 649 | run: (input) => { |
| 650 | lsofSpawns += 1; |
| 651 | if (mode === "fd-budget-no-lsof") return processProbeFailure(input); |
| 652 | return Effect.succeed(processOutput(`p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`)); |
| 653 | }, |
| 654 | }), |
| 655 | Layer.succeed(HostProcess.Platform, mode === "darwin" ? "darwin" : "linux"), |
| 656 | FetchHttpClient.layer, |
| 657 | ), |
| 658 | ), |
| 659 | ); |
| 660 | return Effect.gen(function* () { |
| 661 | const scanner = yield* ownedScanner(); |
| 662 | expect((yield* scanner.scan()).map(({ port }) => port)).toEqual( |
| 663 | mode === "fd-budget-no-lsof" ? [8765] : fallback ? [LSOF_TEST_PORT] : [], |
| 664 | ); |
| 665 | if (mode === "fd-budget-no-lsof") { |
| 666 | for (let i = 0; i < 3; i += 1) { |
| 667 | expect((yield* scanner.scan()).map(({ port }) => port)).toEqual([8765]); |
| 668 | } |
| 669 | expect(procWalks).toBe(4); |
| 670 | } |
| 671 | expect(lsofSpawns).toBe(fallback ? 1 : 0); |
| 672 | }).pipe(Effect.provide(layer)); |
| 673 | }); |
| 674 | |
| 675 | effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => { |
| 676 | let ipv6Fails = true; |
| 677 | const requests: string[] = []; |
| 678 | const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => { |
| 679 | requests.push(String(input)); |
| 680 | return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } })); |
| 681 | }) as typeof globalThis.fetch; |
| 682 | const layer = layerScanner.pipe( |
| 683 | Layer.provide( |
| 684 | Layer.mergeAll( |
| 685 | layerNoProc, |
| 686 | Layer.succeed(ProcessRunner.ProcessRunner, { |
| 687 | run: (input) => { |
| 688 | if (input.command === "tasklist.exe") { |
| 689 | return Effect.succeed( |
| 690 | processOutput('"node.exe","1234","Console","1","50,000 K"\r\n'), |
| 691 | ); |
| 692 | } |
| 693 | const isIpv6 = input.args.includes("tcpv6"); |
| 694 | return Effect.succeed({ |
| 695 | stdout: isIpv6 |
| 696 | ? "" |
| 697 | : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n", |
| 698 | stderr: "", |
| 699 | code: isIpv6 && ipv6Fails ? ChildProcessSpawner.ExitCode(1) : null, |
| 700 | timedOut: false, |
| 701 | stdoutTruncated: false, |
| 702 | stderrTruncated: false, |
| 703 | stdoutInvalidUtf8: false, |
| 704 | stderrInvalidUtf8: false, |
| 705 | }); |
| 706 | }, |
| 707 | }), |
| 708 | Layer.succeed(HostProcess.Platform, "win32"), |
| 709 | FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))), |
| 710 | ), |
| 711 | ), |
| 712 | ); |
| 713 | |
| 714 | return Effect.gen(function* () { |
| 715 | const scanner = yield* PortScanner.PortDiscovery; |
| 716 | yield* scanner.registerTerminalProcesses({ |
| 717 | threadId: "scanner-thread", |
| 718 | terminalId: "scanner-terminal", |
| 719 | processIds: [1234], |
| 720 | }); |
| 721 | expect(yield* scanner.scan()).toEqual([]); |
| 722 | ipv6Fails = false; |
| 723 | expect(yield* scanner.scan()).toMatchObject([ |
| 724 | { port: 5173, pid: 1234, processName: "node", url: "http://localhost:5173" }, |
| 725 | ]); |
| 726 | expect(requests).toEqual([]); |
| 727 | }).pipe(Effect.provide(layer)); |
| 728 | }); |
| 729 | |
| 730 | effectIt.effect("rechecks the socket owner before stopping a Linux server without lsof", () => { |
| 731 | let holder = "4242"; |
| 732 | const missing = FileSystem.makeNoop({}); |
| 733 | const layer = layerProbeFailure( |
| 734 | (input) => |
| 735 | input.command === "lsof" |
| 736 | ? processProbeFailure(input) |
| 737 | : Effect.succeed(processOutput("4242 1 4300\n5000 1 5300\n")), |
| 738 | () => Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } })), |
| 739 | FileSystem.layerNoop({ |
| 740 | readFileString: (path) => { |
| 741 | if (path === "/proc/net/tcp") { |
| 742 | return Effect.succeed(PROC_NET_TCP.split("\n").slice(0, 2).join("\n")); |
| 743 | } |
| 744 | if (/^\/proc\/(4242|5000)\/comm$/.test(path)) return Effect.succeed("node\n"); |
| 745 | if (/^\/proc\/(4242|5000)\/environ$/.test(path)) { |
| 746 | return Effect.succeed(`${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`); |
| 747 | } |
| 748 | return missing.readFileString(path); |
| 749 | }, |
| 750 | readDirectory: (path) => { |
| 751 | if (path === "/proc") return Effect.succeed(["4242", "5000"]); |
| 752 | if (/^\/proc\/(4242|5000)\/fd$/.test(path)) { |
| 753 | return Effect.succeed(path === `/proc/${holder}/fd` ? ["3"] : []); |
| 754 | } |
| 755 | return missing.readDirectory(path); |
| 756 | }, |
| 757 | readLink: (path) => |
| 758 | path === `/proc/${holder}/fd/3` ? Effect.succeed("socket:[5001]") : missing.readLink(path), |
| 759 | }), |
| 760 | ); |
| 761 | |
| 762 | return Effect.gen(function* () { |
| 763 | const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => { |
| 764 | throw Object.assign(new Error("No such process"), { code: "ESRCH" }); |
| 765 | }); |
| 766 | yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore())); |
| 767 | const scanner = yield* PortScanner.PortDiscovery; |
| 768 | expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, port: 8765 }]); |
| 769 | |
| 770 | // The socket outlives its original holder. Its old pid now belongs to another agent job. |
| 771 | holder = "5000"; |
| 772 | const result = yield* scanner |
| 773 | .stopServer({ pid: 4242, port: 8765 }) |
| 774 | .pipe(Effect.match({ onFailure: (error) => error.reason, onSuccess: () => null })); |
| 775 | expect(signal).not.toHaveBeenCalled(); |
| 776 | expect(result).toBe("not-found"); |
| 777 | expect(yield* scanner.scan()).toMatchObject([{ pid: 5000, port: 8765 }]); |
| 778 | yield* scanner.stopServer({ pid: 5000, port: 8765 }); |
| 779 | expect(signal).toHaveBeenCalledExactlyOnceWith(5300, "SIGTERM"); |
| 780 | }).pipe(Effect.provide(layer)); |
| 781 | }); |
| 782 | |
| 783 | effectIt.effect.each(["linux", "darwin", "win32"] as const)( |
| 784 | "reads no listeners on %s while T3CODE_PORT_DISCOVERY=0, and still probes configured URLs", |
| 785 | (platform) => { |
| 786 | const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`; |
| 787 | const commands: string[] = []; |
| 788 | const fileReads: string[] = []; |
| 789 | const requests: string[] = []; |
| 790 | const missing = FileSystem.makeNoop({}); |
| 791 | const layer = layerScanner.pipe( |
| 792 | Layer.provide( |
| 793 | Layer.mergeAll( |
| 794 | FileSystem.layerNoop({ |
| 795 | readFileString: (path) => { |
| 796 | fileReads.push(path); |
| 797 | return missing.readFileString(path); |
| 798 | }, |
| 799 | readDirectory: (path) => { |
| 800 | fileReads.push(path); |
| 801 | return missing.readDirectory(path); |
| 802 | }, |
| 803 | }), |
| 804 | Layer.succeed(ProcessRunner.ProcessRunner, { |
| 805 | run: (input) => { |
| 806 | commands.push(input.command); |
| 807 | return Effect.succeed(processOutput(`p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`)); |
| 808 | }, |
| 809 | }), |
| 810 | Layer.succeed(HostProcess.Platform, platform), |
| 811 | Layer.succeed(HostProcess.Environment, { T3CODE_PORT_DISCOVERY: "0" }), |
| 812 | FetchHttpClient.layer.pipe( |
| 813 | Layer.provide( |
| 814 | Layer.succeed(FetchHttpClient.Fetch, (input) => { |
| 815 | requests.push(String(input)); |
| 816 | return Promise.resolve( |
| 817 | new Response("docs", { headers: { "content-type": "text/html" } }), |
| 818 | ); |
| 819 | }), |
| 820 | ), |
| 821 | ), |
| 822 | ), |
| 823 | ), |
| 824 | ); |
| 825 | |
| 826 | return Effect.gen(function* () { |
| 827 | const scanner = yield* ownedScanner(); |
| 828 | scanner.trackAgent(); |
| 829 | expect(yield* scanner.scan()).toEqual([]); |
| 830 | expect(yield* scanner.scan([configuredUrl])).toMatchObject([ |
| 831 | { port: LSOF_TEST_PORT, pid: null, terminal: null, url: configuredUrl }, |
| 832 | ]); |
| 833 | expect(requests).toEqual([configuredUrl]); |
| 834 | expect(commands).toEqual([]); |
| 835 | expect(fileReads).toEqual([]); |
| 836 | }).pipe(Effect.provide(layer)); |
| 837 | }, |
| 838 | ); |
| 839 | |
| 840 | effectIt.effect.each(["linux", "darwin"] as const)( |
| 841 | "attributes listeners to the agent thread in their environment on %s, after the agent exits", |
| 842 | (platform) => { |
| 843 | const agentPort = 43_124; |
| 844 | const otherPort = 43_125; |
| 845 | // The agent CLI has the thread in its environment too; its own port is not a server. |
| 846 | const agentListener = |
| 847 | `p4242\ncnode\nn127.0.0.1:${agentPort}\n` + `p4300\ncagy\nn127.0.0.1:43126\n`; |
| 848 | const otherListener = `p5000\ncpostgres\nn127.0.0.1:${otherPort}\n`; |
| 849 | let lsofStdout = otherListener; |
| 850 | let lsofFails = false; |
| 851 | let environmentFails = false; |
| 852 | let lsofCalls = 0; |
| 853 | let environmentReads = 0; |
| 854 | const requests: string[] = []; |
| 855 | const missing = FileSystem.makeNoop({}); |
| 856 | const procEnviron: Record<string, string> = { |
| 857 | "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`, |
| 858 | "/proc/5000/environ": "PATH=/usr/bin\0", |
| 859 | }; |
| 860 | const procAgent: Record<string, string> = { |
| 861 | "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0", |
| 862 | "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`, |
| 863 | "/proc/4300/stat": `4300 (agy acp) S ${process.pid} 4300 4300 0`, |
| 864 | }; |
| 865 | const layer = layerScanner.pipe( |
| 866 | Layer.provide( |
| 867 | Layer.mergeAll( |
| 868 | FileSystem.layerNoop({ |
| 869 | readFileString: (path) => { |
| 870 | const agent = procAgent[path]; |
| 871 | if (agent !== undefined) return Effect.succeed(agent); |
| 872 | const content = procEnviron[path]; |
| 873 | if (content === undefined) return missing.readFileString(path); |
| 874 | environmentReads += 1; |
| 875 | return Effect.succeed(content); |
| 876 | }, |
| 877 | }), |
| 878 | Layer.succeed(ProcessRunner.ProcessRunner, { |
| 879 | run: (input) => { |
| 880 | if (input.command === "lsof") { |
| 881 | lsofCalls += 1; |
| 882 | return lsofFails |
| 883 | ? Effect.fail( |
| 884 | new ProcessRunner.ProcessTimeoutError({ |
| 885 | command: input.command, |
| 886 | argumentCount: input.args.length, |
| 887 | cwd: input.cwd, |
| 888 | timeoutMs: 5_000, |
| 889 | }), |
| 890 | ) |
| 891 | : Effect.succeed(processOutput(lsofStdout)); |
| 892 | } |
| 893 | // In its agent CLI's process group, so stop refuses it without signaling anything. |
| 894 | if (input.args[0] === "-A") { |
| 895 | return Effect.succeed(processOutput(`4242 4300 4300\n4300 ${process.pid} 4300\n`)); |
| 896 | } |
| 897 | if (environmentFails) { |
| 898 | return Effect.fail( |
| 899 | new ProcessRunner.ProcessTimeoutError({ |
| 900 | command: input.command, |
| 901 | argumentCount: input.args.length, |
| 902 | timeoutMs: 5_000, |
| 903 | }), |
| 904 | ); |
| 905 | } |
| 906 | environmentReads += 1; |
| 907 | return Effect.succeed( |
| 908 | processOutput( |
| 909 | ` 4242 4300 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` + |
| 910 | ` 4300 ${process.pid} agy acp ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n` + |
| 911 | " 5000 1 postgres -D /data PATH=/usr/bin\n", |
| 912 | ), |
| 913 | ); |
| 914 | }, |
| 915 | }), |
| 916 | Layer.succeed(HostProcess.Platform, platform), |
| 917 | FetchHttpClient.layer.pipe( |
| 918 | Layer.provide( |
| 919 | Layer.succeed(FetchHttpClient.Fetch, (input) => { |
| 920 | requests.push(String(input)); |
| 921 | return Promise.resolve( |
| 922 | new Response("app", { headers: { "content-type": "text/html" } }), |
| 923 | ); |
| 924 | }), |
| 925 | ), |
| 926 | ), |
| 927 | ), |
| 928 | ), |
| 929 | ); |
| 930 | |
| 931 | return Effect.gen(function* () { |
| 932 | const scanner = yield* PortScanner.PortDiscovery; |
| 933 | // Startup reads listeners once. With none marked, later scans stay idle. |
| 934 | expect(yield* scanner.scan()).toEqual([]); |
| 935 | expect(yield* scanner.scan()).toEqual([]); |
| 936 | expect(lsofCalls).toBe(1); |
| 937 | |
| 938 | // The agent exits before any client looks, and the first read fails; its server is still |
| 939 | // found. |
| 940 | lsofStdout = `${agentListener}${otherListener}`; |
| 941 | scanner.trackAgent()(); |
| 942 | lsofFails = true; |
| 943 | expect(yield* scanner.scan()).toEqual([]); |
| 944 | lsofFails = false; |
| 945 | if (platform === "darwin") { |
| 946 | environmentFails = true; |
| 947 | expect(yield* scanner.scan()).toEqual([]); |
| 948 | environmentFails = false; |
| 949 | } |
| 950 | expect(yield* scanner.scan()).toMatchObject([ |
| 951 | { port: agentPort, pid: 4242, terminal: null, agent: { threadId: "thread-agent" } }, |
| 952 | ]); |
| 953 | expect(requests).toEqual([]); |
| 954 | |
| 955 | expect(yield* scanner.scan()).toHaveLength(1); |
| 956 | expect(environmentReads).toBe(2); |
| 957 | |
| 958 | // Stop reads its target's environment again rather than trust the cache, and still finds it. |
| 959 | const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: agentPort })); |
| 960 | expect(stop.reason).toBe("shared-group"); |
| 961 | expect(environmentReads).toBe(3); |
| 962 | |
| 963 | lsofStdout = otherListener; |
| 964 | expect(yield* scanner.scan()).toEqual([]); |
| 965 | const lsofCallsAfterExit = lsofCalls; |
| 966 | expect(yield* scanner.scan()).toEqual([]); |
| 967 | expect(lsofCalls).toBe(lsofCallsAfterExit); |
| 968 | }).pipe(Effect.provide(layer)); |
| 969 | }, |
| 970 | ); |
| 971 | |
| 972 | effectIt.effect("stops only a job's own process group", () => |
| 973 | Effect.sync(() => { |
| 974 | const serverPid = 100; |
| 975 | const rows = [ |
| 976 | { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server |
| 977 | { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job |
| 978 | { pid: serverPid, ppid: 10, pgid: 10 }, |
| 979 | { pid: 200, ppid: serverPid, pgid: 200 }, // agent CLI |
| 980 | { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own |
| 981 | { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell |
| 982 | { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &` |
| 983 | { pid: 401, ppid: 400, pgid: 400 }, |
| 984 | { pid: 500, ppid: serverPid, pgid: 500 }, // terminal shell |
| 985 | { pid: 600, ppid: 500, pgid: 600 }, // terminal job |
| 986 | ]; |
| 987 | const table = new Map(rows.map((row) => [row.pid, row])); |
| 988 | expect(PortScanner.stoppableProcessGroup(table, 401, serverPid)).toBe(400); |
| 989 | expect(PortScanner.stoppableProcessGroup(table, 600, serverPid)).toBe(600); |
| 990 | for (const pid of [20, 210, 500, 999]) { |
| 991 | expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull(); |
| 992 | } |
| 993 | // The tool shell is the command; its `npm run dev &` job only inherited the name. |
| 994 | const variables = new Map([ |
| 995 | [200, new Map<string, string>()], |
| 996 | [300, new Map([["COMMAND", "a"]])], |
| 997 | [400, new Map([["COMMAND", "a"]])], |
| 998 | ]); |
| 999 | expect([...PortScanner.agentCommandsInGroup(variables, table.get(300)!)]).toEqual([ |
| 1000 | ["COMMAND", "a"], |
| 1001 | ]); |
| 1002 | expect(PortScanner.agentCommandsInGroup(variables, table.get(400)!).size).toBe(0); |
| 1003 | expect(PortScanner.agentCommandsInGroup(variables, table.get(600)!).size).toBe(0); |
| 1004 | }), |
| 1005 | ); |
| 1006 | |
| 1007 | const AGENT_SERVER_SCRIPT = ` |
| 1008 | const server = require("node:http").createServer((_, response) => { |
| 1009 | response.writeHead(200, { "content-type": "text/html" }); |
| 1010 | response.end("<html></html>"); |
| 1011 | }); |
| 1012 | server.listen(0, "127.0.0.1", () => { |
| 1013 | process.stdout.write(process.pid + " " + server.address().port + "\\n"); |
| 1014 | }); |
| 1015 | `; |
| 1016 | |
| 1017 | const AGENT_COMMAND_ENV = "T3CODE_TEST_AGENT_COMMAND"; |
| 1018 | |
| 1019 | /** |
| 1020 | * A real HTML server with an agent's environment, started the way an agent's tool shell starts a |
| 1021 | * job: under a detached shell with job control, in a group of its own. Release kills only the pids |
| 1022 | * it started. |
| 1023 | */ |
| 1024 | const agentServer = () => |
| 1025 | Effect.acquireRelease( |
| 1026 | Effect.callback<{ |
| 1027 | readonly child: NodeChildProcess.ChildProcess; |
| 1028 | readonly pid: number; |
| 1029 | readonly port: number; |
| 1030 | readonly exited: Promise<void>; |
| 1031 | }>((resume) => { |
| 1032 | const env = { ...process.env, [PortScanner.AGENT_THREAD_ENV]: "thread-live" }; |
| 1033 | // dash ignores `set -m` without a terminal; bash, like agent tool shells, honors it. |
| 1034 | const child = NodeChildProcess.spawn( |
| 1035 | "bash", |
| 1036 | [ |
| 1037 | "-c", |
| 1038 | `set -m; ${AGENT_COMMAND_ENV}=command-live "$0" -e "$1" & wait`, |
| 1039 | process.execPath, |
| 1040 | AGENT_SERVER_SCRIPT, |
| 1041 | ], |
| 1042 | { detached: true, env, stdio: ["ignore", "pipe", "ignore"] }, |
| 1043 | ); |
| 1044 | const exited = new Promise<void>((resolve) => child.once("exit", () => resolve())); |
| 1045 | child.once("error", (error) => resume(Effect.die(error))); |
| 1046 | child.stdout?.once("data", (chunk) => { |
| 1047 | const [pid, port] = String(chunk).trim().split(" ").map(Number); |
| 1048 | resume(Effect.succeed({ child, pid: pid!, port: port!, exited })); |
| 1049 | }); |
| 1050 | }), |
| 1051 | ({ child, pid }) => |
| 1052 | Effect.sync(() => { |
| 1053 | for (const target of [pid, child.pid]) { |
| 1054 | try { |
| 1055 | if (target !== undefined) process.kill(target, "SIGKILL"); |
| 1056 | } catch {} |
| 1057 | } |
| 1058 | }), |
| 1059 | ); |
| 1060 | |
| 1061 | const isRunning = (pid: number): boolean => { |
| 1062 | try { |
| 1063 | process.kill(pid, 0); |
| 1064 | return true; |
| 1065 | } catch { |
| 1066 | return false; |
| 1067 | } |
| 1068 | }; |
| 1069 | |
| 1070 | effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 1071 | "stops an agent's server through its job's group, and only a listed server", |
| 1072 | () => |
| 1073 | Effect.gen(function* () { |
| 1074 | const scanner = yield* PortScanner.PortDiscovery; |
| 1075 | yield* Effect.acquireRelease(Effect.sync(scanner.trackAgent), (release) => |
| 1076 | Effect.sync(release), |
| 1077 | ); |
| 1078 | const job = yield* agentServer(); |
| 1079 | const stops: Array<readonly [string, boolean]> = []; |
| 1080 | yield* scanner.watchAgentCommandStops({ |
| 1081 | variable: AGENT_COMMAND_ENV, |
| 1082 | onStop: (command) => Effect.sync(() => stops.push([command, isRunning(job.pid)])), |
| 1083 | onStopAbandoned: () => Effect.die("the signal reached the job"), |
| 1084 | }); |
| 1085 | |
| 1086 | expect(yield* scanner.scan()).toEqual( |
| 1087 | expect.arrayContaining([ |
| 1088 | expect.objectContaining({ |
| 1089 | pid: job.pid, |
| 1090 | port: job.port, |
| 1091 | agent: { threadId: "thread-live" }, |
| 1092 | }), |
| 1093 | ]), |
| 1094 | ); |
| 1095 | |
| 1096 | const unlisted = yield* Effect.flip(scanner.stopServer({ pid: process.pid, port: job.port })); |
| 1097 | expect(unlisted.reason).toBe("not-found"); |
| 1098 | expect(stops).toEqual([]); |
| 1099 | |
| 1100 | yield* scanner.stopServer({ pid: job.pid, port: job.port }); |
| 1101 | expect(stops).toEqual([["command-live", true]]); |
| 1102 | // The shell waits on its job, so it exits once the job has. |
| 1103 | yield* Effect.promise(() => job.exited); |
| 1104 | expect(isRunning(job.pid)).toBe(false); |
| 1105 | }).pipe( |
| 1106 | Effect.scoped, |
| 1107 | Effect.provide( |
| 1108 | layerScanner.pipe( |
| 1109 | Layer.provide(ProcessRunner.layer), |
| 1110 | Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)), |
| 1111 | ), |
| 1112 | ), |
| 1113 | ), |
| 1114 | ); |