You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/10/10 10:47:59 UTC
(maka) branch main updated: fix(runtime): bound proxied dispatcher teardown in the remaining call sites (#6003)
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/main by this push:
new df5f25bda0 fix(runtime): bound proxied dispatcher teardown in the remaining call sites (#6003)
df5f25bda0 is described below
commit df5f25bda0c3e5f6d29352c414fb918b9dd589bf
Author: ε°δΈ <gg...@gmail.com>
AuthorDate: Sat Oct 10 18:47:55 2026 +0800
fix(runtime): bound proxied dispatcher teardown in the remaining call sites (#6003)
Two call sites build their own proxy dispatcher and dispose it themselves,
so the abort-before-close teardown pattern that the shared transport fix
reordered (#5900) survives in them:
- testProxyConnection's finally aborts the controller and then awaits the
dispatcher's graceful close. Behind a real proxy that close never
settles, so the call stays pending long past its 8s probe timeout and
wedges the serialized settings lane it occupies on the Desktop.
Start the dispatcher teardown before the abort and race it against a
1s grace, mirroring the transport pattern.
- proxiedFetch's error path awaits the same graceful close after
aborting, so a stalled close delays the rejection the caller is owed.
Apply the same ordering and bound there. The success path keeps its
fire-and-forget close, which owns the streaming body lifecycle and is
intentionally not bounded.
Regression tests stall ProxyAgent.prototype.close (the same
Undici/Node-version-independent technique the transport tests use) and
assert both calls still settle; both tests fail on the previous ordering.
Refs #5978
Generated-by: GLM-5.3-Flash (ZCode)
fix(runtime): escalate proxied dispatcher teardown to destroy after the grace expires
Root cause: the bounded dispatcher teardown in testProxyConnection and the
proxiedFetch error path raced the graceful close against a 1s grace, but
when the grace won, the dispatcher was simply abandoned with its close()
still pending, leaking the agent (flagged as a P3 inline on #6003).
Fix: track who wins the grace race and, when it expires, fire-and-forget
destroy() with a distinguishing reason. The destroy error is swallowed so
teardown can never replace the result or rejection the caller is already
owed. The grace duration and its external semantics are unchanged; the
success path of proxiedFetch keeps its unbounded close, which owns the
streaming body lifecycle.
Verified: new regressions in proxy-test.test.ts and proxied-fetch.test.ts
stub ProxyAgent#close to never settle and assert destroy is called; both
failed before the fix (callCount 0) and pass after. runtime network+bots
suites 167/167, biome check clean, check:asf-headers clean.
Generated-by: GLM-5.3-Flash (ZCode)
---
.../src/bots/__tests__/proxied-fetch.test.ts | 96 ++++++++++++++++++++++
packages/runtime/src/bots/proxied-fetch.ts | 33 +++++++-
.../src/network/__tests__/proxy-test.test.ts | 86 +++++++++++++++++++
packages/runtime/src/network/proxy-test.ts | 32 +++++++-
4 files changed, 245 insertions(+), 2 deletions(-)
diff --git a/packages/runtime/src/bots/__tests__/proxied-fetch.test.ts b/packages/runtime/src/bots/__tests__/proxied-fetch.test.ts
index 1855a6fd20..da27be76ed 100644
--- a/packages/runtime/src/bots/__tests__/proxied-fetch.test.ts
+++ b/packages/runtime/src/bots/__tests__/proxied-fetch.test.ts
@@ -23,6 +23,7 @@ import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { createServer } from 'node:http';
import net from 'node:net';
+import { ProxyAgent } from 'undici';
import { PROXY_DEFAULTS } from '@maka/core/settings/network-settings';
import { setActiveProxy } from '../../network/active-proxy-state.js';
import { proxiedFetch } from '../proxied-fetch.js';
@@ -243,6 +244,101 @@ describe('proxiedFetch', () => {
}
});
+ test('rejects promptly on request failure even when the dispatcher close stalls', async (t) => {
+ const sockets = new Set<net.Socket>();
+ const proxy = net.createServer((socket) => {
+ sockets.add(socket);
+ socket.on('close', () => sockets.delete(socket));
+ socket.on('error', () => sockets.delete(socket));
+ // Accept the proxy TCP connection, then reset it immediately so the
+ // fetch itself fails (with timeoutMs 0 the internal timeout is off and
+ // the graceful close branch of the teardown runs).
+ socket.destroy();
+ });
+ await new Promise<void>((resolve, reject) => {
+ proxy.once('error', reject);
+ proxy.listen(0, '127.0.0.1', () => resolve());
+ });
+ const address = proxy.address();
+ assert.ok(address && typeof address === 'object');
+ setActiveProxy({
+ ...PROXY_DEFAULTS,
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: address.port,
+ bypassList: [],
+ });
+ // Reproduce the dispatcher completion failure independently of
+ // Undici/Node version: a graceful close that never settles must not delay
+ // the rejection the caller is already owed.
+ t.mock.method(ProxyAgent.prototype, 'close', () => new Promise<void>(() => {}));
+
+ try {
+ await withTimeout(
+ assert.rejects(
+ () => proxiedFetch('http://example.com', { timeoutMs: 0 }),
+ /fetch failed|other side closed|ECONNRESET|network/i,
+ ),
+ 5_000,
+ 'proxiedFetch rejection was delayed by a stalled dispatcher close',
+ );
+ } finally {
+ setActiveProxy(null);
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve) => proxy.close(() => resolve()));
+ }
+ });
+
+ test('destroys the dispatcher when a stalled close outlives the teardown grace', async (t) => {
+ const sockets = new Set<net.Socket>();
+ const proxy = net.createServer((socket) => {
+ sockets.add(socket);
+ socket.on('close', () => sockets.delete(socket));
+ socket.on('error', () => sockets.delete(socket));
+ // Accept the proxy TCP connection, then reset it immediately so the
+ // fetch itself fails (with timeoutMs 0 the internal timeout is off and
+ // the graceful close branch of the teardown runs).
+ socket.destroy();
+ });
+ await new Promise<void>((resolve, reject) => {
+ proxy.once('error', reject);
+ proxy.listen(0, '127.0.0.1', () => resolve());
+ });
+ const address = proxy.address();
+ assert.ok(address && typeof address === 'object');
+ setActiveProxy({
+ ...PROXY_DEFAULTS,
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: address.port,
+ bypassList: [],
+ });
+ // Reproduce the dispatcher completion failure independently of
+ // Undici/Node version: once the bounded teardown grace expires with the
+ // graceful close still pending, the abandoned dispatcher must be
+ // destroyed instead of leaking.
+ t.mock.method(ProxyAgent.prototype, 'close', () => new Promise<void>(() => {}));
+ const destroyMock = t.mock.method(ProxyAgent.prototype, 'destroy', () => {});
+
+ try {
+ await withTimeout(
+ assert.rejects(
+ () => proxiedFetch('http://example.com', { timeoutMs: 0 }),
+ /fetch failed|other side closed|ECONNRESET|network/i,
+ ),
+ 5_000,
+ 'proxiedFetch rejection was delayed past the teardown grace',
+ );
+ assert.ok(destroyMock.mock.callCount() > 0);
+ } finally {
+ setActiveProxy(null);
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve) => proxy.close(() => resolve()));
+ }
+ });
+
test('timeoutMs 0 disables the internal timeout for streaming callers', async () => {
const server = createServer((_req, res) => {
setTimeout(() => {
diff --git a/packages/runtime/src/bots/proxied-fetch.ts b/packages/runtime/src/bots/proxied-fetch.ts
index 7726901eae..db697d6aeb 100644
--- a/packages/runtime/src/bots/proxied-fetch.ts
+++ b/packages/runtime/src/bots/proxied-fetch.ts
@@ -24,6 +24,11 @@ import { resolveActiveProxy } from '../network/active-proxy-state.js';
import { FETCH_PROXY_SNAPSHOT } from '../network/scoped-fetch-transport.js';
const DEFAULT_TIMEOUT_MS = 15_000;
+// Bounded wait for dispatcher teardown in the error path: a graceful close
+// that never settles must not delay the rejection the caller is owed. The
+// success path keeps its fire-and-forget close, which owns the streaming
+// body lifecycle and is not bounded here.
+const DISPATCHER_CLOSE_GRACE_MS = 1_000;
export type ProxiedFetchInit = Omit<
NonNullable<Parameters<typeof globalThis.fetch>[1]>,
@@ -95,8 +100,34 @@ export async function proxiedFetch(
: ((await request) as unknown as Response);
} catch (error) {
if (timer) clearTimeout(timer);
+ // Mirror the shared transport teardown ordering: begin dispatcher
+ // teardown before aborting so the graceful close can retire live
+ // CONNECT tunnels, with abort still cancelling pending connects. Keep
+ // the wait bounded so a stalled close cannot hold the rejection.
+ const teardown = disposeDispatcher(timedOut);
controller.abort(error);
- await disposeDispatcher(timedOut);
+ let graceTimer: ReturnType<typeof setTimeout> | undefined;
+ const graceExpired = await Promise.race([
+ teardown.then(() => false),
+ new Promise<boolean>((resolve) => {
+ graceTimer = setTimeout(() => resolve(true), DISPATCHER_CLOSE_GRACE_MS);
+ }),
+ ]);
+ if (graceTimer) clearTimeout(graceTimer);
+ if (graceExpired) {
+ // The graceful close never settled within the grace, so destroy the
+ // dispatcher instead of leaking it. Fire-and-forget with the error
+ // swallowed: teardown must never replace the rejection the caller is
+ // owed.
+ const disposable = dispatcher as {
+ destroy?: (error?: Error) => void | Promise<void>;
+ };
+ if (typeof disposable.destroy === 'function') {
+ void Promise.resolve(
+ disposable.destroy.call(dispatcher, new Error('Dispatcher close grace expired')),
+ ).catch(() => {});
+ }
+ }
throw error;
}
diff --git a/packages/runtime/src/network/__tests__/proxy-test.test.ts b/packages/runtime/src/network/__tests__/proxy-test.test.ts
index 016ecc8522..2905164be1 100644
--- a/packages/runtime/src/network/__tests__/proxy-test.test.ts
+++ b/packages/runtime/src/network/__tests__/proxy-test.test.ts
@@ -20,6 +20,8 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import net from 'node:net';
+import { ProxyAgent } from 'undici';
+import { withTimeout } from '@maka/core/test-only/async-primitives';
import { PROXY_DEFAULTS } from '@maka/core/settings/network-settings';
import { testProxyConnection } from '../proxy-test.js';
@@ -97,6 +99,90 @@ describe('testProxyConnection', () => {
}
});
+ test('settles after a successful probe even when the dispatcher close stalls', async (t) => {
+ const sockets = new Set<net.Socket>();
+ const server = net.createServer((socket) => {
+ sockets.add(socket);
+ socket.on('close', () => sockets.delete(socket));
+ socket.on('error', () => sockets.delete(socket));
+
+ let buffer = '';
+ let tunnelEstablished = false;
+ socket.on('data', (chunk) => {
+ buffer += chunk.toString('latin1');
+ const headerEnd = buffer.indexOf('\r\n\r\n');
+ if (headerEnd === -1) return;
+
+ const requestHead = buffer.slice(0, headerEnd);
+ buffer = buffer.slice(headerEnd + 4);
+ if (!tunnelEstablished && requestHead.startsWith('CONNECT ')) {
+ tunnelEstablished = true;
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ return;
+ }
+
+ socket.end('HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
+ });
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => resolve());
+ });
+ const address = server.address();
+ assert.ok(address && typeof address === 'object');
+
+ // Reproduce the dispatcher completion failure independently of
+ // Undici/Node version: a graceful close that never settles must not keep
+ // testProxyConnection (and the serialized settings lane it occupies)
+ // pending forever after the probe itself has finished.
+ t.mock.method(ProxyAgent.prototype, 'close', () => new Promise<void>(() => {}));
+
+ try {
+ const result = await withTimeout(
+ testProxyConnection({
+ proxy: {
+ ...PROXY_DEFAULTS,
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: address.port,
+ },
+ url: 'http://example.com',
+ timeoutMs: 2_000,
+ }),
+ 5_000,
+ 'testProxyConnection never settled after a stalled dispatcher close',
+ );
+
+ assert.strictEqual(result.ok, true);
+ } finally {
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ });
+
+ test('destroys the dispatcher when a stalled close outlives the teardown grace', async (t) => {
+ // Reproduce the dispatcher completion failure independently of
+ // Undici/Node version: once the bounded teardown grace expires with the
+ // graceful close still pending, the abandoned dispatcher must be
+ // destroyed instead of leaking.
+ t.mock.method(ProxyAgent.prototype, 'close', () => new Promise<void>(() => {}));
+ const destroyMock = t.mock.method(ProxyAgent.prototype, 'destroy', () => {});
+
+ const result = await withTimeout(
+ testProxyConnection({
+ proxy: { ...PROXY_DEFAULTS, enabled: true, type: 'http', host: '127.0.0.1', port: 1 },
+ url: 'http://example.com',
+ timeoutMs: 1_000,
+ }),
+ 5_000,
+ 'testProxyConnection never settled after the teardown grace expired',
+ );
+
+ assert.strictEqual(result.ok, false);
+ assert.ok(destroyMock.mock.callCount() > 0);
+ });
+
test('times out when the proxy accepts TCP but never responds', async () => {
const sockets = new Set<net.Socket>();
const server = net.createServer((socket) => {
diff --git a/packages/runtime/src/network/proxy-test.ts b/packages/runtime/src/network/proxy-test.ts
index 2c9d933bf8..150e9ae972 100644
--- a/packages/runtime/src/network/proxy-test.ts
+++ b/packages/runtime/src/network/proxy-test.ts
@@ -28,6 +28,10 @@ import { fetch, type Dispatcher } from 'undici';
const DEFAULT_PROBE_URL = 'https://icanhazip.com';
const DEFAULT_TIMEOUT_MS = 8_000;
+// Bounded wait for dispatcher teardown: a graceful close that never settles
+// (observed behind real proxies after an abort) must not keep this call β
+// and the serialized settings lane it runs on β pending forever.
+const DISPATCHER_CLOSE_GRACE_MS = 1_000;
export async function testProxyConnection(
input: TestProxyInput = {},
@@ -101,8 +105,34 @@ export async function testProxyConnection(
error: error instanceof Error ? error.message : String(error),
};
} finally {
+ // Mirror the shared transport teardown ordering: begin dispatcher
+ // teardown before aborting, so the graceful close can retire live
+ // CONNECT tunnels before the signal kills their sockets; abort still
+ // cancels any pending connect or handshake. Keep the wait bounded so a
+ // stalled close cannot hold this call past its result.
+ const teardown = disposeDispatcher(timedOut);
controller.abort();
- await disposeDispatcher(timedOut);
+ let graceTimer: ReturnType<typeof setTimeout> | undefined;
+ const graceExpired = await Promise.race([
+ teardown.then(() => false),
+ new Promise<boolean>((resolve) => {
+ graceTimer = setTimeout(() => resolve(true), DISPATCHER_CLOSE_GRACE_MS);
+ }),
+ ]);
+ if (graceTimer) clearTimeout(graceTimer);
+ if (graceExpired) {
+ // The graceful close never settled within the grace, so destroy the
+ // dispatcher instead of leaking it. Fire-and-forget with the error
+ // swallowed: teardown must never replace the result this call owes.
+ const disposable = dispatcher as {
+ destroy?: (error?: Error) => void | Promise<void>;
+ };
+ if (typeof disposable.destroy === 'function') {
+ void Promise.resolve(
+ disposable.destroy.call(dispatcher, new Error('Dispatcher close grace expired')),
+ ).catch(() => {});
+ }
+ }
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org