import { runWithStorageTenant } from './request-scope.ts'; import { parseExactJson } from './exact-json.ts'; import { redisServiceTimes } from './redis/service-times.ts'; import { readHostPort } from './host-port.ts'; // A Protocol 3 pack's whole HTTP surface, served by the kernel from the pack's declarations (docs/contributing/ // architecture.md, "The pack contract: the kernel's root"): the discovery door (`GET /twin`, the manifest's // `discovery`), the vendor's own moves as time passes (`semantics/clock.ts`), the World's doors (the manifest's `doors`, // answered by `semantics/doors.ts`), the vendor's screens (the manifest's `screens`, each answered by its // `screens/.tsx`), and the API (the derived dispatch over the generated surface, the handlers and the core). Every // one of them is answered over the contract's context, which the kernel opens: a pack opens none, reads the tree and // writes it only through one. import { ORIGINAL_PATH_HEADER } from './sigv4.ts'; import { placedCookies, TWIN_PREFIX_HEADER } from './twin-fetch.ts'; import { PREFIX_PARAMS_HEADER } from './derived.ts'; import { withHeaders } from './with-headers.ts'; import { authRefusal, presentedCredential, bindSemantics, contextFor, scenarioLedgerOf, scenarioRecords, storedTenants, LANE_HEADER, SCENARIO_DECISION_HEADER, SCENARIO_FAULT_HEADER, faultError, scenarioDecisionHeader, storedType, coreFor, crossCutting, derivedRequestScopes, graphqlIdempotency, vendorError, type CoreScope, type DerivedManifest, type ErrorSpec, type Handler, type HandlerContext, type LanesDecl, type ScreenDecl, type VendorManifest } from './derived-core.ts'; import { compileSurface, createDerivedFetch, matchOperation, pathParams, type DerivedFetch, type DerivedOperation, type DerivedOwner, type DerivedSurface, type Workspace, type BoardFrame } from './derived.ts'; import { isReadOnlyRequest, READ_ONLY_REQUEST_HEADER, runAsVendorMove, storageTenant } from './request-scope.ts'; import { ScenarioError, statefulTwinManifest, twinManifest, type PackScenarioAdapter, type ScenarioStatusFault } from './scenario.ts'; import { durationMs, placedOn, type PlacedFault } from './placements.ts'; import { noteFault, rateLimited, recordFault, requestFaults, type RateCount, type RateOutcome, type ScenarioLedger } from './scenario-consume.ts'; import { fillRateTemplate } from './rateBudget.ts'; import { sha256 } from './signing.ts'; import { faultAnswer, kernelFault, serveTurn } from './scenario-serve.ts'; import { onAttemptRender, onHeldDelivery, releaseHeldDeliveries, retrySchedule } from './events.ts'; import { getActiveWorldStore, withWorldStore } from './world-store.ts'; import { noteCompleteness } from './completeness.ts'; import { runWithCorrelationId } from './actions.ts'; import { deferPerform, deployableEntries, performRequestGroup, RefusedWriteError, VendorWriteError } from './head.ts'; import { FLUSH, ZERO_SHA, pktLine, readPktLines } from './git/smart-http.ts'; import { concat } from './git/objects.ts'; import { withCors } from './cors.ts'; import type { ApplicationStandIn } from './events.ts'; import { contentAddressOf } from './content-route.ts'; import { getPack, type HostRule } from './packRegistry.ts'; import { hostRules } from '../host-routing.cjs'; /** A descriptor's host rules, as data. */ type PackDescriptorHosts = ReadonlyArray | undefined; import { expireSocketWaits, socketUpgrade, type SocketEngine } from './sockets.ts'; import { liveIngest } from './live/ingest.ts'; import type { LiveEngine } from './live/types.ts'; import { readResourceBlob, removeResourceBlob, writeResourceBlob } from './resource-blob.ts'; import { gitRepositoryOf, resourcesOfType } from './derived-core.ts'; import { worldClockRunning, worldNow } from './world-clock.ts'; import type { WebSocketUpgrade, WebSocketPeer } from './serve-http.ts'; import { MACHINE_POOL, POOL_KINDS, resetFakePool } from './machines.ts'; import { applyTwinWrite } from './serve.ts'; import { graphqlEndpoint, type GraphqlPart, type GraphqlLibraryLoader } from './graphql-wire.ts'; import { gzipSync } from 'node:zlib'; import { decompress } from './bytes.ts'; import { decodedBodyLimit, oversizedBody, RequestBodyTooLargeError } from './request-body.ts'; /** What a pack declares and writes, and nothing it assembles itself. */ export type PackParts = { manifest: DerivedManifest; surface: DerivedSurface; /** `semantics/index.ts`: the handlers, by operationId. */ handlers?: Record; /** `semantics/doors.ts`: a door's answer, by the id the manifest's `doors` gives it. */ doors?: Record; /** Each `screens/.tsx`'s answer, by the id the manifest's `screens` gives it. */ screens?: Record; /** `semantics/around.ts`: what the vendor does around every request to its API, one the surface names or not (a key * checked, a plan's limits, a quota counted after a success), over a context whose operation is the request's (or * `unmatched`); `next` answers the request itself, or the one it is given (the vendor's own rewrite of it: a query * token moved to its header, a caller resolved into a header only the vendor's own front sets). */ around?: (ctx: HandlerContext, next: (request?: Request) => Promise) => Promise; /** `semantics/clock.ts`: the vendor's own moves the World clock has made due, caught up before anything is answered. * They are the vendor's, not the caller's: they land under a read-only request too. */ clock?: (ctx: HandlerContext) => Promise; /** `semantics/scenario.ts`: how the World's scenario decides a model vendor's turn — the operations it decides, the * request each is as the scenario reads it, and the vendor's own matchers and fault body (the adapter). */ scenario?: PackScenario; /** `semantics/gap.ts`: the vendor's answer for what it does not serve, where its manifest's `gap` cannot say it (Clerk's * Frontend API: Go's plain-text 404 for a path it does not have, `signed_out` for an operation asked without a * client), over a context whose operation is the one matched, or `unmatched`. */ gap?: (ctx: HandlerContext) => Response | Promise; /** `semantics/tenant.ts`: the tenant the caller acts in, which the core scopes the manifest's `tenant` by. */ tenant?: (ctx: HandlerContext) => string | undefined | Promise; /** The vendor's lanes, by the name the manifest's `lanes` routes give them: each its own pack fetch and manifest. */ lanes?: Record; /** `semantics/graphql.ts` with the vendor's schema (`generated/graphql-sdl.gen.json`): the GraphQL wire over the same * state, served at the manifest's `graphql.paths` (graphql-wire.ts). */ graphql?: GraphqlPart & { sdl: string; loadLibrary?: GraphqlLibraryLoader }; /** `semantics/sockets.ts`: each socket's engine, by the id the manifest's `sockets` gives it (sockets.ts). */ sockets?: Record>; /** `semantics/board.ts`: the vendor's frames on the World's board, read from its state (`GET /twin/board`). */ board?: (ctx: HandlerContext) => BoardFrame[] | Promise; /** `semantics/live.ts`: each ingest's dialect, by the id the manifest's `live` gives it (live/ingest.ts). */ live?: Record>; }; /** A pack's scenario (`semantics/scenario.ts` exports `scenario`): the adapter the kernel's engine reads the World's * scenario document with, the operations it decides a turn of, and the request an operation is to it (undefined when * the request is not one it decides: the handler answers the vendor's refusal). */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export type PackScenario = { adapter: PackScenarioAdapter; operations: ReadonlyArray; request: (ctx: HandlerContext) => Req | undefined }; /** A lane as its vendor's fetch is given it: its own pack fetch, and its manifest (the doors it declares). */ export type LanePart = { fetch: ((request: Request) => Promise) & { serves?: (method: string, path: string) => boolean; boards?: boolean; draws?: (url: string) => boolean; /** the hosts the lane's built content screens name: its vendor's router sends `/@/` there */ contentHosts?: ReadonlyArray; upgrade?: WebSocketUpgrade; ingest?: import('./twin-fetch.ts').TwinStream; }; manifest: { doors?: ReadonlyArray<{ method: string; path: string }> }; }; /** Where a pack serves: its World's root, whether it was started read-only, the World instant when a caller pins it, the * and the World's managed Postgres the runtime binds a pack declaring `managedDatabase` to (a handler's `ctx.engine`). */ export type PackFetchOptions = { root?: string; readOnly?: boolean; clock?: () => string; database?: string; /** the application a walk stands in for: this fetch's requests and declared events are answered by it */ application?: ApplicationStandIn; }; type Match = { params: Record }; /** A declared path (`/{account}/r2/api-tokens`, `/`, a door's `/_twin/users/{email}`) as a matcher of a request's * path: the path itself, or `prefix` a path under it too (a screen answers its page and the forms it posts). */ function pathMatcher(pattern: string, prefix: boolean): (path: string) => Match | undefined { const names: string[] = []; const body = pattern.replace(/\/+$/, '').split('/').map((seg) => { const m = /^(?:\{([^}]+)\}|<([^>]+)>|:(\w+))$/.exec(seg); if (!m) return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); names.push(m[1] ?? m[2] ?? m[3]!); return '([^/]+)'; }).join('/'); const re = new RegExp(`^${body}${prefix ? '(?:/.*)?' : ''}/?$`); return (path) => { const hit = re.exec(path); return hit ? { params: Object.fromEntries(names.map((n, i) => [n, decodeURIComponent(hit[i + 1]!)])) } : undefined; }; } /** A declared host (`dash.cloudflare.com`, `.daily.co`) as a matcher of a request's host. */ function hostMatcher(pattern: string): (host: string) => Match | undefined { const whole = /^(?:\{([^}]+)\}|<([^>]+)>)$/.exec(pattern); if (whole) return (host) => host ? { params: { [whole[1] ?? whole[2]!]: host } } : undefined; const names: string[] = []; const re = new RegExp(`^${pattern.split('.').map((label) => { const m = /^(?:\{([^}]+)\}|<([^>]+)>)$/.exec(label); if (!m) return label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); names.push(m[1] ?? m[2]!); return '([^.]+)'; }).join('\\.')}$`, 'i'); return (host) => { const hit = re.exec(host); return hit ? { params: Object.fromEntries(names.map((n, i) => [n, hit[i + 1]!])) } : undefined; }; } /** The host a request is for: the vendor host the World's injector names, else its own. */ export const hostOf = (request: Request): string => readHostPort(request.headers.get('x-volter-twin-original-host') ?? request.headers.get('host') ?? new URL(request.url).host)?.host ?? ''; /** Where a workspace asked `?show=:` opens the record (architecture, "Workspace"): the built workspace page * that shows that type, its parameter the id; else the one that lists the type; else the workspace's home (its root * page). Every other parameter a page's path names is the asking page's, and a page that cannot be filled is passed * over. Undefined when nothing is asked; the path (with no `show`) otherwise. */ export function shownRecord(url: URL, workspaces: ReadonlyArray, params: Record): string | undefined { const asked = /^([^:]+):(.+)$/.exec(url.searchParams.get('show') ?? ''); if (!asked) return undefined; const [, type, id] = asked; const fill = (path: string, extra: Record): string | undefined => { let unfilled = false; const filled = path.replace(/\{([^}]+)\}|<([^>]+)>/g, (_, a?: string, b?: string) => { const v = { ...params, ...extra }[(a ?? b)!]; if (v === undefined || v === '') { unfilled = true; return ''; } return encodeURIComponent(v); }); return unfilled ? undefined : filled; }; const shows = workspaces.filter((s) => s.shows?.type === type).map((s) => fill(s.path, { [s.shows!.param]: id! })).find((p) => p !== undefined); const lists = workspaces.filter((s) => s.lists?.includes(type!)).map((s) => fill(s.path, {})).find((p) => p !== undefined); const home = workspaces.find((s) => s.path.replace(/\/+$/, '') === '') ? '/' : undefined; return shows ?? lists ?? home ?? url.pathname; } /** The answer for a path no operation, door or screen serves, and for an operation nothing models: the manifest's * `gap`, its `{method}` and `{path}` filled, else the manifest's not-found refusal. */ function gapAnswer(m: DerivedManifest, request: Request, otherMethod = false): Response { const nf = m.notFound; const gap: ErrorSpec = (otherMethod ? m.wrongMethod : undefined) ?? m.gap ?? { status: nf.status, message: nf.message, ...(nf.code !== undefined ? { code: nf.code } : {}), ...(nf.kind !== undefined ? { kind: nf.kind } : {}) }; const path = new URL(request.url).pathname; return vendorError(m, { ...gap, message: gap.message.replace(/\{method\}/g, request.method).replace(/\{path\}/g, path) }); } const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']; type ContentCoding = 'gzip' | 'zstd' | 'deflate' | 'br'; /** A request with its body decoded as its Content-Encoding says, when the manifest's `encodings` reads that coding; * undefined when the bytes are not what the header names. */ async function decoded(m: DerivedManifest, request: Request): Promise { const codings = (request.headers.get('content-encoding') ?? '').split(',').map(c => c.trim().toLowerCase()).filter(Boolean); if (codings.length > 1) return new Response('Unsupported Content-Encoding', { status: 415 }); if (request.method === 'GET' || request.method === 'HEAD' || request.body === null) return request; // the body read once, here, and every part of the pack given a request made again from its bytes: a served request's // body read through a clone and then read again (an `around` that checks a body before its handler does) tees a stream // whose second branch a Bun server never finishes, and the request hung const raw = new Uint8Array(await request.arrayBuffer()); const coding = (codings[0] ?? '') as ContentCoding; if (!m.encodings?.request?.includes(coding)) return new Request(request.url, { method: request.method, headers: request.headers, body: raw, signal: request.signal }); let body: Uint8Array; try { body = await decompress(raw, coding, decodedBodyLimit(m.descriptor?.maxRequestBodySize)); } catch (error) { return error instanceof RequestBodyTooLargeError ? oversizedBody() : undefined; } const headers = new Headers(request.headers); headers.delete('content-encoding'); headers.delete('content-length'); // A finite single-chunk stream holds the decoder's buffer; BufferSource extraction would copy the entire body. const buffered = new ReadableStream({ start(controller) { controller.enqueue(body); controller.close(); } }); return new Request(request.url, { method: request.method, headers, body: buffered, signal: request.signal, duplex: 'half' } as RequestInit); } /** An answer in the coding the request accepts, when the manifest's `encodings` answers in it. */ async function encoded(m: DerivedManifest, request: Request, res: Response): Promise { if (!m.encodings?.response?.includes('gzip') || res.body === null || res.status === 204 || res.status === 205 || res.headers.has('content-encoding')) return res; const accepts = (request.headers.get('accept-encoding') ?? '').split(',').some((e) => e.trim().split(';')[0]!.toLowerCase() === 'gzip'); if (!accepts) return res; const headers = new Headers(res.headers); headers.set('content-encoding', 'gzip'); headers.delete('content-length'); headers.append('vary', 'Accept-Encoding'); const body = gzipSync(new Uint8Array(await res.arrayBuffer())); // Hold the compressor's buffer with the same finite stream body grammar as decoded(), without copying it. const buffered = new ReadableStream({ start(controller) { controller.enqueue(body); controller.close(); } }); return new Response(buffered, { status: res.status, statusText: res.statusText, headers }); } /** A door's path as it is served and listed: under `/_twin/`, whether the manifest writes the prefix or not. */ const doorPath = (path: string): string => (path.startsWith('/_twin/') ? path : `/_twin${path.startsWith('/') ? '' : '/'}${path}`); /** A declared World door, matched by the same normalized path for serving and response ownership. */ export function worldDoorMatcher(doors: ReadonlyArray): (method: string, path: string) => { door: Door; params: Record } | undefined { const routes = doors.map((door) => ({ door, method: door.method.toUpperCase(), matches: pathMatcher(doorPath(door.path), false) })); return (method, path) => { const at = path.replace(/\/+$/, '') || '/'; for (const route of routes) { if (route.method !== method.toUpperCase()) continue; const hit = route.matches(at); if (hit) return { door: route.door, params: hit.params }; } return undefined; }; } /** A request with its path's repeated slashes merged, as a front that merges them routes it (the manifest's * `mergeSlashes`); one with none is itself. */ export function slashesMerged(request: Request): Request { const url = new URL(request.url); const merged = url.pathname.replace(/\/{2,}/g, '/'); if (merged === url.pathname) return request; url.pathname = merged; return new Request(url, request); } /** The selected unit's request transformation, shared by serving and response judgment. */ export function unitRequestRouter(m: Pick, surface: DerivedSurface, routes: ReturnType): (request: Request) => Request { const prefix = m.pathPrefix ? new RegExp(`^(?:${m.pathPrefix})(?=/)`) : undefined; const base = surface.basePath ?? ''; const baseAlias = m.basePathAlias && base ? new RegExp(`^(?:${m.basePathAlias})(?=/)`) : undefined; const hostPath = m.pathFromHost ? new RegExp(m.pathFromHost, 'i') : undefined; const hostParams = m.hostParams ? new RegExp(m.hostParams, 'i') : undefined; // each operation's spanning parameters, keyed by the operation and the parameter as the route compiles them (a whole // segment's label whose name the surface or the manifest declares spanning), so one operation's spanning name never // keeps another's slashes, nor a label that only part of a segment holds const spanningNames = new Set(surface.spanning ?? []); const spanningOf = new Set(surface.operations.flatMap((op) => ((op.basePath ?? base) + op.path).split('/').flatMap((seg) => { const label = /^\{([^}]+)\}$/.exec(seg)?.[1]; return label !== undefined && spanningNames.has(label) ? [`${op.id}\u0000${label}`] : []; }))); /** A path as the vendor routes it: the manifest's path prefix taken off, the spec's base in an alias's place, a host's * path label (pathFromHost) put in front. */ const rewritten = (pathname: string, host: string): string => { let path = pathname; if (prefix) path = path.replace(prefix, '') || '/'; // a base the vendor serves as its own: the spec's base in its place (a path already under the spec's base stays) if (baseAlias && !(path === base || path.startsWith(`${base}/`))) path = path.replace(baseAlias, base); const label = hostPath?.exec(host)?.[1]; if (label) path = `/${label}${path === '/' ? '' : path}`; return path; }; /** The request as its vendor routes it: duplicate slashes collapsed, unless the rewritten path matches an operation * through one of that operation's spanning parameters (the surface's and the manifest's), whose value keeps its * slashes; then rewritten. */ return (request: Request): Request => { const url = new URL(request.url); const host = hostOf(request); const kept = rewritten(url.pathname, host); const matched = matchOperation(routes, request.method, kept); const spanning = matched !== undefined && Object.keys(matched.params).some((name) => spanningOf.has(`${matched.operation.id}\u0000${name}`)); const source = spanning ? url.pathname : url.pathname.replace(/\/{2,}/g, '/'); // a prefix's named groups (Jira's `/ex/jira/(?[^/]+)`) and the host's (E2B's envd at // `49983-(?…).e2b.app`) join the operation's parameters const groups = { ...(prefix?.exec(source)?.groups ?? {}), ...(hostParams?.exec(host)?.groups ?? {}), ...Object.fromEntries(Object.entries(m.headerParams ?? {}).flatMap(([param, header]) => { const value = request.headers.get(header); return value === null ? [] : [[param, value]]; })) }; const path = spanning ? kept : rewritten(source, host); if (path === url.pathname && !Object.keys(groups).length) return request; // the path the client sent, which a signature over the request (SigV4's canonical URI) covers const headers = new Headers(request.headers); // the path as first sent: a front before this (an attach bridge) may have named the one its client signed if (!headers.has(ORIGINAL_PATH_HEADER)) headers.set(ORIGINAL_PATH_HEADER, url.pathname); if (Object.keys(groups).length) headers.set(PREFIX_PARAMS_HEADER, JSON.stringify(groups)); url.pathname = path; return new Request(url, { method: request.method, headers, body: request.body, signal: request.signal, ...(request.body ? { duplex: 'half' } : {}) } as RequestInit); }; } /** A vendor bucket's refusal (rateBudget.ts RateRefusal): its status and error in the vendor's envelope, or its own body, * and its headers, each a template over the bucket's values. */ function rateRefusal(m: DerivedManifest, refused: RateCount): Response { const refusal = (refused.bucket.refused ?? m.rateBudget!.refused)!; const answer = refusal.body === undefined ? vendorError(m, { ...refusal.error, message: String(fillRateTemplate(refusal.error.message, refused.values)) }) : Response.json(fillRateTemplate(refusal.body, refused.values), { status: refusal.error.status }); for (const [name, value] of Object.entries(refusal.headers ?? {})) answer.headers.set(name, String(fillRateTemplate(value, refused.values))); return answer; } /** An answer with the headers of every bucket that counted its request (a later bucket's header over an earlier's). */ function withRateHeaders(answered: Response, counted: RateCount[]): Response { const headers = counted.flatMap(({ bucket, values }) => Object.entries(bucket.headers ?? {}).map(([name, value]) => [name, String(fillRateTemplate(value, values))] as const)); if (headers.length === 0 || answered.status < 200 || answered.status > 599) return answered; const rebuilt = new Response(answered.body, answered); for (const [name, value] of headers) rebuilt.headers.set(name, value); return rebuilt; } /** A pack's HTTP surface, as the kernel serves it from the pack's parts. */ /** One twin's open work (its requests being served, its byte-stream sessions open), shared by every fetch made of it in * this process: keyed by its vendor and its state root. */ const openWorks = new Map(); function openWork(service: string, root: string | undefined): { serving: number; connections: number } { const key = `${service}\u0000${root ?? ''}`; let work = openWorks.get(key); if (!work) openWorks.set(key, work = { serving: 0, connections: 0 }); return work; } export function createPackFetch(parts: PackParts, options: PackFetchOptions = {}): DerivedFetch { const m = parts.manifest; // the vendor's retry schedule, timeout and batch window are read as the pack loads, so a bad duration refuses the // twin, not a delivery try { retrySchedule(m.events?.retry); } catch (error) { throw new Error(`${m.vendor}: events.retry: ${(error as Error).message}`); } for (const [name, by] of [['timeout', m.events?.timeout], ['batch.within', m.events?.batch?.within]] as const) { if (by !== undefined) try { durationMs(by); } catch (error) { throw new Error(`${m.vendor}: events.${name}: ${(error as Error).message}`); } } const scope: CoreScope = { ...(parts.surface.resources ? { resources: parts.surface.resources } : {}), ...(options.root !== undefined ? { root: options.root } : {}), ...(options.clock ? { clock: options.clock } : {}), ...(options.database !== undefined ? { database: options.database, readOnly: options.readOnly ?? false } : {}), ...(parts.tenant ? { tenant: parts.tenant } : {}), ...(options.application ? { application: options.application } : {}), }; // a command table's surface (Redis's, a vendor that carries Redis over HTTP) names no HTTP operation: its wire is the // pack's front (its `around`), and the table is the denominator the grade counts const surface: DerivedSurface = { ...parts.surface, operations: parts.surface.operations ?? [], ...(m.spanning?.length ? { spanning: [...(parts.surface.spanning ?? []), ...m.spanning] } : {}) }; const routes = compileSurface(surface); const rest = createDerivedFetch({ surface, handlers: bindSemantics(m, (parts.handlers ?? {}) as never, scope), core: coreFor(m, scope), around: crossCutting(m, { readOnly: options.readOnly ?? false, ...scope }), gap: async (request, operation) => { const refused = m.auth?.beforeRouting ? authRefusal(m, request, options.root) : undefined; if (refused) return refused; // an operation this twin does not implement is what the World is missing at this vendor (ADR 0036 §9) noteCompleteness(process.env, { kind: 'unimplemented', vendor: m.vendor, method: request.method, path: new URL(request.url).pathname, ...(operation ? { operation: operation.id } : {}) }); if (parts.gap) { const url = new URL(request.url); const matched = operation ? matchOperation(routes, request.method, url.pathname, url.searchParams, request.headers) : undefined; return parts.gap(await contextFor(m, { request, operation: operation ?? ({ id: 'unmatched', method: request.method, path: url.pathname, class: request.method === 'GET' ? 'retrieve' : 'action' } as DerivedOperation), params: matched?.params ?? pathParams(routes, url.pathname) }, scope)); } const url = new URL(request.url); const other = !matchOperation(routes, request.method, url.pathname, url.searchParams, request.headers) && METHODS.some((x) => x !== request.method && matchOperation(routes, x, url.pathname, url.searchParams, request.headers)); return gapAnswer(m, request, other); }, }); // the GraphQL wire over the same state, at the paths the manifest names (graphql-wire.ts) const gql = m.graphql && parts.graphql ? m.graphql : undefined; const graphql = gql && parts.graphql ? graphqlEndpoint({ sdl: parts.graphql.sdl, part: parts.graphql, loadLibrary: parts.graphql.loadLibrary, context: async (request) => contextFor(m, { request: request.clone(), operation: { id: 'graphql', method: 'POST', path: gql.paths[0]!, class: 'action' } as DerivedOperation, params: {} }, scope) as Promise, unmodeled: ({ type, field }) => Response.json({ errors: [{ ...(gql.unmodeled.type ? { type: gql.unmodeled.type } : {}), message: gql.unmodeled.message.replace('{field}', field).replace('{type}', type) }] }, { status: gql.unmodeled.status ?? 200 }), mutationRefused: (request) => ((options.readOnly ?? false) || isReadOnlyRequest(request) ? vendorError(m, m.readOnly) : undefined), }) : undefined; // the vendor's idempotency layer holds on its GraphQL wire too: a mutation keyed as the manifest declares const keyedGraphql = graphql ? graphqlIdempotency(m, { readOnly: options.readOnly ?? false, ...scope }) : undefined; const api = Object.assign(async (request: Request): Promise => { if (graphql && gql && request.method === 'POST' && gql.paths.includes(new URL(request.url).pathname.replace(/\/+$/, ''))) return keyedGraphql!(request, () => graphql(request)); return rest(request); }, { owners: rest.owners }); // the World's record of placements (placements.ts), read through the World's store at every request as the clock is: a // model vendor's turns, and the faults placed on this vendor's requests, consumed and recorded in its own log const placesThis = (): boolean => placedOn(m.vendor).length > 0; // the work the World's time makes due at this twin (ADR 0036 §4): the vendor's own moves (its catch-up, run for every // account it holds) and every held delivery that fell due. Done when the clock's mover asks (`POST /twin/due`) and waits, // and under a running clock (or none) once for each World minute crossed and at the instant a held delivery falls due; // never by a request. let dueTimer: ReturnType | undefined; const due = async (): Promise => { if (parts.clock) { for (const account of storedTenants(m, options.root)) { await runWithStorageTenant(m.service, account, () => runAsVendorMove(async () => parts.clock!(await open(new Request('http://twin.local/_twin/clock', { method: 'POST' }), 'clock', 'POST', '/_twin/clock', {})))); } } const next = m.events ? await releaseHeldDeliveries(m.service, options.root, m.events.record) : null; if (dueTimer !== undefined) { clearTimeout(dueTimer); dueTimer = undefined; } if (worldClockRunning() && (parts.clock || next !== null)) { const now = Date.parse(worldNow()); const minute = Math.floor(now / 60_000) * 60_000 + 60_000; const at = parts.clock ? Math.min(minute, next === null ? minute : Date.parse(next)) : Date.parse(next!); const store = getActiveWorldStore(); dueTimer = setTimeout(() => { dueTimer = undefined; void withWorldStore(store, due).catch(() => undefined); }, Math.max(0, at - now)); (dueTimer as { unref?: () => void }).unref?.(); } return next; }; // a packet held under a running clock sets the timer for when it falls due; so does a twin that starts (what time crossed // while it was down is done at once) const arm = (): void => { if (worldClockRunning()) void due().catch(() => undefined); }; if (m.events) onHeldDelivery(m.service, options.root, arm); // an event the vendor renders at each attempt is rendered by the pack's render, over a context the kernel opens then const renderEvent = m.events?.renderAt === 'attempt' ? m.events.render : undefined; if (renderEvent) onAttemptRender(m.service, options.root, async (write, type) => renderEvent(await open(new Request('http://twin.local/_twin/events', { method: 'POST' }), 'events', 'POST', '/_twin/events', {}), write, type)); if (m.events || parts.clock) { const store = getActiveWorldStore(); queueMicrotask(() => { void withWorldStore(store, async () => arm()); }); } /** The API, a turn handed its decision (ctx.scenario), or answered as the fault the World's scenario placed on it; an * answer to a request the vendor's switched-on buckets counted carries their headers, and ends its time in flight. */ const decided = async (arrived: Request): Promise => { const rated: { outcome?: RateOutcome } = {}; try { const answered = await decidedAt(arrived, rated); return rated.outcome ? withRateHeaders(answered, rated.outcome.counted) : answered; } finally { rated.outcome?.release(); } }; const decidedAt = async (arrived: Request, rated: { outcome?: RateOutcome }): Promise => { if (!parts.scenario && !placesThis()) return api(arrived); // the body is read once and the request made again from its bytes, so the turn's context and the API each read their // own. const bytes = arrived.method === 'GET' || arrived.method === 'HEAD' ? undefined : await arrived.arrayBuffer(); const request = new Request(arrived.url, { method: arrived.method, headers: arrived.headers, signal: arrived.signal, ...(bytes ? { body: bytes } : {}) }); const url = new URL(request.url); const matched = matchOperation(routes, request.method, url.pathname, url.searchParams, request.headers); if (!matched) return api(request); const turn = parts.scenario?.operations.includes(matched.operation.id) === true; if (!turn && !placesThis()) return api(request); const ctx = await contextFor(m, { request: request.clone(), operation: matched.operation, params: matched.params }, scope); const ledger = scenarioLedgerOf(ctx); const asked = turn ? parts.scenario!.request(ctx) : undefined; /** A fault's answer in the vendor's own envelope: the model wire's, where the pack renders a turn's, else the manifest's * error; null when it holds the request (`slow`) and the answer follows. */ const answerFault = async (fault: PlacedFault): Promise => { const placed = kernelFault(fault); const adapter = parts.scenario?.adapter; if (placed.kind !== 'status' || (asked !== undefined && adapter?.renderFault)) return faultAnswer(fault, asked !== undefined && adapter?.renderFault ? () => adapter.renderFault!(placed as ScenarioStatusFault, asked) : undefined, request.signal); return faultError(m, fault); }; try { // a rejection at the vendor's edge comes before its credential is read, and the vendor's rate limit counts every // request; neither request writes anything (scenario-consume.ts noteFault) const fault = requestFaults(ledger).find((f) => f.on === undefined && f.point === undefined && (f.operation === undefined || f.operation === matched.operation.id)); if (fault?.kind === 'rejected') { await noteFault(ledger, fault, { operation: matched.operation.id }); return (await answerFault(fault))!; } const presented = presentedCredential(m, request); const limited = await rateLimited(ledger, { operation: matched.operation.id, params: matched.params, query: url.searchParams, headers: request.headers, body: ctx.body, credential: presented ? sha256(presented).slice(0, 16) : '', account: storageTenant(m.service) ?? 'default' }, m.rateBudget); if (limited?.refused) return rateRefusal(m, limited.refused); rated.outcome = limited; // the credential is the vendor's first question: a request it refuses takes no turn and meets no other fault if ((turn || fault) && !m.auth?.exempt?.includes(matched.operation.id)) { const refused = authRefusal(m, request, options.root); if (refused) return refused; } // a failure lands in the operation's place, inside the vendor's idempotency layer (crossCutting's, and the GraphQL // wire's), which keeps it under the request's key; no turn is taken (a turn's failure the pack renders is answered // here, in its wire) if (fault?.kind === 'failed' && !(asked !== undefined && parts.scenario?.adapter?.renderFault)) return await api(withHeaders(request, new Headers([...request.headers, [SCENARIO_FAULT_HEADER, String(fault.index)]]))); if (fault) { // a dropped request is never answered and writes nothing await (fault.kind === 'drop' ? noteFault : recordFault)(ledger, fault, { operation: matched.operation.id }); // committed, and its answer lost: the write lands, and the app is told it failed if (fault.kind === 'lost') { await (await answer(request, asked, ledger)).arrayBuffer(); return (await answerFault({ ...fault, kind: 'failed' }))!; } const answered = await answerFault(fault); if (answered) return answered; } return await answer(request, asked, ledger); } catch (error) { if (!(error instanceof ScenarioError)) throw error; return vendorError(m, { status: 500, code: 'scenario_error', message: `the World's scenario: ${error.message}` }); } }; /** The request answered by the API, a turn first decided by the World's scenario. */ const answer = async (request: Request, asked: unknown, ledger: ScenarioLedger): Promise => { if (asked === undefined) return api(request); const served = await serveTurn(asked, ledger, parts.scenario!.adapter, request.signal); if (served.kind === 'fault') return Response.json(served.result.body, { status: served.result.status, headers: served.result.headers ?? {} }); return api(withHeaders(request, new Headers([...request.headers, [SCENARIO_DECISION_HEADER, scenarioDecisionHeader(served)]]))); }; for (const d of m.doors ?? []) if (!parts.doors?.[d.id]) throw new Error(`${m.vendor}: the manifest declares the door ${d.id}, and semantics/doors.ts exports no ${d.id}`); const door = worldDoorMatcher(m.doors ?? []); const screens = (m.screens ?? []).filter((s) => s.status === 'done' && parts.screens?.[s.id]).map((s) => { const hosts = [s.host, ...(s.hosts ?? [])].map(hostMatcher); return { decl: s, host: (h: string) => hosts.map((match) => match(h)).find(Boolean), path: pathMatcher(s.path, true), answer: parts.screens![s.id]! }; }); // the workspaces a person can be shown (Viewing a World): each built workspace screen's id and path, the pack's own // and its lanes' const workspaces = (): Workspace[] => [...(m.screens ?? []).filter((s) => s.kind === 'workspace' && s.status === 'done' && parts.screens?.[s.id]).map((s) => ({ id: s.id, path: s.path, host: s.host })), ...lanesWorkspaces(parts.lanes ?? {})]; /** Whether a built screen a person views (a workspace or a flow, never content an API client reads) draws a url: its host * one the screen names, its path the screen's or under it (a root screen draws its root alone). */ // by what the pack declares built (a screen drawn by another's handler, as X's profile is by its web pages, is built) const viewed = (m.screens ?? []).filter((s) => s.status === 'done' && s.kind !== 'content').map((s) => { const hosts = [s.host, ...(s.hosts ?? [])].map(hostMatcher); return { root: s.path.replace(/\/+$/, '') === '', host: (h: string) => hosts.some((match) => match(h)), path: pathMatcher(s.path, true) }; }); const drawsUrl = (at: string): boolean => { try { const u = new URL(at); const path = u.pathname.replace(/\/+$/, '') || '/'; return viewed.some((s) => s.host(u.hostname.toLowerCase()) && (s.root ? path === '/' : Boolean(s.path(path)))); } catch { return false; } }; // a context the kernel opens for what no surface operation names: a door, a screen, the clock, the board const open = (request: Request, id: string, method: string, path: string, params: Record, streamed?: true): Promise => contextFor(m, { request, operation: { id, method, path, class: method === 'GET' ? 'retrieve' : 'action' } as DerivedOperation, params, ...(streamed ? { streamed } : {}) }, scope); const refusedReadOnly = (): Response => vendorError(m, m.readOnly); const routed = unitRequestRouter(m, surface, routes); const rootServes = (method: string, path: string): boolean => Boolean(matchOperation(routes, method, path)); const lane = m.lanes ? laneRouter(m.vendor, m.lanes, parts.lanes ?? {}, rootServes) : undefined; // Inspect lane-owned World doors directly, without routing them back through the vendor gateway. const laneDoor = (request: Request, path: string): Promise> => laneDoors(parts.lanes ?? {}, request, path); // at a World's place, a page's asset or upload on another of the pack's content hosts is `/@/` // (architecture, "A page at a World's place"): answered by the built content screen that names that host exactly, // routed from it, and by nothing else; a request naming no such host is general routing's const contentScreens = screens.filter((s) => s.decl.kind === 'content'); for (const s of contentScreens) if (s.decl.yieldsToApi) throw new Error(`${m.vendor}: the content screen ${s.decl.id} declares yieldsToApi; a content screen answers its host's requests alone (architecture, "Screens")`); const contentHosts = [...new Set(contentScreens.flatMap((s) => [s.decl.host, ...(s.decl.hosts ?? [])]).filter((h) => !/[{<]/.test(h)).map((h) => h.toLowerCase()))]; const contentNotFound = (host: string, path: string): Response => { const nf = m.notFound; return vendorError(m, { status: nf.status, message: nf.message.replace(/\{object\}/g, host).replace(/\{id\}/g, path), ...(nf.code !== undefined ? { code: nf.code } : {}), ...(nf.kind !== undefined ? { kind: nf.kind } : {}) }); }; /** A request at a World's place for `/@/`, `` one a built content screen of this unit names exactly: * that screen's answer, or the pack's not-found for what the host or the screen does not take. The path is held to * the descriptor's host rules (`rules`: this unit's, or its vendor's for a lane), read as the injector reads them. * Undefined for any other request. */ // the descriptor's host rules: this unit's, or, for a lane (which declares none), its vendor's as registered const descriptorHosts = (): PackDescriptorHosts => m.descriptor?.hosts ?? getPack(m.vendor)?.hosts; const atContentHost = async (request: Request, rules: PackDescriptorHosts = descriptorHosts()): Promise => { if (!request.headers.has(TWIN_PREFIX_HEADER)) return undefined; const url = new URL(request.url); const address = contentAddressOf(url.pathname); if (!address || !contentHosts.includes(address.host)) return undefined; const { host, path: inner } = address; if (address.refused) return contentNotFound(host, inner); const declared = hostRules(rules); if (declared.names(host) && !declared.takes(host, inner)) return contentNotFound(host, inner); const onHost = contentScreens.filter((s) => [s.decl.host, ...(s.decl.hosts ?? [])].some((h) => h.toLowerCase() === host)); const method = request.method.toUpperCase(); const allowed = (s: (typeof screens)[number]): boolean => method === 'GET' || method === 'HEAD' || (method === 'POST' && (s.decl.takes ?? []).includes('POST')); // the request as it reaches the content host, through the pack's own routing of a host (its path prefix and labels) url.pathname = inner; const headers = new Headers(request.headers); headers.set('x-volter-twin-original-host', host); const sent = method === 'POST' && request.body ? { body: request.body, duplex: 'half' } : {}; const there = routed(new Request(url, { method, headers, signal: request.signal, ...sent } as RequestInit)); const path = new URL(there.url).pathname.replace(/\/+$/, '') || '/'; const hit = onHost.map((s) => ({ s, hit: s.path(path) })).find((x) => x.hit && allowed(x.s)); if (!hit) return contentNotFound(host, inner); const asked = options.readOnly && !isReadOnlyRequest(there) ? withHeaders(there, new Headers([...there.headers, [READ_ONLY_REQUEST_HEADER, '1']])) : there; if (method === 'POST' && ((options.readOnly ?? false) || isReadOnlyRequest(asked))) return refusedReadOnly(); return hit.s.answer(await open(asked, hit.s.decl.id, method, hit.s.decl.path, { ...(hit.s.host(host)?.params ?? {}), ...hit.hit!.params }, true)); }; /** A request as the kernel reads it: the headers only the kernel names taken off, its body decoded (undefined when it * does not decode as its Content-Encoding says). */ const prepared = async (arrived: Request): Promise => { if (arrived.headers.has(SCENARIO_DECISION_HEADER) || arrived.headers.has(SCENARIO_FAULT_HEADER) || arrived.headers.has(PREFIX_PARAMS_HEADER)) { const headers = new Headers(arrived.headers); headers.delete(SCENARIO_DECISION_HEADER); headers.delete(SCENARIO_FAULT_HEADER); headers.delete(PREFIX_PARAMS_HEADER); arrived = new Request(arrived, { headers }); } return decoded(m, arrived); }; const undecodable = (arrived: Request): Response => vendorError(m, m.encodings?.undecodable ?? { status: 400, message: `the body does not decode as its Content-Encoding (${arrived.headers.get('content-encoding')}) says` }); /** The content route at the request's arrival: the answer, or undefined when this unit's content screens name no such * host. */ const answerContent = async (arrived: Request): Promise => { const address = arrived.headers.has(TWIN_PREFIX_HEADER) ? contentAddressOf(new URL(arrived.url).pathname) : undefined; if (!address || !contentHosts.includes(address.host)) return undefined; const readable = await prepared(arrived); return readable instanceof Response ? readable : readable ? atContentHost(readable) : undecodable(arrived); }; const fetch = async (received: Request): Promise => { const arrived = m.mergeSlashes ? slashesMerged(received) : received; redisServiceTimes.lap('1 request made by the stream'); // the discovery door is the pack's own, whichever lane would take its path const asked = new URL(arrived.url).pathname.replace(/\/+$/, '') || '/'; const discovery = arrived.method === 'GET' && m.discovery !== undefined && (asked === '/twin' || asked === '/twin/scenario'); // the board is read from the state as it stands, before anything else runs (the clock, a lane, the API): a read, // whoever asks, each frame drawn when a built screen takes its url; a pack that lays out none has an empty board if (arrived.method === 'GET' && asked === '/twin/board') { if (!parts.board) return Response.json({ frames: [] }); const request = withHeaders(arrived, new Headers([...arrived.headers, [READ_ONLY_REQUEST_HEADER, '1']])); const frames = await parts.board(await open(request, 'board', 'GET', '/twin/board', {})); return Response.json({ frames: frames.map((f) => ({ ...f, drawn: drawsUrl(f.url) })) }); } // `/@/` at a World's place, for a host a built content screen of this pack names, is that screen's // alone (only the kernel names a scenario's decision or a path prefix's parameters: `prepared` takes them off); for // one a lane's names, the lane router sends it to that lane's own fetch, wrapped as any request to it is const own = await answerContent(arrived); if (own) return own; // Root World doors belong to the pack at every routed host, including a lane's host. const rootDoor = door(arrived.method, asked); const toLane = discovery || rootDoor ? undefined : lane?.(arrived); if (toLane) return toLane(arrived); const readable = await prepared(arrived); if (readable instanceof Response) return readable; if (!readable) return undecodable(arrived); const incoming = routed(readable); // a twin started read-only marks every request so, so every context it opens knows (isReadOnlyRequest) const request = options.readOnly && !isReadOnlyRequest(incoming) ? withHeaders(incoming, new Headers([...incoming.headers, [READ_ONLY_REQUEST_HEADER, '1']])) : incoming; const url = new URL(request.url); const path = url.pathname.replace(/\/+$/, '') || '/'; const readOnly = (options.readOnly ?? false) || isReadOnlyRequest(request); redisServiceTimes.lap('2 content and lane routes, decoding, routing'); if (request.method === 'GET' && path === '/twin' && m.discovery) { const d = m.discovery; const discoveryDoors = [...(m.doors ?? []), ...(m.machines ? [{ id: 'machine-pool', method: 'POST', path: '/_twin/machine-pool', note: 'Enroll the World execution pool: { kind: docker | none | fake }.' }] : [])]; // the workspaces a person can be shown (Viewing a World): each built workspace screen's id and path const laneDiscovery = await laneDoor(request, '/twin'); const resources: Record }> = {}; for (const [type, spec] of Object.entries(m.resources)) { const resource = resources[storedType(m, type)] ??= { relations: [] }; const relations = [ ...(spec.parent ? [{ field: spec.parent.field, to: storedType(m, spec.parent.resource) }] : []), ...Object.entries(spec.embeds ?? {}).map(([field, to]) => ({ field, to: storedType(m, to) })), ]; for (const relation of relations) if (!resource.relations.some(r => r.field === relation.field && r.to === relation.to)) resource.relations.push(relation); } const shown = { resources, ...(workspaces().length ? { screens: workspaces() } : {}), ...(Object.keys(laneDiscovery).length ? { lanes: laneDiscovery } : {}) }; const identity = d.identity ?? (m.auth?.held ? 'Authenticate as the vendor does, using a credential issued in this World; unknown credentials are refused.' : undefined); // a model vendor's: its state, and what its scenario scripts, with the scenario's live counts if (parts.scenario && d.behavior) { const body = twinManifest({ vendor: m.vendor, twinOf: d.twinOf, stateSentence: `Stateful: it stores ${d.stores}. Create state through the vendor's OWN API with the real SDK or plain fetch pointed here${discoveryDoors.length ? "; what the vendor does on its own pages (not its API) is a door of the World, listed under doors" : ''}.`, behaviorSentence: d.behavior, exampleHandler: d.exampleHandler ?? null, }); const declared = Object.fromEntries(discoveryDoors.map((door) => [`${door.method} ${doorPath(door.path)}`, door.note ?? 'a door of the World'])); return Response.json({ ...shown, ...body, program: { ...(body.program as Record), ...(identity ? { identity } : {}) }, doors: { ...(body.doors as Record), ...declared } }); } return Response.json({ ...statefulTwinManifest({ vendor: m.vendor, twinOf: d.twinOf, stores: d.stores, ...(identity ? { identity } : {}), ...(d.behavior ? { behavior: d.behavior } : {}), ...(d.notes ? { notes: d.notes } : {}), ...(discoveryDoors.length ? { doors: discoveryDoors.map((door) => ({ ...door, path: doorPath(door.path) })) } : {}) }), ...shown }); } // the World's clock has moved: do what it made due, and answer once it is done (ADR 0036 §4) if (request.method === 'POST' && path === '/twin/due') return Response.json({ next: await due() }); // what the World's scenario placed on this vendor, and what the twin consumed of it (its `_decision` and `_fault` records) if (request.method === 'GET' && path === '/twin/scenario') { const lanes = await laneDoor(request, '/twin/scenario'); return Response.json({ ...scenarioRecords(m, options.root), ...(Object.keys(lanes).length ? { lanes } : {}) }); } // a reply a session awaits that the World's clock has run out (sockets.ts) if (m.sockets?.length) expireSocketWaits(m.service, options.root); if (path.startsWith('/_twin/')) { // the World's machine pool, enrolled by the kernel for a vendor that runs images (machines.ts) if (m.machines && path === '/_twin/machine-pool' && request.method === 'POST') { if (readOnly) return refusedReadOnly(); let enrollment: Record = {}; try { enrollment = parseExactJson(await request.clone().text()); } catch {} const kind = enrollment.kind; if (!POOL_KINDS.includes(kind as never)) return Response.json({ message: `kind must be one of ${POOL_KINDS.join(', ')}` }, { status: 400 }); await applyTwinWrite(m.service, { operation: 'machine_pool.enroll', subjectType: MACHINE_POOL, subjectId: 'pool', fields: { kind, ...(kind === 'fake' && Array.isArray(enrollment.httpReplies) ? { httpReplies: enrollment.httpReplies } : {}) }, occurredAt: (await open(request, 'machine-pool', 'POST', '/_twin/machine-pool', {})).occurredAt, actor: { kind: 'system' } }, options.root); if (kind === 'fake') resetFakePool(m.service, options.root); return Response.json({ kind }, { status: 201 }); } const hit = door(request.method, path); if (hit) { if (readOnly && request.method !== 'GET') return refusedReadOnly(); const d = hit.door; return parts.doors![d.id]!(await open(request, d.id, d.method, d.path, hit.params)); } return gapAnswer(m, request); } // a screen on a host it names exactly answers there first (a dashboard's /login on dash.cloudflare.com, where the // API's /{Bucket} would take it); then a path the vendor's API names is the API's; then a screen on a host it names by // pattern (a room's page on .daily.co, which api.daily.co also matches); then a screen by its path alone, at // whichever host the twin is reached (its links carry the twin's own base), never a root screen off its own host const host = hostOf(request); const exact = (s: (typeof screens)[number]): boolean => [s.decl.host, ...(s.decl.hosts ?? [])].some((h) => !/[{<]/.test(h) && h.toLowerCase() === host); const apiPath = Boolean(matchOperation(routes, request.method, url.pathname, url.searchParams, request.headers)); // a screen that yields to the API draws only what no operation names, wherever it would answer (architecture, // "Screens": Hacker News's /login page, whose form posts to POST /login) const hits = screens.map((s) => ({ s, hit: s.path(path), onHost: s.host(host) })).filter((x) => x.hit && !(apiPath && x.s.decl.yieldsToApi)); // reached at a World's place for the twin (`x-forwarded-prefix`, served-world's wire), the host is the World's: a // workspace is shown there by its path alone, its root too (the console frames it so) const placed = request.headers.has(TWIN_PREFIX_HEADER); // a person's browser opening a page there (a navigation, a form, the console's frame) is asking for a screen: one // whose path names it is taken before an API path of the same shape (a dashboard's //workers-and-pages // over R2's /{Bucket}/{Key}), the root workspace at the root alone const page = placed && ['document', 'iframe'].includes(request.headers.get('sec-fetch-dest') ?? ''); const rooted = (x: (typeof hits)[number]): boolean => x.s.decl.path.replace(/\/+$/, '') === ''; // a request the World routed from a vendor's own hostname (its proxy, a site, a call inside the World) is answered by // that host's screens alone: a page of github.com never answers at .github.io, nor Cloudflare's sign-in at a // Worker's Custom Domain; a screen by its path alone is for the twin reached at its own address const addressed = !placed && request.headers.has('x-volter-twin-original-host'); const byPath = hits.find((x) => x.onHost && exact(x.s)) ?? (page ? hits.find((x) => !rooted(x)) ?? (path === '/' ? hits.find((x) => x.s.decl.kind === 'workspace') : undefined) : undefined) ?? (apiPath ? undefined : hits.find((x) => x.onHost) ?? (addressed ? undefined : hits.find((x) => !rooted(x)) ?? (placed ? hits.find((x) => x.s.decl.kind === 'workspace') : undefined))); if (byPath) { const asked = byPath.s.decl.kind === 'workspace' && request.method === 'GET' ? shownRecord(url, screens.filter((x) => x.decl.kind === 'workspace').map((x) => x.decl), { ...(byPath.onHost?.params ?? {}), ...byPath.hit!.params }) : undefined; if (asked !== undefined && asked !== path) return new Response(null, { status: 302, headers: { location: `${(request.headers.get(TWIN_PREFIX_HEADER) ?? '').replace(/\/+$/, '')}${asked}` } }); if (readOnly && request.method !== 'GET' && request.method !== 'HEAD') return refusedReadOnly(); return byPath.s.answer(await open(request, byPath.s.decl.id, request.method, byPath.s.decl.path, { ...(byPath.onHost?.params ?? {}), ...byPath.hit!.params }, true)); } for (const route of m.machineRoutes ?? []) { const host = request.headers.get('x-volter-twin-original-host') ?? new URL(request.url).hostname; const match = new RegExp(route.host).exec(host); if (!match) continue; const ctx = await open(request, 'machine.traffic', request.method, url.pathname, match.groups ?? {}); const field = (row: Record, path: string): unknown => path.split('.').reduce((value, key) => value && typeof value === 'object' ? (value as Record)[key] : undefined, row); const fill = (value: string, row: Record = {}): string => value.replace(/\{([^}]+)\}/g, (_, key: string) => String(match.groups?.[key] ?? field(row, key) ?? '')); const row = ctx.rowsRaw(route.resource).find(row => Object.entries(route.where).every(([key, value]) => String(field(row, key)) === fill(value))); if (!row) return new Response('Guest is unavailable', { status: 503 }); try { return await ctx.machines.request(String(field(row, route.name)), Number(typeof route.port === 'string' ? fill(route.port, row) : route.port), request); } catch { return new Response('Guest is unavailable', { status: 503 }); } } if (!parts.around) return encoded(m, request, await decided(request)); // The front reads a context before forwarding (possibly with new headers). Materialize a transport body before // those independent reads, rather than chaining tees of the incoming stream through the front and the scenario. redisServiceTimes.lap('3 doors, screens and machine routes passed'); const bytes = request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.arrayBuffer(); const buffered = new Request(request.url, { method: request.method, headers: request.headers, signal: request.signal, ...(bytes ? { body: bytes } : {}) }); const matched = matchOperation(routes, buffered.method, url.pathname, url.searchParams, buffered.headers); const operation = matched?.operation ?? ({ id: 'unmatched', method: buffered.method, path: url.pathname, class: buffered.method === 'GET' ? 'retrieve' : 'action' } as DerivedOperation); redisServiceTimes.lap('4 body buffered, operation matched'); const ctx = await contextFor(m, { request: buffered.clone(), operation, params: matched?.params ?? pathParams(routes, url.pathname) }, scope); redisServiceTimes.lap('5 the around context opened'); const answered = await parts.around(ctx, (rewritten) => decided(rewritten ?? buffered)); redisServiceTimes.lap('6d the handler, and the around after it'); const sent = await encoded(m, buffered, answered); redisServiceTimes.lap('7 answer encoded'); return sent; }; // the request's id is the correlation of every entry it appends (runtime contract D3), minted here, always: it is the // group a perform sends as one call (the real-system adapters, "Perform"). Under `auto` the group is performed once // the handler has answered, and the answer names the subjects by the ids the vendor gave them. const correlated = async (request: Request): Promise => { const id = `req_${globalThis.crypto.randomUUID()}`; const { value: answer, appended } = await runWithCorrelationId(id, () => deferPerform(id, () => fetch(request))); if (!appended) return answer; // a receive-pack's pushes (derived-core.ts pushedInput): what the World's refs held before and after each const pushes = m.git ? deployableEntries(m.service, options.root).filter((e) => e.correlationId === id && e.input?.git).map((e) => ({ actionId: e.id, ...(e.input!.git as { name: string; ref: string; before: string; after: string }) })) : []; const performed = await runWithCorrelationId(id, () => performRequestGroup(m.service, id, options.root)); // under `auto`, what the root did is what the World keeps (ADR 0031): a ref it refused goes back to its value before // the push, by compare-and-set under the ref lock (a later push built on it keeps its value), its push and effects // are reverted (head.ts), and the client hears git's own report, `ok` or `ng` for each ref if (pushes.length) { const whole = performed instanceof RefusedWriteError ? performed.reason : performed instanceof VendorWriteError ? performed.message : undefined; const refused = new Map(); for (const p of pushes) { const reason = whole ?? (performed as { refused?: Array<{ actionId: string; reason: string }> }).refused?.find((r) => r.actionId === p.actionId)?.reason; if (reason !== undefined) refused.set(p.actionId, reason); } if (refused.size) { for (const p of [...pushes].reverse()) { if (!refused.has(p.actionId)) continue; const { refs } = gitRepositoryOf(m, p.name, options.root); refs.withLock(() => { if ((refs.get(p.ref) ?? ZERO_SHA) !== p.after) return; if (p.before === ZERO_SHA) refs.delete(p.ref); else refs.set(p.ref, p.before); }); } const ng = new Map(pushes.filter((p) => refused.has(p.actionId)).map((p) => [p.ref, refused.get(p.actionId)!.replace(/\s+/g, ' ')])); const report = concat(...readPktLines(new Uint8Array(await answer.arrayBuffer())).lines.map((line) => { const ref = line.startsWith('ok ') ? line.slice(3).trim() : undefined; return pktLine(ref !== undefined && ng.has(ref) ? `ng ${ref} ${ng.get(ref)}\n` : line); }), FLUSH); const headers = new Headers(answer.headers); headers.delete('content-length'); return new Response(report as unknown as BodyInit, { status: answer.status, headers }); } } // the vendor's refusal, as its status and words (perform names them `: `), in the vendor's error body if (performed instanceof RefusedWriteError) { const said = /^(\d{3}): ([\s\S]*)$/.exec(performed.reason); return vendorError(m, { status: said ? Number(said[1]) : 400, message: said ? said[2]! : performed.reason }); } if (performed instanceof VendorWriteError) return vendorError(m, { status: 502, message: performed.message }); if (performed.response) { const { status, headers: received, body, bodyBytes } = performed.response; const headers = new Headers(received); for (const name of ['content-length', 'content-encoding', 'transfer-encoding', 'connection', 'keep-alive']) headers.delete(name); return new Response([204, 205, 304].includes(status) ? null : bodyBytes ? new Uint8Array(bodyBytes).buffer : body, { status, headers }); } if (!performed.ids.size || !(answer.headers.get('content-type') ?? '').includes('json')) return answer; let text = await answer.text(); for (const [local, vendor] of performed.ids) text = text.split(JSON.stringify(local)).join(JSON.stringify(vendor)); const headers = new Headers(answer.headers); headers.delete('content-length'); return new Response(text, { status: answer.status, statusText: answer.statusText, headers }); }; // the vendor's CORS, as its gateway answers a browser: every answer, a preflight at any path // a JSON answer labelled as the vendor labels it const labelled = m.jsonContentType === undefined ? correlated : async (request: Request): Promise => { const res = await correlated(request); const type = res.headers.get('content-type') ?? ''; if (!type.startsWith('application/json') || type === m.jsonContentType) return res; const headers = new Headers(res.headers); headers.set('content-type', m.jsonContentType!); return new Response(res.body, { status: res.status, statusText: res.statusText, headers }); }; const cors = m.cors ? withCors(m.cors, labelled) : labelled; // at a World's place every cookie the twin sets is kept to the twin's base path (twin-fetch.ts, placedCookies) const selectedAccount = async (request: Request): Promise => { if (m.tenant?.storage !== 'namespaced' || !parts.tenant) return undefined; const authority = routed(request.clone()), path = new URL(authority.url).pathname; return runWithStorageTenant(m.service, undefined, async () => (await parts.tenant!(await open(authority, 'account-authority', request.method, path, {}))) ?? '__unselected__'); }; // what this twin is serving the World's clients now, by connection (ADR 0036 §8): each request, and each byte-stream // session from its connect to its close (`/twin/connection`, which the kernel's stream posts); a position is taken and // a step settles when none is. Counted once for the twin wherever its fetch is made more than once (a byte-stream // pack's stream and its HTTP side are two fetches of one twin) const work = openWork(m.service, options.root); const served = async (request: Request): Promise => { const path = new URL(routed(request.clone()).url).pathname; if (request.method === 'GET' && path === '/twin/open') return Response.json({ open: work.serving + work.connections }); if (request.method === 'POST' && path === '/twin/connection') { // a connection's open or close, counted only as it is said: a body that says neither is refused, never counted as a // close (ADR 0036 §8: the count a settle reads is never lowered by an error) let opened: unknown; try { opened = ((await request.json()) as { open?: unknown }).open; } catch { opened = undefined; } if (typeof opened !== 'boolean') return Response.json({ error: 'a connection is reported as { open: true | false }' }, { status: 400 }); work.connections = Math.max(0, work.connections + (opened ? 1 : -1)); return Response.json({ open: work.serving + work.connections }); } if (path === '/twin' || path.startsWith('/twin/')) return placedCookies(request, await cors(request)); work.serving += 1; try { if (m.tenant?.storage !== 'namespaced' || !parts.tenant) return placedCookies(request, await cors(request)); return runWithStorageTenant(m.service, await selectedAccount(request), async () => placedCookies(request, await cors(request))); } finally { work.serving -= 1; } }; // which paths this pack's API serves, for a vendor's lane router that asks (unlessOnlyRoot) const serves = (method: string, path: string): boolean => Boolean(matchOperation(routes, method, path)); // the vendor's sockets: a request to a declared socket's path opens a session of its engine, over a context of the // request that opened it (operation `socket:`) for (const d of m.sockets ?? []) if (!parts.sockets?.[d.id]) throw new Error(`${m.vendor}: the manifest declares the socket ${d.id}, and semantics/sockets.ts exports no ${d.id}`); const ownUpgrade = m.sockets?.length ? socketUpgrade(m.service, options.root, m.sockets, parts.sockets!, (request, d, params) => open(request, `socket:${d.id}`, 'GET', d.path, params), hostOf, (request) => new URL(routed(request).url).pathname, // a turn a session speaks (a voice agent's reply) is the World's scenario's, as a turn over HTTP is async (asked, context) => (parts.scenario ? serveTurn(asked, scenarioLedgerOf(await context()), parts.scenario.adapter) : undefined)) : undefined; const rawUpgrade = laneUpgrades(parts.lanes ?? {}, ownUpgrade); const opening = new WeakMap>(); const upgrade: WebSocketUpgrade | undefined = rawUpgrade && m.tenant?.storage === 'namespaced' && parts.tenant ? { accepts: request => rawUpgrade.accepts(request), protocol: request => rawUpgrade.protocol?.(request), open(peer, request) { const ready = selectedAccount(request).then(account => runWithStorageTenant(m.service, account, () => rawUpgrade.open(peer, request))); opening.set(peer, ready); void ready.catch(error => peer.close(1011, String(error instanceof Error ? error.message : error).slice(0, 120))); }, async message(peer, data) { await opening.get(peer); return rawUpgrade.message(peer, data); }, close(peer) { const ready = opening.get(peer); opening.delete(peer); void ready?.then(() => rawUpgrade.close(peer), () => undefined); }, } : rawUpgrade; // the broadcasts the vendor takes over RTMP: a publisher's connection, its publish ruled by the pack's dialect over a // context of its own (operation `live:`), its recording kept as the World's bookkeeping and blobs (live/ingest.ts) const ownIngest = m.live?.length ? liveIngest({ world: `${m.service}\u0000${options.root ?? ''}`, decls: m.live, engines: parts.live ?? {}, readOnly: options.readOnly ?? false, open: (decl, ask) => open(new Request(`http://live.${m.vendor}.invalid/${encodeURIComponent(decl.app)}`, { method: 'POST', headers: { 'x-forwarded-for': ask.peer } }), `live:${decl.id}`, 'POST', `/${decl.app}`, {}), run: (fn) => runWithCorrelationId(`live_${globalThis.crypto.randomUUID()}`, () => runAsVendorMove(fn)), store: { rows: (type) => resourcesOfType(m.service, type, options.root) as unknown as Array>, blob: (key) => readResourceBlob(m.service, key, options.root), putBlob: (key, bytes) => writeResourceBlob(m.service, key, bytes, options.root), removeBlob: (key) => removeResourceBlob(m.service, key, options.root), now: () => (options.clock ?? worldNow)(), record: async (type, id, fields, operation) => { await applyTwinWrite(m.service, { operation, subjectType: type, subjectId: id, fields, occurredAt: (options.clock ?? worldNow)(), actor: { kind: 'system' } }, options.root); }, }, }) : undefined; const ingest = ownIngest ?? Object.values(parts.lanes ?? {}).find((l) => l.fetch.ingest)?.fetch.ingest; // what serves each operation: the pack's own, and each lane's, each unit's under its own name const ownersByUnit = (): Record> => ({ '': { ...((surface.format === 'command-reply' || surface.format === 'command-table' && m.descriptor?.transport === 'raw-tcp') ? Object.fromEntries((surface.commands ?? []).map((c) => [c.id, parts.around && !m.unmodeled?.includes(c.id) ? 'handler' : 'gap'])) : api.owners()), ...Object.fromEntries((parts.graphql?.operations ?? []).map((op) => [op.id, `${op.kind === 'query' ? 'Query' : 'Mutation'}.${op.field}` in (parts.graphql?.resolvers ?? {}) ? 'handler' : 'gap'] as const)), }, ...lanesOwners(parts.lanes ?? {}), }); const owners = (): Record => flatOwners(ownersByUnit()); return derivedRequestScopes(m, Object.assign(served, { owners, ownersByUnit, serves, workspaces, boards: Boolean(parts.board), maxRequestBodySize: m.descriptor?.maxRequestBodySize, draws: drawsUrl, contentHosts, ...(upgrade ? { upgrade } : {}), ...(ingest ? { ingest } : {}) }), options.readOnly); } /** The lane selected by the vendor gateway, shared by serving and response judgment. */ export function laneSelector(decl: LanesDecl, lanes: Record }>, rootServes: (method: string, path: string) => boolean = () => false): (request: Request) => string | undefined { const door = worldDoorMatcher(Object.entries(lanes).flatMap(([name, part]) => (part.manifest.doors ?? []).map((d) => ({ ...d, name })))); const laneRoutes = decl.routes.map((r) => { const at = r.path?.replace(/\/+$/, ''); const host = r.host !== undefined ? new RegExp(r.host, 'i') : undefined; const pattern = r.pathPattern !== undefined ? new RegExp(r.pathPattern) : undefined; const except = (r.exceptHosts ?? []).map((h) => h.toLowerCase()); const own = lanes[r.lane]?.fetch.serves; return { lane: r.lane, holds: (request: Request, path: string, name: string): boolean => (at === undefined || path === at || path.startsWith(`${at}/`)) && (pattern === undefined || pattern.test(path)) && (host === undefined || host.test(name)) && (r.header === undefined || (request.headers.get(r.header.name) ?? '').startsWith(r.header.prefix) !== (r.header.absent === true)) && !except.includes(name) && !(r.unlessOnlyRoot && rootServes(request.method, path) && !(own?.(request.method, path) ?? false)), }; }); return (request) => { // `/@/` at a World's place, for a host a lane's built content screen names, goes to that lane, before // any lane is picked by the request's host or path: its own fetch answers it by its content route, under the vendor's // host rules (architecture, "A page at a World's place") const address = request.headers.has(TWIN_PREFIX_HEADER) ? contentAddressOf(new URL(request.url).pathname) : undefined; const content = address && Object.keys(lanes).find((l) => lanes[l]!.fetch.contentHosts?.includes(address.host)); if (content) return content; const path = new URL(request.url).pathname.replace(/\/{2,}/g, '/'); if (path.startsWith('/_twin/')) { const hit = door(request.method, path); if (hit) return hit.door.name; } const name = hostOf(request); return laneRoutes.find((r) => r.holds(request, path, name))?.lane ?? decl.default; }; } /** The vendor's gateway over its lanes: the lane a request goes to (a door to the lane that declares it, then the first * route whose conditions all hold, then the default), behind the gateway's CORS; undefined when none takes it. */ function laneRouter(vendor: string, decl: LanesDecl, lanes: Record, rootServes: (method: string, path: string) => boolean = () => false): (request: Request) => ((request: Request) => Promise) | undefined { const served = (name: string): ((request: Request) => Promise) => { const part = lanes[name]; if (!part) throw new Error(`${vendor}: the manifest routes to the lane ${name}, and the vendor's fetch is given no ${name}`); // the lane is named on the request, so a write it makes records which lane's API made it (LANE_HEADER) const named = (request: Request): Promise => { const headers = new Headers(request.headers); headers.set(LANE_HEADER, name); return part.fetch(withHeaders(request, headers)); }; return decl.cors ? withCors(decl.cors, named) : named; }; const selected = laneSelector(decl, lanes, rootServes); const handlers = new Map([...new Set([...decl.routes.map((route) => route.lane), ...(decl.default === undefined ? [] : [decl.default]), ...Object.keys(lanes)])].map((name) => [name, served(name)])); return (request) => { const name = selected(request); return name === undefined ? undefined : handlers.get(name); }; } /** A vendor whose every API is a lane (Cloudflare's API v4 and R2, AWS's services), served from its manifest: the * discovery door, then its lanes as its gateway sends them; a request no lane takes is the vendor's not-found. */ /** Each lane's answer at one of its World doors (`/twin`, `/twin/scenario`), by lane, read from the lane directly rather * than routed back through the vendor's front: a vendor's discovery holds its lanes' (their doors, their scripts). */ async function laneDoors(lanes: Record, request: Request, path: string): Promise> { const entries = await Promise.all(Object.entries(lanes).map(async ([name, part]) => { const url = new URL(request.url); url.pathname = path; url.search = ''; const answer = await part.fetch(new Request(url, { headers: request.headers, signal: request.signal })); return answer.ok ? [name, await answer.json()] as const : undefined; })); return Object.fromEntries(entries.filter((entry): entry is readonly [string, unknown] => entry !== undefined)); } /** What serves each of a vendor's lanes' operations (a handler, the core, or the gap), by lane: a lane's operation is the * lane's own, so an id it shares with its root or another lane (Clerk's Backend and Frontend APIs both name * `ListOrganizationMemberships`) keeps the lane's own owner, and a lane's gap stays a gap whoever else serves the id. */ const lanesOwners = (lanes: Record): Record> => Object.fromEntries(Object.entries(lanes).map(([name, l]) => [name, (l.fetch as { owners?: () => Record }).owners?.() ?? {}])); /** A vendor's owners as one map, for its breadth: its own API's operations by id, a lane's as `:`. */ const flatOwners = (byUnit: Record>): Record => Object.fromEntries(Object.entries(byUnit).flatMap(([unit, map]) => Object.entries(map).map(([id, owner]) => [unit ? `${unit}:${id}` : id, owner] as const))); /** The workspaces a vendor's lanes draw, as one list. */ const lanesWorkspaces = (lanes: Record): Workspace[] => Object.values(lanes).flatMap((l) => (l.fetch as { workspaces?: () => Workspace[] }).workspaces?.() ?? []); /** Keep each upgraded peer on the vendor or lane engine that accepted its opening request. */ function laneUpgrades(lanes: Record, own?: WebSocketUpgrade): WebSocketUpgrade | undefined { const choices = [own, ...Object.values(lanes).map(lane => lane.fetch.upgrade)].filter((choice): choice is WebSocketUpgrade => choice !== undefined); if (choices.length === 0) return undefined; if (choices.length === 1) return choices[0]; const held = new WeakMap(); const selectedRequests = new WeakMap(); return { async accepts(request) { for (const choice of choices) if (await choice.accepts(request)) { selectedRequests.set(request, choice); return true; } return false; }, protocol: request => selectedRequests.get(request)?.protocol?.(request), open(peer, request) { const selected = selectedRequests.get(request); selectedRequests.delete(request); if (selected) { held.set(peer, selected); selected.open(peer, request); } }, message(peer, data) { return held.get(peer)?.message(peer, data); }, close(peer) { const selected = held.get(peer); held.delete(peer); selected?.close(peer); }, }; } export function createVendorFetch(manifest: VendorManifest, lanes: Record): DerivedFetch { const upgrade = laneUpgrades(lanes); // a lane's live ingest is the vendor's (one RTMP listener beside the vendor's HTTP host) const ingest = Object.values(lanes).find((l) => l.fetch.ingest)?.fetch.ingest; const lane = laneRouter(manifest.vendor, manifest.lanes, lanes); return Object.assign(async (request: Request): Promise => { const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/'; // the discovery door is answered before any lane's clock moves, as a pack's own is (createPackFetch): reading what // the twin is moves no vendor clock if (request.method === 'GET' && path === '/twin' && manifest.discovery) { // the vendor's screens are its lanes' (a dashboard drawn by one lane is the vendor's) const screens = lanesWorkspaces(lanes); const laneDiscovery = await laneDoors(lanes, request, '/twin'); return Response.json({ ...statefulTwinManifest({ vendor: manifest.vendor, ...manifest.discovery }), ...(screens.length ? { screens } : {}), ...(Object.keys(laneDiscovery).length ? { lanes: laneDiscovery } : {}) }); } // the requests the vendor's lanes are serving now, together if (request.method === 'GET' && path === '/twin/open') { let open = 0; for (const l of Object.values(lanes)) { const answer = await l.fetch(new Request(request.url, { method: 'GET', headers: request.headers })); if (answer.ok) open += ((await answer.json()) as { open?: number }).open ?? 0; } return Response.json({ open }); } // the clock's mover asks the vendor to do what time made due: each lane does its own, and the earliest next is the vendor's if (request.method === 'POST' && path === '/twin/due') { let next: string | null = null; for (const l of Object.values(lanes)) { const answer = await l.fetch(new Request(request.url, { method: 'POST', headers: request.headers })); const at = answer.ok ? ((await answer.json()) as { next?: string | null }).next ?? null : null; if (at !== null && (next === null || at < next)) next = at; } return Response.json({ next }); } // the vendor's board is the frames of the lanes that lay one out, each drawn when any lane's screen takes its url if (request.method === 'GET' && path === '/twin/board') { const frames: BoardFrame[] = []; for (const l of Object.values(lanes)) { if (!l.fetch.boards) continue; try { const answer = await l.fetch(new Request(request.url, { headers: request.headers })); if (answer.ok) frames.push(...(((await answer.json()) as { frames?: BoardFrame[] }).frames ?? [])); } catch { /* a lane whose board does not answer lays out nothing */ } } const draws = (url: string): boolean => Object.values(lanes).some((l) => l.fetch.draws?.(url) ?? false); return Response.json({ frames: frames.map((f) => ({ ...f, drawn: draws(f.url) })) }); } if (request.method === 'GET' && path === '/twin/scenario') { const laneScenarios = await laneDoors(lanes, request, '/twin/scenario'); if (Object.keys(laneScenarios).length) return Response.json({ vendor: manifest.vendor, lanes: laneScenarios }); } const to = lane(request); return to ? to(request) : Response.json({ error: `${manifest.vendor}: no lane serves ${request.method} ${path}` }, { status: 404 }); }, { maxRequestBodySize: manifest.descriptor?.maxRequestBodySize, owners: () => flatOwners(lanesOwners(lanes)), ownersByUnit: () => lanesOwners(lanes), workspaces: () => lanesWorkspaces(lanes), ...(upgrade ? { upgrade } : {}), ...(ingest ? { ingest } : {}) }); }