Upstream/server/db.js
jvanvik b56b13880e 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
2026-10-11 18:07:42 +02:00

96 lines
3.5 KiB
JavaScript

'use strict';
/*
* The only module that touches SQLite. Wraps node:sqlite so the driver can be swapped for better-sqlite3 by
* rewriting this file. One connection, owned by the one Node process, WAL mode.
*
* const db = openDb('./data/game.db');
* migrate(db);
* db.tx(() => { db.run('INSERT ...', a, b); return db.get('SELECT ...', id); });
*
* Parameters are always positional (`?`), never interpolated. `tx` nests through savepoints.
*/
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { DatabaseSync } = require('node:sqlite');
class Db {
constructor(file) {
this.file = file;
if (file !== ':memory:') fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
this.raw = new DatabaseSync(file);
this.raw.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
this.cache = new Map();
this.depth = 0;
}
stmt(sql) {
let s = this.cache.get(sql);
if (!s) { s = this.raw.prepare(sql); this.cache.set(sql, s); }
return s;
}
static params(p) { return p.map((v) => (v === undefined ? null : v)); }
run(sql, ...p) { return this.stmt(sql).run(...Db.params(p)); }
get(sql, ...p) { return this.stmt(sql).get(...Db.params(p)); }
all(sql, ...p) { return this.stmt(sql).all(...Db.params(p)); }
exec(sql) { this.raw.exec(sql); }
// Runs fn inside a transaction (BEGIN IMMEDIATE at the top level, a savepoint when nested). Rolls back and
// rethrows on any exception. fn must be synchronous: a transaction never spans an await.
tx(fn) {
const top = this.depth === 0;
const sp = 'sp' + this.depth;
this.raw.exec(top ? 'BEGIN IMMEDIATE' : 'SAVEPOINT ' + sp);
this.depth++;
let out;
try {
out = fn();
if (out && typeof out.then === 'function') throw new Error('db.tx callback must not be async');
} catch (err) {
this.depth--;
this.raw.exec(top ? 'ROLLBACK' : 'ROLLBACK TO ' + sp + '; RELEASE ' + sp);
throw err;
}
this.depth--;
this.raw.exec(top ? 'COMMIT' : 'RELEASE ' + sp);
return out;
}
// Consistent snapshot into a new file (docs/DEPLOY.md: a systemd timer calls tools/admin.js backup).
backup(dest) {
if (fs.existsSync(dest)) throw new Error('backup target exists: ' + dest);
this.raw.exec("VACUUM INTO '" + dest.replace(/'/g, "''") + "'");
}
close() { this.cache.clear(); this.raw.close(); }
}
function openDb(file) { return new Db(file); }
// Applies server/migrations/NNN_name.sql in order. Applied migrations are recorded with a checksum: editing one
// after the fact is an error ("never edited after merge").
function migrate(db, dir) {
dir = dir || path.join(__dirname, 'migrations');
db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, sha TEXT NOT NULL, applied_at INTEGER NOT NULL)');
const files = fs.readdirSync(dir).filter((f) => /^\d+.*\.sql$/.test(f)).sort();
const applied = [];
for (const f of files) {
const sql = fs.readFileSync(path.join(dir, f), 'utf8');
const sha = crypto.createHash('sha256').update(sql).digest('hex');
const row = db.get('SELECT sha FROM schema_migrations WHERE name = ?', f);
if (row) {
if (row.sha !== sha) throw new Error('migration ' + f + ' was edited after it was applied');
continue;
}
db.tx(() => {
db.exec(sql);
db.run('INSERT INTO schema_migrations (name, sha, applied_at) VALUES (?, ?, ?)', f, sha, Date.now());
});
applied.push(f);
}
return applied;
}
module.exports = { openDb, migrate, Db };