import { EventBus } from "@publicdomainrelay/event-bus"; export interface BacklogSequencerOptions { maxBacklog: number; build: (seq: number, evt: TIn) => TFrame; } export interface BacklogSequencer { append(evt: TIn): TFrame; backfill(since?: number): AsyncIterable; live(): AsyncIterable; } export function createBacklogSequencer( opts: BacklogSequencerOptions, ): BacklogSequencer { const { maxBacklog: max, build } = opts; let seq = 0; const backlog: TFrame[] = []; const bus = new EventBus(); return { append(evt: TIn): TFrame { seq++; const frame = build(seq, evt); backlog.push(frame); if (backlog.length > max) backlog.shift(); bus.publish(frame); return frame; }, async *backfill(since?: number) { for (const f of backlog) { if (since !== undefined && f.seq <= since) continue; yield f; } }, live(): AsyncIterable { const queue: TFrame[] = []; let notify: (() => void) | null = null; // Subscribe IMMEDIATELY (not lazily in generator) so frames arriving // between backfill() and the first live .next() are captured. const unsub = bus.subscribe((f) => { queue.push(f); notify?.(); }); let done = false; return { [Symbol.asyncIterator]() { return this as unknown as AsyncIterator; }, async next(): Promise> { if (done) return { value: undefined, done: true }; if (queue.length > 0) return { value: queue.shift()!, done: false }; await new Promise((r) => { notify = r; if (queue.length > 0) r(); }); notify = null; // The notify promise resolved — a frame is in the queue (or the // immediate resolve above drained it). Re-check. if (queue.length > 0) return { value: queue.shift()!, done: false }; // The promise was resolved but queue was already drained by the // immediate check. Loop around. return (this as unknown as AsyncIterator).next(); }, async return(): Promise> { done = true; unsub(); return { value: undefined, done: true }; }, } as unknown as AsyncIterable; }, }; }