Skip to content

An open-source, faster Devin alternative

TypeScript

computer: preview dialer seam (work 103, S3) (#1036)

opencomputer-app[bot]944f8535ab63
diff --git a/computer/src/host/preview-dial.test.ts b/computer/src/host/preview-dial.test.ts
new file mode 100644
index 00000000..e02d5a05
--- /dev/null
+++ b/computer/src/host/preview-dial.test.ts
@@ -0,0 +1,33 @@
+import net from 'node:net';
+import { once } from 'node:events';
+import { afterEach, describe, expect, it } from 'vitest';
+import { loopbackDialer } from './preview-dial.js';
+
+const servers: net.Server[] = [];
+afterEach(() => { for (const s of servers.splice(0)) s.close(); });
+
+async function listen(): Promise<number> {
+ const s = net.createServer((c) => c.end('hello'));
+ servers.push(s);
+ s.listen(0, '127.0.0.1');
+ await once(s, 'listening');
+ return (s.address() as net.AddressInfo).port;
+}
+
+describe('loopbackDialer', () => {
+ it('connects to a port that listens on loopback', async () => {
+ const c = loopbackDialer(await listen());
+ await once(c, 'connect');
+ const [data] = await once(c, 'data');
+ expect(String(data)).toBe('hello');
+ c.destroy();
+ });
+
+ it('reports ECONNREFUSED as an error event when nothing listens', async () => {
+ const port = await listen();
+ servers.splice(0)[0].close();
+ await new Promise((r) => setTimeout(r, 20));
+ const [e] = await once(loopbackDialer(port), 'error');
+ expect((e as NodeJS.ErrnoException).code).toBe('ECONNREFUSED');
+ });
+});
diff --git a/computer/src/host/preview-dial.ts b/computer/src/host/preview-dial.ts
new file mode 100644
index 00000000..631a72b7
--- /dev/null
+++ b/computer/src/host/preview-dial.ts
@@ -0,0 +1,17 @@
+// How the preview proxy and the listen probe reach a previewed port (work
+// 103, seam S3). Both take a Dialer, so where the port lives is decided in one
+// place: today it is this machine's loopback. Invariants: a Dialer returns its
+// connection at once and never throws; the connection emits `connect`, or
+// `error` with code ECONNREFUSED when nothing listens on the port. The proxy
+// keeps connections alive through an http.Agent, which calls a socket's
+// setKeepAlive, setTimeout, ref and unref on them: a Dialer whose connection
+// is not a net.Socket has to provide those.
+
+import net from 'node:net';
+import type { Duplex } from 'node:stream';
+
+/** A connection to this port for http.request's `createConnection`: returned at once, emits `connect` or `error` (code ECONNREFUSED when nothing listens). */
+export type Dialer = (port: number) => Duplex;
+
+/** The port on this machine, over IPv4 loopback, as http.request itself would connect. */
+export const loopbackDialer: Dialer = (port) => net.connect({ host: '127.0.0.1', port, noDelay: true });
diff --git a/computer/src/host/preview-probe.test.ts b/computer/src/host/preview-probe.test.ts
index f2fcdefc..c82a0d4b 100644
--- a/computer/src/host/preview-probe.test.ts
+++ b/computer/src/host/preview-probe.test.ts
@@ -1,6 +1,7 @@
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
+import { loopbackDialer } from './preview-dial.js';
import { frameworkHint, probePort } from './preview-probe.js';
const servers: http.Server[] = [];
@@ -46,6 +47,18 @@ describe('probePort', () => {
expect(host).toBe('demo.opencomputer.app');
});
+ it('reaches the port only through the dialer it is given', async () => {
+ const port = await freePort();
+ await serve(port, (_req, res) => (res.setHeader('x-powered-by', 'Next.js'), res.end('ok')));
+ const dialed: number[] = [];
+ const dial = (p: number) => (dialed.push(p), loopbackDialer(p));
+ expect(await probePort(port, 'demo.opencomputer.app', 2000, dial)).toEqual({ listening: true });
+ expect(dialed).toEqual([port, port]); // the page, then Next's HMR endpoint
+ // A dialer that reaches nothing: the port is not listening, though this machine's loopback has it.
+ const nowhere = await freePort();
+ expect(await probePort(port, 'demo.opencomputer.app', 600, () => loopbackDialer(nowhere))).toEqual({ listening: false });
+ });
+
it('gives up after the wait when nothing listens', async () => {
const port = await freePort();
const t0 = Date.now();
diff --git a/computer/src/host/preview-probe.ts b/computer/src/host/preview-probe.ts
index 4805a394..f7ed0816 100644
--- a/computer/src/host/preview-probe.ts
+++ b/computer/src/host/preview-probe.ts
@@ -12,6 +12,7 @@
// when the wait ends counts as listening too: it is up, only slow.
import http from 'node:http';
+import { type Dialer, loopbackDialer } from './preview-dial.js';
export const PROBE_WAIT_MS = 10_000;
const RETRY_MS = 250;
@@ -35,11 +36,11 @@ const NEXT_CHECK_WAIT_MS = 2_000;
type Attempt = { status: number; body: string; next: boolean } | 'refused' | 'connected';
-function attempt(port: number, host: string, waitMs: number, path = '/', extra: http.OutgoingHttpHeaders = {}): Promise<Attempt> {
+function attempt(dial: Dialer, port: number, host: string, waitMs: number, path = '/', extra: http.OutgoingHttpHeaders = {}): Promise<Attempt> {
return new Promise((resolve) => {
let connected = false;
- const req = http.get({ host: '127.0.0.1', port, path, headers: { host, 'x-forwarded-host': host, 'x-forwarded-proto': 'https', ...extra },
- agent: false }, (res) => {
+ // No `agent` option: with one, false included, http.get ignores createConnection. Without, each attempt has its own connection, closed after it.
+ const req = http.get({ host: '127.0.0.1', port, path, createConnection: () => dial(port), headers: { host, 'x-forwarded-host': host, 'x-forwarded-proto': 'https', ...extra } }, (res) => {
let body = '';
const done = () => resolve({ status: res.statusCode ?? 0, body, next: /next\.js/i.test(String(res.headers['x-powered-by'] ?? '')) });
res.setEncoding('utf8');
@@ -59,13 +60,13 @@ function attempt(port: number, host: string, waitMs: number, path = '/', extra:
}
/** Wait for `port` to answer `GET /` with `Host: host`; at most `waitMs`. */
-export async function probePort(port: number, host: string, waitMs = PROBE_WAIT_MS): Promise<{ listening: boolean; hint?: string }> {
+export async function probePort(port: number, host: string, waitMs = PROBE_WAIT_MS, dial: Dialer = loopbackDialer): Promise<{ listening: boolean; hint?: string }> {
const deadline = Date.now() + waitMs;
for (;;) {
const left = deadline - Date.now();
- const a = await attempt(port, host, Math.max(1, left));
+ const a = await attempt(dial, port, host, Math.max(1, left));
if (typeof a === 'object') {
- const hint = frameworkHint(a.status, a.body) ?? (a.next && a.status !== 403 ? await nextHint(port, host) : undefined);
+ const hint = frameworkHint(a.status, a.body) ?? (a.next && a.status !== 403 ? await nextHint(dial, port, host) : undefined);
return { listening: true, ...(hint && { hint }) };
}
if (a === 'connected') return { listening: true };
@@ -75,7 +76,7 @@ export async function probePort(port: number, host: string, waitMs = PROBE_WAIT_
}
/** Whether a Next dev server refuses its HMR to the preview's origin; the page itself loads either way. */
-async function nextHint(port: number, host: string): Promise<string | undefined> {
- const a = await attempt(port, host, NEXT_CHECK_WAIT_MS, NEXT_HMR_PATH, { origin: `https://${host}` });
+async function nextHint(dial: Dialer, port: number, host: string): Promise<string | undefined> {
+ const a = await attempt(dial, port, host, NEXT_CHECK_WAIT_MS, NEXT_HMR_PATH, { origin: `https://${host}` });
return typeof a === 'object' && a.status === 403 ? frameworkHint(403, 'allowedDevOrigins') : undefined;
}
diff --git a/computer/src/host/preview-proxy.test.ts b/computer/src/host/preview-proxy.test.ts
index 02cf7f40..fc1533e7 100644
--- a/computer/src/host/preview-proxy.test.ts
+++ b/computer/src/host/preview-proxy.test.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import WebSocket, { WebSocketServer } from 'ws';
import type { PreviewConfig } from '../protocol.js';
import { signPreview } from '../signed-header.js';
+import { loopbackDialer } from './preview-dial.js';
import { previewProxy } from './preview-proxy.js';
const KEY = Buffer.alloc(32, 7).toString('base64url');
@@ -62,6 +63,35 @@ describe('preview proxy', () => {
expect(Object.keys(seen.headers).filter((k) => k.startsWith('x-preview-'))).toEqual([]);
});
+ it('keeps the connection to the app between requests, and dials it through its dialer', async () => {
+ const sockets = new Set<unknown>();
+ const seen: (string | undefined)[] = [];
+ const app = await listen(http.createServer((req, res) => (sockets.add(req.socket), seen.push(req.headers.connection), res.end('ok'))));
+ const dialed: number[] = [];
+ const at = await listen(previewProxy(() => ({ tunnelToken: 't', key: KEY, ports: [app] }), [], (p) => (dialed.push(p), loopbackDialer(p))));
+ const headers = { 'x-preview-port': String(app), 'x-preview-auth': signPreview(KEY, app) };
+ for (let n = 0; n < 3; n++) expect((await get(at, headers)).status).toBe(200);
+ expect(sockets.size).toBe(1);
+ expect(dialed).toEqual([app]);
+ expect(seen).toEqual(['keep-alive', 'keep-alive', 'keep-alive']);
+ });
+
+ it('closes its idle connections to the app when it closes', async () => {
+ let open = 0;
+ const appServer = http.createServer((_req, res) => res.end('ok'));
+ appServer.on('connection', (s) => (open++, s.on('close', () => open--)));
+ const app = await listen(appServer);
+ const p = previewProxy(() => ({ tunnelToken: 't', key: KEY, ports: [app] }), []);
+ await new Promise<void>((r) => p.listen(0, '127.0.0.1', r));
+ const at = (p.address() as AddressInfo).port;
+ expect((await get(at, { 'x-preview-port': String(app), 'x-preview-auth': signPreview(KEY, app) })).status).toBe(200);
+ expect(open).toBe(1);
+ p.closeAllConnections();
+ await new Promise((r) => p.close(r));
+ await new Promise((r) => setTimeout(r, 50));
+ expect(open).toBe(0);
+ });
+
it('refuses a port not in the allow-list, a host port, and a request without config', async () => {
const app = await echo();
const { at, signed } = await proxy([app + 1]);
diff --git a/computer/src/host/preview-proxy.ts b/computer/src/host/preview-proxy.ts
index 683453d3..6a2e2f0e 100644
--- a/computer/src/host/preview-proxy.ts
+++ b/computer/src/host/preview-proxy.ts
@@ -3,7 +3,9 @@
// 127.0.0.1:<X-Preview-Port>, WebSocket upgrades (HMR) and streamed bodies
// (SSE) included.
//
-// Invariants: it dials only loopback, only a port in the config's allow-list
+// Invariants: it dials only through its Dialer (preview-dial.ts; loopback
+// unless another is passed; the connections are kept alive by an agent of
+// its own, which ends with it), only a port in the config's allow-list
// that is not one of the host's own, and only for a request whose
// X-Preview-Auth verifies (src/signed-header.ts). Every response it produces,
// proxied ones too, carries `X-Preview-Origin: computer`, the one signal the
@@ -16,6 +18,7 @@ import type { Duplex } from 'node:stream';
import type { PreviewConfig } from '../protocol.js';
import { log } from '../log.js';
import { verifyPreview } from '../signed-header.js';
+import { type Dialer, loopbackDialer } from './preview-dial.js';
export const PREVIEW_PROXY_PORT = 7070;
/** The proxy itself, and cloudflared's default metrics ports. */
@@ -75,13 +78,24 @@ const head = (status: number | undefined, message: string | undefined, raw: stri
return `${s}\r\n`;
};
-/** The proxy; `config` is read per request, so a `previews` frame applies at once. */
-export function previewProxy(config: () => PreviewConfig | undefined, refused = HOST_PORTS): http.Server {
+/**
+ * The connections to the apps, as http's own agent keeps them (kept alive between requests, an idle one closed
+ * after 5 s), dialed through `dial`: http.request without an agent would open one per request and close it.
+ */
+function dialAgent(dial: Dialer): http.Agent {
+ const agent = new http.Agent({ keepAlive: true, scheduling: 'lifo', timeout: 5000 });
+ agent.createConnection = (o) => dial(Number(o.port));
+ return agent;
+}
+
+/** The proxy; `config` is read per request, so a `previews` frame applies at once. Closing it closes its idle connections to the apps. */
+export function previewProxy(config: () => PreviewConfig | undefined, refused = HOST_PORTS, dial: Dialer = loopbackDialer): http.Server {
+ const agent = dialAgent(dial);
const server = http.createServer((req, res) => {
const c = checkRequest(req, config(), refused);
if ('status' in c) return refuse(res, c);
for (const k of HOP) delete c.headers[k];
- const up = http.request({ host: '127.0.0.1', port: c.port, method: req.method, path: req.url, headers: c.headers }, (ures) => {
+ const up = http.request({ host: '127.0.0.1', port: c.port, method: req.method, path: req.url, headers: c.headers, agent }, (ures) => {
res.writeHead(ures.statusCode ?? 502, ures.statusMessage, marked(ures.rawHeaders, (k) => HOP.has(k)));
res.flushHeaders(); // an SSE stream's headers leave before its first event
ures.pipe(res);
@@ -96,7 +110,7 @@ export function previewProxy(config: () => PreviewConfig | undefined, refused =
socket.on('error', () => {});
const c = checkRequest(req, config(), refused);
if ('status' in c) return refuseSocket(socket, c);
- const up = http.request({ host: '127.0.0.1', port: c.port, method: req.method, path: req.url, headers: c.headers });
+ const up = http.request({ host: '127.0.0.1', port: c.port, method: req.method, path: req.url, headers: c.headers, agent });
up.on('upgrade', (ures, usock, uhead) => {
socket.write(head(ures.statusCode, ures.statusMessage, marked(ures.rawHeaders)));
if (uhead.length) socket.write(uhead);
@@ -115,5 +129,6 @@ export function previewProxy(config: () => PreviewConfig | undefined, refused =
socket.on('close', () => up.destroy());
up.end();
});
+ server.on('close', () => agent.destroy());
return server;
}