Files
hyperframes/packages/cli/src/utils/studioSelectionClient.ts
T
JasonandWhoosh 6e8454d6d5 fix(cli): bound the loopback Studio probe so a dropped connection costs 1 s, not 10 (#6466)
Some hosts drop a connection to a closed loopback port instead of refusing it
(WSL 2 mirrored networking, a firewall in stealth mode). The Vite Studio probe
on 127.0.0.1:5190 then waits for fetch's 10 s connect timeout, and since
every render, check and snapshot looks for a Studio through the history owner,
each of them paid 10 s. Aborting the fetch does not help: the connect attempt
keeps its socket, and the process, alive for the full 10 s.

The default probe now connects with node:net under a 1 s bound and destroys
the socket, then fetches only from a host that accepted.

Co-authored-by: Whoosh <nhatkha1407@gmail.com>
2026-11-05 02:38:12 +00:00

189 lines
6.6 KiB
TypeScript

import { existsSync, realpathSync } from "node:fs";
import { connect } from "node:net";
import { resolve } from "node:path";
import { scanActiveServers, type ActiveServer } from "../server/portUtils.js";
import type {
LintResult,
ResolvedProject,
StudioSelectionResponse,
} from "@hyperframes/studio-server";
export type StudioLintResponse = LintResult;
const VITE_STUDIO_DISCOVERY_PORTS = [5190] as const;
interface StudioProjectsResponse {
projects?: ResolvedProject[];
}
interface FindPreviewServerOptions {
preferredPort?: number;
}
export class AmbiguousPreviewServerError extends Error {
readonly ports: number[];
constructor(servers: ActiveServer[]) {
const ports = servers.map((server) => server.port).sort((a, b) => a - b);
super(
`Multiple Studio preview servers match this project (${ports.join(", ")}). Pass --port <port> to choose one.`,
);
this.name = "AmbiguousPreviewServerError";
this.ports = ports;
}
}
export class PreviewServerPortMismatchError extends Error {
readonly requestedPort: number;
readonly ports: number[];
constructor(requestedPort: number, servers: ActiveServer[], hint = "") {
const ports = servers.map((server) => server.port).sort((a, b) => a - b);
super(
`No Studio preview server for this project is running on port ${requestedPort}. Matching server port${ports.length === 1 ? "" : "s"}: ${ports.join(", ")}. Rerun with --port ${ports[0]}${ports.length > 1 ? " or omit --port to see all candidates" : ""}.${hint}`,
);
this.name = "PreviewServerPortMismatchError";
this.requestedPort = requestedPort;
this.ports = ports;
}
}
function normalizePath(path: string): string {
const resolved = resolve(path);
try {
if (existsSync(resolved)) {
return realpathSync(resolved).replace(/\\/g, "/").toLowerCase();
}
} catch {
// Fall through to resolved-path normalization.
}
return resolved.replace(/\\/g, "/").toLowerCase();
}
// A Studio on loopback accepts a connection in milliseconds.
const LOOPBACK_CONNECT_TIMEOUT_MS = 1000;
/**
* Fetches from a loopback Studio only once a bounded connect succeeds. Some
* hosts drop a connection to a closed port instead of refusing it (WSL
* mirrored networking, a firewall in stealth mode): fetch then waits for its
* 10 s connect timeout, and aborting it does not close the socket, so the
* command's process stays alive that long anyway. A destroyed socket does not.
*/
export async function fetchLoopback(url: string): Promise<Response> {
const { hostname, port } = new URL(url);
const host = hostname.replace(/^\[|\]$/g, "");
await new Promise<void>((accept, refuse) => {
const socket = connect({ host, port: Number(port) });
const close = (error?: Error) => {
socket.destroy();
if (error) refuse(error);
else accept();
};
socket.setTimeout(LOOPBACK_CONNECT_TIMEOUT_MS, () =>
close(new Error(`connect to ${host}:${port} timed out`)),
);
socket.once("connect", () => close());
socket.once("error", close);
});
return fetch(url);
}
export async function findPreviewServerForProject(
projectDir: string,
startPort = 3002,
scan: (startPort?: number) => Promise<ActiveServer[]> = scanActiveServers,
fetchImpl: (url: string) => Promise<Response> = fetchLoopback,
options: FindPreviewServerOptions = {},
): Promise<ActiveServer | null> {
const normalizedProjectDir = normalizePath(projectDir);
const servers = await scan(startPort);
const embeddedServers = servers.filter(
(server) => normalizePath(server.projectDir) === normalizedProjectDir,
);
if (options.preferredPort !== undefined) {
const preferred = embeddedServers.find((server) => server.port === options.preferredPort);
if (preferred) return preferred;
const viteServer = await findViteStudioServerForProject(normalizedProjectDir, fetchImpl, [
options.preferredPort,
]);
if (viteServer) return viteServer;
if (embeddedServers.length > 0) {
throw new PreviewServerPortMismatchError(options.preferredPort, embeddedServers);
}
return null;
}
if (embeddedServers.length === 1) return embeddedServers[0]!;
if (embeddedServers.length > 1) throw new AmbiguousPreviewServerError(embeddedServers);
return findViteStudioServerForProject(normalizedProjectDir, fetchImpl);
}
export function studioSelectionUrl(server: ActiveServer): string {
return studioApiUrl(server, "selection");
}
export function studioApiUrl(server: ActiveServer, route: string): string {
const host = server.host ?? "127.0.0.1";
return `http://${host}:${server.port}/api/projects/${encodeURIComponent(server.projectName)}/${route}`;
}
// Vite dev servers bind IPv6 loopback (`::1`) by default while embedded servers
// bind IPv4 (`127.0.0.1`), so probe both — a single family misses the other and
// is exactly why `--selection`/`--context` failed against a local-studio preview.
const LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"] as const;
async function findViteStudioServerForProject(
normalizedProjectDir: string,
fetchImpl: (url: string) => Promise<Response>,
ports: readonly number[] = VITE_STUDIO_DISCOVERY_PORTS,
): Promise<ActiveServer | null> {
for (const port of ports) {
for (const host of LOOPBACK_HOSTS) {
try {
const response = await fetchImpl(`http://${host}:${port}/api/projects`);
if (!response.ok) continue;
const payload = (await response.json()) as StudioProjectsResponse;
const project = payload.projects?.find(
(candidate) => normalizePath(candidate.dir) === normalizedProjectDir,
);
if (!project) continue;
return {
port,
host,
projectName: project.id,
projectDir: project.dir,
version: "studio-dev",
pid: null,
};
} catch {
// Not a Vite-served Studio on this host/port, or unreachable. Try next.
}
}
}
return null;
}
export async function fetchStudioSelection(
server: ActiveServer,
fetchImpl: typeof fetch = fetch,
): Promise<StudioSelectionResponse> {
const url = studioSelectionUrl(server);
const response = await fetchImpl(url);
if (!response.ok) {
throw new Error(`selection endpoint returned ${response.status}`);
}
return (await response.json()) as StudioSelectionResponse;
}
export async function fetchStudioLint(
server: ActiveServer,
fetchImpl: typeof fetch = fetch,
): Promise<StudioLintResponse> {
const url = studioApiUrl(server, "lint");
const response = await fetchImpl(url);
if (!response.ok) {
throw new Error(`lint endpoint returned ${response.status}`);
}
return (await response.json()) as StudioLintResponse;
}