Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,12 @@ describe("DesktopBackendConfiguration", () => {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;

const first = yield* configuration.resolvePrimary;
const second = yield* configuration.resolvePrimary;
const first = yield* configuration.resolvePrimary.pipe(
Effect.provideService(HostProcess.Environment, {}),
);
const second = yield* configuration.resolvePrimary.pipe(
Effect.provideService(HostProcess.Environment, { UV_THREADPOOL_SIZE: "" }),
);

assert.equal(first.executablePath, process.execPath);
assert.deepEqual(first.args.slice(0, 3), [
Expand All @@ -242,6 +246,8 @@ describe("DesktopBackendConfiguration", () => {
assert.equal(first.cwd, environment.backendCwd);
assert.equal(first.captureOutput, true);
assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
assert.equal(first.env.UV_THREADPOOL_SIZE, "16");
assert.equal(second.env.UV_THREADPOOL_SIZE, "");
assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "1");
assert.isUndefined(first.env.T3CODE_PORT);
assert.isUndefined(first.env.T3CODE_MODE);
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/backend/DesktopBackendConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const backendExposure = yield* serverExposure.backendConfig;
const hostEnv = yield* HostProcess.Environment;

const bootstrap = {
mode: "desktop" as const,
Expand Down Expand Up @@ -573,6 +574,8 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
env: {
...backendChildEnvPatch(),
ELECTRON_RUN_AS_NODE: "1",
// A hung getaddrinfo holds a libuv thread for good; the default four starve everything else.
UV_THREADPOOL_SIZE: hostEnv.UV_THREADPOOL_SIZE ?? "16",
T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
[DESKTOP_HOST_SCOPE_ENV]: input.hostScope,
Expand Down
26 changes: 16 additions & 10 deletions apps/server/src/binCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Layer from "effect/Layer";
import { Argument, Command } from "effect/cli";
import * as CliError from "effect/cli/CliError";
Expand Down Expand Up @@ -121,16 +122,21 @@ export const cli = makeCli();

export function runCli() {
extendConnectionAttemptTimeout();
keepOutboundFetchOnHttp1();
offerCliInstall({
args: process.argv.slice(2),
// A child started over IPC (a service launcher) has no one to answer.
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY) && process.send === undefined,
foreground: inTerminalForeground,
confirm: confirmCliInstall,
}).pipe(
// The offer handles its own errors; even an unexpected defect must not stop the command.
Effect.catchDefect(() => Effect.succeed(true)),
HostProcess.Platform.pipe(
Effect.map(keepOutboundFetchOnHttp1),
Effect.andThen(
offerCliInstall({
args: process.argv.slice(2),
// A child started over IPC (a service launcher) has no one to answer.
interactive:
Boolean(process.stdin.isTTY && process.stdout.isTTY) && process.send === undefined,
foreground: inTerminalForeground,
confirm: confirmCliInstall,
}).pipe(
// The offer handles its own errors; even an unexpected defect must not stop the command.
Effect.catchDefect(() => Effect.succeed(true)),
),
),
Effect.flatMap((proceed) =>
proceed
? Command.run(cli, { version: packageJson.version })
Expand Down
162 changes: 161 additions & 1 deletion apps/server/src/outboundHttp.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates.
import * as NodeDns from "node:dns";
import * as NodeHttp from "node:http";
import * as NodeHttp2 from "node:http2";
import * as NodeNet from "node:net";
import * as NodeTls from "node:tls";
Expand All @@ -10,12 +12,13 @@ import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { FetchHttpClient, HttpClient } from "effect/http";
import * as Undici from "undici";
import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
import { afterAll, afterEach, beforeAll, describe, expect, vi } from "vite-plus/test";

import {
builtinFetchUsesHttp2,
ignoreMacosTypeOfServiceEinval,
installHttp1FetchDispatcher,
makeBoundedLookup,
} from "./outboundHttp.ts";

// Non-secret, self-signed 127.0.0.1 certificate, valid until 2126; ALPN h2 requires TLS.
Expand Down Expand Up @@ -55,6 +58,7 @@ beforeAll(async () => {
});

afterEach(() => {
vi.useRealTimers();
Undici.setGlobalDispatcher(defaultDispatcher);
NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(defaultAttemptTimeout);
});
Expand Down Expand Up @@ -164,3 +168,159 @@ if (calls === 0) throw new Error("fetch did not call setTypeOfService");
}).pipe(Effect.provide(NodeServices.layer)),
);
});

describe("makeBoundedLookup", () => {
type Callback = (
error: NodeJS.ErrnoException | null,
address?: string | Array<NodeDns.LookupAddress>,
family?: number,
) => void;
const hangingLookup = () => {};
const resolverOf = (v4: Array<string>, v6: Array<string> = []) => ({
resolve4: (_host: string, cb: (error: Error | null, found?: Array<string>) => void) =>
cb(null, v4),
resolve6: (_host: string, cb: (error: Error | null, found?: Array<string>) => void) =>
cb(null, v6),
});
const run = (
lookup: ReturnType<typeof makeBoundedLookup>,
options: Parameters<typeof lookup>[1],
) =>
new Promise<{
error: NodeJS.ErrnoException | null;
address?: string | Array<NodeDns.LookupAddress> | undefined;
family?: number | undefined;
}>((resolve) =>
lookup("example.test", options, (error, address, family) =>
resolve({ error, address, family }),
),
);

const afterDeadline = <A>(pending: Promise<A>) => {
vi.advanceTimersByTime(10);
return pending;
};

it("passes a prompt dns.lookup answer through untouched", async () => {
const lookup = makeBoundedLookup({
timeoutMs: 50,
lookup: (_host, _options, cb) => cb(null, "10.0.0.1", 4),
resolver: resolverOf(["9.9.9.9"]),
});
expect(await run(lookup, {})).toEqual({ error: null, address: "10.0.0.1", family: 4 });
});

it("falls back to c-ares when getaddrinfo hangs, honoring family and all", async () => {
vi.useFakeTimers();
const lookup = makeBoundedLookup({
timeoutMs: 10,
Comment thread
yordis marked this conversation as resolved.
Resolved
lookup: hangingLookup,
resolver: resolverOf(["192.0.2.1"], ["2001:db8::1"]),
});
expect(await afterDeadline(run(lookup, { family: 4 }))).toEqual({
error: null,
address: "192.0.2.1",
family: 4,
});
expect(await afterDeadline(run(lookup, { family: 6 }))).toEqual({
error: null,
address: "2001:db8::1",
family: 6,
});
expect(await afterDeadline(run(lookup, { all: true }))).toEqual({
error: null,
address: [
{ address: "192.0.2.1", family: 4 },
{ address: "2001:db8::1", family: 6 },
],
family: undefined,
});
});

it("ignores a late getaddrinfo answer after the fallback replied", async () => {
vi.useFakeTimers();
let late: Callback = () => {};
const lookup = makeBoundedLookup({
timeoutMs: 10,
lookup: (_host, _options, cb) => {
late = cb;
},
resolver: resolverOf(["192.0.2.1"]),
});
const calls: Array<unknown> = [];
await afterDeadline(
new Promise<void>((resolve) =>
lookup("example.test", { family: 4 }, (error, address) => {
calls.push(error ?? address);
resolve();
}),
),
);
late(null, "10.9.9.9", 4);
expect(calls).toEqual(["192.0.2.1"]);
});

it("reports ENOTFOUND when the fallback finds nothing", async () => {
vi.useFakeTimers();
const lookup = makeBoundedLookup({
timeoutMs: 10,
lookup: hangingLookup,
resolver: resolverOf([]),
});
expect((await afterDeadline(run(lookup, { family: 4 }))).error?.code).toBe("ENOTFOUND");
});

it("lets undici connect through the bounded lookup while getaddrinfo hangs", async () => {
installHttp1FetchDispatcher({
lookup: makeBoundedLookup({
timeoutMs: 10,
lookup: hangingLookup,
resolver: resolverOf(["127.0.0.1"]),
}),
});
const plain = NodeHttp.createServer((_request, response) => response.end("resolved"));
await new Promise<void>((resolve) => plain.listen(0, "127.0.0.1", resolve));
try {
const port = (plain.address() as NodeNet.AddressInfo).port;
const response = await Undici.request(`http://hung-dns.test:${port}/`);
expect(await response.body.text()).toBe("resolved");
} finally {
await new Promise<void>((resolve) => plain.close(() => resolve()));
}
});

it("resolves an env proxy hostname through the bounded lookup for HTTPS requests", async () => {
const proxy = NodeHttp.createServer();
// CONNECT sockets leave the server's connection tracking, so closeAllConnections misses them.
const tunnels: Array<NodeNet.Socket> = [];
proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => {
const [host, port] = (request.url ?? "").split(":");
const upstream = NodeNet.connect(Number(port), host, () => {
client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
upstream.pipe(client);
client.pipe(upstream);
});
tunnels.push(client, upstream);
});
await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve));
try {
const proxyUrl = `http://hung-proxy.test:${(proxy.address() as NodeNet.AddressInfo).port}`;
for (const name of ["https_proxy", "HTTPS_PROXY"]) vi.stubEnv(name, proxyUrl);
for (const name of ["no_proxy", "NO_PROXY"]) vi.stubEnv(name, "");
Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent());
installHttp1FetchDispatcher({
lookup: makeBoundedLookup({
timeoutMs: 10,
lookup: hangingLookup,
resolver: resolverOf(["127.0.0.1"]),
}),
});
expect(await versionViaGlobalDispatcher()).toBe("1.1");
} finally {
vi.unstubAllEnvs();
for (const socket of tunnels) socket.destroy();
proxy.closeAllConnections();
await new Promise<void>((resolve) => proxy.close(() => resolve()));
Comment thread
yordis marked this conversation as resolved.
Resolved
}
});
});
Loading
Loading