Stage 0-2 server spine: db, scheduler, REST, auth, economy, map

Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event
scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt
passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map +
spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused.
Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet.
NOT done: military, expansion, social, client, push, deploy docs, bots/admin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:07:42 +02:00
parent 9fa76d53a8
commit b56b13880e
39 changed files with 4450 additions and 0 deletions

95
server/scheduler.js Normal file
View file

@ -0,0 +1,95 @@
'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 };