From 8b0d1a873ce685f6afc2518b63ee7fe65b5122e5 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 10:12:41 +0530 Subject: [PATCH 1/4] fix(proxy): keep forwarded requests reachable so a client disconnect reaches the daemon Undici's Request follows its init signal only while the Request itself is reachable: it links the signal to the Request's own controller through a weak reference. The proxy handed each Request it built to a transport or to the authenticate hook and kept no reference, so the first garbage collection during an exchange cut the link. A client that disconnected after that, upstreamTimeoutMs and the five-second health bound no longer reached the transport or the hook, and the daemon kept running the request. Each Request the proxy builds is now kept in a WeakMap keyed by the object it serves: the Node adapter's request by its ServerResponse, the upstream, health and authenticate requests by the client request, and a custom transfer transport's request by the upstream one. An owner keeps every request built for it, so one client request handled twice at once keeps both. A listener on the followed signal is not used because Undici keeps that signal reachable for as long as the Request is, so the Request would never be collected. The garbage-collection cases move to daemon-proxy-cancellation.test.ts. --- .../src/server/http/http-server-proxy.test.ts | 17 +- .../src/daemon-proxy-cancellation.test.ts | 250 ++++++++++++++++++ packages/proxy/src/daemon-proxy.test.ts | 85 ------ packages/proxy/src/daemon-proxy.ts | 75 ++++-- 4 files changed, 321 insertions(+), 106 deletions(-) create mode 100644 packages/proxy/src/daemon-proxy-cancellation.test.ts 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/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts new file mode 100644 index 0000000000..c0adefc5f7 --- /dev/null +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -0,0 +1,250 @@ +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { setFlagsFromString } from 'node:v8'; +import { runInNewContext } from 'node:vm'; +import { expect, 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); + const upstream = abortObservingUpstream(); + try { + 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); + } finally { + timeout.mockRestore(); + } +}); + +test('upstreamTimeoutMs still ends an rpc exchange after a garbage collection', async () => { + const bound = new AbortController(); + const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(bound.signal); + const upstream = abortObservingUpstream(); + try { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: upstream.fetch, + upstreamTimeoutMs: 1234, + }); + const clientRequest = rpcRequest({ + jsonrpc: '2.0', + id: 5, + method: 'agent-device.command', + params: {}, + }); + const response = proxy.handle(clientRequest); + await upstream.received; + expect(timeout.mock.calls).toEqual([[1234]]); + await collectGarbage(); + bound.abort(); + await upstream.aborted; + expect((await response).status).toBe(500); + } finally { + timeout.mockRestore(); + } +}); + +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..9ec2439e05 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,12 +258,15 @@ async function authenticateCaller( : null; } const result = await options.authenticate( - new Request(request.url, { - method: request.method, - headers: request.headers, - signal: request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), + keepAliveWith( + request, + new Request(request.url, { + method: request.method, + headers: request.headers, + signal: request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), + ), ); if (!result) return null; const tenantId = normalizeTenantId( @@ -335,11 +343,14 @@ async function readUpstreamHealth( options: NormalizedProxyOptions, ): Promise { const response = await options.upstreamFetch( - new 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)]), - }), + keepAliveWith( + request, + new 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)]), + }), + ), ); const text = await response.text(); try { @@ -360,12 +371,20 @@ 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), { - method: request.method, - headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), - signal: upstreamSignal(request, options), - ...(body ? { body, duplex: 'half' as const } : {}), - }), + keepAliveWith( + request, + new Request(buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { + method: request.method, + headers: buildUpstreamHeaders( + request.headers, + options.upstreamToken, + route, + caller.tenantId, + ), + signal: upstreamSignal(request, options), + ...(body ? { body, duplex: 'half' as const } : {}), + }), + ), ); const headers = copyProxyResponseHeaders(upstreamResponse, request, route); @@ -381,6 +400,21 @@ 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; +} + 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 +575,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); }, }; From 5d07b1610c8b163f24d061b13995ba220846af1b Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 11:43:48 +0530 Subject: [PATCH 2/4] refactor(proxy): build and keep each forwarded request in one helper forwardedRequest builds the authenticate, health and upstream requests and keeps them with the client request in one step, so the three sites cannot drift. The Node adapter and custom transfer wrappers keep calling keepAliveWith, since they do not build the request. --- packages/proxy/src/daemon-proxy.ts | 53 +++++++++++++----------------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 9ec2439e05..4710b7294b 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -258,15 +258,12 @@ async function authenticateCaller( : null; } const result = await options.authenticate( - keepAliveWith( - request, - new Request(request.url, { - method: request.method, - headers: request.headers, - signal: request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), - ), + forwardedRequest(request, request.url, { + method: request.method, + headers: request.headers, + signal: request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), ); if (!result) return null; const tenantId = normalizeTenantId( @@ -343,14 +340,11 @@ async function readUpstreamHealth( options: NormalizedProxyOptions, ): Promise { const response = await options.upstreamFetch( - keepAliveWith( - request, - new 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)]), - }), - ), + 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)]), + }), ); const text = await response.text(); try { @@ -371,20 +365,12 @@ async function forwardProxyRequest(params: { const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const upstreamResponse = await options.upstreamTransport( route, - keepAliveWith( - request, - new Request(buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { - method: request.method, - headers: buildUpstreamHeaders( - request.headers, - options.upstreamToken, - route, - caller.tenantId, - ), - signal: upstreamSignal(request, options), - ...(body ? { body, duplex: 'half' as const } : {}), - }), - ), + forwardedRequest(request, buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { + method: request.method, + headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), + signal: upstreamSignal(request, options), + ...(body ? { body, duplex: 'half' as const } : {}), + }), ); const headers = copyProxyResponseHeaders(upstreamResponse, request, route); @@ -415,6 +401,11 @@ function keepAliveWith(owner: object, request: Request): 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)]); From 84aa855530adf4588afbe90baef7f43bcdd4b987 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 11:43:48 +0530 Subject: [PATCH 3/4] test(proxy): end one cancellation case on a real upstreamTimeoutMs timer The upstreamTimeoutMs case now uses a real 300 ms AbortSignal.timeout after the collection instead of a mocked signal. The mocked health-bound case restores its spy in onTestFinished, so a timeout there cannot leave AbortSignal.timeout mocked for the next case. --- .../src/daemon-proxy-cancellation.test.ts | 75 +++++++++---------- 1 file changed, 35 insertions(+), 40 deletions(-) diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index c0adefc5f7..ac3e609b69 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -2,7 +2,7 @@ import http from 'node:http'; import type { AddressInfo } from 'node:net'; import { setFlagsFromString } from 'node:v8'; import { runInNewContext } from 'node:vm'; -import { expect, test, vi } from 'vitest'; +import { expect, onTestFinished, test, vi } from 'vitest'; import { createDaemonProxy, createDaemonProxyServer, @@ -172,50 +172,45 @@ test('a client leaving the Node adapter mid-response after a garbage collection 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(); - try { - 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); - } finally { - timeout.mockRestore(); - } + 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 bound = new AbortController(); - const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(bound.signal); const upstream = abortObservingUpstream(); - try { - const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', - upstreamToken: 'daemon-secret', - clientToken: 'client-secret', - upstreamFetch: upstream.fetch, - upstreamTimeoutMs: 1234, - }); - const clientRequest = rpcRequest({ - jsonrpc: '2.0', - id: 5, - method: 'agent-device.command', - params: {}, - }); - const response = proxy.handle(clientRequest); - await upstream.received; - expect(timeout.mock.calls).toEqual([[1234]]); - await collectGarbage(); - bound.abort(); - await upstream.aborted; - expect((await response).status).toBe(500); - } finally { - timeout.mockRestore(); - } + 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 () => { From fae9a52bd860bab39a9116bfbcbae58b4a501748 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 11:43:48 +0530 Subject: [PATCH 4/4] docs(proxy): say the host keeps the Request reachable until the body ends --- packages/proxy/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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