/** * vapor-chamber - Transports * * A transport is the work for the actions it covers: declared once at the * async bus (`createAsyncCommandBus({ transport })`), it sends a command to a * backend where a local handler would run it. Every plugin wraps it, the * bus's retry re-sends through it, and its answer is written there. */ import type { Command, CommandResult, BaseBus, BusError, FailCode, MetaResponse, SendAt, Transport } from './command-bus'; import { _report } from './report'; import { type Delay, countOption, delayOption, isDelay } from './bounds'; import { Accepted } from './accepted'; import { DEV } from './dev'; import { abortedResult, BusError as BusErrorClass, _failures, _groupsAt, _setHub, _okResult, _errResult, _OUTBOX, _opened, _outboxOn, _replayOf, type BusGroups } from './command-bus'; import { createOutbox, type Outbox } from './outbox'; import { _appliedRemotely, _pushed } from './applied-remotely'; import { _answered, _combineSignals, _declaredWait, _encodeJson, _getJson, _headerOf, _headersOf, _postJson, _remoteProblem, _sleepMs } from './http'; import { conditionOf, retryClass } from './failure'; import type { CombinedSignal, GroupHub, HttpClient, HttpResponse } from './http'; import type { ProblemDetails } from './http-errors'; import { signal } from './signal'; import type { Signal } from './signal'; // The answer a 202 gets, for `instanceof` from this entry too. export { Accepted }; // --------------------------------------------------------------------------- // Shared protocol types // --------------------------------------------------------------------------- /** * A command on every wire (docs/contract.md 4): `id` where * answers are multiplexed (a batch, a WebSocket), as on the answer side; `meta` * only with a fact a backend can use. Its HTTP metadata, the idempotency key, * is the `Idempotency-Key` header when the request is the command, and that * name in `headers` when the command is multiplexed (OData JSON 4.01 19.1). * Log s35.138, 36.47. */ export type CommandEnvelope = { id?: string; command: string; target: any; payload?: any; meta?: EnvelopeMeta; headers?: Record; }; /** The part of a command's meta that crosses the wire as the command's own data. */ export type EnvelopeMeta = { correlationId?: string; causationId?: string }; /** * A key as the `Idempotency-Key` value: a Structured Field String, as the * draft requires (RFC 9651), quoted and printable ASCII. Percent-encoding * (UTF-8) yields only unreserved ASCII and %XX, never `"` or `\`, so quoting * is all it needs. It is reversible, so no two keys collide, and any backend * recovers the exact key (rawurldecode). Raw, a target outside Latin-1 made a * value Headers refuses and the request never left. A malformed key (a lone * surrogate) makes this throw, which the bus reports as transport:failed:send * on every wire. A key of unreserved characters only, as every `meta.id` is, * is its own encoding, so the scan skips the encode with the same bytes. * tests/idempotency-header.test.ts, tests/wire-envelope.test.ts. */ const UNRESERVED = /^[\w.~-]*$/; const keyText = (key: string): string => (UNRESERVED.test(key) ? key : encodeURIComponent(key)); const keyHeader = (key: string): string => `"${keyText(key)}"`; // One literal: JSON drops the undefined members, so the wire has only what is // set. The key is never in it: a single request sends it as a header. function envelopeOf(cmd: Command, id?: string): CommandEnvelope { const m = cmd.meta; const meta = m && (m.correlationId ?? m.causationId) !== undefined ? { correlationId: m.correlationId, causationId: m.causationId } : undefined; return { id, command: cmd.action, target: cmd.target, payload: cmd.payload, meta }; } // A multiplexed command (a batch item, a frame): its envelope with its `id`, // and a keyed command's key in `headers`, written only then. function multiplexedOf(cmd: Command, id: string): CommandEnvelope { const envelope = envelopeOf(cmd, id); const key = cmd.meta?.idempotencyKey; if (key) envelope.headers = { 'Idempotency-Key': keyHeader(key) }; return envelope; } /** * A multiplexed command as JSON, or the failure that says it cannot be. A * key's text (`keyText`) holds only unreserved characters, `%` and `!*'()`, * none of which JSON escapes, so its `headers` member is appended as text: the * bytes JSON.stringify writes for it as the last member, with no object and no * escaping pass (tests/idempotency-header.test.ts). */ function encodeMultiplexed(cmd: Command, id: string, url: string): string | BusError { const key = cmd.meta?.idempotencyKey; const data = _encodeJson(envelopeOf(cmd, id), url, cmd.action); return key && typeof data === 'string' ? `${data.slice(0, -1)},"headers":{"Idempotency-Key":"\\"${keyText(key)}\\""}}` : data; } /** * A command's answer, the same on every wire (docs/contract.md 4): * `state` on success, `redirect` for a navigation, `problem` on failure, * one of the three. A batched result and a WebSocket frame carry `id` beside * it; a single command's failure is its non-2xx response's body. */ export type BackendResponse = { state?: unknown; /** * Store states the server declares beside a success, by store id: each * store with that id on the bus takes its state, whatever the command was * (docs/store.md, A store behind a transport). Log s35.186. */ stores?: Record; /** A navigation the backend hands back instead of a result - see `onRedirect`. */ redirect?: string; problem?: ProblemDetails; }; /** * An app's own transport: `send` answers the command, and `local()` runs the * action's local handler (or the missing-handler outcome), its fallback. A * throw or a rejection fails the dispatch as `transport:failed:send`. A send * that calls `local()` declares `localFallback: true`: only then may its * actions have a handler, `optimistic` aside * (tests/register-shadow-check.test.ts). * * @example * const offlineFirst = defineTransport((cmd, local) => (navigator.onLine ? send(cmd) : local()), { localFallback: true }) * const bus = createAsyncCommandBus({ transport: offlineFirst }) */ export function defineTransport(send: Transport['send'], options?: { localFallback?: boolean }): Transport { return { id: ID, localFallback: options?.localFallback === true, send }; } // The transport's own failures, and a backend's: each through its own `fail`, // so neither can speak as the other (docs/contract.md 5). // Every transport's owner name. const ID = 'transport'; const transportFail = _failures(ID); const remoteFail = _failures('remote'); const transportError = (code: FailCode, message: string, action?: string, context?: Record): BusError => transportFail(code, message, { action, context }); /** * Why a request produced no answer. The http client throws the core's failure * already read (`_answered`, log s35.131), and the transport passes it on as it * is - the failure a direct call sees. The one translation left: the caller's * abort of a dispatch is the bus's (`core:aborted:dispatch`). A custom client * that throws something else is read by its `response`, else as no reply. */ function unanswered(e: unknown, action: string, signal?: AbortSignal): CommandResult { if (signal?.aborted || (e as BusError)?.code === 'transport:aborted:request') return abortedResult(action, signal); if (e instanceof BusErrorClass) return _errResult(e); // A custom client's failure: its `response`, else the platform's exception // names (`AbortSignal.timeout()` throws a TimeoutError), else no reply. const err = e as { name?: unknown; message?: string; response?: { status: number; data: unknown; headers?: Record } } | null; if (err?.response) return _errResult(_answered(err.response.status, err.response.data, _headersOf(err.response.headers))); if (err?.name === 'TimeoutError') return _errResult(transportError('timeout:reply', String(err.message), action)); if (err?.name === 'AbortError') return abortedResult(action, signal); return _errResult(transportFail('lost:reply', `No response for "${action}".`, { action, cause: e })); } /** * The limits a server declared to one transport, by action: when each ends, * in ms since the epoch (docs/retry.md, The hold). Held per action, never per * transport: a 429 does not say what it covers (RFC 6585 4), and a whole * transport held would refuse commands the server accepts. tests/hold.test.ts. */ type Holds = Map; /** * A command whose action is held: refused at once and never sent, as * `transport:limited:held` with the time left as `retryIn`. It is the failure * its 429 would have been, so the bus's retry and the outbox wait it as they * wait a 429's (docs/retry.md). A hold past its end is forgotten here. */ function whileHeld(holds: Holds, action: string): CommandResult | undefined { const end = holds.get(action); if (end === undefined) return undefined; const left = end - Date.now(); if (left > 0) return _errResult(transportError('limited:held', `"${action}" is held for ${left}ms: the server declared a limit.`, action, { retryIn: left })); holds.delete(action); return undefined; } /** * `result`, after holding its action when it is a `limited` failure (429, * 503) that declares a wait (`retryIn`, read by `_declaredWait`). A verdict * with a wait, such as a 409 `in_progress`, is one request's state and holds * nothing. A later end extends a hold and an earlier one never shortens it: * Retry-After is a minimum (RFC 9110 10.2.3). Failure paths only. */ function holding(holds: Holds, action: string, result: CommandResult): CommandResult { const wait = (result.error as BusError | undefined)?.context?.retryIn; if (typeof wait === 'number' && conditionOf(result.error) === 'limited') { const end = Date.now() + wait; const held = holds.get(action); if (held === undefined || held < end) holds.set(action, end); } return result; } /** A redirect the backend answered with: the command fails, carrying the url. */ const redirected = (url: string, action: string, handled: boolean): BusError => transportError('refused:redirect', `Redirected to ${url}.${DEV && !handled ? ' No onRedirect handler is configured.' : ''}`, action, { url }); // What `meta.response` holds: the objects the client already built, no copy. const responseOf = (res: { status: number; headers?: Record; url?: string; redirected?: boolean }): MetaResponse => ({ status: res.status, headers: res.headers ?? {}, url: res.url, redirected: res.redirected }); // An answer by contract: a `problem` is the failure, a `redirect` a navigation, // anything else the success, its `state` the value (absent when the handler // returned nothing: JSON drops `undefined`). A result's own headers are the // response's, or the `headers` a batched result // or a frame carries (OData JSON batch), read by `_headersOf`. `status`: a // batched result's or a frame's own (OData 19.5), which stands for the // response's when the problem has none. A single answer has none here. function answerOf(r: BackendResponse, cmd: Command, headers?: unknown, status?: unknown): CommandResult { if (r.problem) { const own = _headersOf(headers); return _errResult(_remoteProblem(r.problem, typeof status === 'number' ? status : undefined, own && _declaredWait(own))); } if (typeof r.redirect === 'string') return _errResult(redirected(r.redirect, cmd.action, false)); // The server applied it: history must not undo or redo it locally (R9). // The store states its reply declares travel with it to the bus. _appliedRemotely.set(cmd, r.stores); return _okResult(r.state); } /** * One answer of an HTTP transport's request. A redirect is a body member (a * browser's fetch cannot read a 3xx's Location): it goes to `navigate` * (typically Inertia's `router.visit`), and the command fails, carrying the * url. Anything else by contract (answerOf). */ function readAnswer(r: BackendResponse, cmd: Command, headers: unknown, navigate: ((url: string) => void) | undefined, status?: unknown): CommandResult { if (typeof r.redirect === 'string' && r.redirect) { navigate?.(r.redirect); return _errResult(redirected(r.redirect, cmd.action, !!navigate)); } return answerOf(r, cmd, headers, status); } /** * An answer's own `Cache-Group-Invalidation` (RFC 9875), on a response, a * batched result or a frame, for the bus's group hub: the app's client (its * reads, the router), else the bus's own (cache()). tests/cache-groups.test.ts, * tests/cache-groups-hub.test.ts. With no hub nothing can act on it, and * development says so once per transport (`said`); production reads nothing. */ function groupsTo(hub: GroupHub | null | undefined, own: unknown, said: { warned: boolean }): void { if (hub) { const named = _headerOf(own, 'cache-group-invalidation'); if (named !== undefined) hub.invalidateGroups(named); } else if (DEV && !said.warned && _headerOf(own, 'cache-group-invalidation') !== undefined) { said.warned = true; _report('warn', 'transport:missing:client', 'an answer named groups in Cache-Group-Invalidation, but nothing on this bus reads them. Give the transport the client the router reads, or install cache().'); } } /** * A transport's bus's groups (BusGroups), its `client` the bus's hub: one * hub per bus, so a second, different client keeps the first and development * warns. At the bus's creation (Transport.attach). */ function joinGroups(bus: BaseBus, client: HttpClient | undefined): BusGroups { const g = _groupsAt(bus); if (client) { if (g.hub === null) _setHub(g, client); else if (DEV && g.hub.invalidateGroups !== client.invalidateGroups) { _report('warn', 'transport:conflict:client', 'two transports of one bus have different httpClients: the groups their answers name reach the first client only. Give the bus one client.'); } } return g; } /** * What both HTTP sends go through. `signal`: the transport's own and its * scope's, either one cancels, combined once (its listeners live as long as * the transport, never detached). `post`: one request, through the app's * `httpClient` with the body as an object, else postCommand's path with it * already JSON. Each command is sent once (`retry: false`): the async bus * re-sends (docs/retry.md), so the two never multiply. `holds`: the limits * the server declared, read before each send; `dispose` forgets them. */ function httpSender(options: HttpTransportOptions) { const { endpoint, csrf = false, csrfCookieUrl, timeout = 10_000, signal, onSessionExpired, scopeController, httpClient, headers, poll } = options; const scope = scopeController && signal ? _combineSignals(signal, scopeController.signal).signal : scopeController?.signal ?? signal; // A NaN behaves like a missing option (bounds.ts): never a hot loop or an endless wait. const interval = delayOption(poll?.interval, 1000); const maxWait = countOption(poll?.maxWait, 300_000); // What stops every follow: the transport's dispose, its scope, or the command's signal. const stop = new AbortController(); const holds: Holds = new Map(); const said = { warned: false }; // The bus's groups, from its attach: where an answer's groups go without a client. let groups: BusGroups | undefined; /** * A status monitor polled to the job's end: its `{ state }`, its problem, or * `transport:timeout:job` past `maxWait`. A passing failure of a poll says * nothing about the job, still running: a transient one by the one retry * rule (failure.ts retryClass) or one declaring a wait polls again. Anything * else ends it, as an abort does (tests/accepted-transient.test.ts). */ async function follow(cmd: Command, location: string, answerHeaders: unknown, base: string | undefined): Promise { let url = location; // A Location no URL holds is followed as sent: its failure ends `done`, never the dispatch. if (base) try { url = new URL(url, base).href; } catch { /* as sent */ } // Combined per follow and detached at its end: a listener left on the // scope would outlive it (tests/combine-signals.test.ts). const scoped = scope ? _combineSignals(stop.signal, scope) : undefined; const combined = cmd.signal ? _combineSignals(scoped ? scoped.signal : stop.signal, cmd.signal) : undefined; const sig = combined ? combined.signal : scoped ? scoped.signal : stop.signal; const end = Date.now() + maxWait; let wait = waitOf(_headersOf(answerHeaders), interval); try { for (;;) { if (sig.aborted) return abortedResult(cmd.action, sig); if (Date.now() + wait > end) return _errResult(transportError('timeout:job', `"${cmd.action}" was not done within ${maxWait}ms.`, cmd.action, { location: url, maxWait })); let r: HttpResponse; try { await _sleepMs(wait, sig); r = httpClient ? await httpClient.get(url, { signal: sig, dedupe: false }) : await _getJson(url, { headers, signal: sig, onSessionExpired }); } catch (e) { if (sig.aborted) return abortedResult(cmd.action, sig); const declared = (e as BusError).context?.retryIn; if (retryClass(e) !== 'transient' && !isDelay(declared)) return _errResult(e as Error); wait = isDelay(declared) ? declared : interval; continue; } if (r.status !== 202) return r.data?.problem ? _errResult(_remoteProblem(r.data.problem)) : _okResult(r.data?.state); wait = waitOf(_headersOf(r.headers), interval); } } finally { combined?.detach(); scoped?.detach(); } } return { signal: scope, holds, /** See groupsTo. A single answer through the client is the client's own. */ groups: (own: unknown): void => groupsTo(httpClient ?? groups?.hub, own, said), attach(bus: BaseBus): void { groups = joinGroups(bus, httpClient); }, post(json: string, body: () => unknown, headers: Record, requestSignal: AbortSignal | undefined): Promise> { const config = { csrf, csrfCookieUrl, headers, timeout, retry: false as const, signal: requestSignal, onSessionExpired }; return httpClient ? httpClient.post(endpoint, body(), config) : _postJson(endpoint, json, config); }, /** * A 202 with a `Location` (RFC 9110 15.3.3): the work goes on, and the * answer is an `Accepted` whose `done` polls the monitor, its first wait * the 202's. `base` resolves a relative Location, as is without one. Any * other answer, a 202 without a Location included, is the result as read. */ accepted(result: CommandResult, answerHeaders: unknown, base: string | undefined, cmd: Command): CommandResult { // One name read, no copy (_headerOf). The URL and the first wait are read // when `done` is: a 202 nobody follows costs neither. const location = result.ok ? _headerOf(answerHeaders, 'location') : undefined; if (!location) return result; return _okResult(new Accepted(() => follow(cmd, location, answerHeaders, base))); }, dispose(): void { stop.abort(); holds.clear(); }, }; } /** What a status monitor answers: `{ state }` when the job is done, a problem when it failed, a 202 while it runs. */ type Monitor = { state?: unknown; problem?: ProblemDetails }; /** * The next poll's wait: the one an answer declares, read as any answer's * (`_declaredWait`: Retry-After, else RateLimit `t` with no quota left, else * X-RateLimit-Reset), else the interval. A poll inside a RateLimit window * exceeds the quota the draft asks a client to keep (-11, 7). */ const waitOf = (own: Record | undefined, interval: Delay): Delay => delayOption((own && _declaredWait(own)) ?? interval, interval); // --------------------------------------------------------------------------- // httpTransport // --------------------------------------------------------------------------- export type HttpTransportOptions = { /** Backend endpoint URL (e.g. '/api/vc') */ endpoint: string; /** * CSRF token strategy: * - `false` (default) - don't attach any CSRF token * - `true` - read from DOM (meta tag, cookie, hidden input) and attach * as the appropriate header. Works with any server-rendered framework * that exposes a token via one of those three sources - Laravel Blade, * Rails, Django, .NET MVC, custom stacks. Auto-refreshes on HTTP 419. * An Inertia app on Laravel uses `true` too: with no meta tag it reads * the XSRF-TOKEN cookie Laravel sets. The transport makes its own requests, * which no Axios interceptor of the app touches. */ csrf?: boolean; /** * URL to fetch on a CSRF-expiry response (HTTP 419) to obtain a fresh * token. The default targets the Laravel Sanctum SPA convention because * it's the most common 419-issuing backend; override for other frameworks * or set to '' to disable the refresh fetch. * Default: '/sanctum/csrf-cookie'. */ csrfCookieUrl?: string; /** Additional headers merged into every request. A name matches in any case: its first spelling is kept and the last value wins (the Fetch Standard's "set"), so it goes out once. */ headers?: Record; /** Request timeout in ms. Default: 10_000 */ timeout?: number; /** External AbortSignal (e.g. tied to component lifecycle) */ signal?: AbortSignal; /** * Called when a 401 session-expired response is received. * A `session-expired` CustomEvent is also dispatched on `window`. */ onSessionExpired?: (status: number) => void; /** * Called when the backend answers with a `{ redirect: '/path' }` field in * its JSON body. Useful for handing a navigation to Inertia's router so a * vapor-chamber dispatch can move the page: * * onRedirect: (url) => router.visit(url) * * Either way the command fails as `transport:refused:redirect`, the url in * `error.context.url`. * * BODY FIELD ONLY, never a 3xx with `Location`: `fetch` defaults to * `redirect: 'follow'`, so the platform resolves a 3xx and hands the transport * the FINAL response. A backend * that wants this hook must say so in the body. Pinned by * `tests/transports-coverage.test.ts` ("does not call onRedirect for a * redirect STATUS without a body field"). */ onRedirect?: (url: string) => void; /** * Coalesce the commands sent within a window into one POST * (`{ commands: [...] }` answered by `{ results: [...] }`). Absent: one * request per command. */ batch?: HttpBatchOptions; /** * Abort controller whose signal cancels all in-flight requests when the * owning scope/component is disposed. In Vapor components, create an * AbortController in setup and pass it here - call `.abort()` in * onScopeDispose to cancel orphaned requests automatically. * * @example * // In