'use strict'; /* * Persistent event queue. There is no tick loop: one timer points at the next due event, and after a restart every * overdue event is caught up in order before traffic is accepted. * * Rules (CLAUDE.md "Time model"): * - events are processed strictly in (due_at, id) order * - each event runs in ONE transaction: handler + mark done. A handler that throws rolls back and the event is * marked failed (never retried in a loop, never blocks the queue) * - handlers must be idempotent; they receive the event's own due_at as the time to settle towns to * - before any command or read touches a town, runDue() processes everything due up to `now` */ const MAX_TIMER_MS = 30 * 1000; // re-check at least this often (setTimeout cannot do more than ~24 days anyway) class Scheduler { // handlers: { [type]: (ctx, event) => void }; ctx = { db, clock, now, enqueue, notify, log } constructor({ db, clock, handlers, log, autoArm }) { this.db = db; this.clock = clock; this.handlers = handlers || {}; this.log = log || (() => {}); this.autoArm = autoArm !== false; this.timer = null; this.running = false; this.closed = false; this.onEvent = null; // optional hook: (event) => void after each processed event (push, tests) } register(type, fn) { this.handlers[type] = fn; } // Insert an event. Call inside a transaction together with the state change it belongs to. enqueue({ worldId, dueAt, type, townId, payload }) { const r = this.db.run('INSERT INTO events (world_id, due_at, type, town_id, payload, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)', worldId, Math.round(dueAt), type, townId === undefined ? null : townId, JSON.stringify(payload || {}), 'pending', this.clock.now()); return Number(r.lastInsertRowid); } notify(userId, worldId, type, payload) { this.db.run('INSERT INTO notifications (user_id, world_id, type, payload, created_at) VALUES (?, ?, ?, ?, ?)', userId, worldId === undefined ? null : worldId, type, JSON.stringify(payload || {}), this.clock.now()); } next() { return this.db.get("SELECT id, due_at FROM events WHERE status = 'pending' ORDER BY due_at, id LIMIT 1"); } // Process every pending event with due_at <= now, in order, including follow-ups that are also already due. // Returns the number processed. Reentrancy-safe: a handler cannot start a nested run. runDue(now) { if (this.running) return 0; this.running = true; let n = 0; try { now = now === undefined ? this.clock.now() : now; for (;;) { const ev = this.db.get("SELECT * FROM events WHERE status = 'pending' AND due_at <= ? ORDER BY due_at, id LIMIT 1", now); if (!ev) break; this.process(ev); n++; } } finally { this.running = false; } return n; } process(ev) { const handler = this.handlers[ev.type]; const event = { id: ev.id, worldId: ev.world_id, dueAt: ev.due_at, type: ev.type, townId: ev.town_id, payload: JSON.parse(ev.payload) }; try { this.db.tx(() => { if (!handler) throw new Error('no handler for event type ' + ev.type); handler({ db: this.db, clock: this.clock, now: ev.due_at, enqueue: (e) => this.enqueue(e), notify: (u, w, t, p) => this.notify(u, w, t, p), log: this.log, scheduler: this }, event); this.db.run("UPDATE events SET status = 'done', done_at = ? WHERE id = ?", this.clock.now(), ev.id); }); } catch (err) { this.log('event ' + ev.id + ' (' + ev.type + ') failed: ' + (err && err.stack || err)); this.db.run("UPDATE events SET status = 'failed', done_at = ?, error = ? WHERE id = ?", this.clock.now(), String(err && err.message || err).slice(0, 500), ev.id); return; } if (this.onEvent) { try { this.onEvent(event); } catch (e) { this.log('onEvent hook failed: ' + e.message); } } } // After a restart: process everything overdue, in order, before accepting traffic. catchUp() { return this.runDue(); } // Point the single timer at the next due event (or re-check soon). Safe to call after every mutation. arm() { if (!this.autoArm || this.closed) return; if (this.timer) { clearTimeout(this.timer); this.timer = null; } const nx = this.next(); const wait = nx ? Math.min(MAX_TIMER_MS, Math.max(0, nx.due_at - this.clock.now())) : MAX_TIMER_MS; this.timer = setTimeout(() => { this.timer = null; try { this.runDue(); } catch (err) { this.log('scheduler run failed: ' + (err && err.stack || err)); } this.arm(); }, wait + 5); if (this.timer.unref) this.timer.unref(); } stop() { this.closed = true; if (this.timer) clearTimeout(this.timer); this.timer = null; } } module.exports = { Scheduler };