// A TWIN'S CALL TO ANOTHER VENDOR (architecture.md, "What an author writes, and how": `ctx.vendorFetch`). A vendor's // service calls another vendor as part of its own behaviour — Clerk trades a Google sign-in's code for the person at // Google's token endpoint — and in a World that other vendor is the World's twin of it. The call is addressed as the // vendor's own URL and reaches that twin by the same host rules the injector routes an application by (vendor-hosts.cjs), // carrying the World's twins key; a vendor the World runs no twin of is refused, never reached: a twin makes no direct // vendor call (simulated execution is deterministic and stays inside the World). A twin this process answers itself (a // journey walk's companions, `setInProcessTwins`) is reached first, in process; the instance's twins otherwise. This is // the one network a handler has; importing this module does nothing. import { twinOrigins, VENDOR_HOSTS } from '../vendor-hosts.cjs'; import type { ApplicationStandIn } from './events.ts'; /** A call to a vendor the World runs no twin of. */ export class VendorUnreachableError extends Error { constructor(message: string, options?: ErrorOptions) { super(message, options); this.name = 'VendorUnreachableError'; } } /** A twin answered in this process: its fetch, as a World's server hands it a request. */ export type InProcessTwin = (request: Request) => Response | Promise; let inProcessTwins: Readonly> = {}; /** The twins this process answers itself, by routing key (a key of VENDOR_HOSTS: a journey walk's companions, over the * walk's own World), consulted before the instance's; returns those set before, which the caller puts back. */ export function setInProcessTwins(twins: Readonly>): Readonly> { const previous = inProcessTwins; inProcessTwins = twins; return previous; } /** The World's twins by vendor: the instance's env (every twin's URL, whenever this process started) over this * process's own; an instance file the World names and this process cannot read refuses the call. */ async function worldTwins(): Promise> { const env = process.env; let instanceEnv: Record = {}; const { worldStateFile } = await import('./world-store.ts'); const file = worldStateFile('instance', env); if (file) { try { const { readFile } = await import('node:fs/promises'); instanceEnv = (JSON.parse(await readFile(file, 'utf8')) as { env?: Record }).env ?? {}; } catch (error) { // the World's routing table could not be read: its twins' hosts are refused by name, never routed on what this // process's env alone says (ADR 0036 §9) throw new VendorUnreachableError(`the World's twins could not be read from ${file} (${error instanceof Error ? error.message : String(error)}), so no vendor call is routed`, { cause: error }); } } return { ...twinOrigins(env), ...twinOrigins(instanceEnv) }; } /** The hosts each claiming twin last listed at its `hostsClaimed` door, by the door's address, and when; read again * after CLAIMS_TTL_MS or for a host it lacks, as the injector polls the doors every five seconds (inject.cjs, "HOSTS A TWIN CLAIMS WHILE IT * RUNS"). */ const claimsRead = new Map; at: number }>(); const CLAIMS_TTL_MS = 5_000; /** The hosts a twin claims at its door: in process (a journey walk's companion) or at its address, within the injector's * first-read deadline (inject.cjs CLAIMS_WAIT_MS, 1500 ms, measured beside it); a door that does not answer claims * nothing. */ async function claimedHosts(at: string, ask: () => Promise, host: string): Promise> { const held = claimsRead.get(at); // a host the held list lacks is asked for again once, as the injector refreshes before it refuses: a domain claimed a // moment ago is found if (held && performance.now() - held.at < CLAIMS_TTL_MS && held.hosts.has(host)) return held.hosts; let hosts = new Set(); try { const r = await ask(); const body = r.ok ? await r.json() as { hosts?: unknown[] } : null; hosts = new Set((body?.hosts ?? []).map((h) => String(h).toLowerCase())); } catch { /* an unanswered door claims nothing */ } claimsRead.set(at, { hosts, at: performance.now() }); return hosts; } /** The twin that claims a host at its `hostsClaimed` door (an R2 bucket's custom domain, a Worker's), as the injector * routes it: a twin this process answers first, the World's twins after. */ async function claimingTwin(target: URL, twins: Record): Promise<{ vendor: string; local: boolean } | undefined> { const { packFacts } = await import('../pack-facts.cjs') as { packFacts: () => { packs: Record } }; const host = target.hostname.toLowerCase(); const key = process.env.VOLTER_TWINS_KEY; const doors = Object.entries(packFacts().packs).flatMap(([vendor, facts]) => (facts.hostsClaimed?.door ? [[vendor, facts.hostsClaimed.door] as const] : [])); for (const [vendor, door] of doors) { const twin = inProcessTwins[vendor]; if (twin && (await claimedHosts(`in-process:${vendor}${door}`, async () => twin(new Request(`http://${vendor}.twin${door}`)), host)).has(host)) return { vendor, local: true }; } for (const [vendor, door] of doors) { const origin = twins[vendor]; if (origin === undefined) continue; const at = `${origin.replace(/\/$/, '')}${door}`; if ((await claimedHosts(at, () => fetch(at, { headers: key ? { 'x-twins-key': key } : {}, signal: AbortSignal.timeout(1500) }), host)).has(host)) return { vendor, local: false }; } return undefined; } /** One URL answered only by a World-held application or vendor twin: the fetch's application stand-in first (its answer * is the application's; `'unreachable'` leaves no application to reach, the World's twins still reachable). */ async function worldResponse(target: URL, init: RequestInit, standIn?: ApplicationStandIn): Promise { const scripted = await standIn?.(target.toString(), init); if (scripted !== undefined && scripted !== 'unreachable') { // A source may answer its headers then lose its body transport. Preserve that failure until the caller reads. const body = scripted.bodyError === undefined ? scripted.body : new ReadableStream({ start(controller) { controller.error(new TypeError(scripted.bodyError)); }, }); return new Response([204, 205, 304].includes(scripted.status) || init.method === 'HEAD' ? null : body, { status: scripted.status, headers: scripted.headers }); } const local = Object.keys(VENDOR_HOSTS).find(v => inProcessTwins[v] !== undefined && VENDOR_HOSTS[v]!(target.hostname, target.pathname)); if (local !== undefined) { const headers = new Headers(init.headers); headers.set('x-volter-twin-original-host', target.host); return inProcessTwins[local]!(new Request(target, { ...init, headers, redirect: 'manual' })); } const twins = await worldTwins(); const vendor = Object.keys(VENDOR_HOSTS).find((v) => twins[v] !== undefined && VENDOR_HOSTS[v]!(target.hostname, target.pathname)); if (vendor !== undefined) { const headers = new Headers(init.headers); headers.set('x-volter-twin-original-host', target.host); const key = process.env.VOLTER_TWINS_KEY; if (key && !headers.has('x-twins-key')) headers.set('x-twins-key', key); return fetch(`${twins[vendor]!.replace(/\/$/, '')}${target.pathname}${target.search}`, { ...init, headers, redirect: 'manual' }); } // the application's own hosts before any twin's claimed ones: a call to the application asks no door const { appDestination, appFetch } = await import('../app-route.cjs') as { appDestination: (url: URL) => unknown; appFetch: (url: URL, init: RequestInit) => Promise }; if (scripted !== 'unreachable' && appDestination(target)) return appFetch(target, { ...init, redirect: 'manual' }); const claimer = await claimingTwin(target, twins); if (claimer !== undefined) { const headers = new Headers(init.headers); headers.set('x-volter-twin-original-host', target.host); if (claimer.local) return inProcessTwins[claimer.vendor]!(new Request(target, { ...init, headers, redirect: 'manual' })); const key = process.env.VOLTER_TWINS_KEY; if (key && !headers.has('x-twins-key')) headers.set('x-twins-key', key); return fetch(`${twins[claimer.vendor]!.replace(/\/$/, '')}${target.pathname}${target.search}`, { ...init, headers, redirect: 'manual' }); } throw new VendorUnreachableError(`${target.host}${target.pathname}: this World holds no application or vendor twin at this URL`); } /** A vendor URL (or the World's application), including redirects, always answered inside the World; `standIn` is the * calling fetch's application stand-in (PackFetchOptions.application), consulted at every hop. */ export async function vendorFetch(url: string | URL, init: RequestInit = {}, standIn?: ApplicationStandIn): Promise { const { followRedirects } = await import('../app-route.cjs') as { followRedirects: (url: string | URL, init: RequestInit, send: (url: URL, init: RequestInit) => Promise, dropped?: string[]) => Promise; }; try { return await followRedirects(url, init, async (target, request) => { if (!['http:', 'https:'].includes(target.protocol)) throw new VendorUnreachableError(`A twin cannot fetch ${target.protocol} URLs`); return worldResponse(target, request, standIn); }, ['x-twins-key', 'x-volter-twin-original-host']); } catch (error) { if (error instanceof VendorUnreachableError) throw error; throw new VendorUnreachableError(error instanceof Error ? error.message : String(error), { cause: error }); } }