Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
101 changes: 89 additions & 12 deletions tests/trace-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response>(() => {});
return Promise.resolve(new Response(null, { status: 201 }));
}) as typeof fetch,
});
const work: Promise<void>[] = [];
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<Response>((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<ArrayBuffer>(() => {});
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 }),
Expand Down Expand Up @@ -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<Response>(() => {})) 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<Response>(() => {})) 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", () => {
Expand Down
41 changes: 28 additions & 13 deletions trace-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -415,23 +418,35 @@ export class TraceClient {
private async send(body: string): Promise<void> {
const doFetch = this.fetchImpl ?? fetch;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
let timer: ReturnType<typeof setTimeout> | 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<never>((_, 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);
}
Expand Down
Loading