From d52ee6619736081c81d0f098f7c4321819fbd5c4 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 5 Nov 2026 21:10:54 -0700 Subject: [PATCH 1/2] Test that an attempt is given up whatever the fetch does Regression tests for #33, which fail until send() has its own bound: a fetch that ignores its abort signal, a late answer or failure, and a body that never ends. The flush()/close() drain test gives each drain its own client, since the second drain would otherwise find nothing in flight once attempts are given up at the timeout. Co-Authored-By: Claude Opus 5.5 --- tests/trace-client.test.ts | 101 ++++++++++++++++++++++++++++++++----- 1 file changed, 89 insertions(+), 12 deletions(-) diff --git a/tests/trace-client.test.ts b/tests/trace-client.test.ts index bb17901..a569a0a 100644 --- a/tests/trace-client.test.ts +++ b/tests/trace-client.test.ts @@ -302,6 +302,81 @@ describe("TraceClient", () => { await client.close(); }); + it("gives up at the timeout when fetch ignores the abort, and frees every slot", { timeout: 15000 }, async () => { + // A wrapper that drops the signal: only the client's own timer can end these attempts. + let calls = 0; + const client = new TraceClient(baseUrl, "MyGame", { + version: "1.2.3", + key: "k", + timeoutMs: 300, + debug, + fetch: (() => { + calls++; + if (calls <= TraceClient.IN_FLIGHT_CAPACITY) return new Promise(() => {}); + return Promise.resolve(new Response(null, { status: 201 })); + }) as typeof fetch, + }); + const work: Promise[] = []; + for (let i = 0; i < TraceClient.IN_FLIGHT_CAPACITY; i++) work.push(client.report("ignored-abort")); + await Promise.all(work); // report()'s promise settles when the attempt is given up + assert.equal( + log.filter((line) => line.includes("could not deliver")).length, + TraceClient.IN_FLIGHT_CAPACITY, + "every attempt given up is logged as a drop", + ); + await client.report("after"); + assert.equal(calls, TraceClient.IN_FLIGHT_CAPACITY + 1, "the slots must be free for the report after them"); + assert.ok(!log.some((line) => line.includes("in-flight cap reached")), log.join("\n")); + await client.close(); + }); + + it("discards an answer or a failure that arrives after the attempt was given up", { timeout: 15000 }, async () => { + const late: Array<{ answer: (response: Response) => void; fail: (failure: Error) => void }> = []; + const client = new TraceClient(baseUrl, "MyGame", { + version: "1.2.3", + key: "k", + timeoutMs: 200, + debug, + fetch: (() => + new Promise((answer, fail) => { + late.push({ answer, fail }); + })) as typeof fetch, + }); + await Promise.all([client.report("answered-late"), client.report("failed-late")]); + assert.equal(log.length, 2, log.join("\n")); + + let bodyRead = false; + const response = new Response(null, { status: 500 }); + response.arrayBuffer = async () => { + bodyRead = true; + return new ArrayBuffer(0); + }; + late[0].answer(response); + late[1].fail(new Error("too late")); // an unhandled rejection here would fail this test + await sleep(50); + assert.equal(bodyRead, false, "a late response's body must not be read"); + assert.equal(log.length, 2, `a late result must not be logged as well: ${log.join("\n")}`); + await client.close(); + }); + + it("stops waiting on a body that never ends, without calling the report dropped", { timeout: 15000 }, async () => { + // The server has answered by then, so this is not a failed delivery; an unreadable body never is. + const client = new TraceClient(baseUrl, "MyGame", { + version: "1.2.3", + key: "k", + timeoutMs: 200, + debug, + fetch: (async () => { + const response = new Response(null, { status: 201 }); + response.arrayBuffer = () => new Promise(() => {}); + return response; + }) as typeof fetch, + }); + await client.report("startup"); + assert.deepEqual(log, []); + await client.close(); + }); + it("sends nothing when disabled or without a key", async () => { const clients = [ new TraceClient(baseUrl, "MyGame", { version: "1.2.3", key: "k", enabled: false }), @@ -766,28 +841,30 @@ describe("TraceClient", () => { }); it("flush() and close() with no argument wait at most the client's own timeout, even when fetch ignores the abort", async () => { - // A fetch that never settles, abort or not: only the drain's own bound can end the wait. - const client = new TraceClient(baseUrl, "MyGame", { - version: "1.2.3", - key: "k", - timeoutMs: 300, - fetch: (() => new Promise(() => {})) as typeof fetch, - }); - client.report("startup"); + // A fetch that never settles, abort or not. Each drain gets its own client: the + // attempt is given up at the timeout, which leaves a second drain nothing to wait on. for (const [label, drain] of [ - ["flush()", () => client.flush()], - ["close()", () => client.close()], + ["flush()", (client: TraceClient) => client.flush()], + ["close()", (client: TraceClient) => client.close()], ] as const) { + const client = new TraceClient(baseUrl, "MyGame", { + version: "1.2.3", + key: "k", + timeoutMs: 300, + fetch: (() => new Promise(() => {})) as typeof fetch, + }); + client.report("startup"); const before = Date.now(); - await drain(); + await drain(client); const elapsed = Date.now() - before; assert.ok(elapsed >= 250, `${label} took ${elapsed}ms; it must wait for in-flight work up to the timeout`); assert.ok( elapsed < 2000, `${label} took ${elapsed}ms; it must default to timeoutMs (300), not ${TraceClient.TIMEOUT_MS} or forever`, ); + assert.equal(client.enabled, label === "flush()", "only close() turns the client off"); + await client.close(); } - assert.equal(client.enabled, false); }); it("rejects a missing, blank or overlong version at construction", () => { From cbd20f75eeb011281cac6f9c9647f302de8cb096 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 5 Nov 2026 21:12:25 -0700 Subject: [PATCH 2/2] Give up on a fetch that ignores its abort signal send() relied on the fetch honouring the abort, so a custom fetch that dropped the signal left report()'s promise unsettled and held its in-flight slot for good. Race the fetch and the body read against the timeout instead. Closes #33. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +++++++ README.md | 2 +- trace-client.ts | 41 ++++++++++++++++++++++++++++------------- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0eabf4e..d83dc09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ against this file to see what a re-vendor would bring. ## [Unreleased] +- A request is now given up at `timeoutMs` whatever the `fetch` does. A + custom `fetch` that ignored its abort signal used to leave the `report()` + promise unsettled and keep its in-flight slot for good, so 256 of them + dropped every later report. It is now a logged drop, and a late answer or + failure from it is discarded, its body unread. A response body that never + ends no longer holds the slot either, and is not logged, since the server + has answered. - `report()` no longer throws or rejects when the failure it is logging cannot be turned into a string, such as an `Object.create(null)` thrown by a tag's `toString` or by a custom `fetch`. The rejecting case also kept diff --git a/README.md b/README.md index 049c8e3..bb61a83 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ Besides `version`, `key`, `enabled` and `env`, the constructor's options take: | Option | Default | Meaning | |---|---|---| | `timeoutMs` | `5000` | How long one request may take before it is aborted. Anything but a positive finite number — `0`, negative, `NaN`, `Infinity`, not a number — falls back to the default. A longer one than `2147483647` (about 24.8 days, the most a timer can hold) is held to that. | -| `fetch` | the global `fetch` | The `fetch` to send with, for a runtime that provides its own or for tests. | +| `fetch` | the global `fetch` | The `fetch` to send with, for a runtime that provides its own or for tests. One that ignores its abort signal is given up on at the timeout all the same, and anything it does later is discarded. | | `installId` | none | The installation's ID, sent as the tag `install`; see [above](#every-event-carries-a-random-installation-id). | | `installIdFile` | none | A file holding the installation's ID, created with a random UUID on first run by an enabled client. | | `debug` | none | Called with one line per dropped report, prefixed `[trace] `. A `debug` that throws, or an `async` one that rejects, is ignored; its promise is not waited for. | diff --git a/trace-client.ts b/trace-client.ts index 51be677..f6cfce6 100644 --- a/trace-client.ts +++ b/trace-client.ts @@ -69,7 +69,10 @@ export interface TraceClientOptions { * Held to 2147483647 (about 24.8 days), the longest a timer can wait. */ timeoutMs?: number; - /** The `fetch` to use. Default: the global one. */ + /** + * The `fetch` to use. Default: the global one. One that ignores its abort + * signal is given up on at `timeoutMs` all the same. + */ fetch?: typeof fetch; /** Receives one line per dropped report. Default: silence. A throw or rejection from it is ignored. */ debug?: (message: string) => void; @@ -415,23 +418,35 @@ export class TraceClient { private async send(body: string): Promise { const doFetch = this.fetchImpl ?? fetch; const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), this.timeoutMs); + let timer: ReturnType | undefined; + // The abort goes first, so a fetch that honours it reports its own failure. + // One that ignores it can no longer hold the slot: the attempt ends here, + // and whatever that fetch does later is discarded, its body unread. + const givenUp = new Promise((_, reject) => { + timer = setTimeout(() => { + controller.abort(); + reject(new Error(`no answer within ${this.timeoutMs}ms`)); + }, this.timeoutMs); + }); try { - const response = await doFetch(this.endpoint, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer " + this.key, - "User-Agent": `trace-client-js/${TRACE_CLIENT_VERSION} (${this.application})`, - }, - body, - signal: controller.signal, - }); + const response = await Promise.race([ + doFetch(this.endpoint, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + this.key, + "User-Agent": `trace-client-js/${TRACE_CLIENT_VERSION} (${this.application})`, + }, + body, + signal: controller.signal, + }), + givenUp, + ]); if (!response.ok) { this.log(`trace server answered ${response.status} for ${body}`); } // Let the connection be reused; never fail on an unreadable body. - await response.arrayBuffer().catch(() => undefined); + await Promise.race([response.arrayBuffer(), givenUp]).catch(() => undefined); } finally { clearTimeout(timer); }