import { runWithStorageTenant, storageTenant } from './request-scope.ts'; // A vendor's persistent wire (architecture, "Other wires: sockets"): a WebSocket its clients hold open, on which the // vendor sends what happens as it happens (Discord's Gateway: a bot identifies, is told the guilds it is in, and is sent // each message, member and interaction as it lands). The manifest declares the socket (`sockets`); the pack's engine // (`semantics/sockets.ts`, one export per socket id) speaks its protocol: what a session is sent when it opens, what it // answers each frame, and which frames a write of the World sends it. The kernel holds the open sessions, serves the // upgrade through the serve seam, and offers every write to every open session of the vendor, after the write's // webhooks. A session's own counters (a sequence number, a heartbeat) are the connection's, never the World's state. // Nothing here runs at module scope beyond the empty registry. import { worldNow } from './world-clock.ts'; import { projectRoot } from './storage.ts'; import type { EventWrite } from './events.ts'; import type { ScenarioDecision, ScenarioFaultResult } from './scenario.ts'; import type { WebSocketPeer, WebSocketUpgrade } from './serve-http.ts'; /** A socket the vendor serves: its path (and host, when the vendor serves it on a host of its own), as the manifest * declares it. */ /** A vendor's socket: its id, path and host; `protocols` are the subprotocols its server selects from those a client * offers in `Sec-WebSocket-Protocol` (OpenAI Realtime's `realtime`), the first offered that it lists. */ export type SocketDecl = { id: string; path: string; host?: string; note: string; source?: string; protocols?: ReadonlyArray }; /** One open connection, as its engine sees it: its own state, and the frames it sends (an object is sent as JSON). */ export type SocketSession = { readonly id: number; readonly socket: string; state: Record; send(frame: unknown): void; close(code?: number, reason?: string): void; /** A reply this session will send, by its correlation key: settles when the engine calls `fulfil(key, value)`, and * rejects when `ms` pass or the session closes (a request answered by a session: the tunnel's relay). */ expect(key: string, ms: number): Promise; /** Settles what `expect(key)` awaits; false when nothing awaits it (a late or unknown reply). */ fulfil(key: string, value: unknown): boolean; /** The World's scenario's decision for a turn this session asks (a model vendor's turn spoken over a socket: a voice * agent's reply), the turn given as the pack's scenario adapter reads a request; undefined when the pack has no * scenario or the World carries none. A fault decision is the engine's to answer in its own frames. */ decide(asked: unknown): Promise; /** The session resumes after the last sequence number it saw: every later frame the vendor's declared events sent the * endpoint it is bound to (`state[]`) is sent again, in order (event-delivery.ts). * Answers how many were sent. */ resume(after: number): Promise; }; /** What the World's scenario serves a turn (scenario-serve.ts): its decision, the miss, or a fault's answer. */ export type ScenarioServed = ScenarioDecision | { kind: 'fault'; result: ScenarioFaultResult; ruleId: string }; /** A socket's protocol, over the handler contract's context (a read of the World as the request that opened it). */ export type SocketEngine = { open?(session: SocketSession, ctx: C): void | Promise; message(session: SocketSession, data: string, ctx: C): void | Promise; /** A write of the World: the frames it sends this session, if any (the engine decides who is told what). */ write?(session: SocketSession, write: EventWrite, ctx: C): void | Promise; /** The session ended (the client hung up, or the engine closed it): the World is read and written as at a frame, so * what the end settles is written (a call's final status). */ close?(session: SocketSession, ctx: C): void | Promise; }; type Open = { tenant?: string; run: (fn: () => T) => T; session: SocketSession; engine: SocketEngine; context: () => Promise; queue: Promise; pending: Map void; reject: (e: Error) => void; timer: ReturnType; due: number }> }; const sessions = new Map>(); /** A World's next session number, per World (its service and root): a session's id is the World's, never the * process's, so a life replayed on a fresh World numbers its sessions as it did the first time. */ const nextSession = new Map(); const keyOf = (service: string, root: string | undefined): string => `${service}\0${root ?? ''}`; /** The open sessions of one socket of the vendor in a World (a handler reaches them as `ctx.sockets(id)`). */ export function openSessions(service: string, root: string | undefined, socket: string): SocketSession[] { return [...(sessions.get(keyOf(service, root)) ?? [])].filter((o) => o.session.socket === socket && o.tenant === storageTenant(service)).map((o) => o.session); } /** What a session awaits that the World's clock has run out (a life's `wait` past a relay's timeout), rejected as the * machine's clock would reject it; called as the vendor serves a request ("A request answered by a session"). */ export function expireSocketWaits(service: string, root: string | undefined): void { const open = sessions.get(keyOf(service, root)); if (!open?.size) return; const now = Date.parse(worldNow()); for (const o of open) for (const [k, p] of o.pending) if (p.due <= now) { clearTimeout(p.timer); o.pending.delete(k); p.reject(new Error('no reply in time')); } } /** The open sessions of one socket of the vendor in the World whose state lives at `root` (resolved, as a delivery's * root is), of every tenant: a delivery binds them by the endpoint's id. */ export function sessionsAt(service: string, root: string, socket: string): SocketSession[] { const out: SocketSession[] = []; for (const [key, open] of sessions) { if (!key.startsWith(`${service}\0`) || projectRoot(key.slice(service.length + 1) || undefined) !== root) continue; for (const o of open) if (o.session.socket === socket) out.push(o.session); } return out; } /** Offer a write to every open session of the vendor, each in its turn after what it is already doing. Queued, never * awaited: the write may be one a session's own frame made, which that session finishes before it is told. */ export function socketWrite(service: string, root: string | undefined, write: EventWrite): void { const open = sessions.get(keyOf(service, root)); if (!open?.size) return; for (const o of open) { const { engine } = o; if (o.tenant !== storageTenant(service)) continue; if (!engine.write) continue; o.queue = o.queue.then(() => o.run(async () => engine.write!(o.session, write, await o.context()))).catch((error) => o.session.close(1011, String((error as Error).message ?? error).slice(0, 120))); } } /** A declared socket path's parameters for a request's path, or undefined when it does not match: a `{name}` segment * matches one segment, as an operation's path parameter does (architecture, sockets). */ function socketParams(declared: string, path: string): Record | undefined { const names: string[] = []; const pattern = (declared.replace(/\/+$/, '') || '/').split(/(\{[^}/]+\})/).map((part) => { const name = /^\{([^}/]+)\}$/.exec(part)?.[1]; if (name === undefined) return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); names.push(name); return '([^/]+)'; }).join(''); const hit = new RegExp(`^${pattern}$`).exec(path); if (!hit) return undefined; try { return Object.fromEntries(names.map((name, i) => [name, decodeURIComponent(hit[i + 1]!)])); } catch { return undefined; } } /** The upgrade the serve seam takes: a request to a declared socket's path (and host) opens a session of its engine. */ export function socketUpgrade( service: string, root: string | undefined, decls: ReadonlyArray, engines: Record>, context: (request: Request, decl: SocketDecl, params: Record) => Promise, hostOf: (request: Request) => string, pathOf: (request: Request) => string, decide: (asked: unknown, context: () => Promise) => Promise, ): WebSocketUpgrade { const matchFor = (request: Request): { decl: SocketDecl; params: Record } | undefined => { const path = pathOf(request).replace(/\/+$/, '') || '/'; for (const d of decls) { if ((d.host && d.host.toLowerCase() !== hostOf(request)) || engines[d.id] === undefined) continue; const params = socketParams(d.path, path); if (params) return { decl: d, params }; } return undefined; }; const declFor = (request: Request): SocketDecl | undefined => matchFor(request)?.decl; const byPeer = new WeakMap(); const key = keyOf(service, root); return { accepts: (request) => declFor(request) !== undefined, // the subprotocol the server answers with: the first the client offers that the socket declares, or, for a socket // that declares none, the first offered (what the ws library and Bun answer by themselves) protocol: (request) => { const offered = (request.headers.get('sec-websocket-protocol') ?? '').split(',').map((p) => p.trim()).filter(Boolean); const declared = declFor(request)?.protocols; return declared ? offered.find((p) => declared.includes(p)) : offered[0]; }, open: (peer, request) => { const { decl, params } = matchFor(request)!; const engine = engines[decl.id]! as SocketEngine; const pending: Open['pending'] = new Map(); const session: SocketSession = { id: (() => { const n = (nextSession.get(key) ?? 0) + 1; nextSession.set(key, n); return n; })(), socket: decl.id, state: {}, send: (frame) => { peer.send(typeof frame === 'string' || frame instanceof Uint8Array ? frame : JSON.stringify(frame)); }, close: (code, reason) => { peer.close(code, reason); }, expect: (key, ms) => new Promise((resolve, reject) => { const timer = setTimeout(() => { pending.delete(key); reject(new Error('no reply in time')); }, ms); pending.set(key, { resolve, reject, timer, due: Date.parse(worldNow()) + ms }); }), fulfil: (key, value) => { const p = pending.get(key); if (!p) return false; clearTimeout(p.timer); pending.delete(key); p.resolve(value); return true; }, decide: (asked) => decide(asked, () => o.context() as Promise), // loaded when a session resumes, so importing the sockets imports no delivery resume: async (after) => o.run(async () => (await import('./event-delivery.ts')).replaySocketDeliveries(service, root, session, after)), }; const tenant = storageTenant(service), run = (fn: () => T): T => runWithStorageTenant(service, tenant, fn); const o: Open = { tenant, run, session, engine, context: () => context(request.clone(), decl, params), queue: Promise.resolve(), pending }; byPeer.set(peer, o); (sessions.get(key) ?? sessions.set(key, new Set()).get(key)!).add(o); if (engine.open) o.queue = o.queue.then(() => o.run(async () => engine.open!(session, await o.context()))).catch((error) => session.close(1011, String((error as Error).message ?? error).slice(0, 120))); }, message: (peer, data) => { const o = byPeer.get(peer); if (!o) return; const text = typeof data === 'string' ? data : new TextDecoder().decode(data); o.queue = o.queue.then(() => o.run(async () => o.engine.message(o.session, text, await o.context()))).catch((error) => o.session.close(1011, String((error as Error).message ?? error).slice(0, 120))); }, close: (peer) => { const o = byPeer.get(peer); if (!o) return; sessions.get(key)?.delete(o); // what awaited this session's replies is told it closed for (const [k, p] of o.pending) { clearTimeout(p.timer); p.reject(new Error('the session closed')); o.pending.delete(k); } // the end is written after what the session is still doing, over its own context // the session is gone, so a failure has no frame to go in: it is reported, never swallowed if (o.engine.close) o.queue = o.queue.then(() => o.run(async () => o.engine.close!(o.session, await o.context()))).catch((error) => { console.error(`${service}: the ${o.session.socket} socket's end was not written: ${String((error as Error)?.message ?? error)}`); }); }, }; }