import { parseExactJson } from './exact-json.ts'; // THE DERIVED DISPATCH — the generated wire's router (docs/contributing/architecture.md, "The derived // pack"). A derived pack's surface (`src/generated/surface.gen.json`, written by `twin-standard derive`) // names every operation the vendor publishes. This matches a request to one of them and hands it to its // owner: the pack's semantics handler for that operationId when there is one, otherwise the pack's // existing fetch, which keeps serving everything not yet moved (and every route outside the spec, such // as the `/twin` door). `owners` says, per operation, which of the two serves it: the count a pack's // move is measured by. Workerd-clean: no fs, no clock, nothing at import. import type { WebSocketUpgrade } from './serve-http.ts'; import type { TwinStream } from './twin-fetch.ts'; import { runWithRequestTrace } from './trace-context.ts'; import { redisServiceTimes } from './redis/service-times.ts'; /** The slice of a generated surface the dispatch reads. */ export type DerivedOperation = { id: string; method: string; path: string; class: string; resource?: string; /** query values that tell this operation from another at the same method and path */ discriminator?: Record; /** request headers that name the operation, for a wire whose operations share a path (AWS JSON's X-Amz-Target) */ headers?: Record; /** the status the vendor answers success with (201 for a create, 204 for an empty answer) */ successStatus?: number; /** how the spec says the request body is encoded (the derivation: json, form, multipart, none) */ bodyEncoding?: string; /** the success is documented with no content (a setting's update answered 200 and nothing else) */ emptySuccess?: boolean; /** a form-encoded operation's number and boolean fields, by bracket path (`items.[].quantity`, `metadata.*`) */ scalars?: Readonly>; /** a form-encoded operation's string fields that take only listed values, by the same bracket path */ enums?: Readonly>>; /** what the success answer is: a resource, a list of them, and the envelope key holding it */ answers?: { resource: string; list: boolean; key?: string }; /** the path its own server puts before it, where the operation names a server other than the surface's */ basePath?: string; /** the query's declared parameters (a strict body checks what is not one of them) */ query?: ReadonlyArray<{ name: string; type: string; required?: boolean }>; /** the credential scopes any one of which lets a caller make the call, and the security schemes it is made with * (`anonymous` where it may also go without; absent when it takes none), from the spec's security */ scopes?: ReadonlyArray; credentials?: ReadonlyArray; /** the body's declared fields: name, type, and the numeric bounds the spec states (a strict body, `ctx.fields`) */ body?: ReadonlyArray<{ name: string; type: string; required?: boolean; minimum?: number | string; maximum?: number | string }>; }; /** `basePath` is what the vendor's server URL puts before every operation path; `spanning` names the * path parameters whose values may hold slashes (a git ref, a file path), which no spec says. */ export type DerivedSurface = { graphql?: { sdl: string }; format?: string; commands?: ReadonlyArray<{ id: string }>; version: string; basePath?: string; spanning?: ReadonlyArray; operations: ReadonlyArray; /** Generated schema facts a handler can read without importing or interpreting the vendor spec. */ resources?: ReadonlyArray<{ name: string; variants?: { discriminator: string; required: Readonly> } }>; }; /** What a semantics handler receives: the request, the operation it matched, and its path parameters. */ export type DerivedCall = { request: Request; operation: DerivedOperation; params: Record; /** a World screen's call, which no perform sends again: a body in a media type the core does not read (anything * but JSON, a form, multipart or text) is the handler's alone, left unread and unrecorded, so an upload streams */ streamed?: true }; /** * A request's body as text, read once per request: the dispatch reads it and tags the request with it, and every clone * made from a tagged request carries the tag, so the malformed-JSON guard, the idempotency signature, the handler's * context and the parameters all take the one string (a publish's body is megabytes, and each read made a copy). */ const BODY_TEXT = Symbol('volter.bodyText'); type Tagged = Request & { [BODY_TEXT]?: string }; function tagBody(request: Request, text: string, key: object = {}): Request { const tagged = request as Tagged; tagged[BODY_TEXT] = text; BODY_PARSE_KEY.set(request, key); const clone = request.clone.bind(request); tagged.clone = () => tagBody(clone(), text, key); return request; } export async function bodyTextOf(request: Request): Promise { const held = (request as Tagged)[BODY_TEXT]; return held !== undefined ? held : request.text(); } /** The body parsed by the malformed-JSON guard, which only checks it: handed once to the handler's context (that parse * would be the same), and never shared further, so no reader sees another's changes. */ const BODY_PARSED = new WeakMap(); /** The body's text, as JSON, or undefined when it is not JSON; the parse is kept for the first taker. */ export async function checkJsonBody(request: Request): Promise { const text = await bodyTextOf(request); if (!text) return true; // a body labelled otherwise and not shaped as JSON is the form it is labelled (an OAuth token request), not bad JSON if (!(request.headers.get('content-type') ?? '').includes('json') && !/^\s*[[{]/.test(text)) return true; try { const value = parseExactJson(text); const tag = (request as Tagged)[BODY_TEXT] !== undefined ? BODY_PARSE_KEY.get(request) : undefined; if (tag) BODY_PARSED.set(tag, { value }); return true; } catch { return false; } } /** The guard's parse of this request's body, taken once (a clone of a tagged request shares its key). */ export function takeParsedBody(request: Request): { value: unknown } | undefined { const tag = BODY_PARSE_KEY.get(request); const held = tag ? BODY_PARSED.get(tag) : undefined; if (tag && held) BODY_PARSED.delete(tag); return held; } /** One key per request as the dispatch received it, shared by every clone made from it. */ const BODY_PARSE_KEY = new WeakMap(); export type DerivedHandler = (call: DerivedCall) => Promise; /** What the derived core made of an operation: an answer, or why it cannot model it. */ export type DerivedCoreOutcome = { served: Response } | { unmodeled: string }; export type DerivedFetchOptions = { surface: DerivedSurface; /** Semantics handlers by operationId. A handler naming an operation the surface lacks is refused. */ handlers?: Record; /** The derived core, and which operations it owns (those of the resources the manifest declares). */ core?: { owns: (operation: DerivedOperation) => boolean; serve: (call: DerivedCall) => Promise }; /** An RPC wire: every method is reached by any HTTP method (Slack's clients POST reads too). */ anyMethod?: boolean; /** What every operation a handler or the core serves passes through (read-only refusal, version * checks, idempotent replay). */ around?: (call: DerivedCall, next: () => Promise) => Promise; /** The vendor's answer for an operation nothing models: the pack's gap. */ gap: (request: Request, operation: DerivedOperation | undefined, reason: string) => Response | Promise; }; class Unmodeled extends Error {} type Route = { operation: DerivedOperation; pattern: RegExp; names: string[]; literals: number }; function compile(operation: DerivedOperation, basePath: string, spanning: ReadonlySet): Route { const names: string[] = []; let literals = 0; const body = ((operation.basePath ?? basePath) + operation.path) .split('/') .map((seg) => { const m = /^\{([^}]+)\}$/.exec(seg); if (m) { names.push(m[1]!); // a parameter the vendor lets hold slashes (a ref, a file path) takes the rest of its segments return spanning.has(m[1]!) ? '(.+?)' : '([^/]+)'; } literals++; // a segment templated in part (OpenAPI's `/report.{format}`, Tinybird's `/v0/pipes/{pipe}.json`) holds its // labels between its literal text, and counts as literal: it is more specific than a bare label return seg.split(/(\{[^}]+\})/).map((part) => { const label = /^\{([^}]+)\}$/.exec(part); if (!label) return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); names.push(label[1]!); return '([^/]+?)'; }).join(''); }) .join('/'); // a path the spec writes with its trailing slash (Django's `/persons/`) is the same path without it, as a router that // takes both answers it (PostHog's `trailing_slash = r"/?"`) return { operation, pattern: new RegExp(`^${body.replace(/\/$/, '')}/?$`), names, literals }; } const compiled = new WeakMap>(); // cache: compiled routes per surface; a surface is immutable generated data /** Routes per method, most literal segments first, so `/v1/customers/search` wins over `/v1/customers/{customer}`. */ export function compileSurface(surface: DerivedSurface): Map { const hit = compiled.get(surface); if (hit) return hit; const byMethod = new Map(); for (const operation of surface.operations) { const method = operation.method.toUpperCase(); const list = byMethod.get(method) ?? []; list.push(compile(operation, surface.basePath ?? '', new Set(surface.spanning ?? []))); byMethod.set(method, list); } // most literal segments first; among equals, an operation with a query discriminator before the one without const disc = (r: Route): number => Object.keys(r.operation.discriminator ?? {}).length + Object.keys(r.operation.headers ?? {}).length; for (const list of byMethod.values()) list.sort((a, b) => b.literals - a.literals || disc(b) - disc(a) || a.operation.path.localeCompare(b.operation.path)); compiled.set(surface, byMethod); return byMethod; } export function matchOperation(routes: Map, method: string, pathname: string, query?: URLSearchParams, headers?: Headers): { operation: DerivedOperation; params: Record } | undefined { for (const route of routes.get(method.toUpperCase()) ?? []) { const m = route.pattern.exec(pathname); if (!m) continue; // a null value asks only that the key be present (S3's UploadPart, `uploadId`) if (Object.entries(route.operation.discriminator ?? {}).some(([k, v]) => (v === null ? !query?.has(k) : query?.get(k) !== v))) continue; if (Object.entries(route.operation.headers ?? {}).some(([k, v]) => (v === null ? !headers?.has(k) : headers?.get(k) !== v))) continue; const params: Record = {}; try { route.names.forEach((name, i) => { params[name] = decodeURIComponent(m[i + 1]!); }); } catch { // a malformed escape matches no operation: whoever serves unmatched requests answers it return undefined; } return { operation: route.operation, params }; } return undefined; } /** The path's template parameters for a request no operation matches (a CORS preflight, a method the path is not * served by): read from the most literal route of any method whose path the request's path fits, discriminators * aside, so `around` and `gap` know the resource the URL names without parsing it (S3's OPTIONS on `/{Bucket}/{Key+}`). */ export function pathParams(routes: Map, pathname: string): Record { const fits = [...routes.values()].flat().filter((r) => r.pattern.test(pathname)).sort((a, b) => b.literals - a.literals || b.names.length - a.names.length); const route = fits[0]; const m = route?.pattern.exec(pathname); if (!route || !m) return {}; const params: Record = {}; try { route.names.forEach((name, i) => { params[name] = decodeURIComponent(m[i + 1]!); }); } catch { return {}; } return params; } export type DerivedOwner = 'handler' | 'core' | 'gap'; /** The header the kernel carries a path prefix's named groups in, from routing to the call (never a client's). */ export const PREFIX_PARAMS_HEADER = 'x-volter-path-prefix-params'; export type DerivedFetch = ((request: Request) => Promise) & { /** Per operationId, who serves it: a semantics handler, the derived core, the pack's existing * fetch while it moves, or nothing (the vendor's gap). */ owners(): Record; /** A vendor's owners by unit: its own API's under `''`, each lane's under the lane's name, each keyed by the unit's own * operation ids (an id two units share is two operations, each served or the gap on its own). `owners()` is this map * flat, a lane's ids written `:`. A fetch with no lanes may leave it out: its one unit is `owners()`. */ ownersByUnit?(): Record>; /** The vendor's sockets (sockets.ts), for the serve seam to upgrade to, when its manifest declares any. */ upgrade?: WebSocketUpgrade; /** The vendor's RTMP ingest (live/ingest.ts), for its server to serve on its side port (`serveStream`), when its * manifest declares `live`. */ ingest?: TwinStream; maxRequestBodySize?: number; /** The workspace screens it draws, its lanes' too (`GET /twin`'s `screens`). */ workspaces?(): Workspace[]; /** Whether it lays out frames of the World's board (`semantics/board.ts`). */ boards?: boolean; /** Whether a built screen of it takes a URL: a board frame it draws. */ draws?(url: string): boolean; /** The hosts its built content screens name: a vendor's lane router sends `/@/` for one of them to * this fetch (pack-fetch.ts). */ contentHosts?: ReadonlyArray; }; /** A workspace screen a pack draws, as `GET /twin` lists it: its id and path (Viewing a World). */ export type Workspace = { id: string; path: string; host?: string }; /** A page of the World's board (architecture, "The board"): a page there is to see at the vendor, a record's own (an * account's profile, each of its posts, a site and each page it serves), as the vendor's pack lists them from its state * (`semantics/board.ts`). Every field is a fact of the World's state: which of them a person looks at is the board's * choice, never the pack's. `GET /twin/board` lists them. */ export type BoardFrame = { /** stable within the vendor, whatever the World's ids: what a saved board names the frame by */ id: string; /** what it is, in the vendor's own word (a site, a repository, a board) */ kind: string; title: string; /** the vendor's container it is grouped under (an account, an organization, a project); `aka`, the ids it was known * by before (an account a deploy adopted), so a board that included it under one still holds it */ section: { id: string; title: string; aka?: string[] }; /** where the vendor shows it: an absolute URL on the vendor's host, or on a hostname the vendor serves for its customer */ url: string; /** the records whose changes are this frame's changes */ covers: Array<{ type: string; id: string }>; /** the id of the page it sits under at the vendor (a post under its author's profile, a site's page under its site): * a board showing everything shows a page with no parent and opens the pages under it from there */ parent?: string; /** the World's own: an account the World's applications or people act as, a page of one, a site the World serves */ ours?: boolean; /** set by the kernel, never the pack: whether a built screen of the vendor's (any of its lanes') draws the url */ drawn?: boolean; }; /** Host-side measurement of actual dispatch, including declared gaps. It changes no request or answer. */ export type DerivedDispatch = { surface: DerivedSurface; operation: DerivedOperation; owner: DerivedOwner }; let dispatchObservers: Set<(dispatch: DerivedDispatch) => void> | undefined; export function observeDerivedDispatch(observer: (dispatch: DerivedDispatch) => void): () => void { (dispatchObservers ??= new Set()).add(observer); return () => { dispatchObservers?.delete(observer); }; } export function createDerivedFetch(options: DerivedFetchOptions): DerivedFetch { const handlers = options.handlers ?? {}; const known = new Set(options.surface.operations.map((o) => o.id)); const unknown = Object.keys(handlers).filter((id) => !known.has(id)); if (unknown.length) throw new Error(`derived dispatch: handlers name operations the surface does not have: ${unknown.sort().join(', ')}`); const routes = compileSurface(options.surface); const fallback = (request: Request, operation: DerivedOperation | undefined, reason: string): Promise => Promise.resolve(options.gap(request, operation, reason)); // a valid incoming W3C traceparent scopes the dispatch, so every entry it appends records it (trace-context.ts) const fetch = ((request: Request): Promise => runWithRequestTrace(request, () => dispatch(request))) as DerivedFetch; const dispatch = async (request: Request): Promise => { const url = new URL(request.url); const matched = options.anyMethod ? [...routes.keys()].map((m) => matchOperation(routes, m, url.pathname, url.searchParams, request.headers)).find(Boolean) : matchOperation(routes, request.method, url.pathname, url.searchParams, request.headers); if (!matched) return fallback(request, undefined, 'no operation at this path'); for (const observer of dispatchObservers ?? []) observer({ surface: options.surface, operation: matched.operation, owner: handlers[matched.operation.id] ? 'handler' : options.core?.owns(matched.operation) ? 'core' : 'gap' }); // the body read once, as text, for everything the dispatch does with it (bodyTextOf) redisServiceTimes.lap('6a around entered, guards and scenario passed, operation matched again'); if (request.method !== 'GET' && request.method !== 'HEAD' && request.body && !(request.headers.get('content-type') ?? '').includes('multipart')) tagBody(request, await request.clone().text()); redisServiceTimes.lap('6b the dispatch read the body as text'); // the path prefix's named groups (pack-fetch.ts, `pathPrefix`) are the call's parameters too const prefixed = request.headers.get(PREFIX_PARAMS_HEADER); const call: DerivedCall = { request, operation: matched.operation, params: prefixed ? { ...(parseExactJson(prefixed) as Record), ...matched.params } : matched.params }; const around = options.around ?? ((_c: DerivedCall, next: () => Promise) => next()); const handler = handlers[matched.operation.id]; if (handler) return around(call, () => handler(call)); if (options.core?.owns(matched.operation)) { // the core reads the body; a clone keeps it for whatever serves an operation the core cannot // model, and that case leaves `around` by a throw, so nothing it records (an idempotent // answer) is recorded for a request the core did not serve try { return await around(call, async () => { const outcome = await options.core!.serve({ ...call, request: request.clone() }); if ('served' in outcome) return outcome.served; throw new Unmodeled(outcome.unmodeled); }); } catch (error) { if (error instanceof Unmodeled) return fallback(request, matched.operation, error.message); throw error; } } return fallback(request, matched.operation, 'no handler'); }; fetch.owners = () => Object.fromEntries( options.surface.operations.map((o) => [o.id, handlers[o.id] ? 'handler' : options.core?.owns(o) ? 'core' : 'gap'] as const), ); return fetch; }