Skip to content

Commit daac727

Browse files
committed
fix(http): carry bound waitUntil onto the narrowed request
1 parent 529fbda commit daac727

3 files changed

Lines changed: 118 additions & 1 deletion

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ Never touch contents inside `<!-- automd -->` in README.md. They are auto genera
9292
## Design Decisions
9393

9494
- No h3/srvx/unstorage dependency — fully standalone
95-
- `waitUntil` is typed as optional on `ServerRequest` (`event.req`) — runtime-specific (srvx ServerRequest, Cloudflare), accessed via `event?.req.waitUntil?.(promise)`
95+
- `waitUntil` is typed as optional on `ServerRequest` (`event.req`) — runtime-specific (srvx ServerRequest, Cloudflare), accessed via `event?.req.waitUntil?.(promise)`. `http.ts`'s request narrowing replaces `event.req` with a fresh `Request`, so it carries `waitUntil` over alongside `runtime`, **bound to the original request** (a bare copy would run with the narrowed `Request` as its receiver; srvx/Cloudflare implement it against the real one). All four `cache.ts` call sites — cache write, SWR background refresh, and both evictions — read `event.req.waitUntil` _after_ that swap, so dropping it made every background write inert on exactly the runtimes that provide it: the isolate can be torn down before the write lands, i.e. every request a MISS forever, with SWR refreshes and post-failure evictions cancelled the same way
9696
- `event.url` is optional — `http.ts` falls back to `new URL(event.req.url)`
9797
- Storage methods are `get`/`set` (not `getItem`/`setItem`)
9898
- `base` supports `string | string[]` — multi-tier: reads try each prefix in order (first hit wins), writes go to all prefixes

