diff --git a/packages/daemon/src/server/http/http-server-proxy.test.ts b/packages/daemon/src/server/http/http-server-proxy.test.ts index 9f12c62043..d37f74bb3c 100644 --- a/packages/daemon/src/server/http/http-server-proxy.test.ts +++ b/packages/daemon/src/server/http/http-server-proxy.test.ts @@ -2,6 +2,8 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import http from 'node:http'; +import { setFlagsFromString } from 'node:v8'; +import { runInNewContext } from 'node:vm'; import { createDaemonProxyServer } from '@agent-device/proxy'; import { createDaemonHttpServer } from './http-server.ts'; import { getRequestSignal } from '@agent-device/host-kit/request'; @@ -237,7 +239,17 @@ test('proxy enforces public-only Maestro HTTP policy on a local daemon', async ( } }); -test('daemon proxy cancels the upstream daemon request when its client disconnects', async (t) => { +/** + * Runs the collection a long-lived proxy eventually runs, so a test sees what an unreferenced + * request loses. A weak reference keeps its target until the job that created it ends. + */ +async function collectGarbage(): Promise { + await new Promise((resolve) => setImmediate(resolve)); + setFlagsFromString('--expose-gc'); + (runInNewContext('gc') as () => void)(); +} + +test('daemon proxy cancels the upstream daemon request when its client disconnects after a garbage collection', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let upstreamStarted!: (requestId: string | undefined) => void; @@ -303,10 +315,11 @@ test('daemon proxy cancels the upstream daemon request when its client disconnec const requestId = await started; assert.match(String(requestId), /req-disconnect/); + await collectGarbage(); client.destroy(); const timeout = new Promise((resolve) => { - setTimeout(() => resolve('upstream request was never canceled'), 5000).unref(); + setTimeout(() => resolve('upstream request was never canceled'), 2000).unref(); }); assert.equal(await Promise.race([canceled, timeout]), 'aborted'); } finally { diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 36f50d904c..d3083f41c7 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -63,13 +63,15 @@ export default { fetch: proxy.handle }; ``` For a WebSocket or other message transport, turn each incoming message into a `Request` and send -the `Response` back. Three things the proxy relies on: +the `Response` back. Four things the proxy relies on: - Without `publicOrigin`, construct `request.url` with the canonical client-facing URL for each request. The embedder is responsible for that URL. `Forwarded` and `X-Forwarded-*` headers do not select the upload ticket origin. - `request.signal` aborts when the client goes away. The proxy then cancels the daemon request, so work the client stopped waiting for does not keep running. +- The host keeps the `Request` reachable until the `Response` body ends. Undici's `Request` stops + following its signal once it is collected, and the abort would then not reach the daemon. - Response bodies stream. Artifact downloads can be large, so forward the body as it arrives. `handle` never rejects. Errors come back as JSON responses with a 4xx or 5xx status, except a route diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts new file mode 100644 index 0000000000..ac3e609b69 --- /dev/null +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -0,0 +1,245 @@ +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { setFlagsFromString } from 'node:v8'; +import { runInNewContext } from 'node:vm'; +import { expect, onTestFinished, test, vi } from 'vitest'; +import { + createDaemonProxy, + createDaemonProxyServer, + type DaemonProxyUpstreamFetch, +} from './daemon-proxy.ts'; + +const PROXY_ORIGIN = 'https://gateway.example.test'; + +function signalled(): { promise: Promise; resolve: () => void } { + let resolve = () => {}; + const promise = new Promise((settle) => { + resolve = settle; + }); + return { promise, resolve }; +} + +/** + * Runs the collection a long-lived proxy eventually runs, so a test sees what an unreferenced + * request loses. A weak reference keeps its target until the job that created it ends. + */ +async function collectGarbage(): Promise { + await new Promise((resolve) => setImmediate(resolve)); + setFlagsFromString('--expose-gc'); + (runInNewContext('gc') as () => void)(); +} + +/** A transport that answers only when its request aborts. */ +function abortObservingUpstream(): { + fetch: DaemonProxyUpstreamFetch; + received: Promise; + aborted: Promise; +} { + const received = signalled(); + const aborted = signalled(); + return { + received: received.promise, + aborted: aborted.promise, + fetch: (request) => + new Promise((_resolve, reject) => { + request.signal.addEventListener('abort', () => { + aborted.resolve(); + reject(request.signal.reason); + }); + received.resolve(); + }), + }; +} + +function proxyWith(upstreamFetch: DaemonProxyUpstreamFetch) { + return createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch, + }); +} + +function rpcRequest(body: unknown, init: RequestInit = {}): Request { + return new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + headers: { authorization: 'Bearer client-secret', 'content-type': 'application/json' }, + body: JSON.stringify(body), + ...init, + }); +} + +test.each([ + { + route: 'rpc', + request: (signal: AbortSignal) => + rpcRequest({ jsonrpc: '2.0', id: 2, method: 'agent-device.command' }, { signal }), + }, + { + route: 'health', + request: (signal: AbortSignal) => + new Request(`${PROXY_ORIGIN}/agent-device/health`, { signal }), + }, + { + route: 'artifact download', + request: (signal: AbortSignal) => + new Request(`${PROXY_ORIGIN}/agent-device/artifacts/art-1`, { + headers: { authorization: 'Bearer client-secret' }, + signal, + }), + }, +])( + 'aborting the client request after a garbage collection aborts the upstream $route exchange', + async ({ request }) => { + const upstream = abortObservingUpstream(); + const proxy = proxyWith(upstream.fetch); + const client = new AbortController(); + + // Like an embedder, the test keeps its request while the proxy answers it. + const clientRequest = request(client.signal); + const response = proxy.handle(clientRequest); + await upstream.received; + await collectGarbage(); + client.abort(); + + await upstream.aborted; + expect((await response).status).toBe(500); + }, +); + +test('a health request handled by two proxies at once aborts both upstream probes after a garbage collection', async () => { + const first = abortObservingUpstream(); + const second = abortObservingUpstream(); + const client = new AbortController(); + // Like an embedder, the test keeps its request while the proxies answer it. + const clientRequest = new Request(`${PROXY_ORIGIN}/agent-device/health`, { + signal: client.signal, + }); + + const responses = Promise.all([ + proxyWith(first.fetch).handle(clientRequest), + proxyWith(second.fetch).handle(clientRequest), + ]); + await Promise.all([first.received, second.received]); + await collectGarbage(); + client.abort(); + + await Promise.all([first.aborted, second.aborted]); + expect((await responses).map((response) => response.status)).toEqual([500, 500]); +}); + +test('a client leaving the Node adapter mid-response after a garbage collection aborts the upstream request', async () => { + const upstreamAborted = signalled(); + const server = createDaemonProxyServer({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: async (request) => { + request.signal.addEventListener('abort', () => upstreamAborted.resolve(), { once: true }); + return new Response( + new ReadableStream({ + start: (controller) => controller.enqueue(new TextEncoder().encode('{}\n')), + }), + ); + }, + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const client = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '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/agent-device/rpc', + headers: { authorization: 'Bearer client-secret', 'content-type': 'application/json' }, + }); + client.on('error', () => {}); + const firstChunk = new Promise((resolve) => { + client.on('response', (response) => response.once('data', () => resolve())); + }); + client.end(JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'agent-device.command' })); + await firstChunk; + await collectGarbage(); + client.destroy(); + + await upstreamAborted.promise; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +}); + +test('the upstream health probe has its own bound without upstreamTimeoutMs', async () => { + const healthBound = new AbortController(); + const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(healthBound.signal); + // A timed-out test never reaches a `finally`; the real timer test below needs the spy gone. + onTestFinished(() => timeout.mockRestore()); + const upstream = abortObservingUpstream(); + const proxy = proxyWith(upstream.fetch); + const clientRequest = new Request(`${PROXY_ORIGIN}/agent-device/health`); + + const response = proxy.handle(clientRequest); + expect(timeout.mock.calls).toEqual([[5_000]]); + await upstream.received; + await collectGarbage(); + healthBound.abort(); + + await upstream.aborted; + expect((await response).status).toBe(500); +}); + +test('upstreamTimeoutMs still ends an rpc exchange after a garbage collection', async () => { + const upstream = abortObservingUpstream(); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: upstream.fetch, + // A real timer, long enough that the collection below runs before it fires. + upstreamTimeoutMs: 300, + }); + const clientRequest = rpcRequest({ + jsonrpc: '2.0', + id: 5, + method: 'agent-device.command', + params: {}, + }); + + const response = proxy.handle(clientRequest); + await upstream.received; + await collectGarbage(); + + await upstream.aborted; + expect((await response).status).toBe(500); +}); + +test('aborting the client request after a garbage collection aborts a pending authenticate', async () => { + const authenticateReceived = signalled(); + const authenticateAborted = signalled(); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({}), + authenticate: (request) => + new Promise((_resolve, reject) => { + request.signal.addEventListener('abort', () => { + authenticateAborted.resolve(); + reject(request.signal.reason); + }); + authenticateReceived.resolve(); + }), + }); + const client = new AbortController(); + + const clientRequest = rpcRequest( + { jsonrpc: '2.0', id: 6, method: 'agent-device.command' }, + { signal: client.signal }, + ); + const response = proxy.handle(clientRequest); + await authenticateReceived.promise; + await collectGarbage(); + client.abort(); + + await authenticateAborted.promise; + expect((await response).status).toBe(500); +}); diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 06525877a2..da03369607 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -23,14 +23,6 @@ function recordingUpstream(respond: (request: Request) => Response | Promise; resolve: () => void } { - let resolve = () => {}; - const promise = new Promise((settle) => { - resolve = settle; - }); - return { promise, resolve }; -} - function proxyWith(upstreamFetch: DaemonProxyUpstreamFetch, maxRpcBodyBytes?: number) { return createDaemonProxy({ upstreamBaseUrl: 'http://daemon.internal:4310', @@ -80,34 +72,6 @@ test('a request without the client token never reaches the upstream transport', expect(upstream.requests).toHaveLength(0); }); -test('aborting the client request aborts the upstream exchange', async () => { - const upstreamReceived = signalled(); - const upstreamAborted = signalled(); - const proxy = proxyWith( - (request) => - new Promise((_resolve, reject) => { - request.signal.addEventListener('abort', () => { - upstreamAborted.resolve(); - reject(request.signal.reason); - }); - upstreamReceived.resolve(); - }), - ); - const client = new AbortController(); - - const response = proxy.handle( - rpcRequest( - { jsonrpc: '2.0', id: 2, method: 'agent-device.command' }, - { signal: client.signal }, - ), - ); - await upstreamReceived.promise; - client.abort(); - - await upstreamAborted.promise; - expect((await response).status).toBe(500); -}); - test.each([ { upstreamTimeoutMs: undefined, timeouts: [] }, { upstreamTimeoutMs: 1234, timeouts: [[1234]] }, @@ -286,55 +250,6 @@ test.each([ expect(upstream.requests).toHaveLength(0); }); -test('the upstream health probe has its own bound without upstreamTimeoutMs', async () => { - const healthBound = new AbortController(); - const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(healthBound.signal); - const upstreamAborted = signalled(); - try { - const proxy = proxyWith( - (request) => - new Promise((_resolve, reject) => { - request.signal.addEventListener('abort', () => { - upstreamAborted.resolve(); - reject(request.signal.reason); - }); - }), - ); - const response = proxy.handle(new Request(`${PROXY_ORIGIN}/agent-device/health`)); - expect(timeout.mock.calls).toEqual([[5_000]]); - healthBound.abort(); - await upstreamAborted.promise; - expect((await response).status).toBe(500); - } finally { - timeout.mockRestore(); - } -}); - -test('aborting a health request aborts the upstream health probe', async () => { - const upstreamReceived = signalled(); - const upstreamAborted = signalled(); - const proxy = proxyWith( - (request) => - new Promise((_resolve, reject) => { - request.signal.addEventListener('abort', () => { - upstreamAborted.resolve(); - reject(request.signal.reason); - }); - upstreamReceived.resolve(); - }), - ); - const client = new AbortController(); - - const response = proxy.handle( - new Request(`${PROXY_ORIGIN}/agent-device/health`, { signal: client.signal }), - ); - await upstreamReceived.promise; - client.abort(); - - await upstreamAborted.promise; - expect((await response).status).toBe(500); -}); - test('an unsupported route answers a bare 404 without reaching the daemon', async () => { const upstream = recordingUpstream(() => Response.json({})); const proxy = proxyWith(upstream.fetch); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index f5e062c9e7..4710b7294b 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -96,6 +96,7 @@ export type DaemonProxy = { * Answers one client request. Without `publicOrigin`, the embedder must construct * `request.url` with the canonical client-facing origin. Forwarding headers do not select it. * Abort `request.signal` when the client goes away so in-flight daemon work is cancelled. + * Keep `request` reachable until the response body ends, or its abort may not reach the daemon. * Resolves with an error response rather than rejecting. */ handle(request: Request): Promise; @@ -163,8 +164,12 @@ export function createDaemonProxyServer(options: DaemonProxyOptions): http.Serve /** Serves a proxy from any `node:http` or `node:https` server. */ export function createDaemonProxyRequestListener(proxy: DaemonProxy): http.RequestListener { return (req, res) => { + const proxyForResponse: DaemonProxy = { + instanceId: proxy.instanceId, + handle: (request) => proxy.handle(keepAliveWith(res, request)), + }; void import('./node-http.ts') - .then(({ serveProxyRequest }) => serveProxyRequest(proxy, req, res)) + .then(({ serveProxyRequest }) => serveProxyRequest(proxyForResponse, req, res)) .catch((error: unknown) => { if (!res.destroyed) res.destroy(error instanceof Error ? error : undefined); }); @@ -253,7 +258,7 @@ async function authenticateCaller( : null; } const result = await options.authenticate( - new Request(request.url, { + forwardedRequest(request, request.url, { method: request.method, headers: request.headers, signal: request.signal, @@ -335,7 +340,7 @@ async function readUpstreamHealth( options: NormalizedProxyOptions, ): Promise { const response = await options.upstreamFetch( - new Request(buildDaemonHttpUrl(options.upstreamBaseUrl, 'health'), { + forwardedRequest(request, buildDaemonHttpUrl(options.upstreamBaseUrl, 'health'), { method: 'GET', headers: buildUpstreamHeaders(new Headers(), options.upstreamToken, '/health'), signal: AbortSignal.any([request.signal, AbortSignal.timeout(UPSTREAM_HEALTH_TIMEOUT_MS)]), @@ -360,7 +365,7 @@ async function forwardProxyRequest(params: { const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const upstreamResponse = await options.upstreamTransport( route, - new Request(buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { + forwardedRequest(request, buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { method: request.method, headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), signal: upstreamSignal(request, options), @@ -381,6 +386,26 @@ async function forwardProxyRequest(params: { return new Response(upstreamResponse.body, { status: upstreamResponse.status, headers }); } +const keptRequests = new WeakMap(); + +/** + * Keeps `request` reachable for as long as `owner` is. Undici's `Request` follows its init signal + * only while the request itself is reachable, so one handed on and dropped stops seeing aborts after + * a garbage collection. Holding it from that signal would keep it forever: Undici keeps the signal + * reachable for as long as the request is. + */ +function keepAliveWith(owner: object, request: Request): Request { + const kept = keptRequests.get(owner); + if (kept) kept.push(request); + else keptRequests.set(owner, [request]); + return request; +} + +/** Builds a request for `owner` to send on, kept reachable for as long as `owner` is. */ +function forwardedRequest(owner: Request, url: string | URL, init: RequestInit): Request { + return keepAliveWith(owner, new Request(url, init)); +} + function upstreamSignal(request: Request, options: NormalizedProxyOptions): AbortSignal { if (options.upstreamTimeoutMs === undefined) return request.signal; return AbortSignal.any([request.signal, AbortSignal.timeout(options.upstreamTimeoutMs)]); @@ -541,7 +566,10 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti const { createNodeTransferFetch, settleUpstreamFetch } = await import('./transfer-transport.ts'); return customUpstreamFetch - ? settleUpstreamFetch(customUpstreamFetch, request) + ? settleUpstreamFetch( + (forwarded) => customUpstreamFetch(keepAliveWith(request, forwarded)), + request, + ) : createNodeTransferFetch()(request); }, };