Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PortScanner.ts

669 lines24.2 KB

1/**
2 * In-process PortScanner implementation.
3 *
4 * macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a
5 * stable line-prefixed field format; this is the only `lsof` flag set we rely
6 * on).
7 *
8 * Windows / lsof missing: checks a curated list of common dev ports through
9 * the shared Net service.
10 *
11 * Listening ports are published only after a bounded HTTP(S) probe finds a
12 * successful HTML document or a redirect to one.
13 * Positive and negative results are cached briefly by candidate URL and listener identity,
14 * limiting repeated requests without leaving stale classifications around.
15 *
16 * Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
17 * polls forever, but each tick is a no-op when the retain count is zero.
18 */
19import {
20 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
21 PREVIEW_URL_MAX_LENGTH,
22 ThreadId,
23 type DiscoveredLocalServer,
24} from "@t3tools/contracts";
25import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
26import * as Net from "@t3tools/shared/Net";
27import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
28import * as Cause from "effect/Cause";
29import * as Clock from "effect/Clock";
30import * as Context from "effect/Context";
31import * as Duration from "effect/Duration";
32import * as Effect from "effect/Effect";
33import * as Layer from "effect/Layer";
34import * as Option from "effect/Option";
35import * as Ref from "effect/Ref";
36import * as Schedule from "effect/Schedule";
37import * as Scope from "effect/Scope";
38import * as Semaphore from "effect/Semaphore";
39import { FetchHttpClient, HttpClient } from "effect/unstable/http";
40​
41import * as ProcessRunner from "../processRunner.ts";
42import { withoutAmbientParentSpan } from "../serverActivation.ts";
43​
44export class PortDiscovery extends Context.Service<
45 PortDiscovery,
46 {
47 readonly scan: (
48 configuredUrls?: ReadonlyArray<string>,
49 ) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
50 readonly subscribe: (
51 input: {
52 readonly configuredUrls: ReadonlyArray<string>;
53 readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
54 },
55 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
56 ) => Effect.Effect<void, never, Scope.Scope>;
57 readonly retain: Effect.Effect<void, never, Scope.Scope>;
58 readonly registerTerminalProcesses: (input: {
59 readonly threadId: string;
60 readonly terminalId: string;
61 readonly processIds: ReadonlyArray<number>;
62 }) => Effect.Effect<void>;
63 readonly unregisterTerminal: (input: {
64 readonly threadId: string;
65 readonly terminalId: string;
66 }) => Effect.Effect<void>;
67 }
68>()("t3/preview/PortScanner/PortDiscovery") {}
69​
70export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
71 3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
72]);
73​
74const POLL_INTERVAL = Duration.seconds(3);
75const LSOF_TIMEOUT_MS = 5_000;
76const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
77const WEB_PROBE_TIMEOUT = Duration.seconds(1);
78const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
79const WEB_PROBE_CONCURRENCY = 16;
80const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
81​
82type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
83​
84interface ListenerSubscription {
85 readonly configuredUrls: ReadonlyArray<string>;
86 readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
88​
89interface ScannerState {
90 readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
91 readonly terminalProcesses: ReadonlyMap<
92 string,
93 {
94 readonly owner: TerminalProcessOwner;
95 readonly processIds: ReadonlySet<number>;
96 }
97 >;
98 readonly retainCount: number;
100​
101interface TerminalProcessOwner {
102 readonly threadId: ThreadId;
103 readonly terminalId: string;
105​
106interface WebProbeCacheEntry {
107 readonly pid: number | null;
108 readonly isWeb: boolean;
109 readonly expiresAtMillis: number;
111​
112interface WebProbeGroup {
113 readonly server: DiscoveredLocalServer;
114 readonly urls: ReadonlyArray<string>;
115 readonly configuredKey: string | null;
117​
118interface WebProbeSnapshot {
119 readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
120 readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
122​
123const terminalOwnerKey = (owner: {
124 readonly threadId: string;
125 readonly terminalId: string;
126}): string => `${owner.threadId}\u0000${owner.terminalId}`;
127​
128const parseConfiguredUrl = (raw: string): URL | null => {
129 try {
130 const url = new URL(raw);
131 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
132 if (!isLoopbackHost(url.hostname)) return null;
133 return url;
134 } catch {
135 return null;
136 }
137};
138​
139const localServerKey = (host: string, port: number): string =>
140 `${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
141​
142const urlPort = (url: URL): number =>
143 url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
144​
145const webProbeCacheKey = (raw: string): string => {
146 const url = new URL(raw);
147 url.hash = "";
148 return url.href;
149};
150​
151const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
152 ...new Set(
153 urls
154 .slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
155 .filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
156 .map(parseConfiguredUrl)
157 .filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
158 .map((url) => {
159 if (url.hostname === "0.0.0.0") url.hostname = "localhost";
160 return url.href;
161 })
162 .filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
163 ),
164];
165​
166const projectWebProbeSnapshot = (
167 snapshot: WebProbeSnapshot,
168 configuredUrls: ReadonlyArray<string>,
169): ReadonlyArray<DiscoveredLocalServer> => {
170 const visibleByServer = new Map<string, DiscoveredLocalServer>();
171 for (const raw of normalizeConfiguredUrls(configuredUrls)) {
172 const url = new URL(raw);
173 const port = urlPort(url);
174 const serverKey = localServerKey(url.hostname, port);
175 if (visibleByServer.has(serverKey)) continue;
176 const configured = snapshot.configured.get(webProbeCacheKey(raw));
177 if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
178 }
179 for (const server of snapshot.discovered) {
180 const key = localServerKey(server.host, server.port);
181 if (!visibleByServer.has(key)) visibleByServer.set(key, server);
182 }
183 return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
184};
185​
186const parseLsofOutput = (
187 raw: string,
188 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
189): ReadonlyArray<DiscoveredLocalServer> => {
190 const seen = new Map<string, DiscoveredLocalServer>();
191 let pid: number | null = null;
192 let processName: string | null = null;
193​
194 for (const line of raw.split("\n")) {
195 if (line.length === 0) continue;
196 const tag = line.charAt(0);
197 const value = line.slice(1);
198 if (tag === "p") {
199 const parsed = Number.parseInt(value, 10);
200 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
201 processName = null;
202 continue;
203 }
204 if (tag === "c") {
205 processName = value.trim() || null;
206 continue;
207 }
208 if (tag === "n") {
209 const portMatch = parsePortFromLsofName(value);
210 if (portMatch == null) continue;
211 const url = `http://localhost:${portMatch}`;
212 const key = `localhost:${portMatch}`;
213 if (seen.has(key)) continue;
214 seen.set(key, {
215 host: "localhost",
216 port: portMatch,
217 url,
218 processName,
219 pid,
220 terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),
221 });
222 }
223 }
224​
225 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
226};
227​
228const parsePortFromLsofName = (name: string): number | null => {
229 // Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
230 // "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
231 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
232 if (trimmed.length === 0) return null;
233 const lastColon = trimmed.lastIndexOf(":");
234 if (lastColon < 0) return null;
235 const hostPart = trimmed.slice(0, lastColon);
236 const portPart = trimmed.slice(lastColon + 1);
237 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
238 const port = Number.parseInt(portPart, 10);
239 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
240 return port;
241};
242​
243const parseWindowsListenerOutput = (
244 raw: string,
245 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
246): ReadonlyArray<DiscoveredLocalServer> => {
247 const seen = new Map<number, DiscoveredLocalServer>();
248 for (const line of raw.split(/\r?\n/g)) {
249 const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
250 const host = hostRaw?.trim() ?? "";
251 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
252 const port = Number(portRaw);
253 const pid = Number(pidRaw);
254 if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
255 const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
256 if (seen.has(port)) continue;
257 seen.set(port, {
258 host: "localhost",
259 port,
260 url: `http://localhost:${port}`,
261 processName: processNameRaw?.trim() || null,
262 pid: normalizedPid,
263 terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),
264 });
265 }
266 return [...seen.values()].toSorted((left, right) => left.port - right.port);
267};
268​
269const serversEqual = (
270 left: ReadonlyArray<DiscoveredLocalServer>,
271 right: ReadonlyArray<DiscoveredLocalServer>,
272): boolean => {
273 if (left.length !== right.length) return false;
274 for (let i = 0; i < left.length; i += 1) {
275 const a = left[i];
276 const b = right[i];
277 if (!a || !b) return false;
278 if (
279 a.host !== b.host ||
280 a.port !== b.port ||
281 a.url !== b.url ||
282 a.processName !== b.processName ||
283 a.pid !== b.pid ||
284 a.terminal?.threadId !== b.terminal?.threadId ||
285 a.terminal?.terminalId !== b.terminal?.terminalId
286 ) {
287 return false;
288 }
289 }
290 return true;
291};
292​
293export const make = Effect.gen(function* PortDiscoveryMake() {
294 const net = yield* Net.NetService;
295 const processRunner = yield* ProcessRunner.ProcessRunner;
296 const hostPlatform = yield* HostProcessPlatform;
297 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
298 const stateRef = yield* Ref.make<ScannerState>({
299 listeners: new Map(),
300 terminalProcesses: new Map(),
301 retainCount: 0,
302 });
303 const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
304 const scanSemaphore = yield* Semaphore.make(1);
305​
306 const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
307 const results = yield* Effect.forEach(
308 COMMON_DEV_PORTS,
309 (port) =>
310 net.isPortAvailableOnLoopback(port).pipe(
311 Effect.map((available) => ({
312 port,
313 listening: !available,
314 })),
315 ),
316 { concurrency: "unbounded" },
317 );
318 return results
319 .filter((result) => result.listening)
320 .map<DiscoveredLocalServer>((result) => ({
321 host: "localhost",
322 port: result.port,
323 url: `http://localhost:${result.port}`,
324 processName: null,
325 pid: null,
326 terminal: null,
327 }));
328 });
329​
330 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
331 httpClient.get(url).pipe(
332 Effect.map((response) => {
333 const location = response.headers.location?.trim();
334 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
335 if (response.status < 200 || response.status >= 300) return null;
336 if (response.status === 204 || response.status === 205) return null;
337 const contentType = response.headers["content-type"]
338 ?.split(";", 1)[0]
339 ?.trim()
340 .toLowerCase();
341 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
342 }),
343 Effect.scoped,
344 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
345 Effect.map(Option.getOrNull),
346 Effect.orElseSucceed(() => null),
347 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
348 ),
349 );
350​
351 const makeWebProbeGroups = (
352 servers: ReadonlyArray<DiscoveredLocalServer>,
353 configuredUrls: ReadonlyArray<string>,
354 ): ReadonlyArray<WebProbeGroup> => {
355 const serversByKey = new Map(
356 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
357 );
358 const groups: WebProbeGroup[] = [];
359 const configuredResources = new Set<string>();
360​
361 for (const raw of configuredUrls) {
362 const url = new URL(raw);
363 const port = urlPort(url);
364 const key = localServerKey(url.hostname, port);
365 const resourceKey = webProbeCacheKey(raw);
366 if (configuredResources.has(resourceKey)) continue;
367 configuredResources.add(resourceKey);
368 groups.push({
369 server: serversByKey.get(key) ?? {
370 host: url.hostname,
371 port,
372 url: raw,
373 processName: null,
374 pid: null,
375 terminal: null,
376 },
377 urls: [raw],
378 configuredKey: resourceKey,
379 });
380 }
381​
382 for (const server of servers) {
383 groups.push({
384 server,
385 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
386 configuredKey: null,
387 });
388 }
389​
390 return groups;
391 };
392​
393 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
394 servers: ReadonlyArray<DiscoveredLocalServer>,
395 configuredUrls: ReadonlyArray<string>,
396 ) {
397 const nowMillis = yield* Clock.currentTimeMillis;
398 const cached = yield* Ref.get(webProbeCacheRef);
399 const groups = makeWebProbeGroups(servers, configuredUrls);
400 const batchProbes = new Map<
401 string,
402 Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
403 >();
404 const batchProbeSemaphore = yield* Semaphore.make(1);
405 const getProbe = (url: string, pid: number | null) => {
406 const key = webProbeCacheKey(url);
407 const identity = `${key}\u0000${pid ?? ""}`;
408 return batchProbeSemaphore
409 .withPermits(1)(
410 Effect.gen(function* () {
411 const existing = batchProbes.get(identity);
412 if (existing) return [existing] as const;
413 const cachedProbe = cached.get(key);
414 const cachedIsCurrent =
415 cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
416 const memoized = yield* Effect.cached(
417 cachedIsCurrent
418 ? Effect.succeed({ probe: cachedProbe, fresh: false })
419 : probeWebUrl(url).pipe(
420 Effect.map((result) => ({
421 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
422 fresh: true,
423 })),
424 ),
425 );
426 batchProbes.set(identity, memoized);
427 return [memoized] as const;
428 }),
429 )
430 .pipe(Effect.flatMap(([probe]) => probe));
431 };
432 const probed = yield* Effect.forEach(
433 groups,
434 (group) =>
435 Effect.gen(function* () {
436 const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
437 let visibleUrl: string | null = null;
438 for (const url of group.urls) {
439 const key = webProbeCacheKey(url);
440 const { probe, fresh } = yield* getProbe(url, group.server.pid);
441 probes.push([key, probe, fresh]);
442 if (probe.isWeb) {
443 visibleUrl = url;
444 break;
445 }
446 }
447 return { group, probes, visibleUrl };
448 }),
449 { concurrency: WEB_PROBE_CONCURRENCY },
450 );
451 const completedAtMillis = yield* Clock.currentTimeMillis;
452 const nextCache = new Map(
453 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
454 );
455 const discovered: DiscoveredLocalServer[] = [];
456 const configured = new Map<string, DiscoveredLocalServer>();
457 for (const { group, probes, visibleUrl } of probed) {
458 for (const [key, probe, fresh] of probes) {
459 nextCache.set(
460 key,
461 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
462 );
463 }
464 if (visibleUrl === null) continue;
465 const server = { ...group.server, url: visibleUrl };
466 if (group.configuredKey === null) discovered.push(server);
467 else configured.set(group.configuredKey, server);
468 }
469 yield* Ref.set(webProbeCacheRef, nextCache);
470 return { discovered, configured } satisfies WebProbeSnapshot;
471 });
472​
473 const recoverProcessProbeFailure =
474 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
475 Effect.logDebug("preview port process probe failed; falling back to common-port probes", {
476 cause: error,
477 probe,
478 platform: hostPlatform,
479 }).pipe(Effect.as(null));
480​
481 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
482 configuredUrls: ReadonlyArray<string>,
483 ) {
484 const state = yield* Ref.get(stateRef);
485 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
486 for (const registration of state.terminalProcesses.values()) {
487 for (const processId of registration.processIds) {
488 terminalByProcessId.set(processId, registration.owner);
489 }
490 }
491 if (hostPlatform === "win32") {
492 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
493 const command =
494 'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
495 const listeners = yield* processRunner
496 .run({
497 command: "powershell.exe",
498 args: ["-NoProfile", "-NonInteractive", "-Command", command],
499 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
500 maxOutputBytes: 1024 * 1024,
501 outputMode: "truncate",
502 })
503 .pipe(
504 Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
505 Effect.catchTags({
506 ProcessSpawnError: recoverWindowsProbeFailure,
507 ProcessStdinError: recoverWindowsProbeFailure,
508 ProcessOutputLimitError: recoverWindowsProbeFailure,
509 ProcessReadError: recoverWindowsProbeFailure,
510 ProcessTimeoutError: recoverWindowsProbeFailure,
511 }),
512 );
513 if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls);
514 return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
515 }
516 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
517 const lsofResult = yield* processRunner
518 .run({
519 command: "lsof",
520 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
521 timeout: Duration.millis(LSOF_TIMEOUT_MS),
522 maxOutputBytes: 1024 * 1024,
523 outputMode: "truncate",
524 })
525 .pipe(
526 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
527 Effect.catchTags({
528 ProcessSpawnError: recoverLsofProbeFailure,
529 ProcessStdinError: recoverLsofProbeFailure,
530 ProcessOutputLimitError: recoverLsofProbeFailure,
531 ProcessReadError: recoverLsofProbeFailure,
532 ProcessTimeoutError: recoverLsofProbeFailure,
533 }),
534 );
535 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
536 return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
537 });
538​
539 const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
540 (configuredUrls: ReadonlyArray<string>) =>
541 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
542 );
543​
544 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
545 const normalized = normalizeConfiguredUrls(configuredUrls);
546 return scanSnapshot(normalized).pipe(
547 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
548 );
549 };
550​
551 const pollTickActive = Effect.fn("PortDiscovery.pollTick")(
552 function* () {
553 const configuredUrls = [
554 ...new Set(
555 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
556 (subscription) => subscription.configuredUrls,
557 ),
558 ),
559 ];
560 const snapshot = yield* scanSnapshot(configuredUrls);
561 const notifications = yield* Ref.modify(stateRef, (state) => {
562 const listeners = new Map(state.listeners);
563 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
564 for (const [listener, subscription] of listeners) {
565 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
566 if (serversEqual(subscription.lastSnapshot, next)) continue;
567 listeners.set(listener, { ...subscription, lastSnapshot: next });
568 changed.push([listener, next]);
569 }
570 return [changed, { ...state, listeners }];
571 });
572 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
573 discard: true,
574 });
575 },
576 Effect.catchCause((cause: Cause.Cause<never>) =>
577 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
578 ),
579 );
580​
581 // Idle early-return stays outside Effect.fn so no-op ticks create no span; detach ParentSpan (#5410).
582 const pollTick = Effect.gen(function* () {
583 if ((yield* Ref.get(stateRef)).retainCount <= 0) return;
584 yield* pollTickActive();
585 });
586​
587 yield* Effect.forkScoped(
588 withoutAmbientParentSpan(pollTick.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL)))),
589 );
590 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
591 const wasIdle = yield* Ref.modify(stateRef, (state) => [
592 state.retainCount === 0,
593 { ...state, retainCount: state.retainCount + 1 },
594 ]);
595 if (wasIdle) {
596 // Run an immediate scan + broadcast so the new retainer doesn't have
597 // to wait up to POLL_INTERVAL for the first emission.
598 yield* pollTick;
599 }
600 });
601​
602 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
603 Ref.update(stateRef, (state) => ({
604 ...state,
605 retainCount: Math.max(0, state.retainCount - 1),
606 })),
607 );
608​
609 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
610 (input, listener) =>
611 Effect.acquireRelease(
612 Ref.update(stateRef, (state) => {
613 const listeners = new Map(state.listeners);
614 listeners.set(listener, {
615 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
616 lastSnapshot: input.initialSnapshot,
617 });
618 return { ...state, listeners };
619 }),
620 () =>
621 Ref.update(stateRef, (state) => {
622 const listeners = new Map(state.listeners);
623 listeners.delete(listener);
624 return { ...state, listeners };
625 }),
626 ),
627 );
628​
629 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
630 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
631 const owner = {
632 threadId: ThreadId.make(input.threadId),
633 terminalId: input.terminalId,
634 };
635 const processIds = new Set(
636 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
637 );
638 yield* Ref.update(stateRef, (state) => {
639 const terminalProcesses = new Map(state.terminalProcesses);
640 const key = terminalOwnerKey(owner);
641 if (processIds.size === 0) {
642 terminalProcesses.delete(key);
643 } else {
644 terminalProcesses.set(key, { owner, processIds });
645 }
646 return { ...state, terminalProcesses };
647 });
648 });
649​
650 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
651 "PortDiscovery.unregisterTerminal",
652 )(function* (input) {
653 yield* Ref.update(stateRef, (state) => {
654 const terminalProcesses = new Map(state.terminalProcesses);
655 terminalProcesses.delete(terminalOwnerKey(input));
656 return { ...state, terminalProcesses };
657 });
658 });
659​
660 return PortDiscovery.of({
661 scan: scanOnce,
662 subscribe,
663 retain,
664 registerTerminalProcesses,
665 unregisterTerminal,
666 });
667});
668​
669export const layer = Layer.effect(PortDiscovery, make);