‎src/http.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,15 @@ export function defineCachedHandler<E extends HTTPEvent = HTTPEvent>(
479479
if ((originalReq as any).runtime) {
480480
(event.req as any).runtime = (originalReq as any).runtime;
481481
}
482+
// Inherit the runtime's background-task hook — *bound* to the original request,
483+
// since a bare copy would run with the narrowed Request as its receiver (srvx and
484+
// Cloudflare both implement it against the real request). Every background cache
485+
// write, SWR refresh and eviction in `cache.ts` reads `event.req.waitUntil` *after*
486+
// this swap, so dropping it makes all of them inert on exactly the runtimes that
487+
// provide it: the isolate can be torn down before the write lands.
488+
if (typeof originalReq.waitUntil === "function") {
489+
event.req.waitUntil = originalReq.waitUntil.bind(originalReq);
490+
}
482491
if (allowedQueryNames && event.url) {
483492
(event as any).url = new URL(_reqUrl);
484493
}

‎test/index.test.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4529,3 +4529,111 @@ describe("getKey returning Object.prototype member names", () => {
45294529
expect(calls).toBe(1);
45304530
});
45314531
});
4532+
4533+
// Request narrowing swaps `event.req` for a plain `new Request(...)` and used to copy only
4534+
// `runtime`, dropping `waitUntil`. Every background cache write, SWR refresh and eviction in
4535+
// `cache.ts` reads `event.req.waitUntil` *after* that swap, so on the very runtimes that
4536+
// provide it (Cloudflare Workers, srvx) none of them were ever handed to the runtime: the
4537+
// isolate can be torn down before the write lands, making every request a MISS forever.
4538+
// The copy must be *bound* to the original request — a bare copy loses the receiver.
4539+
describe("waitUntil survives request narrowing", () => {
4540+
// The original request carries a cookie, which narrowing always strips (no `allowCookies`),
4541+
// so a receiver-dependent `waitUntil` can tell the original request from the narrowed one.
4542+
function makeWaitUntilEvent(path: string) {
4543+
const promises: Promise<unknown>[] = [];
4544+
const receivers: unknown[] = [];
4545+
const seenCookies: (string | null)[] = [];
4546+
const req = new Request(`http://localhost${path}`, { headers: { cookie: "sid=s1" } });
4547+
(req as any).waitUntil = function (this: Request, promise: Promise<unknown>) {
4548+
receivers.push(this);
4549+
seenCookies.push(this.headers.get("cookie"));
4550+
promises.push(promise);
4551+
};
4552+
return { event: { req } as HTTPEvent, req, promises, receivers, seenCookies };
4553+
}
4554+
4555+
it("registers exactly one waitUntil call for the cache write on a MISS", async () => {
4556+
let calls = 0;
4557+
const handler = defineCachedHandler(
4558+
() => {
4559+
calls++;
4560+
return new Response("ok");
4561+
},
4562+
{ maxAge: 10, name: "wuMiss" },
4563+
);
4564+
4565+
const { event, promises } = makeWaitUntilEvent("/wu-miss");
4566+
const r1 = (await handler(event)) as Response;
4567+
expect(r1.headers.get("x-cache")).toBe("MISS");
4568+
expect(calls).toBe(1);
4569+
// The cache write — and nothing else — was handed to the runtime.
4570+
expect(promises).toHaveLength(1);
4571+
4572+
await Promise.all(promises);
4573+
const r2 = (await handler({ req: new Request("http://localhost/wu-miss") })) as Response;
4574+
expect(r2.headers.get("x-cache")).toBe("HIT");
4575+
expect(calls).toBe(1);
4576+
});
4577+
4578+
it("registers the SWR background refresh on a stale read", async () => {
4579+
let calls = 0;
4580+
const handler = defineCachedHandler(
4581+
() => {
4582+
calls++;
4583+
return new Response(`v${calls}`);
4584+
},
4585+
{ maxAge: 0.01, swr: true, staleMaxAge: 10, name: "wuSwr" },
4586+
);
4587+
4588+
const first = makeWaitUntilEvent("/wu-swr");
4589+
await handler(first.event);
4590+
await Promise.all(first.promises);
4591+
expect(calls).toBe(1);
4592+
4593+
await new Promise((r) => setTimeout(r, 20));
4594+
4595+
const second = makeWaitUntilEvent("/wu-swr");
4596+
const stale = (await handler(second.event)) as Response;
4597+
expect(stale.headers.get("x-cache")).toBe("STALE");
4598+
expect(await stale.text()).toBe("v1");
4599+
// The background revalidation was handed to the runtime instead of being left to run
4600+
// untracked (where the isolate would be free to die before it finishes).
4601+
expect(second.promises.length).toBeGreaterThanOrEqual(1);
4602+
4603+
await Promise.all(second.promises);
4604+
// The refresh's own cache write is registered too; drain it as the runtime would.
4605+
await Promise.all(second.promises);
4606+
expect(calls).toBe(2);
4607+
});
4608+
4609+
it("hands waitUntil to the resolver bound to the original request", async () => {
4610+
let seenInHandler: unknown;
4611+
const handler = defineCachedHandler(
4612+
(event: HTTPEvent) => {
4613+
seenInHandler = event.req.waitUntil;
4614+
return new Response("ok");
4615+
},
4616+
{ maxAge: 10, name: "wuBound" },
4617+
);
4618+
4619+
const { event, req, promises, receivers, seenCookies } = makeWaitUntilEvent("/wu-bound");
4620+
await handler(event);
4621+
4622+
// The resolver ran against the narrowed request (cookie stripped) and still saw waitUntil.
4623+
expect(event.req).not.toBe(req);
4624+
expect(typeof seenInHandler).toBe("function");
4625+
expect(event.req.headers.get("cookie")).toBe(null);
4626+
4627+
// Bound: every call ran with the ORIGINAL request as `this`, so a receiver-dependent
4628+
// implementation still sees the real request. A bare copy would pass the narrowed one.
4629+
expect(receivers.length).toBeGreaterThan(0);
4630+
expect(receivers.every((r) => r === req)).toBe(true);
4631+
expect(seenCookies.every((c) => c === "sid=s1")).toBe(true);
4632+
4633+
// Still reachable and callable after the handler returned.
4634+
const later = Promise.resolve("later");
4635+
event.req.waitUntil!(later);
4636+
expect(promises.at(-1)).toBe(later);
4637+
expect(receivers.at(-1)).toBe(req);
4638+
});
4639+
});

0 commit comments

Comments
 (0)