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:
parent
9fa76d53a8
commit
b56b13880e
39 changed files with 4450 additions and 0 deletions
32
server/commands/build.js
Normal file
32
server/commands/build.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
'use strict';
|
||||
/* POST /towns/:id/build. Validate ownership and rules (rules.buildPlan), pay, enqueue the completion event. */
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadTown, settle, spend, pendingBuilds } = require('../state');
|
||||
|
||||
module.exports = function build(ctx, { userId, townId, key }) {
|
||||
const { db, now, scheduler } = ctx;
|
||||
const town = ownedTown(db, userId, townId);
|
||||
settle(db, town, now);
|
||||
const pending = pendingBuilds(db, town.id);
|
||||
const plan = R.buildPlan(town, key, now, pending);
|
||||
if (!plan.ok) {
|
||||
throw new GameError(plan.code, { key, type: plan.type, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing });
|
||||
}
|
||||
spend(db, town, plan.cost);
|
||||
const id = scheduler.enqueue({
|
||||
worldId: town.worldId, townId: town.id, type: 'buildDone', dueAt: now + plan.durationMs,
|
||||
payload: { key, type: plan.type, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId },
|
||||
});
|
||||
return { eventId: id, key, type: plan.type, toLevel: plan.toLevel, startedAt: now, dueAt: now + plan.durationMs, cost: plan.cost };
|
||||
};
|
||||
|
||||
// The town, if the user owns it; otherwise not_found (never reveal that a foreign town exists).
|
||||
function ownedTown(db, userId, townId) {
|
||||
const row = db.get(`SELECT t.id FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?`, townId, userId);
|
||||
const town = row ? loadTown(db, row.id) : null;
|
||||
if (!town) throw new GameError('not_found', { what: 'town' });
|
||||
return town;
|
||||
}
|
||||
|
||||
module.exports.ownedTown = ownedTown;
|
||||
22
server/commands/cancelBuild.js
Normal file
22
server/commands/cancelBuild.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use strict';
|
||||
/* DELETE /towns/:id/queue/:eventId. Cancels a running build and refunds 80% (rounded down). */
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { settle } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
|
||||
const REFUND = 0.8;
|
||||
|
||||
module.exports = function cancelBuild(ctx, { userId, townId, eventId }) {
|
||||
const { db, now } = ctx;
|
||||
const town = ownedTown(db, userId, townId);
|
||||
const ev = db.get("SELECT id, payload FROM events WHERE id = ? AND town_id = ? AND type = 'buildDone' AND status = 'pending'", eventId, town.id);
|
||||
if (!ev) throw new GameError('not_found', { what: 'queue entry' });
|
||||
settle(db, town, now);
|
||||
const cost = JSON.parse(ev.payload).cost || {};
|
||||
const cap = require('../../public/js/rules.js').storageCap(town);
|
||||
for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(cap, town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND));
|
||||
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
|
||||
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ?", now, ev.id);
|
||||
return { cancelled: ev.id };
|
||||
};
|
||||
28
server/commands/index.js
Normal file
28
server/commands/index.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Player commands: one file each, validate + apply in one transaction. `run` first catches the event queue up to now
|
||||
* (so a town is never touched with an overdue event pending), then runs the command in a transaction, then re-arms the
|
||||
* scheduler timer because the command may have enqueued events.
|
||||
*/
|
||||
const handlers = {
|
||||
signup: require('./signup'),
|
||||
joinWorld: require('./joinWorld'),
|
||||
build: require('./build'),
|
||||
cancelBuild: require('./cancelBuild'),
|
||||
renameTown: require('./renameTown'),
|
||||
};
|
||||
|
||||
function createCommands({ db, clock, scheduler }) {
|
||||
function run(name, args) {
|
||||
const fn = handlers[name];
|
||||
if (!fn) throw new Error('unknown command ' + name);
|
||||
scheduler.runDue();
|
||||
const now = clock.now();
|
||||
const out = db.tx(() => fn({ db, clock, now, scheduler }, args));
|
||||
scheduler.arm();
|
||||
return out;
|
||||
}
|
||||
return { run, handlers };
|
||||
}
|
||||
|
||||
module.exports = { createCommands };
|
||||
51
server/commands/joinWorld.js
Normal file
51
server/commands/joinWorld.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
'use strict';
|
||||
/* Create an operator for a user in a world, with a capital POP placed by the spawn ring. Not a player-facing route
|
||||
* on its own: signup and `POST /worlds/:id/join` call it. */
|
||||
const crypto = require('crypto');
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadWorld } = require('../state');
|
||||
|
||||
module.exports = function joinWorld(ctx, { userId, worldId }) {
|
||||
const { db, now } = ctx;
|
||||
const world = loadWorld(db, worldId);
|
||||
if (!world || world.status !== 'running') throw new GameError('not_found', { what: 'world' });
|
||||
const user = db.get('SELECT id, username FROM users WHERE id = ?', userId);
|
||||
if (!user) throw new GameError('not_found', { what: 'user' });
|
||||
if (db.get('SELECT 1 AS x FROM operators WHERE world_id = ? AND user_id = ?', worldId, userId)) throw new GameError('conflict', { what: 'already joined' });
|
||||
|
||||
const towns = db.all('SELECT x, y FROM towns WHERE world_id = ?', worldId);
|
||||
const spot = R.pickSpawn(world.seed, world.map_radius, towns.length, towns);
|
||||
if (!spot) throw new GameError('world_full');
|
||||
|
||||
let asn;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
asn = crypto.randomInt(D.AS_RANGE.min, D.AS_RANGE.max);
|
||||
if (!db.get('SELECT 1 AS x FROM operators WHERE world_id = ? AND as_number = ?', worldId, asn)) break;
|
||||
asn = null;
|
||||
}
|
||||
if (!asn) throw new GameError('internal_error');
|
||||
|
||||
const protectionMs = Math.round(D.PROTECTION_HOURS * D.HOUR_MS / world.speed);
|
||||
const op = db.run('INSERT INTO operators (world_id, user_id, name, as_number, protection_until, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
worldId, userId, user.username, asn, now + protectionMs, now);
|
||||
const operatorId = Number(op.lastInsertRowid);
|
||||
|
||||
const townId = createTown(db, { worldId, ownerId: operatorId, name: user.username + ' POP 1', x: spot.x, y: spot.y, isCapital: true, now });
|
||||
return { operatorId, townId, x: spot.x, y: spot.y, asNumber: asn };
|
||||
};
|
||||
|
||||
// A town with the starting buildings and resources. Also used by expansion (stage 4) with different `start` data.
|
||||
function createTown(db, { worldId, ownerId, name, x, y, isCapital, now, buildings, res }) {
|
||||
const start = res || D.START.resources;
|
||||
const t = db.run(`INSERT INTO towns (world_id, owner_id, name, x, y, is_capital, loyalty, loyalty_at, fiber, hardware, capital,
|
||||
battery, footprint, res_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
|
||||
worldId, ownerId, name, x, y, isCapital ? 1 : 0, D.START.loyalty, now, start.fiber, start.hardware, start.capital, D.START.battery, now, now);
|
||||
const id = Number(t.lastInsertRowid);
|
||||
const b = buildings || R.initialBuildings();
|
||||
for (const key of Object.keys(b)) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', id, key, b[key].type, b[key].level);
|
||||
return id;
|
||||
}
|
||||
|
||||
module.exports.createTown = createTown;
|
||||
20
server/commands/renameTown.js
Normal file
20
server/commands/renameTown.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
const { GameError } = require('../errors');
|
||||
const { ownedTown } = require('./build');
|
||||
|
||||
const STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
|
||||
|
||||
// Display-name hygiene: no control or bidi characters, collapsed whitespace, 2..24 characters.
|
||||
function cleanName(v) {
|
||||
const s = Array.from(String(v).replace(STRIP, '').replace(/\s+/g, ' ').trim()).slice(0, 24).join('').trim();
|
||||
return s;
|
||||
}
|
||||
|
||||
module.exports = function renameTown(ctx, { userId, townId, name }) {
|
||||
const town = ownedTown(ctx.db, userId, townId);
|
||||
const clean = cleanName(name);
|
||||
if (clean.length < 2) throw new GameError('validation_failed', { errors: [{ path: 'name', message: 'too short' }] });
|
||||
ctx.db.run('UPDATE towns SET name = ? WHERE id = ?', clean, town.id);
|
||||
return { name: clean };
|
||||
};
|
||||
module.exports.cleanName = cleanName;
|
||||
18
server/commands/signup.js
Normal file
18
server/commands/signup.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
'use strict';
|
||||
/* Create account + operator + capital POP + first token in one transaction. The password hash and token hash are
|
||||
* computed by the route before the transaction (scrypt is async, a transaction never spans an await). */
|
||||
const { GameError } = require('../errors');
|
||||
const joinWorld = require('./joinWorld');
|
||||
|
||||
module.exports = function signup(ctx, { username, passHash, tokenHash, device, worldId }) {
|
||||
const { db, now } = ctx;
|
||||
if (db.get('SELECT 1 AS x FROM users WHERE username = ?', username)) throw new GameError('username_taken');
|
||||
const w = worldId !== undefined ? db.get("SELECT id FROM worlds WHERE id = ? AND status = 'running'", worldId)
|
||||
: db.get("SELECT id FROM worlds WHERE status = 'running' ORDER BY id LIMIT 1");
|
||||
if (!w) throw new GameError('not_found', { what: 'world' });
|
||||
const u = db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', username, passHash, now);
|
||||
const userId = Number(u.lastInsertRowid);
|
||||
const joined = joinWorld(ctx, { userId, worldId: w.id });
|
||||
const t = db.run('INSERT INTO tokens (user_id, token_hash, device, created_at, last_used_at) VALUES (?, ?, ?, ?, ?)', userId, tokenHash, device || '', now, now);
|
||||
return Object.assign({ userId, tokenId: Number(t.lastInsertRowid) }, joined);
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue