| 8 | |
| 9 | /** Serializes timer and post-tool ticks, including their evidence writes, and drains on shutdown. */ |
| 10 | export class ActorDriver<A> { |
| 11 | private queue: Promise<void> = Promise.resolve(); |
| 12 | private active = true; |
| 13 | error?: Error; |
| 14 | |
| 15 | constructor( |
| 16 | private readonly actor: Tickable<A>, |
| 17 | private readonly changed: (actions: A[]) => Promise<void>, |
| 18 | private readonly now: () => number = Date.now, |
| 19 | ) {} |
| 20 | |
| 21 | tick(trigger?: Call, source: "timer" | "post-tool" = "timer"): Promise<void> { |
| 22 | if (!this.active) return Promise.resolve(); |
| 23 | const next = this.queue.then(async () => { |
| 24 | if (this.error) throw this.error; |
| 25 | const before = this.actor.actions.length; |
| 26 | await this.actor.tick(this.now(), trigger, source); |
| 27 | if (this.actor.actions.length > before) await this.changed(this.actor.actions.slice(before)); |
| 28 | }); |
| 29 | this.queue = next.catch(error => { this.error = error instanceof Error ? error : new Error(String(error)); }); |
| 30 | return next; |
| 31 | } |
| 32 | |
| 33 | async close(): Promise<void> { |
| 34 | this.active = false; |
| 35 | await this.queue; |
| 36 | if (this.error) throw this.error; |
| 37 | } |
| 38 | } |