Skip to content
Open
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
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,17 @@ 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')
}
```

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

Expand Down
7 changes: 4 additions & 3 deletions src/core/define-middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand All @@ -96,10 +96,11 @@ describe('defineMiddleware', () => {
fetchHandler as (req: Request, ...a: unknown[]) => Promise<Response>
)(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()
}
Expand Down
23 changes: 4 additions & 19 deletions src/core/define-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ export {
isContext,
runtimeName,
seedContext,
waitUntil,
} from './runtime.js'
export type {
BaseContext,
ExecutionContextLike,
FetchHandler,
Handler,
RuntimeName,
Expand Down
100 changes: 99 additions & 1 deletion src/core/runtime.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'

import {
bufferRequest,
getEnv,
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)', () => {
Expand Down Expand Up @@ -115,3 +117,99 @@ describe('bufferRequest (host entry points)', () => {
expect(await res.json()).toEqual({ peek: '{"a":1}', handler: '{"a":1}' })
})
})

describe('waitUntil', () => {
const withA = defineMiddleware<'a', void, Record<never, never>, number>({
key: 'a',
run: () => async (_req, ctx) => {
waitUntil(ctx, Promise.resolve('from-middleware'))
return { a: 1 }
},
})
const withB = defineMiddleware<'b', void, Record<never, never>, number>({
key: 'b',
run: () => async () => ({ b: 2 }),
})

type Fetch = (req: Request, ...args: unknown[]) => Promise<Response>

it("hands promises from every layer to the host's execution context", async () => {
const promises: Promise<unknown>[] = []
const executionContext = {
waitUntil(promise: Promise<unknown>) {
// 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<unknown>) => {
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('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()
})
})
75 changes: 73 additions & 2 deletions src/core/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,22 +152,93 @@ export type FetchHandler = (
ctx?: BaseContext,
) => Promise<Response>

/**
* 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<unknown>): 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.
*
* 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 {
if (platformArg && typeof platformArg === 'object') {
platformEnv = platformArg as Record<string, unknown>
}
return { [CONTEXT_MARK]: true }
const ctx: Record<symbol, unknown> = { [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`), 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<unknown>): void {
const executionContext = (ctx as Record<symbol, unknown>)[EXECUTION_CONTEXT]
if (isExecutionContext(executionContext)) {
executionContext.waitUntil(promise)
return
}
Promise.resolve(promise).catch((error: unknown) => {
console.error('middleware: a waitUntil promise rejected', error)
})
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe('public API surface', () => {
'pipeline',
'runtimeName',
'seedContext',
'waitUntil',
])
})

Expand All @@ -34,6 +35,7 @@ describe('public API surface', () => {
'pipeline',
'runtimeName',
'seedContext',
'waitUntil',
])
})

Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ export {
isContext,
runtimeName,
seedContext,
waitUntil,
} from './core/runtime.js'
export type {
BaseContext,
ExecutionContextLike,
FetchHandler,
Handler,
RuntimeName,
Expand Down
7 changes: 7 additions & 0 deletions test/runtimes/workers/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
})
26 changes: 22 additions & 4 deletions test/runtimes/workers/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
isContext,
pipeline,
runtimeName,
waitUntil,
} from '@supabase/middleware'

// On Workers, `getEnv` has nothing to read before the first request.
Expand All @@ -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,
}),
),
})
}),
}