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

PortScanner.ts

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