diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0b80cae..a7170cb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -142,11 +142,11 @@ root README in the same commit. ## Writing a middleware -The full authoring guide — `defineMiddleware`, request-side and generator forms, tests, publishing, and composing alongside the built-in entries — is in [`docs/authoring-guide.md`](./docs/authoring-guide.md). The composition primitives (`ctx` shape, conflict & prerequisite enforcement, the response seam) are documented in [`src/core/README.md`](./src/core/README.md), with [`feature-flag`](./src/middleware/feature-flag/README.md) and [`cors`](./src/middleware/cors/README.md) as worked examples. +The full authoring guide — `defineMiddleware`, request-side and generator forms, tests, publishing, and composing alongside the built-in entries — is in [`docs/authoring-guide.md`](./docs/authoring-guide.md). The composition primitives (`ctx` shape, conflict & prerequisite enforcement, the response seam) are documented in [`src/core/README.md`](./src/core/README.md), with [`feature-flag`](./src/middleware/feature-flag/README.md), [`cors`](./src/middleware/cors/README.md) and [`timing`](./src/middleware/timing/README.md) as worked examples. -Your middleware is its own package. This repository ships the composition primitives and two worked examples (`cors` and `feature-flag`) and takes no new middleware; the authoring guide's [Where it lives](./docs/authoring-guide.md#where-it-lives) section covers the options. Middleware Supabase maintains lives in [`@supabase/server`](https://github.com/supabase/server); to propose one, open an issue there. +Your middleware is its own package. This repository ships the composition primitives and three worked examples (`feature-flag`, `cors` and `timing`) and takes no new middleware; the authoring guide's [Where it lives](./docs/authoring-guide.md#where-it-lives) section covers the options. Middleware Supabase maintains lives in [`@supabase/server`](https://github.com/supabase/server); to propose one, open an issue there. -To change one of the two built-ins, see [`src/middleware/README.md`](./src/middleware/README.md) for the directory layout and subpath wiring. +To change one of the built-ins, see [`src/middleware/README.md`](./src/middleware/README.md) for the directory layout and subpath wiring. ## Submitting Changes diff --git a/README.md b/README.md index d07e1cf..3a9e548 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ deno add jsr:@supabase/middleware | `@supabase/middleware` | `pipeline`, `defineMiddleware`, `getEnv`, `runtimeName`, `seedContext`, `isContext`, and the core types: `Entry`, `FetchHandler`, `Middleware`, `BaseContext`. | | `@supabase/middleware/feature-flag` | Provider-agnostic feature flag — admit or short-circuit per request. | | `@supabase/middleware/cors` | CORS — answers preflight and stamps response headers (the worked example of the response seam). | +| `@supabase/middleware/timing` | Adds the time spent in middleware and in named calls (database queries) to `Server-Timing`. | ## Bundling several into one @@ -206,13 +207,13 @@ run: (config) => The `yield` expression resolves to the downstream `Response` (typed as `Response`, inferred — no annotation). `yield` the contribution at most once — `yield` means "run downstream and hand me the response." To short-circuit (handler never runs), `return new Response(...)`, exactly as a plain request-side middleware does. `try/finally` around the `yield` gives request-spanning cleanup; `try/catch` can turn a downstream throw into a `Response`. -This is the **one** place the "request-side" guarantee is relaxed, and writing `function*` is the visible, opt-in signal — the 95% plain-`async` path is unchanged. [`/cors`](./src/middleware/cors/README.md) is the worked example. +This is the **one** place the "request-side" guarantee is relaxed, and writing `function*` is the visible, opt-in signal — the 95% plain-`async` path is unchanged. [`/cors`](./src/middleware/cors/README.md) and [`/timing`](./src/middleware/timing/README.md) are the worked examples. ## Docs - [Authoring guide](./docs/authoring-guide.md) — **build your own middleware**: `defineMiddleware`, tests, publishing, and composing it in the same `pipeline` array as the built-in entries. - [Composition primitives](./src/core/README.md) — `ctx` shape, conflict & prerequisite enforcement, composition rules, the response seam. -- Per-middleware: [feature-flag](./src/middleware/feature-flag/README.md) — the request-side worked example · [cors](./src/middleware/cors/README.md) — the response-seam worked example. +- Per-middleware: [feature-flag](./src/middleware/feature-flag/README.md) — the request-side worked example · [cors](./src/middleware/cors/README.md) and [timing](./src/middleware/timing/README.md) — the response-seam worked examples. Full generated API reference: [supabase.github.io/middleware](https://supabase.github.io/middleware/). diff --git a/docs/authoring-guide.md b/docs/authoring-guide.md index e0fd699..e4b259a 100644 --- a/docs/authoring-guide.md +++ b/docs/authoring-guide.md @@ -74,8 +74,8 @@ as for anyone else's: [`@supabase-labs/middleware-openfeature`](https://github.com/supabase/middleware-openfeature) is one. -This repository ships the composition primitives and two worked examples, -`withCors` and `withFeatureFlag`. It takes no new middleware. +This repository ships the composition primitives and three worked examples: +`withFeatureFlag`, `withCors` and `withTiming`. It takes no new middleware. [`@supabase/server`](https://github.com/supabase/server) holds the middleware Supabase maintains: `withSupabase`, `withSupabaseClient`, `withPostgresClient`, @@ -1752,68 +1752,86 @@ When a concern is genuinely two-sided, write `run` as an `async function*`. `yield` is the seam: code before it is the request phase, the `yield` expression resolves to the downstream `Response`, and code after it is the response phase. -```ts -// src/with-timing.ts -import { defineMiddleware } from '@supabase/middleware' -import type { Middleware } from '@supabase/middleware' +The built-in [`withTiming`](../src/middleware/timing/with-timing.ts) is the +example. It starts a clock and hands the handler `ctx.timing`, whose `mark()` +ends the pipeline entry and whose `measure(name, fn)` times calls such as +database queries. Once the handler's response comes back, it writes what was +recorded to `Server-Timing`. Its `run`: -/** Per-instance configuration for {@link withTiming}. */ -export interface WithTimingConfig { - /** Metric name used in the `Server-Timing` header. @defaultValue `'total'` */ - metric?: string -} +```ts +run: (config) => { + // Outside the generator: runs once, when the stack is built. + const pipelineMetric = config?.pipelineMetric ?? 'mw' + assertMetricName(pipelineMetric) + + // Inside: runs per request, so this state is per request. + return async function* () { + const startedAt = performance.now() // request phase + let pipelineDur: number | undefined + const measured = new Map() + + const timing: TimingContribution = { + mark() { + pipelineDur ??= performance.now() - startedAt + }, + async measure(name, fn) { + assertMetricName(name) + const start = performance.now() + try { + return await fn() + } finally { + const entry = measured.get(name) ?? { dur: 0, calls: 0 } + entry.dur += performance.now() - start + entry.calls += 1 + measured.set(name, entry) + } + }, + } -/** Shape contributed at `ctx.timing`. */ -export interface TimingContribution { - /** When the request entered this middleware, from `performance.now()`. */ - startedAt: number -} + // Contribute, then suspend. The rest of the stack runs. + const response = yield { timing } -/** - * Times the request and stamps a `Server-Timing` header on the way out. - * - * Genuinely two-sided, so `run` is an `async function*`: code before the - * `yield` is the request phase, the `yield` expression resolves to the - * downstream `Response`, and code after it is the response phase. - */ -export const withTiming: Middleware< - 'timing', - WithTimingConfig | undefined, - Record, - TimingContribution -> = defineMiddleware< - 'timing', - WithTimingConfig | undefined, - Record, - TimingContribution ->({ - key: 'timing', - run: (config) => - async function* () { - const metric = config?.metric ?? 'total' - const startedAt = performance.now() // request phase - - // Contribute, then suspend. The rest of the stack runs. - const response = yield { timing: { startedAt } } - - // Response phase. Copy the headers so an immutable response is handled. - const headers = new Headers(response.headers) - headers.append( - 'Server-Timing', - `${metric};dur=${(performance.now() - startedAt).toFixed(1)}`, - ) - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers, - }) - }, -}) + // Response phase. + const entries: string[] = [] + if (pipelineDur !== undefined) { + entries.push(`${pipelineMetric};dur=${ms(pipelineDur)}`) + } + for (const [name, { dur, calls }] of measured) { + const desc = calls === 1 ? '1 call' : `${calls} calls` + entries.push(`${name};dur=${ms(dur)};desc="${desc}"`) + } + if (entries.length === 0) return response + if (response.status < 200 || response.status > 599) return response + + // Copy the headers so an immutable response is handled. + const headers = new Headers(response.headers) + headers.append('Server-Timing', entries.join(', ')) + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }) + } +}, ``` -Typing `Config` as `WithTimingConfig | undefined` is what makes the config -argument optional, so consumers can write `withTiming()` as well as -`withTiming({ metric: 'api' })`. +A few things here carry over to any seam middleware: + +- **Per-request state lives inside the generator.** `run(config)` is called + once per stack, so anything above the `return` is shared by every request. + Validate config there, so a bad value fails at startup. +- **The contribution can be a set of methods,** not just data. The handler + calls back into the middleware through it, and the response phase reads what + it recorded. +- **The middleware can't see where the handler starts.** Placed first, it times + everything after it as one span, so the handler marks the boundary itself. +- **Pass through what you didn't change.** With nothing recorded it returns the + downstream response as is, and it leaves alone statuses the `Response` + constructor can't rebuild (`Response.error()`'s 0, a WebSocket 101). + +`withTiming` types its `Config` as `WithTimingConfig | undefined`, which is what +makes the config argument optional: consumers can write `withTiming()` as well +as `withTiming({ pipelineMetric: 'setup' })`. Rules for the seam: @@ -1827,8 +1845,8 @@ Rules for the seam: - Returning nothing passes the downstream response through untouched. The runtime picks the path from what the body returns, so the plain `async` case -is unaffected. [`withCors`](../src/middleware/cors/with-cors.ts) is the -built-in worked example: it answers preflight with a `return` before the +is unaffected. [`withCors`](../src/middleware/cors/with-cors.ts) is the other +built-in seam middleware: it answers preflight with a `return` before the `yield`, and stamps headers after. ## Variant: bundling middleware into one @@ -1960,5 +1978,7 @@ as any other nested stack. request-side worked example. - [`cors`](../src/middleware/cors/README.md) — the built-in response-seam worked example. +- [`timing`](../src/middleware/timing/README.md) — the built-in response-seam + worked example whose contribution the handler calls back into. - [Adding a middleware to this repository](../src/middleware/README.md) — for built-ins rather than standalone packages. diff --git a/jsr.json b/jsr.json index 10fd949..08cde9b 100644 --- a/jsr.json +++ b/jsr.json @@ -4,7 +4,8 @@ "exports": { ".": "./src/index.ts", "./feature-flag": "./src/middleware/feature-flag/index.ts", - "./cors": "./src/middleware/cors/index.ts" + "./cors": "./src/middleware/cors/index.ts", + "./timing": "./src/middleware/timing/index.ts" }, "imports": { "std-env": "npm:std-env@^4.2.0" diff --git a/package.json b/package.json index d86b6ac..3524ea1 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,16 @@ "default": "./dist/middleware/cors/index.cjs" } }, + "./timing": { + "import": { + "types": "./dist/middleware/timing/index.d.mts", + "default": "./dist/middleware/timing/index.mjs" + }, + "require": { + "types": "./dist/middleware/timing/index.d.cts", + "default": "./dist/middleware/timing/index.cjs" + } + }, "./package.json": "./package.json" }, "main": "./dist/index.cjs", diff --git a/skills/supabase-middleware/SKILL.md b/skills/supabase-middleware/SKILL.md index 321b3b1..a54240b 100644 --- a/skills/supabase-middleware/SKILL.md +++ b/skills/supabase-middleware/SKILL.md @@ -1,6 +1,6 @@ --- name: supabase-middleware -description: Use when writing or modifying a Web Fetch handler that composes cross-cutting concerns with `@supabase/middleware` — CORS, feature flags, auth, rate limiting, logging — on Deno, Supabase Edge Functions, Cloudflare Workers, Bun, or Node. Trigger **before** writing or editing any file that imports from `@supabase/middleware` or a subpath (`/cors`, `/feature-flag`); calls `pipeline`, `defineMiddleware`, `getEnv`, `runtimeName`, or `seedContext`; or annotates a handler with `satisfies FetchHandler`. Also trigger during planning — if a plan mentions any of the above, load this skill before drafting code. Also trigger when porting middleware idioms that do not apply here: `app.use()` registries, `next()` chains, Express/Koa/Hono middleware being translated, or hand-rolled `(req) => wrapper(wrapper(handler))` nesting. +description: Use when writing or modifying a Web Fetch handler that composes cross-cutting concerns with `@supabase/middleware` — CORS, feature flags, auth, rate limiting, logging — on Deno, Supabase Edge Functions, Cloudflare Workers, Bun, or Node. Trigger **before** writing or editing any file that imports from `@supabase/middleware` or a subpath (`/cors`, `/feature-flag`, `/timing`); calls `pipeline`, `defineMiddleware`, `getEnv`, `runtimeName`, or `seedContext`; or annotates a handler with `satisfies FetchHandler`. Also trigger during planning — if a plan mentions any of the above, load this skill before drafting code. Also trigger when porting middleware idioms that do not apply here: `app.use()` registries, `next()` chains, Express/Koa/Hono middleware being translated, or hand-rolled `(req) => wrapper(wrapper(handler))` nesting. --- # @supabase/middleware @@ -50,15 +50,15 @@ export default { Paths are repo-relative. When `@supabase/middleware` is installed as a dependency, prefix them with `node_modules/@supabase/middleware/` — the same files ship in the package. -| Question | Doc | -| ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | -| How do I compose a stack? What is on `ctx`? | `src/core/README.md` | -| When is `satisfies FetchHandler` required, and what breaks without it? | `src/core/README.md` | -| A middleware needs to see the response too | `src/core/README.md` (response seam), `src/middleware/cors/README.md` | -| How do I write and publish my own middleware? | `docs/authoring-guide.md`, and the `create-supabase-middleware` skill | -| How do I add a built-in to this repo? | `src/middleware/README.md` | -| Environment access, runtime differences, Workers `env` | `README.md` | -| Config for the bundled middleware | `src/middleware/feature-flag/README.md`, `src/middleware/cors/README.md` | -| Full API reference | | +| Question | Doc | +| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| How do I compose a stack? What is on `ctx`? | `src/core/README.md` | +| When is `satisfies FetchHandler` required, and what breaks without it? | `src/core/README.md` | +| A middleware needs to see the response too | `src/core/README.md` (response seam), `src/middleware/cors/README.md`, `src/middleware/timing/README.md` | +| How do I write and publish my own middleware? | `docs/authoring-guide.md`, and the `create-supabase-middleware` skill | +| How do I add a built-in to this repo? | `src/middleware/README.md` | +| Environment access, runtime differences, Workers `env` | `README.md` | +| Config for the bundled middleware | `src/middleware/feature-flag/README.md`, `src/middleware/cors/README.md`, `src/middleware/timing/README.md` | +| Full API reference | | Release history and current status: . diff --git a/src/core/README.md b/src/core/README.md index 6e7a44d..b1b72a5 100644 --- a/src/core/README.md +++ b/src/core/README.md @@ -156,3 +156,4 @@ export default { - [Authoring guide](../../docs/authoring-guide.md) — write your own middleware. - [`feature-flag/`](../middleware/feature-flag/README.md) — the worked example (request-side). - [`cors/`](../middleware/cors/README.md) — the worked example of the response seam (`async function*`). +- [`timing/`](../middleware/timing/README.md) — a response-seam middleware whose contribution the handler calls back into. diff --git a/src/exports.test.ts b/src/exports.test.ts index 2d187bb..b7851e6 100644 --- a/src/exports.test.ts +++ b/src/exports.test.ts @@ -4,6 +4,7 @@ import * as root from './index.js' import * as core from './core/index.js' import * as cors from './middleware/cors/index.js' import * as featureFlag from './middleware/feature-flag/index.js' +import * as timing from './middleware/timing/index.js' /** * Guards the public *value* exports of every entry point. Type-only exports are @@ -40,5 +41,6 @@ describe('public API surface', () => { it('middleware subpaths', () => { expect(typeof featureFlag.withFeatureFlag).toBe('function') expect(typeof cors.withCors).toBe('function') + expect(typeof timing.withTiming).toBe('function') }) }) diff --git a/src/index.ts b/src/index.ts index 4655eb7..6c8b97a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,6 +10,7 @@ * * - `@supabase/middleware/feature-flag` * - `@supabase/middleware/cors` + * - `@supabase/middleware/timing` * * @packageDocumentation */ diff --git a/src/middleware/README.md b/src/middleware/README.md index 5b28070..62e756e 100644 --- a/src/middleware/README.md +++ b/src/middleware/README.md @@ -6,6 +6,7 @@ This directory holds the middleware that ship with `@supabase/middleware`. | ------------------------------------------- | ----------------- | ------------------------------------------------------------------- | | [`feature-flag/`](./feature-flag/README.md) | `ctx.featureFlag` | Provider-agnostic feature flag. The request-side worked example. | | [`cors/`](./cors/README.md) | `ctx.cors` | CORS — preflight in, headers out. The response-seam worked example. | +| [`timing/`](./timing/README.md) | `ctx.timing` | `Server-Timing` entries for the middleware and named calls. | > **Writing your own middleware?** See the [authoring guide](../../docs/authoring-guide.md). > It covers the full path — `defineMiddleware`, tests, publishing, and composing @@ -18,13 +19,13 @@ repository**. ## Adding a built-in -The built-ins are worked examples of the primitives, one per side: -`feature-flag` for the request side and `cors` for the response seam. New +The built-ins are worked examples of the primitives: `feature-flag` for the +request side, and `cors` and `timing` for the response seam. New middleware does not land here. Your middleware is its own package, and the middleware Supabase maintains lives in [`@supabase/server`](https://github.com/supabase/server). See [Where it lives](../../docs/authoring-guide.md#where-it-lives) in the authoring -guide. The layout below applies to changes to the two existing built-ins. +guide. The layout below applies to changes to the existing built-ins. Mirror [`feature-flag/`](./feature-flag/README.md): diff --git a/src/middleware/timing/README.md b/src/middleware/timing/README.md new file mode 100644 index 0000000..15c2713 --- /dev/null +++ b/src/middleware/timing/README.md @@ -0,0 +1,57 @@ +# `@supabase/middleware/timing` + +Adds the handler's own entries to the response's `Server-Timing` header: how long the middleware before the handler took, and the time spent in named calls such as database queries. + +> Like [`cors`](../cors/README.md), this is a response-seam middleware: it starts the clock before the `yield` and writes the header after it. Read [`with-timing.ts`](./with-timing.ts) alongside the [core README](../../core/README.md#response-seam-generator-middleware). + +```ts +import { pipeline } from '@supabase/middleware' +import { withTiming } from '@supabase/middleware/timing' + +export default { + fetch: pipeline( + [withTiming(), withAuth(), withDbClient()], + async (_req, ctx) => { + ctx.timing.mark() + const user = await ctx.timing.measure('db', () => ctx.db.getUser()) + const posts = await ctx.timing.measure('db', () => + ctx.db.listPosts(user.id), + ) + return Response.json({ user, posts }) + }, + ), +} +// Server-Timing: mw;dur=3.2, db;dur=8.4;desc="2 calls" +``` + +Put `withTiming` first, so the pipeline entry covers the rest of the middleware. + +## Config + +| Field | Type | Description | +| ---------------- | --------- | -------------------------------------------------------------------------------- | +| `pipelineMetric` | `string?` | `Server-Timing` name for the time from `withTiming` to `mark()`. Default `'mw'`. | + +The config is optional: `withTiming()` works. + +## `ctx.timing` + +| Member | Description | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mark()` | Ends the pipeline entry. Call it first thing in the handler. Only the first call counts. | +| `measure(name, fn)` | Times `fn` under `name` and returns its result. Calls that share a name are summed into one entry with a call count, and a call that throws still counts. | + +## Behavior notes + +- **Entries are appended** to any `Server-Timing` the response already carries, so the handler and other hops can add their own. +- **Calls that share a name become one entry,** so the header stays bounded however many queries run. Use distinct names (`db-read`, `db-write`) to keep calls apart. Concurrent calls each add their own duration, so the sum can exceed the wall time. +- **Missing pieces are left out.** Without `mark()` there is no pipeline entry; with nothing recorded, the response passes through untouched. +- **Durations use `performance.now()`**, a monotonic clock, so they're unaffected by clock skew between hosts. Values are in milliseconds, to one decimal place. +- **Names must be HTTP tokens** (letters, digits and symbols such as `-`, `_` and `.`; no spaces, `;`, `,` or `=`). A bad `pipelineMetric` throws when the stack is built; a bad `measure` name throws when it's called. +- **Only time before the response counts.** The header is written when the handler returns, so a `measure` that finishes later (inside a streaming body, say) isn't reported. +- The response is rebuilt with copied headers, so an immutable response (e.g. one returned from `fetch`) is handled and a streaming body passes through untouched. + +## See also + +- [Core README: the response seam](../../core/README.md#response-seam-generator-middleware) +- [Authoring guide: the response seam](../../../docs/authoring-guide.md#variant-the-response-seam) diff --git a/src/middleware/timing/index.ts b/src/middleware/timing/index.ts new file mode 100644 index 0000000..da877ce --- /dev/null +++ b/src/middleware/timing/index.ts @@ -0,0 +1,9 @@ +/** + * Timing middleware. + * + * @packageDocumentation + */ + +export type { FetchHandler } from '../../core/index.js' +export { withTiming } from './with-timing.js' +export type { TimingContribution, WithTimingConfig } from './with-timing.js' diff --git a/src/middleware/timing/with-timing.test.ts b/src/middleware/timing/with-timing.test.ts new file mode 100644 index 0000000..2402f8a --- /dev/null +++ b/src/middleware/timing/with-timing.test.ts @@ -0,0 +1,192 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { withTiming, type FetchHandler } from './index.js' +import { defineMiddleware, pipeline } from '../../core/index.js' + +const _anchored = withTiming(async (_req, ctx) => { + ctx.timing.mark() + return new Response('ok') +}) satisfies FetchHandler +void _anchored + +// A clock the tests move by hand, so durations are exact. +let now = 0 +const advance = (ms: number) => { + now += ms +} + +beforeEach(() => { + now = 1000 + vi.spyOn(performance, 'now').mockImplementation(() => now) +}) +afterEach(() => { + vi.restoreAllMocks() +}) + +const req = () => new Request('http://localhost/') + +// Stands in for auth or client setup: middleware that takes time before the +// handler runs. +const withSlowSetup = defineMiddleware< + 'setup', + number, + Record, + true +>({ + key: 'setup', + run: (ms) => async () => { + advance(ms) + return { setup: true } + }, +}) + +describe('withTiming', () => { + it('times the middleware before the handler and each named call', async () => { + const handler = pipeline( + [withTiming(), withSlowSetup(3.25)], + async (_req, ctx) => { + ctx.timing.mark() + await ctx.timing.measure('db', () => advance(5)) + await ctx.timing.measure('db', () => advance(2)) + await ctx.timing.measure('storage', () => advance(1)) + return Response.json({ ok: true }) + }, + ) + + const res = await handler(req()) + expect(res.headers.get('Server-Timing')).toBe( + 'mw;dur=3.3, db;dur=7.0;desc="2 calls", storage;dur=1.0;desc="1 call"', + ) + expect(await res.json()).toEqual({ ok: true }) + }) + + it('counts only the first mark', async () => { + const handler = pipeline( + [withTiming(), withSlowSetup(2)], + async (_req, ctx) => { + ctx.timing.mark() + advance(10) + ctx.timing.mark() + return new Response('ok') + }, + ) + + const res = await handler(req()) + expect(res.headers.get('Server-Timing')).toBe('mw;dur=2.0') + }) + + it('names the pipeline entry from config', async () => { + const handler = withTiming( + { pipelineMetric: 'setup' }, + async (_req, ctx) => { + ctx.timing.mark() + return new Response('ok') + }, + ) + + const res = await handler(req()) + expect(res.headers.get('Server-Timing')).toBe('setup;dur=0.0') + }) + + it('appends to entries the handler already set', async () => { + const handler = withTiming(async (_req, ctx) => { + ctx.timing.mark() + return new Response('ok', { headers: { 'Server-Timing': 'app;dur=1' } }) + }) + + const res = await handler(req()) + expect(res.headers.get('Server-Timing')).toBe('app;dur=1, mw;dur=0.0') + }) + + it('passes the response through untouched when nothing was recorded', async () => { + const original = new Response('ok', { status: 201 }) + const res = await withTiming(async () => original)(req()) + + expect(res).toBe(original) + expect(res.headers.get('Server-Timing')).toBeNull() + }) + + it('returns the result of a measured call', async () => { + const handler = withTiming(async (_req, ctx) => { + const rows = await ctx.timing.measure('db', async () => [{ id: 1 }]) + return Response.json(rows) + }) + + expect(await (await handler(req())).json()).toEqual([{ id: 1 }]) + }) + + it('records a measured call that throws, then rethrows', async () => { + const handler = withTiming(async (_req, ctx) => { + try { + await ctx.timing.measure('db', () => { + advance(4) + throw new Error('connection refused') + }) + } catch { + return new Response('db down', { status: 503 }) + } + return new Response('unreachable') + }) + + const res = await handler(req()) + expect(res.status).toBe(503) + expect(res.headers.get('Server-Timing')).toBe('db;dur=4.0;desc="1 call"') + }) + + it('rejects a metric name that is not an HTTP token', async () => { + expect(() => + withTiming({ pipelineMetric: 'two words' }, async () => new Response()), + ).toThrow(TypeError) + + const handler = withTiming(async (_req, ctx) => { + await ctx.timing.measure('db;dur=0', () => undefined) + return new Response('unreachable') + }) + await expect(handler(req())).rejects.toThrow(TypeError) + }) + + it('preserves status, headers and a streaming body', async () => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('chunk')) + controller.close() + }, + }) + const handler = withTiming(async (_req, ctx) => { + ctx.timing.mark() + return new Response(body, { + status: 202, + statusText: 'Accepted', + headers: { 'content-type': 'text/plain' }, + }) + }) + + const res = await handler(req()) + expect(res.status).toBe(202) + expect(res.statusText).toBe('Accepted') + expect(res.headers.get('content-type')).toBe('text/plain') + expect(res.body).toBe(body) + expect(await res.text()).toBe('chunk') + }) + + it('passes through a response the constructor cannot rebuild', async () => { + const error = Response.error() + const handler = withTiming(async (_req, ctx) => { + ctx.timing.mark() + return error + }) + + expect(await handler(req())).toBe(error) + }) + + it('keeps no state between requests', async () => { + const handler = withTiming(async (_req, ctx) => { + await ctx.timing.measure('db', () => advance(1)) + return new Response('ok') + }) + + await handler(req()) + const res = await handler(req()) + expect(res.headers.get('Server-Timing')).toBe('db;dur=1.0;desc="1 call"') + }) +}) diff --git a/src/middleware/timing/with-timing.ts b/src/middleware/timing/with-timing.ts new file mode 100644 index 0000000..49299d6 --- /dev/null +++ b/src/middleware/timing/with-timing.ts @@ -0,0 +1,152 @@ +/** + * Timing middleware: adds the handler's own entries to `Server-Timing`. + * + * The platform hops in front of a function each add their own time to the + * response's `Server-Timing` header. `withTiming` adds the entries only the + * function can see: how long the middleware pipeline took before the handler + * started, and the time spent in named calls such as database queries. + * + * Like `withCors`, it is a response-seam middleware: it starts the clock before + * the `yield` and writes the header after it. + */ + +import { defineMiddleware } from '../../core/index.js' +import type { Middleware } from '../../core/index.js' + +/** + * Per-instance configuration for {@link withTiming}. + * + * @category Middleware + */ +export interface WithTimingConfig { + /** + * The `Server-Timing` name for the time from `withTiming` to + * `ctx.timing.mark()`: the middleware that ran before the handler. + * + * @defaultValue `'mw'` + */ + pipelineMetric?: string +} + +/** + * Shape contributed at `ctx.timing`. + * + * @category Middleware + */ +export interface TimingContribution { + /** + * Ends the pipeline entry. Call it first thing in the handler. Only the first + * call counts; without one, the pipeline entry is left out. + */ + mark(): void + + /** + * Times `fn` under `name` and returns its result. Calls that share a name are + * summed into one entry with a call count, so `measure('db', …)` around every + * query adds a single `db` entry. Concurrent calls each add their own + * duration, so the sum can exceed the wall time. + * + * @throws TypeError when `name` is not a valid `Server-Timing` metric name. + */ + measure(name: string, fn: () => T | Promise): Promise +} + +// `Server-Timing` metric names are HTTP tokens (RFC 9110 §5.6.2). +const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +function assertMetricName(name: string): void { + if (!TOKEN.test(name)) { + throw new TypeError(`Invalid Server-Timing metric name: ${name}`) + } +} + +const ms = (dur: number): string => dur.toFixed(1) + +/** + * Timing middleware. Put it first, so the pipeline entry covers the rest of the + * middleware. + * + * @example + * ```ts + * import { pipeline } from '@supabase/middleware' + * import { withTiming } from '@supabase/middleware/timing' + * + * export default { + * fetch: pipeline([withTiming(), withAuth()], async (_req, ctx) => { + * ctx.timing.mark() + * const rows = await ctx.timing.measure('db', () => sql`select 1`) + * return Response.json(rows) + * }), + * } + * // Server-Timing: mw;dur=3.2, db;dur=8.4;desc="1 call" + * ``` + * + * @category Middleware + */ +export const withTiming: Middleware< + 'timing', + WithTimingConfig | undefined, + Record, + TimingContribution +> = defineMiddleware< + 'timing', + WithTimingConfig | undefined, + Record, + TimingContribution +>({ + key: 'timing', + run: (config) => { + const pipelineMetric = config?.pipelineMetric ?? 'mw' + assertMetricName(pipelineMetric) + + return async function* () { + const startedAt = performance.now() + let pipelineDur: number | undefined + const measured = new Map() + + const timing: TimingContribution = { + mark() { + pipelineDur ??= performance.now() - startedAt + }, + async measure(name, fn) { + assertMetricName(name) + const start = performance.now() + try { + return await fn() + } finally { + const entry = measured.get(name) ?? { dur: 0, calls: 0 } + entry.dur += performance.now() - start + entry.calls += 1 + measured.set(name, entry) + } + }, + } + + const response = yield { timing } + + const entries: string[] = [] + if (pipelineDur !== undefined) { + entries.push(`${pipelineMetric};dur=${ms(pipelineDur)}`) + } + for (const [name, { dur, calls }] of measured) { + const desc = calls === 1 ? '1 call' : `${calls} calls` + entries.push(`${name};dur=${ms(dur)};desc="${desc}"`) + } + if (entries.length === 0) return response + + // The constructor can't rebuild `Response.error()` (status 0) or an + // informational/upgrade status such as a WebSocket 101. + if (response.status < 200 || response.status > 599) return response + + // Copy the headers so an immutable response (e.g. from `fetch`) is + // handled; the body passes through without buffering. + const headers = new Headers(response.headers) + headers.append('Server-Timing', entries.join(', ')) + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }) + } + }, +}) diff --git a/tsdown.config.ts b/tsdown.config.ts index d9e8fc0..ba84978 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -5,6 +5,7 @@ export default defineConfig({ 'src/index.ts', 'src/middleware/feature-flag/index.ts', 'src/middleware/cors/index.ts', + 'src/middleware/timing/index.ts', ], format: ['esm', 'cjs'], dts: true, diff --git a/typedoc.json b/typedoc.json index 2fc3a20..8268ccb 100644 --- a/typedoc.json +++ b/typedoc.json @@ -3,7 +3,8 @@ "entryPoints": [ "src/index.ts", "src/middleware/feature-flag/index.ts", - "src/middleware/cors/index.ts" + "src/middleware/cors/index.ts", + "src/middleware/timing/index.ts" ], "out": "api-docs", "json": "api-docs/spec.json", @@ -21,7 +22,8 @@ "src/core/README.md", "src/middleware/README.md", "src/middleware/cors/README.md", - "src/middleware/feature-flag/README.md" + "src/middleware/feature-flag/README.md", + "src/middleware/timing/README.md" ], "highlightLanguages": [ "typescript",