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
2 changes: 1 addition & 1 deletion dist/cli.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/cli.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

50 changes: 50 additions & 0 deletions src/payment-preauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,56 @@ describe("payment pre-auth — per-request pricing safety", () => {
spy.mockRestore();
});

it("hands every send the caller's own signal, so an abort survives GC of the Request", async () => {
// Node's fetch follows a Request's signal only through a weak reference:
// once the Request this module builds is collected, aborting the caller's
// signal no longer reaches a fetch in flight (repro: a cloned Request on a
// hung socket, gc(), abort — the fetch never settles). The fix passes the
// caller's signal to each send; pin that it is the SAME object, not a
// follower, on the unpaid probe, the paid retry and a pre-auth send.
const gw = fakeGateway();
const signals: Array<AbortSignal | null | undefined> = [];
const recording = (async (input: RequestInfo | URL, init?: RequestInit) => {
signals.push(init?.signal);
return gw.fn(input, init);
}) as typeof fetch;
const pay = createPayFetchWithPreAuth(recording, testClient(), undefined, {
estimateAmount: () => "1000",
});
const caller = new AbortController();

await pay(URL, { method: "POST", body: body(), signal: caller.signal }); // probe + paid retry
await pay(URL, { method: "POST", body: body(), signal: caller.signal }); // pre-auth
expect(gw.calls.map((c) => c.paid)).toEqual([false, true, true]);
expect(signals).toHaveLength(3);
for (const signal of signals) expect(signal).toBe(caller.signal);
});

it("honours an explicit signal: null that detaches an aborted input Request", async () => {
const gw = fakeGateway();
// Like real fetch: a send whose effective signal is already aborted rejects.
const honouringAbort = (async (input: RequestInfo | URL, init?: RequestInit) => {
const signal =
init?.signal !== undefined
? init.signal
: input instanceof Request
? input.signal
: undefined;
if (signal?.aborted) throw new DOMException("This operation was aborted", "AbortError");
return gw.fn(input, init);
}) as typeof fetch;
const pay = createPayFetchWithPreAuth(honouringAbort, testClient(), undefined, {
estimateAmount: () => "1000",
});
const aborted = new AbortController();
aborted.abort();
const input = new Request(URL, { method: "POST", body: body(), signal: aborted.signal });

const res = await pay(input, { signal: null });
expect(res.status).toBe(200);
expect(gw.calls.map((c) => c.paid)).toEqual([false, true]);
});

it("disables pre-auth entirely when no estimator is provided (never underpays)", async () => {
const gw = fakeGateway();
const pay = createPayFetchWithPreAuth(gw.fn, testClient(), undefined, {}); // no estimateAmount
Expand Down
26 changes: 22 additions & 4 deletions src/payment-preauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,24 @@ export function createPayFetchWithPreAuth(

return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const request = new Request(input, init);
// Every request below is `request` or a clone of it, and Node's fetch ties a
// Request's signal to the caller's only through a weak reference: once the
// Request built here is garbage-collected, an abort of the caller's signal
// no longer reaches the fetch in flight. The proxy's global deadline and
// client-disconnect abort then do nothing, and a hung upstream holds the
// call until the socket times out (a batch payment in flight sat through a
// 1.5s deadline for 30s+ once GC ran mid-request). Passing the caller's
// own signal to each fetch keeps the link strong. An explicit
// `signal: null` detaches the input Request's signal, so only an absent
// one inherits it.
const callerSignal =
init?.signal !== undefined
? init.signal
: input instanceof Request
? input.signal
: undefined;
const send: FetchFn = (req, extra) =>
baseFetch(req, callerSignal ? { ...extra, signal: callerSignal } : extra);
const urlPath = new URL(request.url).pathname;

// Extract model + size from the request body. Model gives a per-model cache
Expand Down Expand Up @@ -250,7 +268,7 @@ export function createPayFetchWithPreAuth(
preAuthRequest.headers.set(key, value);
}
paymentInFlight = true;
const response = await baseFetch(preAuthRequest);
const response = await send(preAuthRequest);
if (response.status !== 402) {
notifyAcceptedPayment(response, payload);
return response; // Pre-auth worked — saved ~200ms
Expand Down Expand Up @@ -292,7 +310,7 @@ export function createPayFetchWithPreAuth(
const closesAtStart = batch ? await batch.payer.closeFence() : undefined;
const batchTemplate = batch ? request.clone() : undefined;
const clonedRequest = request.clone();
const response = await baseFetch(request);
const response = await send(request);
if (response.status !== 402) {
return response;
}
Expand Down Expand Up @@ -330,7 +348,7 @@ export function createPayFetchWithPreAuth(
batchTemplate,
paymentRequired,
closesAtStart,
baseFetch,
send,
httpClient,
);
if (outcome.kind === "done") {
Expand Down Expand Up @@ -358,7 +376,7 @@ export function createPayFetchWithPreAuth(
for (const [key, value] of Object.entries(paymentHeaders)) {
clonedRequest.headers.set(key, value);
}
const paidResponse = await baseFetch(clonedRequest);
const paidResponse = await send(clonedRequest);
if (paidResponse.status === 402) notifyDeclinedPayment();
notifyAcceptedPayment(paidResponse, payload);
return paidResponse;
Expand Down
Loading