Open History to see the last commit
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/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>;
86}
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;
98}
99
100interface TerminalProcessOwner {
101 readonly threadId: ThreadId;
102 readonly terminalId: string;
103}
104
105interface WebProbeCacheEntry {
106 readonly pid: number | null;
107 readonly isWeb: boolean;
108 readonly expiresAtMillis: number;
109}
110
111interface WebProbeGroup {
112 readonly server: DiscoveredLocalServer;
113 readonly urls: ReadonlyArray<string>;
114 readonly configuredKey: string | null;
115}
116
117interface WebProbeSnapshot {
118 readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
119 readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
120}
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
292/** @public Service construction is part of the canonical Effect module API. */
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 pollTick = 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 // Single layer-scoped polling fiber. Ticks skip the scan and its span when no
582 // client is currently retained, so the cost is one Ref.get every POLL_INTERVAL.
583 const pollIfRetained = Ref.get(stateRef).pipe(
584 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
585 );
586 yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
587
588 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
589 const wasIdle = yield* Ref.modify(stateRef, (state) => [
590 state.retainCount === 0,
591 { ...state, retainCount: state.retainCount + 1 },
592 ]);
593 if (wasIdle) {
594 // Run an immediate scan + broadcast so the new retainer doesn't have
595 // to wait up to POLL_INTERVAL for the first emission.
596 yield* pollTick();
597 }
598 });
599
600 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
601 Ref.update(stateRef, (state) => ({
602 ...state,
603 retainCount: Math.max(0, state.retainCount - 1),
604 })),
605 );
606
607 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
608 (input, listener) =>
609 Effect.acquireRelease(
610 Ref.update(stateRef, (state) => {
611 const listeners = new Map(state.listeners);
612 listeners.set(listener, {
613 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
614 lastSnapshot: input.initialSnapshot,
615 });
616 return { ...state, listeners };
617 }),
618 () =>
619 Ref.update(stateRef, (state) => {
620 const listeners = new Map(state.listeners);
621 listeners.delete(listener);
622 return { ...state, listeners };
623 }),
624 ),
625 );
626
627 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
628 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
629 const owner = {
630 threadId: ThreadId.make(input.threadId),
631 terminalId: input.terminalId,
632 };
633 const processIds = new Set(
634 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
635 );
636 yield* Ref.update(stateRef, (state) => {
637 const terminalProcesses = new Map(state.terminalProcesses);
638 const key = terminalOwnerKey(owner);
639 if (processIds.size === 0) {
640 terminalProcesses.delete(key);
641 } else {
642 terminalProcesses.set(key, { owner, processIds });
643 }
644 return { ...state, terminalProcesses };
645 });
646 });
647
648 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
649 "PortDiscovery.unregisterTerminal",
650 )(function* (input) {
651 yield* Ref.update(stateRef, (state) => {
652 const terminalProcesses = new Map(state.terminalProcesses);
653 terminalProcesses.delete(terminalOwnerKey(input));
654 return { ...state, terminalProcesses };
655 });
656 });
657
658 return PortDiscovery.of({
659 scan: scanOnce,
660 subscribe,
661 retain,
662 registerTerminalProcesses,
663 unregisterTerminal,
664 });
665}).pipe(Effect.withSpan("PortDiscovery.make"));
666
667export const layer = Layer.effect(PortDiscovery, make);