mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(engine): a capture proxy shared by many browsers no longer drops tunnels at 128 (#8362)
* fix(engine): a capture proxy shared by many browsers no longer drops tunnels at 128 * fix(engine): keep the worker ceiling's reasons beside its use
This commit is contained in:
@@ -27,6 +27,9 @@ import {
|
||||
type BeforeCaptureHook,
|
||||
} from "./frameCapture.js";
|
||||
import { psnrDb, resolveDeVerifyMinDb } from "../utils/psnr.js";
|
||||
// Hard ceiling on `--workers N`: past it, CDP dispatch through Node's event loop and OS scheduling noise
|
||||
// outweigh more parallelism. Raised 10 -> 24 in hf#732 so 32-96+ core hosts can use their cores.
|
||||
import { ABSOLUTE_MAX_WORKERS } from "../utils/workerLimits.js";
|
||||
import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
|
||||
import { assertSwiftShader } from "../utils/assertSwiftShader.js";
|
||||
import { readWebGlVendorInfoFromCanvas } from "../utils/readWebGlVendorInfoFromCanvas.js";
|
||||
@@ -167,12 +170,6 @@ const APPLE_DISK_CORES_PER_WORKER = 1.75;
|
||||
const APPLE_DISK_MAX_WORKERS = 8;
|
||||
const MIN_WORKERS = 1;
|
||||
const MAX_WORKER_DIAGNOSTIC_LINES = 8;
|
||||
// Hard ceiling on explicit `--workers N` requests. Above this, the cost of
|
||||
// CDP-protocol dispatch through Node's main event loop and OS scheduling
|
||||
// noise overwhelms any further parallelism. Bumped from 10 → 24 in hf#732
|
||||
// follow-up so high-core hosts (32-96+ cores) can actually surface the
|
||||
// hardware to renders that are CPU-bound on DOM capture.
|
||||
const ABSOLUTE_MAX_WORKERS = 24;
|
||||
// `auto` concurrency picks this many workers as the upper bound. Bumped
|
||||
// from a hardcoded 6 → CPU-scaled value (floor(cpuCount/8), floor at 6,
|
||||
// ceiling at 16) in hf#732 follow-up. Rationale: the prior fixed cap of 6
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createServer, request } from "node:http";
|
||||
import { connect } from "node:net";
|
||||
import {
|
||||
connect,
|
||||
createServer as createTcpServer,
|
||||
type Server as TcpServer,
|
||||
type Socket,
|
||||
} from "node:net";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { logRefusal, onRenderRefusal, startCaptureProxy } from "./captureProxy.js";
|
||||
import {
|
||||
BROWSER_PROXY_MAX_CONNECTIONS,
|
||||
logRefusal,
|
||||
onRenderRefusal,
|
||||
POD_PROXY_MAX_CONNECTIONS,
|
||||
startCaptureProxy,
|
||||
type CaptureFailure,
|
||||
} from "./captureProxy.js";
|
||||
import { ABSOLUTE_MAX_WORKERS } from "../../utils/workerLimits.js";
|
||||
import { NonPublicHostError } from "./publicNetwork.js";
|
||||
|
||||
const { resolveAddress } = vi.hoisted(() => ({ resolveAddress: vi.fn() }));
|
||||
@@ -155,6 +168,84 @@ describe("capture proxy", () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("connection cap", () => {
|
||||
const sockets: Socket[] = [];
|
||||
const targets: TcpServer[] = [];
|
||||
afterEach(async () => {
|
||||
for (const socket of sockets.splice(0)) socket.destroy();
|
||||
await Promise.all(targets.splice(0).map((t) => new Promise((resolve) => t.close(resolve))));
|
||||
});
|
||||
|
||||
async function tcpTarget(): Promise<number> {
|
||||
const target = createTcpServer((socket) => socket.on("error", () => {}));
|
||||
targets.push(target);
|
||||
await new Promise<void>((resolve) => target.listen(0, "127.0.0.1", resolve));
|
||||
return (target.address() as { port: number }).port;
|
||||
}
|
||||
|
||||
/** The first status line the proxy answers a held-open CONNECT with, or "closed" when it drops the socket. */
|
||||
function openTunnel(proxyUrl: string, port: number): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const socket = connect(Number(new URL(proxyUrl).port), "127.0.0.1", () =>
|
||||
socket.write(
|
||||
`CONNECT tunnel.example.com:${port} HTTP/1.1\r\nHost: tunnel.example.com\r\n\r\n`,
|
||||
),
|
||||
);
|
||||
sockets.push(socket);
|
||||
socket.on("error", () => {});
|
||||
socket.once("data", (data) => resolve(String(data).split("\r\n")[0]!));
|
||||
socket.once("close", () => resolve("closed"));
|
||||
});
|
||||
}
|
||||
|
||||
it("holds more tunnels open at once than a browser's cap when given a pod's cap", async () => {
|
||||
resolveAddress.mockResolvedValue("127.0.0.1");
|
||||
const port = await tcpTarget();
|
||||
const proxy = await startCaptureProxy(null, undefined, undefined, { maxConnections: 200 });
|
||||
proxies.push(proxy);
|
||||
const answers = await Promise.all(
|
||||
Array.from({ length: 150 }, () => openTunnel(proxy.url, port)),
|
||||
);
|
||||
expect(answers.filter((a) => a === "HTTP/1.1 200 Connection Established")).toHaveLength(150);
|
||||
});
|
||||
|
||||
it("reports a connection dropped at the cap, with the count of open connections", async () => {
|
||||
resolveAddress.mockResolvedValue("127.0.0.1");
|
||||
const port = await tcpTarget();
|
||||
const failures: CaptureFailure[] = [];
|
||||
const proxy = await startCaptureProxy(null, undefined, undefined, {
|
||||
onFailed: (failure) => failures.push(failure),
|
||||
});
|
||||
proxies.push(proxy);
|
||||
const answers = await Promise.all(
|
||||
Array.from({ length: BROWSER_PROXY_MAX_CONNECTIONS + 1 }, () =>
|
||||
openTunnel(proxy.url, port),
|
||||
),
|
||||
);
|
||||
expect(answers.filter((a) => a === "closed")).toHaveLength(1);
|
||||
expect(failures).toEqual([{ reason: "connection_cap", open: BROWSER_PROXY_MAX_CONNECTIONS }]);
|
||||
});
|
||||
|
||||
it("reports a tunnel whose upstream never connects", async () => {
|
||||
resolveAddress.mockResolvedValue("127.0.0.1");
|
||||
const closedPort = await tcpTarget();
|
||||
await new Promise((resolve) => targets.pop()!.close(resolve));
|
||||
const failures: CaptureFailure[] = [];
|
||||
const proxy = await startCaptureProxy(null, undefined, undefined, {
|
||||
onFailed: (failure) => failures.push(failure),
|
||||
});
|
||||
proxies.push(proxy);
|
||||
expect(await openTunnel(proxy.url, closedPort)).toBe("closed");
|
||||
expect(failures).toEqual([{ reason: "upstream_failed", open: 1 }]);
|
||||
});
|
||||
|
||||
it("sizes a pod's cap for every browser the engine can run at once, plus the pod's own traffic", () => {
|
||||
expect(POD_PROXY_MAX_CONNECTIONS).toBe(
|
||||
(ABSOLUTE_MAX_WORKERS + 1) * BROWSER_PROXY_MAX_CONNECTIONS,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("closes idle CONNECT clients during teardown", async () => {
|
||||
const proxy = await startCaptureProxy();
|
||||
proxies.push(proxy);
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type UpstreamProxy,
|
||||
} from "./upstreamProxy.js";
|
||||
import { listenOnBrowserSafePort } from "../../utils/browserSafePort.js";
|
||||
import { ABSOLUTE_MAX_WORKERS } from "../../utils/workerLimits.js";
|
||||
|
||||
const CONNECTION_TIMEOUT_MS = 15_000;
|
||||
const HOP_HEADERS = new Set([
|
||||
@@ -55,6 +56,19 @@ function destination(raw: string, tunnel: boolean): URL {
|
||||
|
||||
type OnRefused = (hostClass: RefusedHostClass) => void;
|
||||
|
||||
export const BROWSER_PROXY_MAX_CONNECTIONS = 128;
|
||||
export const POD_PROXY_MAX_CONNECTIONS = (ABSOLUTE_MAX_WORKERS + 1) * BROWSER_PROXY_MAX_CONNECTIONS;
|
||||
|
||||
export interface CaptureFailure {
|
||||
reason: "connection_cap" | "upstream_failed";
|
||||
open: number;
|
||||
}
|
||||
type OnFailed = (failure: CaptureFailure) => void;
|
||||
|
||||
export const logFailure: OnFailed = ({ reason, open }) => {
|
||||
console.warn(`[CaptureProxy:FAILED] reason=${reason} open=${open}`);
|
||||
};
|
||||
|
||||
const refusalListeners = new Set<OnRefused>();
|
||||
|
||||
export function onRenderRefusal(listener: OnRefused): () => void {
|
||||
@@ -91,6 +105,7 @@ async function forwardHttp(
|
||||
sockets: Set<Socket>,
|
||||
proxy: UpstreamProxy | undefined,
|
||||
onRefused: OnRefused | undefined,
|
||||
fail: () => void,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const url = destination(incoming.url ?? "", false);
|
||||
@@ -118,6 +133,7 @@ async function forwardHttp(
|
||||
upstream.destroy(new Error("Capture request timed out")),
|
||||
);
|
||||
upstream.on("error", () => {
|
||||
fail();
|
||||
if (!response.headersSent) response.writeHead(502, { Connection: "close" });
|
||||
response.end();
|
||||
});
|
||||
@@ -143,6 +159,7 @@ async function forwardTunnelViaUpstream(
|
||||
client: Duplex,
|
||||
head: Buffer,
|
||||
sockets: Set<Socket>,
|
||||
fail: () => void,
|
||||
): Promise<void> {
|
||||
let upstream: Socket;
|
||||
try {
|
||||
@@ -150,6 +167,7 @@ async function forwardTunnelViaUpstream(
|
||||
onSocket: (socket) => trackSocket(socket, sockets),
|
||||
});
|
||||
} catch {
|
||||
fail();
|
||||
if (!client.destroyed) {
|
||||
client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
||||
}
|
||||
@@ -172,12 +190,13 @@ async function forwardTunnel(
|
||||
sockets: Set<Socket>,
|
||||
proxy: UpstreamProxy | undefined,
|
||||
onRefused: OnRefused | undefined,
|
||||
fail: () => void,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const url = destination(incoming.url ?? "", true);
|
||||
if (proxy) {
|
||||
assertPublicHostname(url.hostname);
|
||||
return await forwardTunnelViaUpstream(url, proxy, client, head, sockets);
|
||||
return await forwardTunnelViaUpstream(url, proxy, client, head, sockets, fail);
|
||||
}
|
||||
const address = await resolvePublicAddress(url.hostname);
|
||||
if (client.destroyed) return;
|
||||
@@ -187,7 +206,9 @@ async function forwardTunnel(
|
||||
connectDeadline.unref();
|
||||
upstream.once("close", () => clearTimeout(connectDeadline));
|
||||
upstream.setTimeout(CONNECTION_TIMEOUT_MS, () => upstream.destroy());
|
||||
let connected = false;
|
||||
upstream.once("connect", () => {
|
||||
connected = true;
|
||||
clearTimeout(connectDeadline);
|
||||
if (client.destroyed) return upstream.destroy();
|
||||
client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
|
||||
@@ -195,7 +216,10 @@ async function forwardTunnel(
|
||||
upstream.pipe(client);
|
||||
client.pipe(upstream);
|
||||
});
|
||||
upstream.once("close", () => client.destroy());
|
||||
upstream.once("close", () => {
|
||||
if (!connected && !client.destroyed) fail();
|
||||
client.destroy();
|
||||
});
|
||||
client.once("close", () => upstream.destroy());
|
||||
} catch (error) {
|
||||
reportRefusal(error, onRefused);
|
||||
@@ -208,20 +232,31 @@ export async function startCaptureProxy(
|
||||
upstream: UpstreamProxy | null = captureUpstreamProxy() ?? null,
|
||||
onRefused?: OnRefused,
|
||||
fixedLoopbackPort?: number,
|
||||
{
|
||||
maxConnections = BROWSER_PROXY_MAX_CONNECTIONS,
|
||||
onFailed = logFailure,
|
||||
}: { maxConnections?: number; onFailed?: OnFailed } = {},
|
||||
): Promise<{ url: string; close(): Promise<void> }> {
|
||||
const proxy = upstream ?? undefined;
|
||||
const sockets = new Set<Socket>();
|
||||
const clients = new Set<Socket>();
|
||||
const fail = () => closing || onFailed({ reason: "upstream_failed", open: clients.size });
|
||||
const server = createServer(
|
||||
(incoming, response) => void forwardHttp(incoming, response, sockets, proxy, onRefused),
|
||||
(incoming, response) => void forwardHttp(incoming, response, sockets, proxy, onRefused, fail),
|
||||
);
|
||||
server.on("connection", (socket) => trackSocket(socket, sockets));
|
||||
server.on("connection", (socket) => {
|
||||
trackSocket(socket, sockets);
|
||||
clients.add(socket);
|
||||
socket.once("close", () => clients.delete(socket));
|
||||
});
|
||||
server.on("drop", () => onFailed({ reason: "connection_cap", open: clients.size }));
|
||||
server.on(
|
||||
"connect",
|
||||
(incoming, socket, head) =>
|
||||
void forwardTunnel(incoming, socket, head, sockets, proxy, onRefused),
|
||||
void forwardTunnel(incoming, socket, head, sockets, proxy, onRefused, fail),
|
||||
);
|
||||
server.on("upgrade", (_incoming, socket) => socket.destroy());
|
||||
server.maxConnections = 128;
|
||||
server.maxConnections = maxConnections;
|
||||
server.headersTimeout = CONNECTION_TIMEOUT_MS;
|
||||
server.requestTimeout = 30_000;
|
||||
server.keepAliveTimeout = 1_000;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const ABSOLUTE_MAX_WORKERS = 24;
|
||||
Reference in New Issue
Block a user