// A read held until the World writes (architecture, "Other wires": a read held until the World writes): HTTP long // polling, as Telegram's getUpdates is, where a client asks again at once on an empty answer. A handler that finds // nothing to answer awaits `ctx.awaitWrite(types, ms)`: it settles true when a write of one of the stored types lands in // the same World (the derived core's one write path tells it, as it tells the open sockets), false when the time runs // out or the client hangs up. The wait is the connection's, never World state: the handler reads the tree again and // answers what it holds. Nothing here runs at module scope beyond the empty registry. type Waiter = { types: ReadonlySet; settle: (wrote: boolean) => void }; const waiting = new Map>(); const keyOf = (service: string, root: string | undefined): string => `${service}\0${root ?? ''}`; /** Tell every read held in this World that a subject of `storedType` was written. */ export function heldReadsWrite(service: string, root: string | undefined, storedType: string): void { const held = waiting.get(keyOf(service, root)); if (!held?.size) return; for (const w of [...held]) if (w.types.has(storedType)) w.settle(true); } /** Wait until a write of one of `storedTypes` lands in this World (true), or `ms` pass or `signal` aborts (false). */ export function awaitWrite(service: string, root: string | undefined, storedTypes: ReadonlyArray, ms: number, signal?: AbortSignal): Promise { if (!(ms > 0) || signal?.aborted) return Promise.resolve(false); const key = keyOf(service, root); return new Promise((resolve) => { let held = waiting.get(key); if (!held) { held = new Set(); waiting.set(key, held); } const set = held; const waiter: Waiter = { types: new Set(storedTypes), settle: (wrote) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); set.delete(waiter); if (!set.size) waiting.delete(key); resolve(wrote); }, }; const onAbort = (): void => waiter.settle(false); const timer = setTimeout(() => waiter.settle(false), ms); signal?.addEventListener('abort', onAbort, { once: true }); set.add(waiter); }); } /** Hold a read until its condition holds, within the caller's timeout. The kernel owns elapsed time. */ export async function awaitCondition(service: string, root: string | undefined, storedTypes: ReadonlyArray, ms: number, pollMs: number, condition: () => Promise, signal?: AbortSignal): Promise { if (!(pollMs > 0)) throw new Error('a held condition requires a positive observation cadence'); const deadline = performance.now() + Math.max(0, ms); for (;;) { if (await condition()) return true; const remaining = deadline - performance.now(); if (remaining <= 0 || signal?.aborted) return false; await awaitWrite(service, root, storedTypes, Math.min(remaining, pollMs), signal); } }