diff --git a/README.md b/README.md index d07e1cf..7a35da5 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,19 @@ runtimeName // 'node' | 'deno' | 'bun' | 'workerd' | … ('' when unknown) — v Host detection is delegated to [`std-env`](https://github.com/unjs/std-env) (which tracks the WinterCG Runtime Keys proposal), once at module load. On Cloudflare Workers, env bindings are not ambient — they arrive per request as the second `fetch` argument — so the entry call captures them module-scoped and `getEnv` reads them first, falling back to the host's global env (`process.env`, `Deno.env`). One consequence: on Workers, `getEnv` returns `undefined` at module top level, before the first request. -Supported entry signatures are **`(request)`** and **`(request, env)`**. A third `fetch` argument — the Workers `ExecutionContext` (`waitUntil` / `passThroughOnException`) — is **not honored**: it's ignored with a one-time `console.warn`. The Deno target never passes one. +Supported entry signatures are **`(request)`**, **`(request, env)`** and **`(request, env, executionContext)`**. The third `fetch` argument, the Workers `ExecutionContext`, is kept on the seeded context behind a symbol (not a `ctx` key), and `waitUntil` hands background work to it from any middleware or the handler: + +```ts +import { waitUntil } from '@supabase/middleware' +;async (req, ctx) => { + waitUntil(ctx, flushTelemetry()) // keeps the request alive after the response + return new Response('ok') +} +``` + +A host without a bindings argument can pass its execution context second, as Next.js does with the `proxy(request, event)` event. A second argument with a `waitUntil` method is taken as the execution context, so `waitUntil` reaches it there too, and it is not captured as the platform env. + +When the host passed no execution context (the Deno target never passes one), `waitUntil` runs the promise unattached and logs a rejection, so middleware can call it on any host. `passThroughOnException` is not used. ## Request-side by default diff --git a/src/core/define-middleware.test.ts b/src/core/define-middleware.test.ts index 44c1736..e3f37d5 100644 --- a/src/core/define-middleware.test.ts +++ b/src/core/define-middleware.test.ts @@ -84,7 +84,7 @@ describe('defineMiddleware', () => { seedContext({}) // clear the stash so other tests see a clean slate }) - it('warns (does not throw) and ignores a third fetch argument (exec context)', async () => { + it('accepts a third fetch argument (exec context) without warning or leaking it into ctx', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { const fetchHandler = withGreeting(async (_req, ctx) => @@ -96,10 +96,11 @@ describe('defineMiddleware', () => { fetchHandler as (req: Request, ...a: unknown[]) => Promise )(new Request('http://localhost/'), { SECRET: 's' }, { waitUntil() {} }) - // Proceeds normally; the env (arg 2) still does not leak into ctx, and the - // execution context (arg 3) is ignored rather than throwing. + // Neither the env (arg 2) nor the execution context (arg 3) becomes a + // ctx key; the execution context is reachable only through waitUntil. expect(res.status).toBe(200) expect(await res.json()).toEqual({ keys: ['greeting'] }) + expect(warn).not.toHaveBeenCalled() } finally { warn.mockRestore() } diff --git a/src/core/define-middleware.ts b/src/core/define-middleware.ts index 8e6d295..479a8d7 100644 --- a/src/core/define-middleware.ts +++ b/src/core/define-middleware.ts @@ -2,20 +2,6 @@ import type { ConfigArgs, Conflict, ContributedKeys, Entry } from './types.js' import type { BaseContext } from './runtime.js' import { bufferRequest, isContext, seedContext } from './runtime.js' -/** - * Warn (once per process) that a host passed a third `fetch` argument — the - * Workers `ExecutionContext` (`waitUntil` / `passThroughOnException`) — which is - * not honored. The request still proceeds; only the execution context is ignored. - */ -let warnedThirdArg = false -function warnUnhonoredThirdArg(): void { - if (warnedThirdArg) return - warnedThirdArg = true - console.warn( - 'middleware: a third fetch argument (the Workers ExecutionContext / waitUntil) was supplied but is not honored; it will be ignored. Supported entry signatures are (request) and (request, env).', - ) -} - /** * Defines a middleware. * @@ -166,12 +152,11 @@ export function defineMiddleware< upstream = maybeCtx } else { // Entry call. A third positional argument is the host's execution - // context (the Cloudflare Workers `ExecutionContext` — `waitUntil` / - // `passThroughOnException`). We don't honor it; warn once rather than - // silently dropping it, and continue (the Deno target never passes one). - if (rest.length > 0) warnUnhonoredThirdArg() + // context (the Cloudflare Workers `ExecutionContext`). It rides the + // seeded context behind a symbol for `waitUntil`; the Deno target never + // passes one. workingReq = req.body ? bufferRequest(req) : req - upstream = seedContext(maybeCtx) + upstream = seedContext(maybeCtx, rest[0]) } const runInner = handler diff --git a/src/core/index.ts b/src/core/index.ts index 17d055a..7ed7933 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -31,9 +31,11 @@ export { isContext, runtimeName, seedContext, + waitUntil, } from './runtime.js' export type { BaseContext, + ExecutionContextLike, FetchHandler, Handler, RuntimeName, diff --git a/src/core/runtime.test.ts b/src/core/runtime.test.ts index 6060cf7..c972768 100644 --- a/src/core/runtime.test.ts +++ b/src/core/runtime.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { bufferRequest, @@ -6,8 +6,10 @@ import { isContext, runtimeName, seedContext, + waitUntil, } from './runtime.js' import { defineMiddleware } from './define-middleware.js' +import { defineComposite } from './define-composite.js' import { pipeline } from './pipeline.js' describe('importable env access (getEnv)', () => { @@ -115,3 +117,162 @@ describe('bufferRequest (host entry points)', () => { expect(await res.json()).toEqual({ peek: '{"a":1}', handler: '{"a":1}' }) }) }) + +describe('waitUntil', () => { + const withA = defineMiddleware<'a', void, Record, number>({ + key: 'a', + run: () => async (_req, ctx) => { + waitUntil(ctx, Promise.resolve('from-middleware')) + return { a: 1 } + }, + }) + const withB = defineMiddleware<'b', void, Record, number>({ + key: 'b', + run: () => async () => ({ b: 2 }), + }) + + type Fetch = (req: Request, ...args: unknown[]) => Promise + + it("hands promises from every layer to the host's execution context", async () => { + const promises: Promise[] = [] + const executionContext = { + waitUntil(promise: Promise) { + // Called as a method, so a host that needs `this` (workerd) works. + expect(this).toBe(executionContext) + promises.push(promise) + }, + } + const app = pipeline( + [withA(), defineComposite({ build: () => [withB()] as const })()], + async (_req, ctx) => { + waitUntil(ctx, Promise.resolve('from-handler')) + return Response.json(Object.keys(ctx)) + }, + ) as Fetch + + const res = await app( + new Request('http://localhost/'), + {}, + executionContext, + ) + + expect(await res.json()).toEqual(['a', 'b']) + expect(await Promise.all(promises)).toEqual([ + 'from-middleware', + 'from-handler', + ]) + }) + + it('keeps execution contexts apart across concurrent requests', async () => { + const seen: string[] = [] + const app = pipeline([withB()], async (req, ctx) => { + await new Promise((resolve) => setTimeout(resolve, 0)) + waitUntil(ctx, Promise.resolve(new URL(req.url).pathname)) + return new Response() + }) as Fetch + const contextFor = (name: string) => ({ + waitUntil: (promise: Promise) => { + void promise.then((value) => seen.push(`${name}:${String(value)}`)) + }, + }) + + await Promise.all([ + app(new Request('http://localhost/one'), {}, contextFor('one')), + app(new Request('http://localhost/two'), {}, contextFor('two')), + ]) + await Promise.resolve() + + expect(seen.sort()).toEqual(['one:/one', 'two:/two']) + }) + + it('runs the promise unattached and logs a rejection without an execution context', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const failure = new Error('flush failed') + const app = pipeline([withB()], async (_req, ctx) => { + waitUntil(ctx, Promise.reject(failure)) + return new Response('ok') + }) as Fetch + + const res = await app(new Request('http://localhost/')) + expect(await res.text()).toBe('ok') + + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(error).toHaveBeenCalledWith( + 'middleware: a waitUntil promise rejected', + failure, + ) + } finally { + error.mockRestore() + } + }) + + it('takes a second argument with a waitUntil method as the execution context', async () => { + // The shape of the Next.js `proxy(request, event)` event: no bindings, + // `waitUntil` on the prototype, and string fields of its own. + class FetchEvent { + sourcePage = '/proxy' + promises: Promise[] = [] + waitUntil(promise: Promise) { + this.promises.push(promise) + } + } + const event = new FetchEvent() + const app = pipeline([withA()], async (_req, ctx) => { + waitUntil(ctx, Promise.resolve('from-handler')) + return Response.json(Object.keys(ctx)) + }) as Fetch + + seedContext({ BOUND: 'kept' }) + try { + const res = await app(new Request('http://localhost/'), event) + + expect(await res.json()).toEqual(['a']) + expect(await Promise.all(event.promises)).toEqual([ + 'from-middleware', + 'from-handler', + ]) + // The event is not the platform env: its fields are not readable through + // getEnv, and bindings captured earlier are still there. + expect(getEnv('sourcePage')).toBeUndefined() + expect(getEnv('BOUND')).toBe('kept') + } finally { + seedContext({}) + } + }) + + it('prefers the third argument when both carry waitUntil', async () => { + const second = { waitUntil: vi.fn(), BOUND: 'binding' } + const third = { waitUntil: vi.fn() } + const promise = Promise.resolve() + + try { + waitUntil(seedContext(second, third), promise) + + expect(third.waitUntil).toHaveBeenCalledWith(promise) + expect(second.waitUntil).not.toHaveBeenCalled() + // With a real execution context in third position the second argument + // is the bindings object, as before. + expect(getEnv('BOUND')).toBe('binding') + } finally { + seedContext({}) + } + }) + + it('still captures a second argument without waitUntil as the platform env', async () => { + try { + const ctx = seedContext({ BOUND: 'binding', waitUntil: 'not a function' }) + + expect(getEnv('BOUND')).toBe('binding') + expect(() => waitUntil(ctx, Promise.resolve())).not.toThrow() + } finally { + seedContext({}) + } + }) + + it('ignores a third argument without a waitUntil method', async () => { + const ctx = seedContext(undefined, { passThroughOnException() {} }) + expect(Object.keys(ctx)).toEqual([]) + expect(() => waitUntil(ctx, Promise.resolve())).not.toThrow() + }) +}) diff --git a/src/core/runtime.ts b/src/core/runtime.ts index 576125d..cd811db 100644 --- a/src/core/runtime.ts +++ b/src/core/runtime.ts @@ -152,22 +152,108 @@ export type FetchHandler = ( ctx?: BaseContext, ) => Promise +/** + * Carries the host's execution context on a seeded context. Like + * {@link CONTEXT_MARK} it is a symbol, so it flows through every + * `{ ...upstream }` merge and stays invisible to `Object.keys` and to the type. + * It rides the context rather than module scope because, unlike Workers + * bindings, an execution context is different for every request. + */ +const EXECUTION_CONTEXT = Symbol.for('@supabase/middleware:execution-context') + +/** + * The part of a host's execution context this package uses: the Cloudflare + * Workers `ExecutionContext`, or any object with a `waitUntil` method. + * + * @category Types + */ +export interface ExecutionContextLike { + waitUntil(promise: Promise): void +} + +function isExecutionContext(value: unknown): value is ExecutionContextLike { + return ( + !!value && + typeof value === 'object' && + typeof (value as ExecutionContextLike).waitUntil === 'function' + ) +} + /** * Seed a fresh base context for an entry call, capturing the host's second * `fetch` argument (a Workers `env`, a Deno `ServeHandlerInfo`, …) as the * module-scoped platform env for {@link getEnv}. The platform value itself is * never merged into `ctx`. * + * The optional third `fetch` argument, the host's execution context (the + * Workers `ExecutionContext`), is kept on the seeded context behind a symbol so + * {@link waitUntil} can reach it from any layer. It is not a `ctx` key either. + * + * A host without a bindings argument can pass its execution context second, as + * Next.js does with the `proxy(request, event)` event. A second argument with a + * `waitUntil` method is therefore taken as the execution context and is not + * captured as the platform env. + * * Public so a host embedding the engine (e.g. `@supabase/server`) can mint a * valid upstream context and spread its own keys onto it. * * @category Composition */ -export function seedContext(platformArg?: unknown): BaseContext { +export function seedContext( + platformArg?: unknown, + executionContext?: unknown, +): BaseContext { + // Bindings never carry a `waitUntil` function, so an object that does is the + // host's execution context in the second position. + if ( + !isExecutionContext(executionContext) && + isExecutionContext(platformArg) + ) { + executionContext = platformArg + platformArg = undefined + } if (platformArg && typeof platformArg === 'object') { platformEnv = platformArg as Record } - return { [CONTEXT_MARK]: true } + const ctx: Record = { [CONTEXT_MARK]: true } + if (isExecutionContext(executionContext)) { + ctx[EXECUTION_CONTEXT] = executionContext + } + return ctx +} + +/** + * Keep the request alive until `promise` settles, without delaying the + * response: flushing telemetry, writing an audit log, revalidating a cache. + * + * When the host passed an execution context, as the third `fetch` argument (the + * Cloudflare Workers `ExecutionContext`) or as the second (the Next.js `proxy` + * event), this calls its `waitUntil`. Otherwise + * the promise runs unattached and a rejection is logged instead of surfacing as + * an unhandled rejection, so a middleware or handler can call it on any host. + * Hosts that end the invocation with the response (most serverless functions + * without an execution context) may stop the work early in that case. + * + * Pass the `ctx` the middleware or handler received: + * + * ```ts + * async (req, ctx) => { + * waitUntil(ctx, sendAnalytics(req)) + * return new Response('ok') + * } + * ``` + * + * @category Environment + */ +export function waitUntil(ctx: BaseContext, promise: Promise): void { + const executionContext = (ctx as Record)[EXECUTION_CONTEXT] + if (isExecutionContext(executionContext)) { + executionContext.waitUntil(promise) + return + } + Promise.resolve(promise).catch((error: unknown) => { + console.error('middleware: a waitUntil promise rejected', error) + }) } /** diff --git a/src/exports.test.ts b/src/exports.test.ts index 2d187bb..b82abdb 100644 --- a/src/exports.test.ts +++ b/src/exports.test.ts @@ -21,6 +21,7 @@ describe('public API surface', () => { 'pipeline', 'runtimeName', 'seedContext', + 'waitUntil', ]) }) @@ -34,6 +35,7 @@ describe('public API surface', () => { 'pipeline', 'runtimeName', 'seedContext', + 'waitUntil', ]) }) diff --git a/src/index.ts b/src/index.ts index 4655eb7..d0a56d1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,9 +30,11 @@ export { isContext, runtimeName, seedContext, + waitUntil, } from './core/runtime.js' export type { BaseContext, + ExecutionContextLike, FetchHandler, Handler, RuntimeName, diff --git a/test/runtimes/workers/runtime.test.ts b/test/runtimes/workers/runtime.test.ts index 4f7ab4c..b7a0f36 100644 --- a/test/runtimes/workers/runtime.test.ts +++ b/test/runtimes/workers/runtime.test.ts @@ -12,3 +12,10 @@ it('the built engine serves a pipeline inside workerd', async () => { isCtx: true, }) }) + +it('hands waitUntil work to the Workers ExecutionContext', async () => { + const first = await SELF.fetch('http://example.com/background') + expect(await first.json()).toEqual({ ran: false, attached: true }) + const second = await SELF.fetch('http://example.com/background') + expect(await second.json()).toEqual({ ran: true, attached: true }) +}) diff --git a/test/runtimes/workers/worker.ts b/test/runtimes/workers/worker.ts index 7c76ff5..25d8343 100644 --- a/test/runtimes/workers/worker.ts +++ b/test/runtimes/workers/worker.ts @@ -6,6 +6,7 @@ import { isContext, pipeline, runtimeName, + waitUntil, } from '@supabase/middleware' // On Workers, `getEnv` has nothing to read before the first request. @@ -23,15 +24,32 @@ const probe = defineMiddleware< }), }) +// Set by a waitUntil promise that settles after the response is built, to show +// the execution context reached the handler. +let backgroundRan = false + export default { - fetch: pipeline([probe()], async (_req, ctx) => - Response.json({ + fetch: pipeline([probe()], async (req, ctx) => { + if (new URL(req.url).pathname === '/background') { + const ran = backgroundRan + waitUntil( + ctx, + Promise.resolve().then(() => { + backgroundRan = true + }), + ) + // The real ExecutionContext rides the seeded context behind this symbol. + const attached = + Symbol.for('@supabase/middleware:execution-context') in ctx + return Response.json({ ran, attached }) + } + return Response.json({ runtime: runtimeName, atModuleLoad, env: getEnv('WM_RUNTIME_TEST') ?? null, upstreamKeys: ctx.probe.upstreamKeys, handlerKeys: Object.keys(ctx), isCtx: ctx.probe.isCtx, - }), - ), + }) + }), }