Fixed: validator rejects __proto__/constructor keys at any depth (transport capacity bypass); trade and site shipments cannot be recalled; trade escrow refund capped by Rack hall; CSP/nosniff on static files and connect-src 'self'; IPv6 /64 limiter keys + LRU eviction + per-username login bucket + scrypt concurrency cap; 5 s footprint cache for rankings; rename uses text.cleanText; 429s no longer pinned in the idempotency store; 30-day notification prune; units_offline notification on first offline. Accepted items listed in docs/DECISIONS.md R1. Tested: npm test 182/182 incl. test/review-fixes.test.js (regression tests). Not re-reviewed after the fixes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
111 lines
5.7 KiB
JavaScript
111 lines
5.7 KiB
JavaScript
'use strict';
|
|
/*
|
|
* Unit power: while the battery is empty and net power is negative, the units in a POP are offline (no attack or
|
|
* defence value, cannot move). After MILITARY.decommissionHours (divided by world speed) offline, the most expensive
|
|
* units are decommissioned until the draw fits the output again.
|
|
*
|
|
* Whether units are online right now is always computed from the lazy battery value (`online`), so reads and combat
|
|
* never depend on an event having run. The `powerCheck` event exists for the side effects: the "units offline"
|
|
* notification and the decommission. `reschedule` is idempotent: it cancels the pending check of the POP and enqueues
|
|
* the one that is correct for the current rates. Call it after ANYTHING that changes unit draw or building levels of a
|
|
* POP (units arriving or leaving, losses, buildings finishing or being damaged).
|
|
*/
|
|
const R = require('../../public/js/rules.js');
|
|
const D = require('../../public/js/data.js');
|
|
const { loadTown, settle } = require('../state');
|
|
const U = require('./units');
|
|
|
|
const EPS = D.MILITARY.batteryEpsilon;
|
|
|
|
// Are the units in this town online at `now`? (the town object may be unsettled: resourcesAt projects it)
|
|
function online(town, now) {
|
|
const c = R.resourcesAt(town, now);
|
|
return !(c.amounts.battery <= EPS && c.rates.powerNet < 0);
|
|
}
|
|
|
|
// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }.
|
|
function drawingUnits(db, townId) {
|
|
const out = U.homeUnits(db, townId);
|
|
for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units);
|
|
return out;
|
|
}
|
|
|
|
function reschedule(ctx, townId, now) {
|
|
const { db } = ctx;
|
|
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type = 'powerCheck' AND status = 'pending'", now, townId);
|
|
const town = loadTown(db, townId);
|
|
if (!town) return;
|
|
if (!(town.unitDraw > 0)) { db.run('DELETE FROM town_power WHERE town_id = ?', townId); return; }
|
|
if (online(town, now)) {
|
|
db.run('DELETE FROM town_power WHERE town_id = ?', townId);
|
|
const at = R.batteryEmptyAt(town, now);
|
|
if (at !== null) ctx.enqueue({ worldId: town.worldId, dueAt: at + 1, type: 'powerCheck', townId, payload: { townId } });
|
|
return;
|
|
}
|
|
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', townId);
|
|
if (!row || row.offline_since === null) {
|
|
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', townId, now);
|
|
row = { offline_since: now };
|
|
const uid = U.userOfOperator(db, town.ownerId);
|
|
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId, since: now });
|
|
}
|
|
ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } });
|
|
}
|
|
|
|
// Decommission the most expensive units (home first, then reinforcements) until the draw fits. The town is settled.
|
|
function decommission(ctx, town, now) {
|
|
const { db } = ctx;
|
|
const units = drawingUnits(db, town.id);
|
|
const rates = R.ratesPerHour(Object.assign({}, town, { unitDraw: 0 }));
|
|
const plan = R.decommissionPlan(units, rates.powerOut - rates.powerDraw);
|
|
const removed = {};
|
|
const byOwner = new Map(); // userId -> { unit: n }, who lost units
|
|
const note = (userId, unit, n) => { if (!byOwner.has(userId)) byOwner.set(userId, {}); const o = byOwner.get(userId); o[unit] = (o[unit] || 0) + n; };
|
|
const ownerUser = U.userOfOperator(db, town.ownerId);
|
|
for (const unit of Object.keys(plan)) {
|
|
let left = plan[unit];
|
|
const home = U.homeUnits(db, town.id)[unit] || 0;
|
|
const fromHome = Math.min(home, left);
|
|
if (fromHome > 0) { U.setHomeUnit(db, town.id, unit, home - fromHome); left -= fromHome; note(ownerUser, unit, fromHome); }
|
|
for (const g of U.hostedGroups(db, town.id)) {
|
|
if (left <= 0) break;
|
|
const have = g.units[unit] || 0;
|
|
const n = Math.min(have, left);
|
|
if (n > 0) {
|
|
U.setStationed(db, town.id, g.ownerTownId, unit, have - n); left -= n;
|
|
const ot = db.get('SELECT t.owner_id AS oid FROM towns t WHERE t.id = ?', g.ownerTownId);
|
|
note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n);
|
|
}
|
|
}
|
|
removed[unit] = plan[unit] - left;
|
|
}
|
|
for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost });
|
|
return removed;
|
|
}
|
|
|
|
// Event handler: payload { townId }. Settles the POP to the due time and acts on what it finds.
|
|
function powerCheck(ctx, ev) {
|
|
const { db } = ctx;
|
|
const town = loadTown(db, ev.townId);
|
|
if (!town) return;
|
|
settle(db, town, ev.dueAt);
|
|
if (town.unitDraw > 0 && !online(town, ev.dueAt)) {
|
|
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', town.id);
|
|
if (!row || row.offline_since === null) {
|
|
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', town.id, ev.dueAt);
|
|
row = { offline_since: ev.dueAt };
|
|
const uid = U.userOfOperator(db, town.ownerId);
|
|
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId: town.id, since: ev.dueAt });
|
|
}
|
|
if (ev.dueAt >= row.offline_since + R.decommissionMs(town.speed)) {
|
|
const removed = decommission(ctx, town, ev.dueAt);
|
|
if (!Object.keys(removed).some((k) => removed[k] > 0)) { // rounding noise, nothing to remove: stand down, never loop
|
|
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
reschedule(ctx, town.id, ev.dueAt);
|
|
}
|
|
|
|
module.exports = { online, drawingUnits, reschedule, decommission, powerCheck };
|