fix(preview): only show browser-ready local servers (#6021)
This commit is contained in:
1 parent
710fd0eeb3
commit
9fd788b5a9
15 files changed
+1069
-217
No files matched your search
@@ -1,35 +1,60 @@
|
||||
import * as NodeNet from "node:net";
|
||||
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import {
|
||||
CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
|
||||
PREVIEW_URL_MAX_LENGTH,
|
||||
type DiscoveredLocalServer,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { expect } from "vite-plus/test";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as PortScanner from "./PortScanner.ts";
|
||||
const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
|
||||
run: (input) =>
|
||||
Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command: input.command,
|
||||
argumentCount: input.args.length,
|
||||
cwd: input.cwd,
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description: "PowerShell is not installed in the test environment",
|
||||
}),
|
||||
const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
|
||||
Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command: input.command,
|
||||
argumentCount: input.args.length,
|
||||
cwd: input.cwd,
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description: "PowerShell is not installed in the test environment",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
|
||||
run: processProbeFailure,
|
||||
});
|
||||
|
||||
const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"]) =>
|
||||
let integrationListeningPort: number | null = null;
|
||||
|
||||
const TestIntegrationNet = Layer.succeed(Net.NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: (port) => Effect.sync(() => port !== integrationListeningPort),
|
||||
reserveLoopbackPort: () => Effect.succeed(40_000),
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
});
|
||||
|
||||
const makeProbeFailureLayer = (
|
||||
run: ProcessRunner.ProcessRunner["Service"]["run"],
|
||||
fetch: typeof globalThis.fetch = globalThis.fetch,
|
||||
) =>
|
||||
PortScanner.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
@@ -41,19 +66,64 @@ const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
}),
|
||||
Layer.succeed(HostProcessPlatform, "linux"),
|
||||
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const TestPortDiscoveryLive = PortScanner.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(TestProcessRunner, Net.layer, Layer.succeed(HostProcessPlatform, "win32")),
|
||||
Layer.mergeAll(
|
||||
TestProcessRunner,
|
||||
TestIntegrationNet,
|
||||
Layer.succeed(HostProcessPlatform, "win32"),
|
||||
FetchHttpClient.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const openServer = (port: number): Effect.Effect<NodeNet.Server | null> =>
|
||||
const LSOF_TEST_PORT = 43_123;
|
||||
|
||||
const makeLsofScannerLayer = (input: {
|
||||
readonly pid: () => number;
|
||||
readonly fetch: typeof globalThis.fetch;
|
||||
}) =>
|
||||
PortScanner.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ProcessRunner.ProcessRunner, {
|
||||
run: () =>
|
||||
Effect.succeed({
|
||||
stdout: `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`,
|
||||
stderr: "",
|
||||
code: null,
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
}),
|
||||
Layer.succeed(Net.NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(40_000),
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
}),
|
||||
Layer.succeed(HostProcessPlatform, "linux"),
|
||||
FetchHttpClient.layer.pipe(
|
||||
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const openServer = (
|
||||
port: number,
|
||||
onConnection: (socket: NodeNet.Socket) => void,
|
||||
): Effect.Effect<NodeNet.Server | null> =>
|
||||
Effect.callback((resume) => {
|
||||
const server = NodeNet.createServer();
|
||||
const server = NodeNet.createServer(onConnection);
|
||||
server.once("error", () => {
|
||||
resume(Effect.succeed(null));
|
||||
});
|
||||
@@ -72,9 +142,10 @@ const closeServer = (server: NodeNet.Server): Effect.Effect<void> =>
|
||||
|
||||
const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
|
||||
ports: ReadonlyArray<number>,
|
||||
onConnection: (socket: NodeNet.Socket) => void,
|
||||
) {
|
||||
for (const port of ports) {
|
||||
const server = yield* openServer(port);
|
||||
const server = yield* openServer(port, onConnection);
|
||||
if (server !== null) return { port, server };
|
||||
}
|
||||
return yield* Effect.die(
|
||||
@@ -83,8 +154,46 @@ const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(fun
|
||||
});
|
||||
|
||||
const commonDevServer = Effect.acquireRelease(
|
||||
openCommonDevServer(PortScanner.COMMON_DEV_PORTS),
|
||||
({ server }) => closeServer(server),
|
||||
openCommonDevServer(PortScanner.COMMON_DEV_PORTS, (socket) => {
|
||||
socket.once("data", () => {
|
||||
socket.end("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 5\r\n\r\nhello");
|
||||
});
|
||||
}).pipe(
|
||||
Effect.tap(({ port }) =>
|
||||
Effect.sync(() => {
|
||||
integrationListeningPort = port;
|
||||
}),
|
||||
),
|
||||
),
|
||||
({ server }) =>
|
||||
closeServer(server).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
integrationListeningPort = null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const commonNonHttpServer = Effect.acquireRelease(
|
||||
openCommonDevServer(PortScanner.COMMON_DEV_PORTS.toReversed(), (socket) => {
|
||||
socket.on("error", () => undefined);
|
||||
socket.once("data", () => socket.end("MYSQL\r\n\r\n"));
|
||||
}).pipe(
|
||||
Effect.tap(({ port }) =>
|
||||
Effect.sync(() => {
|
||||
integrationListeningPort = port;
|
||||
}),
|
||||
),
|
||||
),
|
||||
({ server }) =>
|
||||
closeServer(server).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
integrationListeningPort = null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -94,7 +203,7 @@ const commonDevServer = Effect.acquireRelease(
|
||||
*/
|
||||
effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
|
||||
it.effect(
|
||||
"scan() returns a server we just opened on a curated dev port",
|
||||
"scan() returns an HTTP server we just opened on a curated dev port",
|
||||
Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
|
||||
const { port } = yield* commonDevServer;
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
@@ -105,13 +214,23 @@ effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fall
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"scan() excludes a listening port that does not speak HTTP",
|
||||
Effect.fn("PortScannerTest.scanExcludesNonHttpServer")(function* () {
|
||||
const { port } = yield* commonNonHttpServer;
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const result = yield* scanner.scan();
|
||||
expect(result.some((server) => server.port === port)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"retain drives an immediate broadcast to subscribers",
|
||||
Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
|
||||
const { port } = yield* commonDevServer;
|
||||
const received: number[] = [];
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
yield* scanner.subscribe((servers) =>
|
||||
yield* scanner.subscribe({ configuredUrls: [], initialSnapshot: [] }, (servers) =>
|
||||
Effect.sync(() => {
|
||||
for (const server of servers) received.push(server.port);
|
||||
}),
|
||||
@@ -122,7 +241,395 @@ effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fall
|
||||
);
|
||||
});
|
||||
|
||||
effectIt("does not swallow process probe defects", () =>
|
||||
effectIt.effect("revalidates a successful HTML probe after its cache entry expires", () => {
|
||||
let responds = true;
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return responds
|
||||
? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
|
||||
: Promise.reject(new TypeError("not HTTP"));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
expect(yield* scanner.scan()).toHaveLength(1);
|
||||
expect(yield* scanner.scan()).toHaveLength(1);
|
||||
expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
|
||||
|
||||
responds = false;
|
||||
yield* TestClock.adjust(Duration.seconds(15));
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
expect(requests).toEqual([
|
||||
`http://localhost:${LSOF_TEST_PORT}/`,
|
||||
`http://localhost:${LSOF_TEST_PORT}/`,
|
||||
`https://localhost:${LSOF_TEST_PORT}/`,
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
|
||||
const requests: string[] = [];
|
||||
const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
const url = String(input);
|
||||
requests.push(url);
|
||||
return Promise.resolve(
|
||||
url === configuredUrl
|
||||
? new Response("docs", { headers: { "content-type": "text/html" } })
|
||||
: new Response("not found", {
|
||||
status: 404,
|
||||
headers: { "content-type": "text/html" },
|
||||
}),
|
||||
);
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const servers = yield* scanner.scan([configuredUrl]);
|
||||
expect(servers).toHaveLength(1);
|
||||
expect(servers[0]?.url).toBe(configuredUrl);
|
||||
expect(requests).toContain(configuredUrl);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
|
||||
const customPort = 43_124;
|
||||
const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
|
||||
const expectedUrl = `http://localhost:${customPort}/docs`;
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeProbeFailureLayer(processProbeFailure, fetchFn);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const servers = yield* scanner.scan([configuredUrl]);
|
||||
expect(servers).toHaveLength(1);
|
||||
expect(servers[0]?.host).toBe("localhost");
|
||||
expect(servers[0]?.port).toBe(customPort);
|
||||
expect(servers[0]?.url).toBe(expectedUrl);
|
||||
expect(requests).toEqual([expectedUrl]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
|
||||
const ipv4Url = "https://127.0.0.1:43125/docs";
|
||||
const ipv6Url = "http://[::1]:43126/docs";
|
||||
const wildcardPrefix = "http://0.0.0.0/";
|
||||
const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
|
||||
PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
|
||||
)}`;
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeProbeFailureLayer(processProbeFailure, fetchFn);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
|
||||
expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
|
||||
expect(requests).toEqual([ipv4Url, ipv6Url]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
|
||||
const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
|
||||
const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
const url = String(input);
|
||||
return Promise.resolve(
|
||||
url === docsUrl || url === adminUrl
|
||||
? new Response("app", { headers: { "content-type": "text/html" } })
|
||||
: new Response("not found", { status: 404 }),
|
||||
);
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
|
||||
const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
|
||||
yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
|
||||
Effect.sync(() => docsSnapshots.push(servers)),
|
||||
);
|
||||
yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
|
||||
Effect.sync(() => adminSnapshots.push(servers)),
|
||||
);
|
||||
yield* scanner.retain;
|
||||
|
||||
expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
|
||||
expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
|
||||
}).pipe(Effect.scoped, Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"keeps each subscriber's candidates when their combined union exceeds the per-client cap",
|
||||
() => {
|
||||
const firstSubscriberUrls = Array.from(
|
||||
{ length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
|
||||
(_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
|
||||
);
|
||||
const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
|
||||
Promise.resolve(
|
||||
String(input) === secondSubscriberUrl
|
||||
? new Response("app", { headers: { "content-type": "text/html" } })
|
||||
: new Response("not found", { status: 404 }),
|
||||
)) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
|
||||
yield* scanner.subscribe(
|
||||
{ configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
|
||||
() => Effect.void,
|
||||
);
|
||||
yield* scanner.subscribe(
|
||||
{ configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
|
||||
(servers) => Effect.sync(() => secondSnapshots.push(servers)),
|
||||
);
|
||||
yield* scanner.retain;
|
||||
|
||||
expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
|
||||
}).pipe(Effect.scoped, Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
|
||||
const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
|
||||
const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
const url = String(input);
|
||||
requests.push(url);
|
||||
return Promise.resolve(
|
||||
url === docsUrl || url === adminUrl
|
||||
? new Response("app", { headers: { "content-type": "text/html" } })
|
||||
: new Response("not found", { status: 404 }),
|
||||
);
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const docsScope = yield* Scope.make();
|
||||
yield* scanner
|
||||
.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
|
||||
.pipe(Effect.provideService(Scope.Scope, docsScope));
|
||||
yield* scanner.subscribe(
|
||||
{ configuredUrls: [adminUrl], initialSnapshot: [] },
|
||||
() => Effect.void,
|
||||
);
|
||||
yield* scanner.retain;
|
||||
yield* Scope.close(docsScope, Exit.void);
|
||||
|
||||
requests.length = 0;
|
||||
yield* TestClock.adjust(Duration.seconds(15));
|
||||
expect(requests).toContain(adminUrl);
|
||||
expect(requests).not.toContain(docsUrl);
|
||||
}).pipe(Effect.scoped, Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
|
||||
const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
|
||||
const requestCount = requests.length;
|
||||
expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
|
||||
expect(requests).toHaveLength(requestCount);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("shares a configured root probe with discovered-root classification", () => {
|
||||
const requests: string[] = [];
|
||||
const rootUrl = `http://localhost:${LSOF_TEST_PORT}/`;
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
|
||||
expect(requests).toEqual([rootUrl]);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(15));
|
||||
expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
|
||||
expect(requests).toEqual([rootUrl, rootUrl]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("starts fresh cache entries after the probing batch completes", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseClock = yield* Clock.Clock;
|
||||
const times = [0, 20_000, 20_000, 20_000];
|
||||
let timeIndex = 0;
|
||||
const currentTimeMillis = () => times[Math.min(timeIndex++, times.length - 1)]!;
|
||||
const clock: Clock.Clock = {
|
||||
...baseClock,
|
||||
currentTimeMillisUnsafe: currentTimeMillis,
|
||||
currentTimeMillis: Effect.sync(currentTimeMillis),
|
||||
};
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
expect(yield* scanner.scan()).toHaveLength(1);
|
||||
expect(yield* scanner.scan()).toHaveLength(1);
|
||||
expect(requests).toHaveLength(1);
|
||||
}).pipe(Effect.provide(layer), Effect.provideService(Clock.Clock, clock));
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("caches a failed web probe until its bounded cache entry expires", () => {
|
||||
let responds = false;
|
||||
const requests: string[] = [];
|
||||
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
|
||||
requests.push(String(input));
|
||||
return responds
|
||||
? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
|
||||
: Promise.reject(new TypeError("not HTTP"));
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
expect(requests).toHaveLength(2);
|
||||
|
||||
responds = true;
|
||||
yield* TestClock.adjust(Duration.seconds(15));
|
||||
expect(yield* scanner.scan()).toHaveLength(1);
|
||||
expect(requests).toHaveLength(3);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
|
||||
const redirects: Array<string | undefined> = [];
|
||||
const fetchFn = (async (
|
||||
input: Parameters<typeof globalThis.fetch>[0],
|
||||
init?: Parameters<typeof globalThis.fetch>[1],
|
||||
) => {
|
||||
redirects.push(init?.redirect);
|
||||
if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
|
||||
return new Response(null, { status: 302, headers: { location: "https://example.com" } });
|
||||
}) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const servers = yield* scanner.scan();
|
||||
expect(servers).toHaveLength(1);
|
||||
expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
|
||||
expect(redirects).toEqual(["manual", "manual"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"excludes HTTP errors, non-navigation responses, and successful non-documents",
|
||||
() => {
|
||||
let pid = 1;
|
||||
let makeResponse = () =>
|
||||
new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
|
||||
const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
|
||||
Promise.resolve(makeResponse())) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => pid, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
|
||||
pid += 1;
|
||||
makeResponse = () =>
|
||||
new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
|
||||
pid += 1;
|
||||
makeResponse = () =>
|
||||
new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
|
||||
pid += 1;
|
||||
makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
|
||||
pid += 1;
|
||||
makeResponse = () =>
|
||||
new Response(null, { status: 204, headers: { "content-type": "text/html" } });
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
|
||||
pid += 1;
|
||||
makeResponse = () => new Response(null, { status: 302 });
|
||||
expect(yield* scanner.scan()).toHaveLength(0);
|
||||
|
||||
pid += 1;
|
||||
makeResponse = () =>
|
||||
new Response("<html />", {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
|
||||
});
|
||||
expect(yield* scanner.scan()).toHaveLength(1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
effectIt.effect("aborts HTTP and HTTPS probes when they time out", () => {
|
||||
const aborted: string[] = [];
|
||||
const fetchFn = ((
|
||||
input: Parameters<typeof globalThis.fetch>[0],
|
||||
init?: Parameters<typeof globalThis.fetch>[1],
|
||||
) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
const signal = init?.signal;
|
||||
const onAbort = () => {
|
||||
aborted.push(String(input));
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
if (signal?.aborted) {
|
||||
onAbort();
|
||||
} else {
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
})) as typeof globalThis.fetch;
|
||||
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const scanFiber = yield* Effect.forkChild(scanner.scan());
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
expect(yield* Fiber.join(scanFiber)).toHaveLength(0);
|
||||
expect(aborted).toEqual([
|
||||
`http://localhost:${LSOF_TEST_PORT}/`,
|
||||
`https://localhost:${LSOF_TEST_PORT}/`,
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
effectIt.effect("does not swallow process probe defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const defect = new Error("unexpected process probe defect");
|
||||
const layer = makeProbeFailureLayer(() => Effect.die(defect));
|
||||
@@ -140,7 +647,7 @@ effectIt("does not swallow process probe defects", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt("does not swallow process probe interruption", () =>
|
||||
effectIt.effect("does not swallow process probe interruption", () =>
|
||||
Effect.gen(function* () {
|
||||
const layer = makeProbeFailureLayer(() => Effect.interrupt);
|
||||
|
||||
|
||||
@@ -8,29 +8,49 @@
|
||||
* Windows / lsof missing: checks a curated list of common dev ports through
|
||||
* the shared Net service.
|
||||
*
|
||||
* Listening ports are published only after a bounded HTTP(S) probe finds a
|
||||
* successful HTML document or a redirect to one.
|
||||
* Positive and negative results are cached briefly by candidate URL and listener identity,
|
||||
* limiting repeated requests without leaving stale classifications around.
|
||||
*
|
||||
* Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
|
||||
* polls forever, but each tick is a no-op when the retain count is zero.
|
||||
*/
|
||||
import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
|
||||
import {
|
||||
CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
|
||||
PREVIEW_URL_MAX_LENGTH,
|
||||
ThreadId,
|
||||
type DiscoveredLocalServer,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
|
||||
import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
export class PortDiscovery extends Context.Service<
|
||||
PortDiscovery,
|
||||
{
|
||||
readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
|
||||
readonly scan: (
|
||||
configuredUrls?: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
|
||||
readonly subscribe: (
|
||||
input: {
|
||||
readonly configuredUrls: ReadonlyArray<string>;
|
||||
readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
|
||||
},
|
||||
listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly retain: Effect.Effect<void, never, Scope.Scope>;
|
||||
@@ -53,12 +73,20 @@ export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
|
||||
const POLL_INTERVAL = Duration.seconds(3);
|
||||
const LSOF_TIMEOUT_MS = 5_000;
|
||||
const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
|
||||
const WEB_PROBE_TIMEOUT = Duration.seconds(1);
|
||||
const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
|
||||
const WEB_PROBE_CONCURRENCY = 16;
|
||||
const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
||||
|
||||
type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
|
||||
|
||||
interface ScannerState {
|
||||
interface ListenerSubscription {
|
||||
readonly configuredUrls: ReadonlyArray<string>;
|
||||
readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
|
||||
readonly listeners: ReadonlySet<Listener>;
|
||||
}
|
||||
|
||||
interface ScannerState {
|
||||
readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
|
||||
readonly terminalProcesses: ReadonlyMap<
|
||||
string,
|
||||
{
|
||||
@@ -74,11 +102,86 @@ interface TerminalProcessOwner {
|
||||
readonly terminalId: string;
|
||||
}
|
||||
|
||||
interface WebProbeCacheEntry {
|
||||
readonly pid: number | null;
|
||||
readonly isWeb: boolean;
|
||||
readonly expiresAtMillis: number;
|
||||
}
|
||||
|
||||
interface WebProbeGroup {
|
||||
readonly server: DiscoveredLocalServer;
|
||||
readonly urls: ReadonlyArray<string>;
|
||||
readonly configuredKey: string | null;
|
||||
}
|
||||
|
||||
interface WebProbeSnapshot {
|
||||
readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
|
||||
readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
|
||||
}
|
||||
|
||||
const terminalOwnerKey = (owner: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}): string => `${owner.threadId}\u0000${owner.terminalId}`;
|
||||
|
||||
const parseConfiguredUrl = (raw: string): URL | null => {
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
||||
if (!isLoopbackHost(url.hostname)) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const localServerKey = (host: string, port: number): string =>
|
||||
`${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
|
||||
|
||||
const urlPort = (url: URL): number =>
|
||||
url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
|
||||
|
||||
const webProbeCacheKey = (raw: string): string => {
|
||||
const url = new URL(raw);
|
||||
url.hash = "";
|
||||
return url.href;
|
||||
};
|
||||
|
||||
const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
|
||||
...new Set(
|
||||
urls
|
||||
.slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
|
||||
.filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
|
||||
.map(parseConfiguredUrl)
|
||||
.filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
|
||||
.map((url) => {
|
||||
if (url.hostname === "0.0.0.0") url.hostname = "localhost";
|
||||
return url.href;
|
||||
})
|
||||
.filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
|
||||
),
|
||||
];
|
||||
|
||||
const projectWebProbeSnapshot = (
|
||||
snapshot: WebProbeSnapshot,
|
||||
configuredUrls: ReadonlyArray<string>,
|
||||
): ReadonlyArray<DiscoveredLocalServer> => {
|
||||
const visibleByServer = new Map<string, DiscoveredLocalServer>();
|
||||
for (const raw of normalizeConfiguredUrls(configuredUrls)) {
|
||||
const url = new URL(raw);
|
||||
const port = urlPort(url);
|
||||
const serverKey = localServerKey(url.hostname, port);
|
||||
if (visibleByServer.has(serverKey)) continue;
|
||||
const configured = snapshot.configured.get(webProbeCacheKey(raw));
|
||||
if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
|
||||
}
|
||||
for (const server of snapshot.discovered) {
|
||||
const key = localServerKey(server.host, server.port);
|
||||
if (!visibleByServer.has(key)) visibleByServer.set(key, server);
|
||||
}
|
||||
return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
|
||||
};
|
||||
|
||||
const parseLsofOutput = (
|
||||
raw: string,
|
||||
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
|
||||
@@ -190,12 +293,14 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
const net = yield* Net.NetService;
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
|
||||
const stateRef = yield* Ref.make<ScannerState>({
|
||||
lastSnapshot: [],
|
||||
listeners: new Set(),
|
||||
listeners: new Map(),
|
||||
terminalProcesses: new Map(),
|
||||
retainCount: 0,
|
||||
});
|
||||
const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
|
||||
const scanSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
|
||||
const results = yield* Effect.forEach(
|
||||
@@ -221,6 +326,149 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
}));
|
||||
});
|
||||
|
||||
const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
|
||||
httpClient.get(url).pipe(
|
||||
Effect.map((response) => {
|
||||
const location = response.headers.location?.trim();
|
||||
if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
|
||||
if (response.status < 200 || response.status >= 300) return null;
|
||||
if (response.status === 204 || response.status === 205) return null;
|
||||
const contentType = response.headers["content-type"]
|
||||
?.split(";", 1)[0]
|
||||
?.trim()
|
||||
.toLowerCase();
|
||||
return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
|
||||
}),
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(WEB_PROBE_TIMEOUT),
|
||||
Effect.map(Option.getOrNull),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
|
||||
),
|
||||
);
|
||||
|
||||
const makeWebProbeGroups = (
|
||||
servers: ReadonlyArray<DiscoveredLocalServer>,
|
||||
configuredUrls: ReadonlyArray<string>,
|
||||
): ReadonlyArray<WebProbeGroup> => {
|
||||
const serversByKey = new Map(
|
||||
servers.map((server) => [localServerKey(server.host, server.port), server] as const),
|
||||
);
|
||||
const groups: WebProbeGroup[] = [];
|
||||
const configuredResources = new Set<string>();
|
||||
|
||||
for (const raw of configuredUrls) {
|
||||
const url = new URL(raw);
|
||||
const port = urlPort(url);
|
||||
const key = localServerKey(url.hostname, port);
|
||||
const resourceKey = webProbeCacheKey(raw);
|
||||
if (configuredResources.has(resourceKey)) continue;
|
||||
configuredResources.add(resourceKey);
|
||||
groups.push({
|
||||
server: serversByKey.get(key) ?? {
|
||||
host: url.hostname,
|
||||
port,
|
||||
url: raw,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
},
|
||||
urls: [raw],
|
||||
configuredKey: resourceKey,
|
||||
});
|
||||
}
|
||||
|
||||
for (const server of servers) {
|
||||
groups.push({
|
||||
server,
|
||||
urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
|
||||
configuredKey: null,
|
||||
});
|
||||
}
|
||||
|
||||
return groups;
|
||||
};
|
||||
|
||||
const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
|
||||
servers: ReadonlyArray<DiscoveredLocalServer>,
|
||||
configuredUrls: ReadonlyArray<string>,
|
||||
) {
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
const cached = yield* Ref.get(webProbeCacheRef);
|
||||
const groups = makeWebProbeGroups(servers, configuredUrls);
|
||||
const batchProbes = new Map<
|
||||
string,
|
||||
Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
|
||||
>();
|
||||
const batchProbeSemaphore = yield* Semaphore.make(1);
|
||||
const getProbe = (url: string, pid: number | null) => {
|
||||
const key = webProbeCacheKey(url);
|
||||
const identity = `${key}\u0000${pid ?? ""}`;
|
||||
return batchProbeSemaphore
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const existing = batchProbes.get(identity);
|
||||
if (existing) return [existing] as const;
|
||||
const cachedProbe = cached.get(key);
|
||||
const cachedIsCurrent =
|
||||
cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
|
||||
const memoized = yield* Effect.cached(
|
||||
cachedIsCurrent
|
||||
? Effect.succeed({ probe: cachedProbe, fresh: false })
|
||||
: probeWebUrl(url).pipe(
|
||||
Effect.map((result) => ({
|
||||
probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
|
||||
fresh: true,
|
||||
})),
|
||||
),
|
||||
);
|
||||
batchProbes.set(identity, memoized);
|
||||
return [memoized] as const;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.flatMap(([probe]) => probe));
|
||||
};
|
||||
const probed = yield* Effect.forEach(
|
||||
groups,
|
||||
(group) =>
|
||||
Effect.gen(function* () {
|
||||
const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
|
||||
let visibleUrl: string | null = null;
|
||||
for (const url of group.urls) {
|
||||
const key = webProbeCacheKey(url);
|
||||
const { probe, fresh } = yield* getProbe(url, group.server.pid);
|
||||
probes.push([key, probe, fresh]);
|
||||
if (probe.isWeb) {
|
||||
visibleUrl = url;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { group, probes, visibleUrl };
|
||||
}),
|
||||
{ concurrency: WEB_PROBE_CONCURRENCY },
|
||||
);
|
||||
const completedAtMillis = yield* Clock.currentTimeMillis;
|
||||
const nextCache = new Map(
|
||||
[...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
|
||||
);
|
||||
const discovered: DiscoveredLocalServer[] = [];
|
||||
const configured = new Map<string, DiscoveredLocalServer>();
|
||||
for (const { group, probes, visibleUrl } of probed) {
|
||||
for (const [key, probe, fresh] of probes) {
|
||||
nextCache.set(
|
||||
key,
|
||||
fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
|
||||
);
|
||||
}
|
||||
if (visibleUrl === null) continue;
|
||||
const server = { ...group.server, url: visibleUrl };
|
||||
if (group.configuredKey === null) discovered.push(server);
|
||||
else configured.set(group.configuredKey, server);
|
||||
}
|
||||
yield* Ref.set(webProbeCacheRef, nextCache);
|
||||
return { discovered, configured } satisfies WebProbeSnapshot;
|
||||
});
|
||||
|
||||
const recoverProcessProbeFailure =
|
||||
(probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
|
||||
Effect.logDebug("preview port process probe failed; falling back to common-port probes", {
|
||||
@@ -229,7 +477,9 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
platform: hostPlatform,
|
||||
}).pipe(Effect.as(null));
|
||||
|
||||
const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
|
||||
const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
|
||||
configuredUrls: ReadonlyArray<string>,
|
||||
) {
|
||||
const state = yield* Ref.get(stateRef);
|
||||
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
|
||||
for (const registration of state.terminalProcesses.values()) {
|
||||
@@ -259,8 +509,8 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
ProcessTimeoutError: recoverWindowsProbeFailure,
|
||||
}),
|
||||
);
|
||||
if (listeners !== null) return listeners;
|
||||
return yield* probeCommonPorts();
|
||||
if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls);
|
||||
return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
|
||||
}
|
||||
const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
|
||||
const lsofResult = yield* processRunner
|
||||
@@ -281,27 +531,47 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
ProcessTimeoutError: recoverLsofProbeFailure,
|
||||
}),
|
||||
);
|
||||
if (lsofResult !== null) return lsofResult;
|
||||
return yield* probeCommonPorts();
|
||||
if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
|
||||
return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
|
||||
});
|
||||
|
||||
const broadcast = Effect.fn("PortDiscovery.broadcast")(function* (
|
||||
servers: ReadonlyArray<DiscoveredLocalServer>,
|
||||
) {
|
||||
const listeners = (yield* Ref.get(stateRef)).listeners;
|
||||
yield* Effect.forEach(listeners, (listener) => listener(servers), { discard: true });
|
||||
});
|
||||
const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
|
||||
(configuredUrls: ReadonlyArray<string>) =>
|
||||
scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
|
||||
);
|
||||
|
||||
const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
|
||||
const normalized = normalizeConfiguredUrls(configuredUrls);
|
||||
return scanSnapshot(normalized).pipe(
|
||||
Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
|
||||
);
|
||||
};
|
||||
|
||||
const pollTick = Effect.fn("PortDiscovery.pollTick")(
|
||||
function* () {
|
||||
if ((yield* Ref.get(stateRef)).retainCount <= 0) return;
|
||||
const next = yield* scanOnce();
|
||||
const changed = yield* Ref.modify(stateRef, (state) =>
|
||||
serversEqual(state.lastSnapshot, next)
|
||||
? [false, state]
|
||||
: [true, { ...state, lastSnapshot: next }],
|
||||
);
|
||||
if (changed) yield* broadcast(next);
|
||||
const configuredUrls = [
|
||||
...new Set(
|
||||
[...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
|
||||
(subscription) => subscription.configuredUrls,
|
||||
),
|
||||
),
|
||||
];
|
||||
const snapshot = yield* scanSnapshot(configuredUrls);
|
||||
const notifications = yield* Ref.modify(stateRef, (state) => {
|
||||
const listeners = new Map(state.listeners);
|
||||
const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
|
||||
for (const [listener, subscription] of listeners) {
|
||||
const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
|
||||
if (serversEqual(subscription.lastSnapshot, next)) continue;
|
||||
listeners.set(listener, { ...subscription, lastSnapshot: next });
|
||||
changed.push([listener, next]);
|
||||
}
|
||||
return [changed, { ...state, listeners }];
|
||||
});
|
||||
yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
|
||||
discard: true,
|
||||
});
|
||||
},
|
||||
Effect.catchCause((cause: Cause.Cause<never>) =>
|
||||
Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
|
||||
@@ -332,15 +602,19 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
);
|
||||
|
||||
const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
|
||||
(listener) =>
|
||||
(input, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Ref.update(stateRef, (state) => ({
|
||||
...state,
|
||||
listeners: new Set([...state.listeners, listener]),
|
||||
})),
|
||||
Ref.update(stateRef, (state) => {
|
||||
const listeners = new Map(state.listeners);
|
||||
listeners.set(listener, {
|
||||
configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
|
||||
lastSnapshot: input.initialSnapshot,
|
||||
});
|
||||
return { ...state, listeners };
|
||||
}),
|
||||
() =>
|
||||
Ref.update(stateRef, (state) => {
|
||||
const listeners = new Set(state.listeners);
|
||||
const listeners = new Map(state.listeners);
|
||||
listeners.delete(listener);
|
||||
return { ...state, listeners };
|
||||
}),
|
||||
|
||||
+15
-7
@@ -2131,23 +2131,31 @@ const makeWsRpcLayer = (
|
||||
observeRpcStream(WS_METHODS.subscribePreviewEvents, previewManager.events, {
|
||||
"rpc.aggregate": "preview",
|
||||
}),
|
||||
[WS_METHODS.subscribeDiscoveredLocalServers]: (_input) =>
|
||||
[WS_METHODS.subscribeDiscoveredLocalServers]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeDiscoveredLocalServers,
|
||||
Stream.callback<DiscoveredLocalServerList>((queue) =>
|
||||
Effect.gen(function* () {
|
||||
const configuredUrls = input.configuredUrls ?? [];
|
||||
yield* portDiscovery.retain;
|
||||
const initial = yield* portDiscovery.scan();
|
||||
const initial = yield* portDiscovery.scan(configuredUrls);
|
||||
const initialScannedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* Queue.offer(queue, {
|
||||
servers: initial,
|
||||
scannedAt: initialScannedAt,
|
||||
configuredUrlProbing: true,
|
||||
});
|
||||
yield* portDiscovery.subscribe((servers) =>
|
||||
Effect.gen(function* () {
|
||||
const scannedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* Queue.offer(queue, { servers, scannedAt });
|
||||
}),
|
||||
yield* portDiscovery.subscribe(
|
||||
{ configuredUrls, initialSnapshot: initial },
|
||||
(servers) =>
|
||||
Effect.gen(function* () {
|
||||
const scannedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* Queue.offer(queue, {
|
||||
servers,
|
||||
scannedAt,
|
||||
configuredUrlProbing: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -12,7 +12,6 @@ const mocks = vi.hoisted(() => ({
|
||||
pid: number | null;
|
||||
terminal: null;
|
||||
source: "scanner";
|
||||
listening: boolean;
|
||||
}>,
|
||||
}));
|
||||
|
||||
@@ -38,7 +37,6 @@ function server(port: number) {
|
||||
pid: 1,
|
||||
terminal: null,
|
||||
source: "scanner" as const,
|
||||
listening: true,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ interface Props {
|
||||
threadRef: ScopedThreadRef;
|
||||
environmentId: EnvironmentId;
|
||||
configuredUrls?: ReadonlyArray<string> | undefined;
|
||||
recentlySeenUrls?: ReadonlyArray<string> | undefined;
|
||||
recentEntries: ReadonlyArray<BrowserHistoryEntry>;
|
||||
onRemoveRecent: (url: string) => void;
|
||||
onOpenUrl: (url: string) => void;
|
||||
@@ -22,7 +21,6 @@ export function PreviewEmptyState({
|
||||
threadRef,
|
||||
environmentId,
|
||||
configuredUrls,
|
||||
recentlySeenUrls,
|
||||
recentEntries,
|
||||
onRemoveRecent,
|
||||
onOpenUrl,
|
||||
@@ -30,7 +28,6 @@ export function PreviewEmptyState({
|
||||
const servers = useDiscoveredLocalServers({
|
||||
environmentId,
|
||||
configuredUrls,
|
||||
recentlySeenUrls,
|
||||
});
|
||||
const recents = recentEntries.filter((entry) => URL.canParse(entry.url)).slice(0, 8);
|
||||
|
||||
@@ -42,7 +39,7 @@ export function PreviewEmptyState({
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>No preview yet</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Type a URL above, or run a dev script. Listening localhost ports will show up here
|
||||
Type a URL above, or run a dev script. Browser-ready localhost servers will show up here
|
||||
automatically.
|
||||
</EmptyDescription>
|
||||
</Empty>
|
||||
@@ -51,7 +48,7 @@ export function PreviewEmptyState({
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 overflow-y-auto px-5 py-8">
|
||||
<div className="m-auto flex w-full max-w-xl flex-col gap-6">
|
||||
<div className="mx-auto flex w-full max-w-xl flex-col gap-6">
|
||||
{recents.length > 0 ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
@@ -88,7 +85,7 @@ export function PreviewEmptyState({
|
||||
))}
|
||||
</div>
|
||||
<p className="px-1 text-xs text-muted-foreground">
|
||||
Select a listening port to open it in this browser tab.
|
||||
Select a live local server to open it in this browser tab.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -24,32 +24,11 @@ export function PreviewLocalServerCard({ threadRef, server, onOpen }: Props) {
|
||||
{server.host}:{server.port}
|
||||
</span>
|
||||
</div>
|
||||
{server.listening ? <PulsingDot /> : <DimDot />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function describeServer(server: PreviewableServer): string {
|
||||
if (server.processName) return server.processName;
|
||||
if (server.listening) return "Listening";
|
||||
if (server.source === "configured") return "Configured";
|
||||
return "Recently seen";
|
||||
}
|
||||
|
||||
function PulsingDot() {
|
||||
return (
|
||||
<span aria-label="Listening" className="relative inline-flex size-2 shrink-0">
|
||||
<span className="absolute inset-0 animate-status-ping rounded-full bg-success opacity-60" />
|
||||
<span className="relative inline-flex size-2 rounded-full bg-success" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function DimDot() {
|
||||
return (
|
||||
<span
|
||||
aria-label="Not currently listening"
|
||||
className="size-2 shrink-0 rounded-full bg-muted-foreground/40"
|
||||
/>
|
||||
);
|
||||
return "Listening";
|
||||
}
|
||||
@@ -713,7 +713,6 @@ export function PreviewView({
|
||||
threadRef={threadRef}
|
||||
environmentId={threadRef.environmentId}
|
||||
configuredUrls={configuredUrls}
|
||||
recentlySeenUrls={previewState.recentlySeenUrls}
|
||||
recentEntries={recentHistoryEntries}
|
||||
onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
|
||||
onOpenUrl={(next) => void handleOpenServerUrl(next)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { DiscoveredLocalServer } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { mergeServers, type PreviewableServer } from "./useDiscoveredLocalServers";
|
||||
import { mergeServers } from "./useDiscoveredLocalServers";
|
||||
|
||||
const scannerServer = (
|
||||
overrides: Partial<DiscoveredLocalServer & { requestedUrl: string }>,
|
||||
@@ -21,7 +21,6 @@ describe("mergeServers", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({})],
|
||||
configuredUrls: [],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
@@ -29,7 +28,6 @@ describe("mergeServers", () => {
|
||||
port: 5173,
|
||||
requestedUrl: "http://localhost:5173",
|
||||
source: "scanner",
|
||||
listening: true,
|
||||
processName: "vite",
|
||||
});
|
||||
});
|
||||
@@ -38,75 +36,97 @@ describe("mergeServers", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({ port: 5173, processName: "node", pid: 9999 })],
|
||||
configuredUrls: ["http://localhost:5173"],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
port: 5173,
|
||||
source: "configured",
|
||||
listening: true,
|
||||
processName: "node",
|
||||
pid: 9999,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps configured entries that the scanner doesn't see, with listening=false", () => {
|
||||
it("excludes configured entries that the live scanner doesn't see", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [],
|
||||
configuredUrls: ["http://localhost:5173"],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
source: "configured",
|
||||
listening: false,
|
||||
requestedUrl: "http://localhost:5173/",
|
||||
});
|
||||
});
|
||||
|
||||
it("dedupes recently-seen URLs against scanner+configured entries", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({ port: 5173 })],
|
||||
configuredUrls: [],
|
||||
recentlySeenUrls: ["http://localhost:5173/", "http://localhost:8080/"],
|
||||
});
|
||||
expect(result.map((s) => s.port)).toEqual([5173, 8080]);
|
||||
expect(result.find((s) => s.port === 5173)?.source).toBe("scanner");
|
||||
expect(result.find((s) => s.port === 8080)?.source).toBe("recent");
|
||||
expect(result.find((s) => s.port === 8080)?.requestedUrl).toBe("http://localhost:8080/");
|
||||
});
|
||||
|
||||
it("ignores non-loopback URLs in configured/recent inputs", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [],
|
||||
configuredUrls: ["https://example.com", "ws://localhost:5173"],
|
||||
recentlySeenUrls: ["https://api.example.com"],
|
||||
});
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("sorts: configured before scanner before recent, then by port", () => {
|
||||
it("ignores non-loopback configured URLs", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({})],
|
||||
configuredUrls: ["https://example.com", "ws://localhost:5173"],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.source).toBe("scanner");
|
||||
});
|
||||
|
||||
it("sorts configured live servers before scanner-only servers", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({ port: 8080 }), scannerServer({ port: 3000 })],
|
||||
configuredUrls: ["http://localhost:5173"],
|
||||
recentlySeenUrls: ["http://localhost:9000/", "http://localhost:4321/"],
|
||||
configuredUrls: ["http://localhost:8080"],
|
||||
});
|
||||
expect(result.map((s) => `${s.source}:${s.port}`)).toEqual([
|
||||
"configured:5173",
|
||||
"scanner:3000",
|
||||
"scanner:8080",
|
||||
"recent:4321",
|
||||
"recent:9000",
|
||||
]);
|
||||
expect(result.map((s) => `${s.source}:${s.port}`)).toEqual(["configured:8080", "scanner:3000"]);
|
||||
});
|
||||
|
||||
it("dedupes by lowercased host", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({ host: "Localhost", port: 5173 })],
|
||||
configuredUrls: ["http://localhost:5173"],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.source).toBe("configured");
|
||||
});
|
||||
|
||||
it.each(["127.0.0.1", "0.0.0.0", "[::1]"])(
|
||||
"matches configured loopback alias %s to a live localhost server",
|
||||
(host) => {
|
||||
const result = mergeServers({
|
||||
scanner: [
|
||||
scannerServer({ requestedUrl: `http://localhost:5173/dashboard?mode=test#results` }),
|
||||
],
|
||||
configuredUrls: [`http://${host}:5173/dashboard?mode=test#results`],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.source).toBe("configured");
|
||||
expect(result[0]?.requestedUrl).toBe("http://localhost:5173/dashboard?mode=test#results");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the scanner-verified path and protocol", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [
|
||||
scannerServer({
|
||||
url: "https://env-42.example.dev:5173/",
|
||||
requestedUrl: "http://localhost:5173/dashboard?mode=test#results",
|
||||
}),
|
||||
],
|
||||
configuredUrls: ["https://localhost:5173/dashboard?mode=test#results"],
|
||||
});
|
||||
expect(result[0]?.url).toBe("https://env-42.example.dev:5173/");
|
||||
expect(result[0]?.requestedUrl).toBe("http://localhost:5173/dashboard?mode=test#results");
|
||||
});
|
||||
|
||||
it("overlays a configured path when an older server does not advertise path probing", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({ requestedUrl: "http://localhost:5173/" })],
|
||||
configuredUrls: ["https://localhost:5173/docs?mode=test#results"],
|
||||
configuredUrlProbing: false,
|
||||
});
|
||||
|
||||
expect(result[0]?.requestedUrl).toBe("https://localhost:5173/docs?mode=test#results");
|
||||
});
|
||||
|
||||
it("does not overlay an unverified configured path when the server probes paths", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({ requestedUrl: "http://localhost:5173/" })],
|
||||
configuredUrls: ["http://localhost:5173/docs"],
|
||||
configuredUrlProbing: true,
|
||||
});
|
||||
|
||||
expect(result[0]?.requestedUrl).toBe("http://localhost:5173/");
|
||||
});
|
||||
|
||||
it("keeps a scanner entry's pre-resolution requestedUrl distinct from a resolved url", () => {
|
||||
@@ -119,21 +139,8 @@ describe("mergeServers", () => {
|
||||
}),
|
||||
],
|
||||
configuredUrls: [],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
expect(result[0]?.url).toBe("https://env-42.example.dev:5173/");
|
||||
expect(result[0]?.requestedUrl).toBe("http://localhost:5173/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PreviewableServer interface", () => {
|
||||
it("preserves listening flag through enrichment", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [scannerServer({})],
|
||||
configuredUrls: ["http://localhost:5173"],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
const merged: PreviewableServer | undefined = result[0];
|
||||
expect(merged?.listening).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -4,15 +4,10 @@ import { useMemo } from "react";
|
||||
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
import { useDiscoveredPorts } from "~/portDiscoveryState";
|
||||
import { useDiscoveredPortsState } from "~/portDiscoveryState";
|
||||
|
||||
export interface PreviewableServer extends DiscoveredLocalServer {
|
||||
source: "scanner" | "configured" | "recent";
|
||||
/**
|
||||
* True when the port scanner currently sees this server listening. A
|
||||
* `configured` entry can also be `listening` when the scan enriched it.
|
||||
*/
|
||||
listening: boolean;
|
||||
source: "scanner" | "configured";
|
||||
/**
|
||||
* Pre-resolution loopback url. `url` is the resolved navigation target
|
||||
* (volatile on a remote environment); history must key off this instead.
|
||||
@@ -23,99 +18,62 @@ export interface PreviewableServer extends DiscoveredLocalServer {
|
||||
interface UseDiscoveredLocalServersInput {
|
||||
environmentId: EnvironmentId;
|
||||
configuredUrls?: ReadonlyArray<string> | undefined;
|
||||
recentlySeenUrls?: ReadonlyArray<string> | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the environment-level port snapshot with configured / recently-seen
|
||||
* Enrich the environment-level live server snapshot with matching configured
|
||||
* URLs and return a stable sorted list.
|
||||
*/
|
||||
export function useDiscoveredLocalServers(
|
||||
input: UseDiscoveredLocalServersInput,
|
||||
): ReadonlyArray<PreviewableServer> {
|
||||
const scannerSnapshot = useDiscoveredPorts(input.environmentId);
|
||||
const scannerState = useDiscoveredPortsState(input.environmentId, input.configuredUrls);
|
||||
|
||||
return useMemo(
|
||||
() =>
|
||||
mergeServers({
|
||||
scanner: scannerSnapshot.map((server) => ({
|
||||
scanner: scannerState.servers.map((server) => ({
|
||||
...server,
|
||||
url: resolveDiscoveredServerUrl(input.environmentId, server.url),
|
||||
requestedUrl: server.url,
|
||||
})),
|
||||
configuredUrls: input.configuredUrls ?? [],
|
||||
recentlySeenUrls: input.recentlySeenUrls ?? [],
|
||||
configuredUrlProbing: scannerState.configuredUrlProbing,
|
||||
}),
|
||||
[input.environmentId, scannerSnapshot, input.configuredUrls, input.recentlySeenUrls],
|
||||
[input.environmentId, scannerState, input.configuredUrls],
|
||||
);
|
||||
}
|
||||
|
||||
export function mergeServers(input: {
|
||||
scanner: ReadonlyArray<DiscoveredLocalServer & { requestedUrl: string }>;
|
||||
configuredUrls: ReadonlyArray<string>;
|
||||
recentlySeenUrls: ReadonlyArray<string>;
|
||||
configuredUrlProbing?: boolean;
|
||||
}): ReadonlyArray<PreviewableServer> {
|
||||
const seen = new Map<string, PreviewableServer>();
|
||||
const configuredByServer = new Map<string, { host: string; port: number; url: string }>();
|
||||
|
||||
for (const url of input.configuredUrls) {
|
||||
const parsed = parseLocalUrl(url);
|
||||
if (!parsed) continue;
|
||||
const key = canonicalKey(parsed.host, parsed.port);
|
||||
if (seen.has(key)) continue;
|
||||
seen.set(key, {
|
||||
host: parsed.host,
|
||||
port: parsed.port,
|
||||
url: parsed.url,
|
||||
requestedUrl: parsed.url,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
source: "configured",
|
||||
listening: false,
|
||||
});
|
||||
if (!configuredByServer.has(key)) configuredByServer.set(key, parsed);
|
||||
}
|
||||
|
||||
const live: PreviewableServer[] = [];
|
||||
for (const server of input.scanner) {
|
||||
const key = canonicalKey(server.host, server.port);
|
||||
const existing = seen.get(key);
|
||||
if (existing) {
|
||||
// Enrich a configured entry with live process metadata; flip
|
||||
// `listening` so it pulses green like a scanner-discovered entry.
|
||||
seen.set(key, {
|
||||
...existing,
|
||||
processName: server.processName ?? existing.processName,
|
||||
pid: server.pid ?? existing.pid,
|
||||
terminal: server.terminal ?? existing.terminal,
|
||||
listening: true,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
seen.set(key, { ...server, source: "scanner", listening: true });
|
||||
}
|
||||
|
||||
for (const url of input.recentlySeenUrls) {
|
||||
const parsed = parseLocalUrl(url);
|
||||
if (!parsed) continue;
|
||||
const key = canonicalKey(parsed.host, parsed.port);
|
||||
if (seen.has(key)) continue;
|
||||
seen.set(key, {
|
||||
host: parsed.host,
|
||||
port: parsed.port,
|
||||
url: parsed.url,
|
||||
requestedUrl: parsed.url,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
source: "recent",
|
||||
listening: false,
|
||||
const configured = configuredByServer.get(key);
|
||||
live.push({
|
||||
...server,
|
||||
requestedUrl:
|
||||
configured && input.configuredUrlProbing === false ? configured.url : server.requestedUrl,
|
||||
source: configured ? "configured" : "scanner",
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(seen.values()).toSorted((a, b) => {
|
||||
return live.toSorted((a, b) => {
|
||||
const sourceOrder: Record<PreviewableServer["source"], number> = {
|
||||
configured: 0,
|
||||
scanner: 1,
|
||||
recent: 2,
|
||||
};
|
||||
if (sourceOrder[a.source] !== sourceOrder[b.source]) {
|
||||
return sourceOrder[a.source] - sourceOrder[b.source];
|
||||
@@ -125,7 +83,8 @@ export function mergeServers(input: {
|
||||
}
|
||||
|
||||
function canonicalKey(host: string, port: number): string {
|
||||
return `${host.toLowerCase()}:${port}`;
|
||||
const normalizedHost = host.toLowerCase();
|
||||
return `${isLoopbackHost(normalizedHost) ? "loopback" : normalizedHost}:${port}`;
|
||||
}
|
||||
|
||||
function parseLocalUrl(raw: string): { host: string; port: number; url: string } | null {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS, PREVIEW_URL_MAX_LENGTH } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { boundConfiguredLocalServerUrls } from "./portDiscoveryState";
|
||||
|
||||
describe("boundConfiguredLocalServerUrls", () => {
|
||||
it("keeps subscription payloads within the discovery RPC bounds", () => {
|
||||
const urls = Array.from(
|
||||
{ length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS + 1 },
|
||||
(_, index) => `http://localhost:${3_000 + index}`,
|
||||
);
|
||||
urls.unshift(
|
||||
"https://example.com",
|
||||
"not a URL",
|
||||
`http://localhost/${"a".repeat(PREVIEW_URL_MAX_LENGTH)}`,
|
||||
);
|
||||
|
||||
const bounded = boundConfiguredLocalServerUrls(urls);
|
||||
|
||||
expect(bounded).toHaveLength(CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS);
|
||||
expect(bounded.every((url) => url.startsWith("http://localhost:"))).toBe(true);
|
||||
});
|
||||
|
||||
it("does not let fragment-only variants crowd out another server", () => {
|
||||
const fragments = Array.from(
|
||||
{ length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
|
||||
(_, index) => `http://localhost:3000/docs#section-${index}`,
|
||||
);
|
||||
|
||||
expect(boundConfiguredLocalServerUrls([...fragments, "http://localhost:4000/app"])).toEqual([
|
||||
"http://localhost:3000/docs#section-0",
|
||||
"http://localhost:4000/app",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,11 @@
|
||||
import type { DiscoveredLocalServer, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
|
||||
PREVIEW_URL_MAX_LENGTH,
|
||||
type DiscoveredLocalServer,
|
||||
type EnvironmentId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isLoopbackHost } from "@t3tools/shared/preview";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { previewEnvironment } from "./state/preview";
|
||||
@@ -6,15 +13,63 @@ import { useEnvironmentQuery } from "./state/query";
|
||||
|
||||
const EMPTY_PORTS: ReadonlyArray<DiscoveredLocalServer> = Object.freeze([]);
|
||||
|
||||
interface DiscoveredPortsState {
|
||||
readonly servers: ReadonlyArray<DiscoveredLocalServer>;
|
||||
readonly configuredUrlProbing: boolean;
|
||||
}
|
||||
|
||||
export function boundConfiguredLocalServerUrls(
|
||||
urls: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
const bounded: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of urls ?? []) {
|
||||
if (raw.length === 0 || raw.length > PREVIEW_URL_MAX_LENGTH || raw.trim().length !== raw.length)
|
||||
continue;
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") continue;
|
||||
if (!isLoopbackHost(url.hostname) || url.href.length > PREVIEW_URL_MAX_LENGTH) continue;
|
||||
const resourceUrl = new URL(url.href);
|
||||
resourceUrl.hash = "";
|
||||
if (seen.has(resourceUrl.href)) continue;
|
||||
seen.add(resourceUrl.href);
|
||||
bounded.push(url.href);
|
||||
if (bounded.length >= CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS) break;
|
||||
} catch {
|
||||
// Invalid and non-local project preview URLs are not discovery candidates.
|
||||
}
|
||||
}
|
||||
return bounded;
|
||||
}
|
||||
|
||||
export function useDiscoveredPorts(
|
||||
environmentId: EnvironmentId | null,
|
||||
configuredUrls?: ReadonlyArray<string>,
|
||||
): ReadonlyArray<DiscoveredLocalServer> {
|
||||
return useDiscoveredPortsState(environmentId, configuredUrls).servers;
|
||||
}
|
||||
|
||||
export function useDiscoveredPortsState(
|
||||
environmentId: EnvironmentId | null,
|
||||
configuredUrls?: ReadonlyArray<string>,
|
||||
): DiscoveredPortsState {
|
||||
const boundedConfiguredUrls = boundConfiguredLocalServerUrls(configuredUrls);
|
||||
const query = useEnvironmentQuery(
|
||||
environmentId === null
|
||||
? null
|
||||
: previewEnvironment.discoveredServers({ environmentId, input: {} }),
|
||||
: previewEnvironment.discoveredServers({
|
||||
environmentId,
|
||||
input: boundedConfiguredUrls.length ? { configuredUrls: boundedConfiguredUrls } : {},
|
||||
}),
|
||||
);
|
||||
return useMemo(
|
||||
() => ({
|
||||
servers: query.data?.servers ?? EMPTY_PORTS,
|
||||
configuredUrlProbing: query.data?.configuredUrlProbing === true,
|
||||
}),
|
||||
[query.data?.configuredUrlProbing, query.data?.servers],
|
||||
);
|
||||
return query.data?.servers ?? EMPTY_PORTS;
|
||||
}
|
||||
|
||||
export function useThreadDiscoveredPorts(input: {
|
||||
|
||||
@@ -41,6 +41,9 @@ export function createPreviewEnvironmentAtoms<R, E>(
|
||||
discoveredServers: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
|
||||
label: "environment-data:preview:discovered-servers",
|
||||
tag: WS_METHODS.subscribeDiscoveredLocalServers,
|
||||
// Configured URLs are part of this atom's key. Dispose immediately so
|
||||
// unmounted projects stop contributing probe candidates on the server.
|
||||
idleTtlMs: 0,
|
||||
}),
|
||||
automationRequests: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
|
||||
label: "environment-data:preview:automation-requests",
|
||||
|
||||
@@ -2,7 +2,10 @@ import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
ConfiguredLocalServerUrls,
|
||||
CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
|
||||
DiscoveredLocalServer,
|
||||
PREVIEW_URL_MAX_LENGTH,
|
||||
PreviewEvent,
|
||||
PreviewNavStatus,
|
||||
PreviewSessionSnapshot,
|
||||
@@ -21,6 +24,7 @@ const decodePreviewEvent = Schema.decodeUnknownSync(PreviewEvent);
|
||||
const decodeSnapshot = Schema.decodeUnknownSync(PreviewSessionSnapshot);
|
||||
const decodeNavStatus = Schema.decodeUnknownSync(PreviewNavStatus);
|
||||
const decodeServer = Schema.decodeUnknownSync(DiscoveredLocalServer);
|
||||
const decodeConfiguredLocalServerUrls = Schema.decodeUnknownSync(ConfiguredLocalServerUrls);
|
||||
const decodeViewport = Schema.decodeUnknownSync(PreviewViewportSetting);
|
||||
const decodeResizeInput = Schema.decodeUnknownSync(PreviewAutomationResizeInput);
|
||||
const decodeOpenInput = Schema.decodeUnknownSync(PreviewAutomationOpenInput);
|
||||
@@ -342,3 +346,19 @@ describe("DiscoveredLocalServer", () => {
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ConfiguredLocalServerUrls", () => {
|
||||
it("bounds the number and length of probe candidates", () => {
|
||||
expect(() =>
|
||||
decodeConfiguredLocalServerUrls(
|
||||
Array.from(
|
||||
{ length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS + 1 },
|
||||
(_, index) => `http://localhost:${3_000 + index}`,
|
||||
),
|
||||
),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
decodeConfiguredLocalServerUrls([`http://localhost/${"a".repeat(PREVIEW_URL_MAX_LENGTH)}`]),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,14 @@
|
||||
import { Schema } from "effect";
|
||||
import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
|
||||
const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(2048));
|
||||
export const PREVIEW_URL_MAX_LENGTH = 2_048;
|
||||
export const CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS = 32;
|
||||
|
||||
const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(PREVIEW_URL_MAX_LENGTH));
|
||||
|
||||
export const ConfiguredLocalServerUrls = Schema.Array(Url).check(
|
||||
Schema.isMaxLength(CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS),
|
||||
);
|
||||
const Title = Schema.String.check(Schema.isMaxLength(512));
|
||||
|
||||
export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
|
||||
@@ -272,6 +279,7 @@ export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
|
||||
export const DiscoveredLocalServerList = Schema.Struct({
|
||||
servers: Schema.Array(DiscoveredLocalServer),
|
||||
scannedAt: Schema.String,
|
||||
configuredUrlProbing: Schema.optional(Schema.Literal(true)),
|
||||
});
|
||||
export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
|
||||
|
||||
|
||||
@@ -129,6 +129,7 @@ import {
|
||||
} from "./terminal.ts";
|
||||
import {
|
||||
DiscoveredLocalServerList,
|
||||
ConfiguredLocalServerUrls,
|
||||
PreviewCloseInput,
|
||||
PreviewError,
|
||||
PreviewEvent,
|
||||
@@ -849,7 +850,9 @@ export const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewE
|
||||
export const WsSubscribeDiscoveredLocalServersRpc = Rpc.make(
|
||||
WS_METHODS.subscribeDiscoveredLocalServers,
|
||||
{
|
||||
payload: Schema.Struct({}),
|
||||
payload: Schema.Struct({
|
||||
configuredUrls: Schema.optional(ConfiguredLocalServerUrls),
|
||||
}),
|
||||
success: DiscoveredLocalServerList,
|
||||
error: EnvironmentAuthorizationError,
|
||||
stream: true,
|
||||
|
||||
Reference in new issue
Block a user