// One queue per session (lab 08). // // Two messages for the same session must never be processed at the same time: both would read // the same history, both would append to it, and the log would interleave two turns. Messages // for DIFFERENT sessions are independent and can run in parallel. // // Each key has a "tail": the promise of the last task queued for it. A new task waits for the // tail, then becomes the new tail. A failed task does not block the ones after it. export class KeyedQueue { private readonly tails = new Map>(); private pending = 0; run(key: string, task: () => Promise): Promise { const previous = this.tails.get(key) ?? Promise.resolve(); this.pending++; const result = previous.then(task).finally(() => { this.pending--; }); const tail = result.then( () => undefined, () => undefined, ); this.tails.set(key, tail); void tail.then(() => { if (this.tails.get(key) === tail) this.tails.delete(key); }); return result; } /** Tasks queued or running, across all keys. */ get depth(): number { return this.pending; } /** Resolves when every task queued so far has finished. */ async idle(): Promise { await Promise.all([...this.tails.values()]); } }