Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push (docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels. Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js, rankings DoS, static headers, ...): fixes follow in the next commit. NOT done: bots/balance, e2e suite, real-device checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
117 lines
6 KiB
JavaScript
117 lines
6 KiB
JavaScript
'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)
|
|
// Notification outbox (stage 6 push): every notify() row is also queued here and handed to onNotify only AFTER the
|
|
// transaction that wrote it committed, so a rolled-back change never pushes. Nothing is queued without a listener.
|
|
this.onNotify = null; // optional hook: ({ id, userId, worldId, type, payload }) => void, post-commit
|
|
this.outbox = [];
|
|
}
|
|
|
|
// Outbox helpers for code that owns a transaction (process() below, commands.run).
|
|
outboxMark() { return this.outbox.length; }
|
|
outboxRollback(mark) { if (this.outbox.length > mark) this.outbox.length = mark; }
|
|
// Deliver queued notifications. A no-op inside a transaction: the outermost commit delivers them.
|
|
flushOutbox() {
|
|
if (!this.outbox.length || this.db.depth > 0) return;
|
|
const items = this.outbox; this.outbox = [];
|
|
if (!this.onNotify) return;
|
|
for (const n of items) { try { this.onNotify(n); } catch (e) { this.log('onNotify hook failed: ' + e.message); } }
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
// Write a notification row (call inside the transaction of the change it announces). Returns the row id.
|
|
notify(userId, worldId, type, payload) {
|
|
const r = 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());
|
|
const id = Number(r.lastInsertRowid);
|
|
if (this.onNotify) { this.outbox.push({ id, userId, worldId: worldId === undefined ? null : worldId, type, payload: payload || {} }); this.flushOutbox(); }
|
|
return id;
|
|
}
|
|
|
|
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) };
|
|
const mark = this.outboxMark();
|
|
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.outboxRollback(mark);
|
|
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;
|
|
}
|
|
this.flushOutbox();
|
|
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 };
|