Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
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
This commit is contained in:
parent
249818a7aa
commit
b18645dca1
87 changed files with 10201 additions and 71 deletions
|
|
@ -127,6 +127,7 @@ function dissolve(ctx, allianceId, reason) {
|
|||
db.run('DELETE FROM alliance_notes WHERE alliance_id = ?', a.id);
|
||||
const ids = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id);
|
||||
for (const m of ids) removeMember(db, m.operator_id);
|
||||
require('./endgame').onAllianceDissolved(ctx, a.id); // its backbone landing sites are the incumbent's again
|
||||
db.run('DELETE FROM alliances WHERE id = ?', a.id);
|
||||
}
|
||||
|
||||
|
|
@ -172,9 +173,19 @@ const confederated = (db, opA, opB) => { const r = operatorRelation(db, opA, opB
|
|||
// May not attack each other: same alliance, NAP or confederation.
|
||||
const pactPartners = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'nap' || r === 'confed' || r === 'same_alliance'; };
|
||||
|
||||
// Every other operator for whom `confederated(db, operatorId, x)` holds: the rest of the own alliance plus the members of
|
||||
// alliances in a confederation with it. [] without an alliance.
|
||||
function confederatedOperators(db, operatorId) {
|
||||
const me = db.get('SELECT alliance_id FROM operators WHERE id = ?', operatorId);
|
||||
if (!me || !me.alliance_id) return [];
|
||||
const ids = [me.alliance_id];
|
||||
for (const r of db.all("SELECT a_id, b_id FROM alliance_relations WHERE state = 'confed' AND (a_id = ? OR b_id = ?)", me.alliance_id, me.alliance_id)) ids.push(r.a_id === me.alliance_id ? r.b_id : r.a_id);
|
||||
return db.all('SELECT id FROM operators WHERE alliance_id IN (' + ids.map(() => '?').join(',') + ') AND id != ? ORDER BY id', ...ids, operatorId).map((r) => r.id);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
S, HOUR, operatorOf, peeringLevel, membership, getAlliance, memberCount, leaderOf, allianceBrief, effectiveCap, refreshCap,
|
||||
addMember, removeMember, requireRole, userOfOperator, notifyOperator, notifyAlliance, dissolve,
|
||||
pairOf, getRelation, setRelation, withdrawProposals,
|
||||
relationBetween, operatorRelation, atWar, confederated, pactPartners,
|
||||
relationBetween, operatorRelation, atWar, confederated, pactPartners, confederatedOperators,
|
||||
};
|
||||
|
|
|
|||
40
server/commands/backboneBuild.js
Normal file
40
server/commands/backboneBuild.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /backbone/:id/build: start the next Backbone node level on a landing site your alliance holds. The level's cost comes out
|
||||
* of the site's stockpile (shipped in by the holders, see backboneShip) at once; one level at a time; the level lands when the
|
||||
* `backboneDone` event runs. Needs the `backboneBuild` permission.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadWorld } = require('../state');
|
||||
const A = require('../alliances');
|
||||
const E = require('../endgame');
|
||||
const ctxOf = require('../military/ctx');
|
||||
|
||||
// The site, the caller's operator in its world, and proof that the caller's alliance holds it. Shared with backboneShip.
|
||||
function holderContext(db, userId, siteId, now) {
|
||||
const site = E.siteRow(db, siteId);
|
||||
if (!site) throw new GameError('not_found', { what: 'landing site' });
|
||||
const world = loadWorld(db, site.world_id);
|
||||
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, site.world_id);
|
||||
if (!op) throw new GameError('not_found', { what: 'landing site' });
|
||||
if (!E.isOpen(world, now)) throw new GameError('backbone_closed', { opensAtDay: require('../../public/js/data.js').ENDGAME.openDay });
|
||||
const m = A.membership(db, op.id);
|
||||
if (!site.holder_alliance_id || !m || m.alliance_id !== site.holder_alliance_id) throw new GameError('forbidden', { need: 'holder' });
|
||||
return { site, world, op, member: m };
|
||||
}
|
||||
|
||||
module.exports = function backboneBuild(ctx0, { userId, siteId }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const { site, world, op, member } = holderContext(db, userId, siteId, now);
|
||||
if (!R.allianceCan(member.role, 'backboneBuild')) throw new GameError('forbidden', { need: 'backboneBuild', role: member.role });
|
||||
const plan = R.backbonePlan({ level: site.level, build: site.build_to ? { to: site.build_to } : null, pool: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } }, world.speed);
|
||||
if (!plan.ok) throw new GameError(plan.code, { siteId: site.id, toLevel: plan.toLevel, cost: plan.cost, have: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } });
|
||||
const dueAt = now + plan.durationMs;
|
||||
const ev = ctx.enqueue({ worldId: site.world_id, dueAt, type: 'backboneDone', payload: { siteId: site.id, toLevel: plan.toLevel, by: op.id } });
|
||||
db.run(`UPDATE landing_sites SET fiber = fiber - ?, hardware = hardware - ?, capital = capital - ?, build_to = ?, build_event_id = ?, build_started_at = ?, build_due_at = ?, build_cost = ? WHERE id = ?`,
|
||||
plan.cost.fiber, plan.cost.hardware, plan.cost.capital, plan.toLevel, ev, now, dueAt, JSON.stringify(plan.cost), site.id);
|
||||
return { siteId: site.id, eventId: ev, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost };
|
||||
};
|
||||
module.exports.holderContext = holderContext;
|
||||
23
server/commands/backboneShip.js
Normal file
23
server/commands/backboneShip.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /backbone/:id/ship {fromTownId, cargo}: send resources from one of your POPs to a landing site your alliance holds, to
|
||||
* feed its stockpile. A normal transport (same links, 500 per link, 12 tiles/h) whose target is the site's tile; on arrival it is
|
||||
* added to the stockpile if the sender's alliance still holds the site, otherwise it rides home.
|
||||
*/
|
||||
const { GameError } = require('../errors');
|
||||
const { settle } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
const { launchTransport } = require('./sendTransport');
|
||||
const { holderContext } = require('./backboneBuild');
|
||||
const ctxOf = require('../military/ctx');
|
||||
|
||||
module.exports = function backboneShip(ctx0, { userId, siteId, fromTownId, cargo }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const { site } = holderContext(db, userId, siteId, now);
|
||||
const from = ownedTown(db, userId, fromTownId);
|
||||
if (from.worldId !== site.world_id) throw new GameError('not_found', { what: 'town' });
|
||||
settle(db, from, now);
|
||||
const mv = launchTransport(ctx, from, { x: site.x, y: site.y }, cargo || {}, { siteId: site.id });
|
||||
return { movementId: mv.id, type: 'transport', siteId: site.id, fromTownId: from.id, toTownId: null, to: { x: site.x, y: site.y }, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt };
|
||||
};
|
||||
|
|
@ -40,19 +40,35 @@ const handlers = {
|
|||
messageDelete: require('./messageDelete'),
|
||||
messageBlock: require('./messageBlock').messageBlock,
|
||||
messageUnblock: require('./messageBlock').messageUnblock,
|
||||
// trade, end game, shared reports
|
||||
reportShare: require('./reportShare').reportShare,
|
||||
reportUnshare: require('./reportShare').reportUnshare,
|
||||
tradeOffer: require('./tradeOffer'),
|
||||
tradeCancel: require('./tradeCancel'),
|
||||
tradeAccept: require('./tradeAccept'),
|
||||
backboneBuild: require('./backboneBuild'),
|
||||
backboneShip: require('./backboneShip'),
|
||||
};
|
||||
|
||||
function createCommands({ db, clock, scheduler }) {
|
||||
// hooks.onCommand(name, args, out): optional, called after a command committed (stage 6 push). Never throws into the caller.
|
||||
const hooks = { onCommand: null };
|
||||
function run(name, args) {
|
||||
const fn = handlers[name];
|
||||
if (!fn) throw new Error('unknown command ' + name);
|
||||
scheduler.runDue();
|
||||
require('../endgame').guard(db, name, args); // an ended world refuses every command except reading state and chatting
|
||||
const now = clock.now();
|
||||
const out = db.tx(() => fn({ db, clock, now, scheduler }, args));
|
||||
const mark = scheduler.outboxMark();
|
||||
let out;
|
||||
try { out = db.tx(() => fn({ db, clock, now, scheduler }, args)); }
|
||||
catch (err) { scheduler.outboxRollback(mark); throw err; }
|
||||
scheduler.flushOutbox(); // notifications written by the command go out now that it is committed
|
||||
if (hooks.onCommand) { try { hooks.onCommand(name, args, out); } catch (e) { if (scheduler.log) scheduler.log('onCommand hook failed: ' + e.message); } }
|
||||
scheduler.arm();
|
||||
return out;
|
||||
}
|
||||
return { run, handlers };
|
||||
return { run, handlers, hooks };
|
||||
}
|
||||
|
||||
module.exports = { createCommands };
|
||||
|
|
|
|||
51
server/commands/reportShare.js
Normal file
51
server/commands/reportShare.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The alliance's shared report folder. Two commands in one file (registered separately in commands/index.js):
|
||||
* reportShare { userId, reportId } put one of YOUR reports into your alliance's folder (needs `shareReport`)
|
||||
* reportUnshare { userId, reportId } take it out again: whoever shared it, or `unshareReport` (leader, officer)
|
||||
* The alliance is the caller's alliance in the report's world. Sharing an already shared report changes nothing
|
||||
* ({ changed: false }). A shared report lives at least reportRetentionMs from the moment it was shared (the expiry is pushed
|
||||
* out; it is one row for everybody, so the participants keep it that long too) and is deleted with the report.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const A = require('../alliances');
|
||||
const { ensureCleanup } = require('../military/reports');
|
||||
|
||||
function context(db, userId, reportId) {
|
||||
const rep = db.get(`SELECT r.id, r.world_id, r.expires_at FROM reports r JOIN report_recipients rr ON rr.report_id = r.id AND rr.user_id = ? WHERE r.id = ?`, userId, reportId);
|
||||
if (!rep) throw new GameError('not_found', { what: 'report' }); // not yours: never reveal it exists
|
||||
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, rep.world_id);
|
||||
if (!op) throw new GameError('not_found', { what: 'report' });
|
||||
const m = A.membership(db, op.id);
|
||||
if (!m) throw new GameError('not_in_alliance');
|
||||
return { rep, op, member: m };
|
||||
}
|
||||
|
||||
function reportShare(ctx, { userId, reportId }) {
|
||||
const { db, now } = ctx;
|
||||
const { rep, op, member } = context(db, userId, reportId);
|
||||
if (!R.allianceCan(member.role, 'shareReport')) throw new GameError('forbidden', { need: 'shareReport', role: member.role });
|
||||
const r = db.run('INSERT OR IGNORE INTO report_shares (report_id, alliance_id, shared_by, created_at) VALUES (?, ?, ?, ?)', rep.id, member.alliance_id, op.id, now);
|
||||
if (!r.changes) return { changed: false, reportId: rep.id, allianceId: member.alliance_id };
|
||||
const until = now + D.MILITARY.reportRetentionMs;
|
||||
if (rep.expires_at < until) db.run('UPDATE reports SET expires_at = ? WHERE id = ?', until, rep.id);
|
||||
ensureCleanup(ctx, rep.world_id, now);
|
||||
return { changed: true, reportId: rep.id, allianceId: member.alliance_id };
|
||||
}
|
||||
|
||||
function reportUnshare(ctx, { userId, reportId }) {
|
||||
const { db } = ctx;
|
||||
// the report may no longer list the caller as a recipient (it is only theirs through the alliance): look the share up directly
|
||||
const share = db.get(`SELECT s.*, r.world_id FROM report_shares s JOIN reports r ON r.id = s.report_id WHERE s.report_id = ?
|
||||
AND s.alliance_id IN (SELECT m.alliance_id FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE o.user_id = ?)`, reportId, userId);
|
||||
if (!share) throw new GameError('not_found', { what: 'shared report' });
|
||||
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, share.world_id);
|
||||
const member = A.membership(db, op.id);
|
||||
if (op.id !== share.shared_by && !R.allianceCan(member.role, 'unshareReport')) throw new GameError('forbidden', { need: 'unshareReport', role: member.role });
|
||||
db.run('DELETE FROM report_shares WHERE report_id = ? AND alliance_id = ?', share.report_id, share.alliance_id);
|
||||
return { changed: true, reportId: share.report_id, allianceId: share.alliance_id };
|
||||
}
|
||||
|
||||
module.exports = { reportShare, reportUnshare };
|
||||
|
|
@ -18,7 +18,7 @@ const TYPES = ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle'];
|
|||
const HOSTILE = ['raid', 'attack', 'takeover'];
|
||||
|
||||
// The target of a movement: a POP (by id or by tile) or a bare tile. -> { town: row|null, x, y, tile }
|
||||
function resolveTarget(db, world, args) {
|
||||
function resolveTarget(db, world, args, now) {
|
||||
let town = null, x, y;
|
||||
if (args.toTownId !== undefined && args.toTownId !== null) {
|
||||
town = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', args.toTownId, world.id);
|
||||
|
|
@ -30,7 +30,7 @@ function resolveTarget(db, world, args) {
|
|||
} else {
|
||||
throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'give toTownId or x and y' }] });
|
||||
}
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
if (tile.type === 'void') throw new GameError('invalid_target', { reason: 'outside_map' });
|
||||
return { town, x, y, tile };
|
||||
}
|
||||
|
|
@ -52,7 +52,7 @@ module.exports = function sendMovement(ctx0, args) {
|
|||
for (const k of Object.keys(units)) if ((home[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: home[k] || 0, want: units[k] });
|
||||
if (!P.online(from, now)) throw new GameError('units_offline', { townId: from.id });
|
||||
|
||||
const tgt = resolveTarget(db, world, args);
|
||||
const tgt = resolveTarget(db, world, args, now);
|
||||
if (tgt.town && tgt.town.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' });
|
||||
const dist = R.distance(from.x, from.y, tgt.x, tgt.y);
|
||||
const arriveAt = now + R.movementMs(dist, units, world.speed);
|
||||
|
|
@ -81,6 +81,10 @@ module.exports = function sendMovement(ctx0, args) {
|
|||
}
|
||||
} else if (tgt.tile.type === 'incumbent') {
|
||||
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'incumbent_scan_or_attack_only' });
|
||||
} else if (tgt.tile.type === 'backbone') {
|
||||
require('../endgame').checkLandingTarget(db, world, op, tgt, type, now, ctx); // scan or attack only, alliance members, no pact partners
|
||||
} else if (R.isBackboneSite(world.seed, world.map_radius, tgt.x, tgt.y)) {
|
||||
throw new GameError('backbone_closed', { opensAtDay: D.ENDGAME.openDay }); // the landing site is not there yet
|
||||
} else {
|
||||
throw new GameError('invalid_target', { reason: 'nothing_there' });
|
||||
}
|
||||
|
|
@ -98,7 +102,7 @@ module.exports = function sendMovement(ctx0, args) {
|
|||
const own = U.operatorTowns(db, op.id);
|
||||
let nearest = Infinity;
|
||||
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, tgt.x, tgt.y));
|
||||
const chk2 = R.settleCheck({ tileType: tgt.tile.type, occupied: !!tgt.town, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
|
||||
const chk2 = R.settleCheck({ tileType: tgt.tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, tgt.x, tgt.y), occupied: !!tgt.town, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
|
||||
if (!chk2.ok) throw new GameError(chk2.code, chk2);
|
||||
extra.wild = R.cleanWild(args.wild);
|
||||
}
|
||||
|
|
|
|||
54
server/commands/tradeAccept.js
Normal file
54
server/commands/tradeAccept.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /trade/offers/:id/accept {townId}: take an open offer with one of your POPs. In ONE transaction:
|
||||
* - the payment (the wanted resource) leaves the acceptor's POP as a transport to the poster's POP (needs a free link there,
|
||||
* the usual transport rules: capacity, resources),
|
||||
* - the poster's escrow leaves as a transport to the acceptor's POP (on the link the open offer held in reserve),
|
||||
* - the offer becomes `accepted`; it is `completed` when both transports have been delivered (see server/trade.js).
|
||||
* Any failure rolls everything back. Not your own offer; the acceptor's POP needs an Internet exchange and must be in range
|
||||
* (the offer's max distance and the exchange's reach).
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { settle, loadWorld } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
const { launchTransport } = require('./sendTransport');
|
||||
const ctxOf = require('../military/ctx');
|
||||
const M = require('../military/movements');
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeAccept(ctx0, { userId, offerId, townId }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const o = T.getOffer(db, offerId);
|
||||
const mine = ownedTown(db, userId, townId);
|
||||
if (!o || o.world_id !== mine.worldId) throw new GameError('not_found', { what: 'offer' });
|
||||
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
|
||||
if (mine.ownerId === o.operator_id) throw new GameError('own_offer');
|
||||
const poster = db.get('SELECT * FROM towns WHERE id = ?', o.town_id);
|
||||
if (!poster || poster.owner_id !== o.operator_id) throw new GameError('offer_closed', { status: 'void' });
|
||||
const level = R.transportLinks(mine);
|
||||
const dist = R.distance(mine.x, mine.y, poster.x, poster.y);
|
||||
if (level < 1) throw new GameError('no_transport_link', { links: 0, active: 0 });
|
||||
if (!R.tradeInRange(dist, o.max_distance, level)) throw new GameError('trade_out_of_range', { distance: dist, maxDistance: o.max_distance, reach: R.tradeReach(level) });
|
||||
settle(db, mine, now);
|
||||
|
||||
// acceptor -> poster: the wanted resource (validates links, capacity and resources, deducts, inserts the movement)
|
||||
const pay = launchTransport(ctx, mine, poster, { [o.want_res]: o.want_amount }, { tradeId: o.id, role: 'payment' });
|
||||
// poster -> acceptor: the escrow
|
||||
const world = loadWorld(db, o.world_id);
|
||||
const goods = M.insertMovement(ctx, {
|
||||
worldId: o.world_id, ownerId: o.operator_id, type: 'transport', fromTownId: poster.id, toTownId: mine.id,
|
||||
from: { x: poster.x, y: poster.y }, to: { x: mine.x, y: mine.y }, units: {}, cargo: { [o.give_res]: o.give_amount },
|
||||
departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: { tradeId: o.id, role: 'goods' },
|
||||
});
|
||||
db.run("UPDATE trade_offers SET status = 'accepted', accepted_by_operator = ?, accepted_town_id = ?, accepted_at = ?, goods_movement_id = ?, payment_movement_id = ? WHERE id = ?",
|
||||
mine.ownerId, mine.id, now, goods.id, pay.id, o.id);
|
||||
if (o.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, o.expire_event_id);
|
||||
const posterUser = T.userOfOperator(db, o.operator_id);
|
||||
if (posterUser) ctx.notify(posterUser, o.world_id, 'trade_accepted', { offerId: o.id, townId: poster.id, byTownId: mine.id, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount } });
|
||||
return {
|
||||
offerId: o.id, status: 'accepted', goodsMovementId: goods.id, paymentMovementId: pay.id, distance: dist,
|
||||
arriveAt: goods.arriveAt, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount },
|
||||
};
|
||||
};
|
||||
15
server/commands/tradeCancel.js
Normal file
15
server/commands/tradeCancel.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
'use strict';
|
||||
/* DELETE /trade/offers/:id: take your open offer back; the escrow returns to the POP. */
|
||||
const { GameError } = require('../errors');
|
||||
const ctxOf = require('../military/ctx');
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeCancel(ctx0, { userId, offerId }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const o = T.getOffer(db, offerId);
|
||||
if (!o || T.userOfOperator(db, o.operator_id) !== userId) throw new GameError('not_found', { what: 'offer' });
|
||||
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
|
||||
T.closeOffer(ctx, o, 'cancelled', now);
|
||||
return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: o.give_amount } };
|
||||
};
|
||||
33
server/commands/tradeOffer.js
Normal file
33
server/commands/tradeOffer.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /trade/offers: "give X of A for Y of B, max distance Z" from one of your POPs with an Internet exchange. The offered
|
||||
* amount leaves the POP now (escrow), one transport link stays reserved for it, and the offer expires after TRADE.ttlHours
|
||||
* (divided by world speed). Both amounts must fit one transport link and differ by at most 1:2.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { settle, spend } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
const M = require('../military/movements');
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeOffer(ctx, { userId, townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance }) {
|
||||
const { db, now, scheduler } = ctx;
|
||||
const town = ownedTown(db, userId, townId);
|
||||
const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance });
|
||||
if (!terms.ok) throw new GameError(terms.code, terms);
|
||||
const links = R.transportLinks(town);
|
||||
const inUse = M.activeLinks(db, town.id);
|
||||
if (links < 1 || inUse >= links) throw new GameError('no_transport_link', { links, active: inUse });
|
||||
settle(db, town, now);
|
||||
if (R.resourcesAt(town, now).amounts[giveRes] + 1e-6 < giveAmount) throw new GameError('not_enough_resources', { resource: giveRes, want: giveAmount });
|
||||
spend(db, town, { [giveRes]: giveAmount });
|
||||
const expiresAt = now + T.expiryMs(town.speed);
|
||||
const id = Number(db.run(`INSERT INTO trade_offers (world_id, town_id, operator_id, give_res, give_amount, want_res, want_amount, max_distance, status, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)`, town.worldId, town.id, town.ownerId, giveRes, giveAmount, wantRes, wantAmount, maxDistance, now, expiresAt).lastInsertRowid);
|
||||
const ev = scheduler.enqueue({ worldId: town.worldId, dueAt: expiresAt, type: 'tradeExpire', townId: town.id, payload: { offerId: id } });
|
||||
db.run('UPDATE trade_offers SET expire_event_id = ? WHERE id = ?', ev, id);
|
||||
const o = T.getOffer(db, id);
|
||||
return { offer: T.offerView(db, o, new Map([[town.id, town]])) };
|
||||
};
|
||||
192
server/endgame.js
Normal file
192
server/endgame.js
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
'use strict';
|
||||
/*
|
||||
* End game: backbone landing sites, the Backbone node race, the winner, the end of the world.
|
||||
*
|
||||
* Representation (DECISIONS.md E1): a landing site is NOT a POP. It is a row of `landing_sites` (position from the world seed,
|
||||
* holder alliance, node level, stockpile, build in progress). The tile reads 'backbone' (rules.tileAt with the world age) from
|
||||
* D.ENDGAME.openDay on; before that it is plain land that nobody may settle or spawn on. A site is defended by a static value
|
||||
* only (rules.backboneDefence: incumbent defence x defenceMult, + a bonus per node level), so there are no reinforcements at a
|
||||
* site. Holders keep the level when the site is taken; the stockpile and a running build stay with the site as well.
|
||||
*
|
||||
* Time: world age is in world days (real days x speed). Everything here takes `now` (ms) from the caller.
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const { loadWorld } = require('./state');
|
||||
|
||||
const DAY = 24 * D.HOUR_MS;
|
||||
const E = D.ENDGAME;
|
||||
|
||||
const ageDays = (world, now) => R.worldAgeDays(world.start_at, now, world.speed);
|
||||
const phase = (world, now) => R.worldPhase(world.status, ageDays(world, now));
|
||||
const isOpen = (world, now) => ageDays(world, now) >= E.openDay;
|
||||
|
||||
// ---------------------------------------------------------------- site rows
|
||||
|
||||
// Create the site rows (idempotent). Writers call this; reads use `siteStates`, which never writes. The first call that really
|
||||
// creates them (whatever touches a site first once the world is old enough) tells every operator, when it was given a `ctx`
|
||||
// with notify. There is no timer event for this on purpose: nothing is pending in a quiet world.
|
||||
function ensureSites(db, world, now, ctx) {
|
||||
if (!isOpen(world, now)) return [];
|
||||
let created = 0;
|
||||
for (const s of R.backboneSites(world.seed, world.map_radius)) created += Number(db.run('INSERT OR IGNORE INTO landing_sites (world_id, idx, x, y) VALUES (?, ?, ?, ?)', world.id, s.index, s.x, s.y).changes);
|
||||
const rows = db.all('SELECT * FROM landing_sites WHERE world_id = ? ORDER BY idx', world.id);
|
||||
if (created && ctx && ctx.notify) notifyWorld(ctx, world.id, 'backbone_open', { sites: rows.map((r) => ({ siteId: r.id, index: r.idx, x: r.x, y: r.y })) });
|
||||
return rows;
|
||||
}
|
||||
const siteRow = (db, id) => db.get('SELECT * FROM landing_sites WHERE id = ?', id) || null;
|
||||
const siteAt = (db, worldId, idx) => db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', worldId, idx) || null;
|
||||
|
||||
// Every site of the world as { site: {index,x,y}, row: landing_sites row | null } (no row = never touched: still the incumbent's).
|
||||
function siteStates(db, world, now) {
|
||||
if (!isOpen(world, now)) return [];
|
||||
const rows = new Map(db.all('SELECT * FROM landing_sites WHERE world_id = ?', world.id).map((r) => [r.idx, r]));
|
||||
return R.backboneSites(world.seed, world.map_radius).map((s) => ({ site: s, row: rows.get(s.index) || null }));
|
||||
}
|
||||
|
||||
function allianceInfo(db, id) {
|
||||
if (!id) return null;
|
||||
const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id);
|
||||
return a ? { allianceId: a.id, tag: a.tag, name: a.name } : null;
|
||||
}
|
||||
const opBrief = (db, id) => { const o = id ? db.get('SELECT id, name FROM operators WHERE id = ?', id) : null; return o ? { operatorId: o.id, name: o.name } : null; };
|
||||
|
||||
// Public view of one site. `row` may be null (untouched).
|
||||
function siteView(db, world, s, row) {
|
||||
const level = row ? row.level : 0;
|
||||
const pool = { fiber: row ? row.fiber : 0, hardware: row ? row.hardware : 0, capital: row ? row.capital : 0 };
|
||||
const build = row && row.build_to ? { toLevel: row.build_to, startedAt: row.build_started_at, dueAt: row.build_due_at } : null;
|
||||
return {
|
||||
id: row ? row.id : null, index: s.index, x: s.x, y: s.y,
|
||||
holder: row ? allianceInfo(db, row.holder_alliance_id) : null,
|
||||
takenBy: row ? opBrief(db, row.holder_operator_id) : null, takenAt: row ? row.taken_at : null,
|
||||
level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build,
|
||||
next: level < E.maxLevel ? { toLevel: level + 1, cost: R.backboneCost(level + 1), durationMs: R.backboneTimeMs(level + 1, world.speed) } : null,
|
||||
};
|
||||
}
|
||||
|
||||
function winnerView(w) {
|
||||
return w.winner_alliance_id || w.winner_name ? { allianceId: w.winner_alliance_id, name: w.winner_name, tag: w.winner_tag, siteId: w.winner_site_id, wonAt: w.won_at } : null;
|
||||
}
|
||||
|
||||
// GET /worlds/:id/status
|
||||
function statusView(db, world, now) {
|
||||
const age = ageDays(world, now);
|
||||
return {
|
||||
worldId: world.id, name: world.name, speed: world.speed, status: world.status, phase: phase(world, now),
|
||||
ageDays: age, openDay: E.openDay, opensAt: world.start_at + Math.round(E.openDay * DAY / world.speed),
|
||||
sites: siteStates(db, world, now).map(({ site, row }) => siteView(db, world, site, row)),
|
||||
winner: winnerView(world), endsAt: world.status === 'ended' ? world.end_at : (world.won_at ? world.end_at : null), endedAt: world.status === 'ended' ? world.end_at : null,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the ended-world gate
|
||||
|
||||
// Commands that stay possible after the world ended (reading state, chatting): everything else is refused with `world_ended`.
|
||||
const WHEN_ENDED = new Set(['markReportRead', 'messageSend', 'messageRead', 'messageDelete', 'messageBlock', 'messageUnblock']);
|
||||
const PROBES = [
|
||||
['townId', 'SELECT world_id AS w FROM towns WHERE id = ?'], ['fromTownId', 'SELECT world_id AS w FROM towns WHERE id = ?'], ['hostTownId', 'SELECT world_id AS w FROM towns WHERE id = ?'],
|
||||
['allianceId', 'SELECT world_id AS w FROM alliances WHERE id = ?'], ['movementId', 'SELECT world_id AS w FROM movements WHERE id = ?'],
|
||||
['inviteId', 'SELECT a.world_id AS w FROM alliance_invites i JOIN alliances a ON a.id = i.alliance_id WHERE i.id = ?'],
|
||||
['proposalId', 'SELECT world_id AS w FROM alliance_proposals WHERE id = ?'], ['offerId', 'SELECT world_id AS w FROM trade_offers WHERE id = ?'],
|
||||
['siteId', 'SELECT world_id AS w FROM landing_sites WHERE id = ?'], ['reportId', 'SELECT world_id AS w FROM reports WHERE id = ?'],
|
||||
];
|
||||
// The world a command acts in: an explicit worldId, else the world of whatever it points at, else the caller's default operator's.
|
||||
function worldOfCommand(db, args) {
|
||||
if (args.worldId) return args.worldId;
|
||||
for (const [key, sql] of PROBES) {
|
||||
if (args[key]) { const r = db.get(sql, args[key]); if (r) return r.w; }
|
||||
}
|
||||
if (args.userId) { const r = db.get('SELECT world_id AS w FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', args.userId); if (r) return r.w; }
|
||||
return null;
|
||||
}
|
||||
// Called by commands.run before every command. Throws world_ended when the world of the command has ended.
|
||||
function guard(db, name, args) {
|
||||
if (WHEN_ENDED.has(name) || !args) return;
|
||||
const w = worldOfCommand(db, args);
|
||||
if (!w) return;
|
||||
const row = db.get('SELECT status FROM worlds WHERE id = ?', w);
|
||||
if (row && row.status === 'ended') throw new GameError('world_ended', { worldId: w });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- notifications
|
||||
|
||||
function notifyAlliance(ctx, allianceId, type, payload) {
|
||||
for (const m of ctx.db.all('SELECT o.user_id AS uid, o.world_id AS wid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', allianceId)) ctx.notify(m.uid, m.wid, type, payload);
|
||||
}
|
||||
function notifyWorld(ctx, worldId, type, payload) {
|
||||
for (const o of ctx.db.all('SELECT user_id FROM operators WHERE world_id = ?', worldId)) ctx.notify(o.user_id, worldId, type, payload);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- taking a site, winning, the end
|
||||
|
||||
// Sending checks (sendMovement): landing sites can be scanned and attacked, nothing else. Attacking needs an alliance; you cannot
|
||||
// attack a site your own alliance or a pact partner holds.
|
||||
function checkLandingTarget(db, world, op, tgt, type, now, ctx) {
|
||||
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'landing_scan_or_attack_only' });
|
||||
if (type !== 'attack') return;
|
||||
if (!op.alliance_id) throw new GameError('invalid_target', { reason: 'no_alliance' });
|
||||
const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site);
|
||||
denyIfFriendly(db, op, row);
|
||||
}
|
||||
function denyIfFriendly(db, op, row) {
|
||||
if (!row || !row.holder_alliance_id) return;
|
||||
if (row.holder_alliance_id === op.alliance_id) throw new GameError('invalid_target', { reason: 'own_site' });
|
||||
const rel = require('./alliances').relationBetween(db, op.alliance_id, row.holder_alliance_id);
|
||||
if (rel === 'nap' || rel === 'confed') throw new GameError('invalid_target', { reason: 'pact' });
|
||||
}
|
||||
|
||||
// The site changes hands: the attacking operator's alliance holds it now. Level, stockpile and a running build stay.
|
||||
function transferSite(ctx, site, attackerOp, now) {
|
||||
const { db } = ctx;
|
||||
const old = site.holder_alliance_id;
|
||||
db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, taken_at = ? WHERE id = ?', attackerOp.alliance_id, attackerOp.id, now, site.id);
|
||||
const body = { siteId: site.id, index: site.idx, x: site.x, y: site.y, level: site.level, by: allianceInfo(db, attackerOp.alliance_id), from: allianceInfo(db, old) };
|
||||
if (old) notifyAlliance(ctx, old, 'backbone_lost', body);
|
||||
notifyAlliance(ctx, attackerOp.alliance_id, 'backbone_taken', body);
|
||||
maybeWin(ctx, siteRow(db, site.id), now); // a finished node taken while nobody held it completes for the new holder
|
||||
}
|
||||
|
||||
// The holder of a node at maxLevel wins, once per world. Called when a level completes and when such a site changes hands.
|
||||
function maybeWin(ctx, site, now) {
|
||||
const { db } = ctx;
|
||||
if (!site || site.level < E.maxLevel || !site.holder_alliance_id) return false;
|
||||
const world = loadWorld(db, site.world_id);
|
||||
if (!world || world.status === 'ended' || world.winner_alliance_id) return false;
|
||||
const a = allianceInfo(db, site.holder_alliance_id);
|
||||
const endsAt = now + Math.round(E.graceDays * DAY / world.speed);
|
||||
db.run('UPDATE worlds SET winner_alliance_id = ?, winner_name = ?, winner_tag = ?, winner_site_id = ?, won_at = ?, end_at = ? WHERE id = ?', a.allianceId, a.name, a.tag, site.id, now, endsAt, world.id);
|
||||
ctx.enqueue({ worldId: world.id, dueAt: endsAt, type: 'worldEnd', payload: { reason: 'backbone', siteId: site.id } });
|
||||
notifyWorld(ctx, world.id, 'backbone_won', { allianceId: a.allianceId, name: a.name, tag: a.tag, siteId: site.id, endsAt });
|
||||
return true;
|
||||
}
|
||||
|
||||
// An alliance is gone: its sites are the incumbent's again (the level stays with the site).
|
||||
function onAllianceDissolved(ctx, allianceId) {
|
||||
ctx.db.run('UPDATE landing_sites SET holder_alliance_id = NULL WHERE holder_alliance_id = ?', allianceId);
|
||||
}
|
||||
|
||||
// A shipment of resources reached a landing site (called from military/arrivals.arriveTransport). Only the holder alliance's
|
||||
// members may feed the stockpile: if the site changed hands on the way the cargo rides home. -> true when it was stored
|
||||
function deliverShipment(ctx, mv, now) {
|
||||
const { db } = ctx;
|
||||
const site = siteRow(db, mv.extra.siteId);
|
||||
const sender = db.get('SELECT * FROM operators WHERE id = ?', mv.ownerId);
|
||||
const uid = sender ? sender.user_id : null;
|
||||
if (!site || !site.holder_alliance_id || !sender || sender.alliance_id !== site.holder_alliance_id) {
|
||||
if (uid) ctx.notify(uid, mv.worldId, 'backbone_ship_bounced', { movementId: mv.id, siteId: mv.extra.siteId, cargo: mv.cargo });
|
||||
return false;
|
||||
}
|
||||
const c = { fiber: mv.cargo.fiber || 0, hardware: mv.cargo.hardware || 0, capital: mv.cargo.capital || 0 };
|
||||
db.run('UPDATE landing_sites SET fiber = fiber + ?, hardware = hardware + ?, capital = capital + ? WHERE id = ?', c.fiber, c.hardware, c.capital, site.id);
|
||||
db.run(`INSERT INTO landing_contributions (site_id, operator_id, fiber, hardware, capital) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (site_id, operator_id) DO UPDATE SET fiber = fiber + excluded.fiber, hardware = hardware + excluded.hardware, capital = capital + excluded.capital`, site.id, sender.id, c.fiber, c.hardware, c.capital);
|
||||
if (uid) ctx.notify(uid, mv.worldId, 'backbone_delivered', { movementId: mv.id, siteId: site.id, cargo: c });
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DAY, ageDays, phase, isOpen, ensureSites, siteRow, siteAt, siteStates, siteView, allianceInfo, opBrief, winnerView, statusView,
|
||||
guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment,
|
||||
};
|
||||
50
server/endgameQueries.js
Normal file
50
server/endgameQueries.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
'use strict';
|
||||
/* Read models of the end game: world status (the race), the final results, one landing site. Reads catch the event queue up first
|
||||
* and never write (an untouched site has no row yet and shows as the incumbent's, level 0). */
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const { loadWorld } = require('./state');
|
||||
const A = require('./alliances');
|
||||
const E = require('./endgame');
|
||||
|
||||
function createEndgameQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
const world = (id) => { const w = loadWorld(db, id); if (!w) throw new GameError('not_found', { what: 'world' }); return w; };
|
||||
|
||||
function status(userId, worldId) {
|
||||
const now = fresh();
|
||||
return Object.assign({ serverTime: now }, E.statusView(db, world(worldId), now));
|
||||
}
|
||||
|
||||
function results(userId, worldId) {
|
||||
const now = fresh();
|
||||
const w = world(worldId);
|
||||
const row = db.get('SELECT created_at, data FROM world_rankings WHERE world_id = ?', w.id);
|
||||
if (!row) return { serverTime: now, available: false, status: w.status, winner: E.winnerView(w), endsAt: w.won_at ? w.end_at : null, results: null };
|
||||
return { serverTime: now, available: true, status: w.status, winner: E.winnerView(w), endsAt: w.end_at, results: JSON.parse(row.data) };
|
||||
}
|
||||
|
||||
// One site. Holders (members of the holding alliance) also get the contribution ledger and what they may do.
|
||||
function site(userId, siteId) {
|
||||
const now = fresh();
|
||||
const row = E.siteRow(db, siteId);
|
||||
const w = row ? world(row.world_id) : null;
|
||||
const op = w ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, w.id) : null;
|
||||
if (!row || !op || !E.isOpen(w, now)) throw new GameError('not_found', { what: 'landing site' });
|
||||
const s = R.backboneSites(w.seed, w.map_radius).find((x) => x.index === row.idx);
|
||||
const m = A.membership(db, op.id);
|
||||
const holder = !!(m && row.holder_alliance_id && m.alliance_id === row.holder_alliance_id);
|
||||
const out = { serverTime: now, site: E.siteView(db, w, s, row), you: { holder, canBuild: holder && R.allianceCan(m.role, 'backboneBuild'), canShip: holder, canAttack: !!op.alliance_id && !(holder) } };
|
||||
if (holder) {
|
||||
out.contributions = db.all(`SELECT c.operator_id AS oid, o.name AS name, c.fiber, c.hardware, c.capital FROM landing_contributions c JOIN operators o ON o.id = c.operator_id
|
||||
WHERE c.site_id = ? ORDER BY (c.fiber + c.hardware + c.capital) DESC, c.operator_id`, row.id)
|
||||
.map((c) => ({ operatorId: c.oid, name: c.name, fiber: c.fiber, hardware: c.hardware, capital: c.capital }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
return { status, results, site };
|
||||
}
|
||||
|
||||
module.exports = { createEndgameQueries };
|
||||
|
|
@ -56,6 +56,13 @@ const CODES = {
|
|||
recall_expired: [409, 'The recall window (first 90 seconds) has passed.'],
|
||||
capacity_exceeded: [409, 'More than one transport link can carry.'],
|
||||
no_transport_link: [409, 'All transport links are busy (or there is no Internet exchange).'],
|
||||
// trade and end game
|
||||
trade_ratio: [409, 'The offered and the wanted amount may differ by at most 1:2.'],
|
||||
offer_closed: [409, 'That offer is not open any more.'],
|
||||
own_offer: [409, 'You cannot accept your own offer.'],
|
||||
trade_out_of_range: [409, 'That POP is too far from the offer (its max distance or your Internet exchange reach).'],
|
||||
world_ended: [409, 'This world has ended: it can still be read, but nothing can be changed.'],
|
||||
backbone_closed: [409, 'The backbone landing sites have not appeared yet.'],
|
||||
};
|
||||
|
||||
class GameError extends Error {
|
||||
|
|
|
|||
22
server/events/backboneDone.js
Normal file
22
server/events/backboneDone.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use strict';
|
||||
/* A Backbone node level finished. Payload { siteId, toLevel, by }. Idempotent: only acts while the site's build points at THIS
|
||||
* event. The level lands on the SITE (a capture during the build does not stop it); level maxLevel makes the holder alliance the
|
||||
* winner (once per world) and schedules the end of the world. */
|
||||
const D = require('../../public/js/data.js');
|
||||
const { loadWorld } = require('../state');
|
||||
const E = require('../endgame');
|
||||
|
||||
module.exports = function backboneDone(ctx, ev) {
|
||||
const { db } = ctx;
|
||||
const site = E.siteRow(db, ev.payload.siteId);
|
||||
if (!site || site.build_event_id !== ev.id) return;
|
||||
const world = loadWorld(db, site.world_id);
|
||||
if (!world || world.status === 'ended') return;
|
||||
const level = site.build_to;
|
||||
db.run('UPDATE landing_sites SET level = ?, build_to = NULL, build_event_id = NULL, build_started_at = NULL, build_due_at = NULL, build_cost = NULL WHERE id = ?', level, site.id);
|
||||
const fresh = E.siteRow(db, site.id);
|
||||
if (fresh.holder_alliance_id && (level % D.ENDGAME.notifyEvery === 0 || level >= D.ENDGAME.maxLevel)) {
|
||||
E.notifyAlliance(ctx, fresh.holder_alliance_id, 'backbone_level', { siteId: site.id, index: site.idx, level });
|
||||
}
|
||||
E.maybeWin(ctx, fresh, ev.dueAt);
|
||||
};
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
'use strict';
|
||||
/* A building level finished. Payload: { key, type, toLevel, userId }. Idempotent: a level never goes down. */
|
||||
/* A building level finished. Payload: { key, type, toLevel, userId }. Each build event adds exactly ONE level to what the
|
||||
* building is at the moment it finishes (relative, not absolute): exploit kits may have knocked the building down while the
|
||||
* upgrade was in flight, and the finished level must not undo that. Never lowers a level; `toLevel` is the level the
|
||||
* upgrade was queued for and is only an upper bound. Events run once (status), so +1 is safe. */
|
||||
const { loadTown, settle } = require('../state');
|
||||
|
||||
module.exports = function buildDone(ctx, ev) {
|
||||
|
|
@ -9,8 +12,12 @@ module.exports = function buildDone(ctx, ev) {
|
|||
if (!town) return;
|
||||
settle(db, town, ev.dueAt); // values up to the moment of completion, at the OLD rates
|
||||
const cur = town.buildings[key];
|
||||
if (!cur) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, toLevel);
|
||||
else if (cur.level < toLevel) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', toLevel, town.id, key);
|
||||
let level;
|
||||
if (!cur) { level = 1; db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, level); }
|
||||
else {
|
||||
level = cur.level < toLevel ? cur.level + 1 : cur.level;
|
||||
if (level !== cur.level) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', level, town.id, key);
|
||||
}
|
||||
require('../military/power').reschedule(ctx, town.id, ev.dueAt); // building draw / battery cap changed: units' power check
|
||||
if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel });
|
||||
if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level });
|
||||
};
|
||||
|
|
|
|||
|
|
@ -10,4 +10,8 @@ module.exports = {
|
|||
reportCleanup: require('./reportCleanup'),
|
||||
buildDone: require('./buildDone'),
|
||||
diploChange: require('./diploChange'),
|
||||
// trade and end game
|
||||
tradeExpire: require('./tradeExpire'),
|
||||
backboneDone: require('./backboneDone'),
|
||||
worldEnd: require('./worldEnd'),
|
||||
};
|
||||
|
|
|
|||
12
server/events/tradeExpire.js
Normal file
12
server/events/tradeExpire.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
'use strict';
|
||||
/* An open Internet exchange offer ran out of time: the escrow goes back to the POP. Payload { offerId }. Idempotent: acts only
|
||||
* while the offer is still open (accepted/cancelled offers cancel their own expiry event, this is the second line of defence). */
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeExpire(ctx, ev) {
|
||||
const o = T.getOffer(ctx.db, ev.payload.offerId);
|
||||
if (!o || o.status !== 'open') return;
|
||||
T.closeOffer(ctx, o, 'expired', ev.dueAt);
|
||||
const uid = T.userOfOperator(ctx.db, o.operator_id);
|
||||
if (uid) ctx.notify(uid, o.world_id, 'trade_expired', { offerId: o.id, townId: o.town_id, returned: { resource: o.give_res, amount: o.give_amount } });
|
||||
};
|
||||
20
server/events/worldEnd.js
Normal file
20
server/events/worldEnd.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
/* The world ends (two world days after a node reached the last level; payload { reason, siteId }). Stores the final ranking
|
||||
* snapshot, sets status 'ended', gives the escrow of open trade offers back to its POPs, cancels everything still pending in this world (the world is frozen: no arrival, training or
|
||||
* trade changes anything any more; reads keep working) and tells every operator. Idempotent: an ended world is left alone. */
|
||||
const { loadWorld } = require('../state');
|
||||
const E = require('../endgame');
|
||||
const T = require('../trade');
|
||||
const { finalRanking } = require('../finalRanking');
|
||||
|
||||
module.exports = function worldEnd(ctx, ev) {
|
||||
const { db } = ctx;
|
||||
const world = loadWorld(db, ev.worldId);
|
||||
if (!world || world.status === 'ended') return;
|
||||
const snapshot = finalRanking(db, world, ev.dueAt);
|
||||
db.run('INSERT OR REPLACE INTO world_rankings (world_id, created_at, data) VALUES (?, ?, ?)', world.id, ev.dueAt, JSON.stringify(snapshot));
|
||||
db.run("UPDATE worlds SET status = 'ended', end_at = ? WHERE id = ?", ev.dueAt, world.id);
|
||||
for (const o of db.all("SELECT * FROM trade_offers WHERE world_id = ? AND status = 'open'", world.id)) T.closeOffer(ctx, o, 'expired', ev.dueAt); // escrow back in its POP: every unit stays accounted for
|
||||
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE world_id = ? AND status = 'pending' AND id != ?", ev.dueAt, world.id, ev.id);
|
||||
E.notifyWorld(ctx, world.id, 'world_ended', { winner: snapshot.winner, endedAt: ev.dueAt });
|
||||
};
|
||||
49
server/finalRanking.js
Normal file
49
server/finalRanking.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The final ranking snapshot written when a world ends (events/worldEnd.js) and served by GET /worlds/:id/results:
|
||||
* operators by footprint, alliances by the sum over their members, top attackers and defenders by battle points, the winner.
|
||||
* Same footprint numbers as /rankings (socialQueries.footprints), computed at the end time. Top D.ENDGAME.rankingTop per list.
|
||||
*/
|
||||
const D = require('../public/js/data.js');
|
||||
const { createSocialQueries } = require('./socialQueries');
|
||||
const E = require('./endgame');
|
||||
|
||||
const round2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
function finalRanking(db, world, at) {
|
||||
const social = createSocialQueries({ db, clock: { now: () => at }, scheduler: { runDue() {} } });
|
||||
const fp = social.footprints(world.id, at);
|
||||
const top = D.ENDGAME.rankingTop;
|
||||
const ranked = (rows) => rows.slice(0, top).map((r, i) => Object.assign({ rank: i + 1 }, r));
|
||||
|
||||
const ops = db.all('SELECT o.id AS id, o.name AS name, o.as_number AS asn, a.id AS aid, a.tag AS tag FROM operators o LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?', world.id)
|
||||
.map((o) => { const f = fp.get(o.id) || { footprint: 0, towns: 0 }; return { operatorId: o.id, name: o.name, asNumber: o.asn, allianceId: o.aid, allianceTag: o.tag, towns: f.towns, footprint: round2(f.footprint) }; })
|
||||
.sort((x, y) => y.footprint - x.footprint || x.operatorId - y.operatorId);
|
||||
|
||||
const byAlliance = new Map();
|
||||
for (const o of ops) {
|
||||
if (!o.allianceId) continue;
|
||||
const c = byAlliance.get(o.allianceId) || { footprint: 0, members: 0, towns: 0 };
|
||||
c.footprint += o.footprint; c.members += 1; c.towns += o.towns;
|
||||
byAlliance.set(o.allianceId, c);
|
||||
}
|
||||
const alliances = db.all('SELECT id, name, tag FROM alliances WHERE world_id = ?', world.id)
|
||||
.map((a) => { const c = byAlliance.get(a.id) || { footprint: 0, members: 0, towns: 0 }; return { allianceId: a.id, name: a.name, tag: a.tag, members: c.members, towns: c.towns, footprint: round2(c.footprint) }; })
|
||||
.sort((x, y) => y.footprint - x.footprint || x.allianceId - y.allianceId);
|
||||
|
||||
const stats = db.all(`SELECT o.id AS id, o.name AS name, a.tag AS tag, s.attack_points AS att, s.defense_points AS def FROM operator_stats s
|
||||
JOIN operators o ON o.id = s.operator_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?`, world.id)
|
||||
.map((r) => ({ operatorId: r.id, name: r.name, allianceTag: r.tag, attackPoints: round2(r.att || 0), defensePoints: round2(r.def || 0) }));
|
||||
const attackers = stats.filter((r) => r.attackPoints > 0).sort((x, y) => y.attackPoints - x.attackPoints || x.operatorId - y.operatorId);
|
||||
const defenders = stats.filter((r) => r.defensePoints > 0).sort((x, y) => y.defensePoints - x.defensePoints || x.operatorId - y.operatorId);
|
||||
|
||||
const winner = E.winnerView(db.get('SELECT * FROM worlds WHERE id = ?', world.id));
|
||||
const sites = E.siteStates(db, world, at).map(({ site, row }) => E.siteView(db, world, site, row));
|
||||
return {
|
||||
worldId: world.id, at, winner, sites,
|
||||
totals: { operators: ops.length, alliances: alliances.length },
|
||||
operators: ranked(ops), alliances: ranked(alliances), attackers: ranked(attackers), defenders: ranked(defenders),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { finalRanking };
|
||||
|
|
@ -17,7 +17,7 @@ const { TokenBucket, clientIp } = require('./net');
|
|||
const { applySecurityHeaders } = require('./static');
|
||||
|
||||
const MAX_BODY = 32 * 1024;
|
||||
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId']);
|
||||
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId', 'reportId']);
|
||||
|
||||
// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound.
|
||||
class Limiter {
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ const routes = require('./routes');
|
|||
const eventHandlers = require('./events');
|
||||
const { createStaticHandler, applySecurityHeaders } = require('./static');
|
||||
const { parseTrustProxy, parseTrustedProxies, listenDual, listUrls } = require('./net');
|
||||
const { createPush } = require('./push');
|
||||
const { bindGame, pushDeps } = require('./pushHooks');
|
||||
|
||||
function defaultLog(msg) { console.log(new Date().toISOString() + ' ' + msg); }
|
||||
|
||||
|
|
@ -55,6 +57,11 @@ async function createServer(userOpts) {
|
|||
routes.register(api.router, services);
|
||||
api.services = services;
|
||||
|
||||
// WebSocket push on /ws (docs/PROTOCOL.md): hints only, the REST API stays the source of truth and works without it
|
||||
const push = createPush(Object.assign({ clock, authenticate: auth.authenticate, opts: o, log }, pushDeps(db)));
|
||||
bindGame({ push, db, scheduler, commands });
|
||||
services.push = push;
|
||||
|
||||
const serveStatic = createStaticHandler(o.publicDir);
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = req.url || '/';
|
||||
|
|
@ -66,6 +73,7 @@ async function createServer(userOpts) {
|
|||
if (url.startsWith('/api/')) return api.handle(req, res);
|
||||
return serveStatic(req, res).catch((err) => { log('static error: ' + (err && err.message)); if (!res.headersSent) res.writeHead(500); res.end(); });
|
||||
});
|
||||
server.on('upgrade', push.onUpgrade);
|
||||
server.headersTimeout = 20000; server.requestTimeout = 30000; server.keepAliveTimeout = 5000;
|
||||
const sockets = new Set();
|
||||
server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
|
||||
|
|
@ -81,6 +89,7 @@ async function createServer(userOpts) {
|
|||
if (closePromise) return closePromise;
|
||||
closePromise = (async () => {
|
||||
scheduler.stop(); clearInterval(idemTimer);
|
||||
await push.close(); // 1001 to every socket, so server.close() below is not held up
|
||||
await new Promise((r) => { server.close(() => r()); if (server.closeIdleConnections) server.closeIdleConnections(); setTimeout(() => { for (const s of sockets) s.destroy(); }, 1000).unref(); });
|
||||
db.close();
|
||||
})();
|
||||
|
|
|
|||
90
server/migrations/004_trade_endgame.sql
Normal file
90
server/migrations/004_trade_endgame.sql
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
-- Trade (Internet exchange offers), shared report folder, end game (backbone landing sites, winner, final ranking).
|
||||
-- Times are integer ms since the epoch (UTC). Every game row carries world_id.
|
||||
|
||||
-- An offer "give X of A for Y of B, max distance Z". The offered amount is ESCROWED: it left the POP when the offer was
|
||||
-- created and lives in this row until the offer is accepted (it then travels as a transport), cancelled or expired (it goes
|
||||
-- back to the POP). status: open | accepted | completed | cancelled | expired | void (the POP changed hands).
|
||||
CREATE TABLE trade_offers (
|
||||
id INTEGER PRIMARY KEY,
|
||||
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||
town_id INTEGER NOT NULL REFERENCES towns(id), -- the POP that posted it (the escrow came from there)
|
||||
operator_id INTEGER NOT NULL REFERENCES operators(id),
|
||||
give_res TEXT NOT NULL,
|
||||
give_amount INTEGER NOT NULL CHECK (give_amount > 0),
|
||||
want_res TEXT NOT NULL,
|
||||
want_amount INTEGER NOT NULL CHECK (want_amount > 0),
|
||||
max_distance INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'open',
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
expire_event_id INTEGER,
|
||||
accepted_by_operator INTEGER REFERENCES operators(id),
|
||||
accepted_town_id INTEGER REFERENCES towns(id),
|
||||
accepted_at INTEGER,
|
||||
goods_movement_id INTEGER, -- transport poster -> acceptor (the escrow)
|
||||
payment_movement_id INTEGER, -- transport acceptor -> poster
|
||||
legs_done INTEGER NOT NULL DEFAULT 0,
|
||||
closed_at INTEGER
|
||||
);
|
||||
CREATE INDEX trade_offers_open ON trade_offers(world_id, status, id);
|
||||
CREATE INDEX trade_offers_town ON trade_offers(town_id, status);
|
||||
CREATE INDEX trade_offers_operator ON trade_offers(operator_id, id);
|
||||
|
||||
-- Reports shared to an alliance (the shared report folder). Gone with the report (cleanup) or the alliance.
|
||||
CREATE TABLE report_shares (
|
||||
report_id INTEGER NOT NULL REFERENCES reports(id) ON DELETE CASCADE,
|
||||
alliance_id INTEGER NOT NULL REFERENCES alliances(id) ON DELETE CASCADE,
|
||||
shared_by INTEGER NOT NULL REFERENCES operators(id),
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (report_id, alliance_id)
|
||||
);
|
||||
CREATE INDEX report_shares_alliance ON report_shares(alliance_id, report_id);
|
||||
|
||||
-- Backbone landing sites (end game). Positions are a pure function of the world seed (rules.backboneSites); a row is
|
||||
-- created lazily by whatever touches a site first once the world is at day D.ENDGAME.openDay (no timer event). holder_alliance_id NULL = still held by the incumbent
|
||||
-- (or the holder disbanded: the level stays with the site). `fiber/hardware/capital` is the stockpile shipped in by the holders
|
||||
-- for the next level. build_* describe the level being built (one at a time).
|
||||
CREATE TABLE landing_sites (
|
||||
id INTEGER PRIMARY KEY,
|
||||
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||
idx INTEGER NOT NULL,
|
||||
x INTEGER NOT NULL,
|
||||
y INTEGER NOT NULL,
|
||||
holder_alliance_id INTEGER REFERENCES alliances(id) ON DELETE SET NULL,
|
||||
holder_operator_id INTEGER REFERENCES operators(id), -- who took it
|
||||
taken_at INTEGER,
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
fiber INTEGER NOT NULL DEFAULT 0,
|
||||
hardware INTEGER NOT NULL DEFAULT 0,
|
||||
capital INTEGER NOT NULL DEFAULT 0,
|
||||
build_to INTEGER,
|
||||
build_event_id INTEGER,
|
||||
build_started_at INTEGER,
|
||||
build_due_at INTEGER,
|
||||
build_cost TEXT,
|
||||
UNIQUE (world_id, idx),
|
||||
UNIQUE (world_id, x, y)
|
||||
);
|
||||
|
||||
-- What each operator shipped into a site's stockpile (kept when the site changes hands: it is a ledger, not a balance).
|
||||
CREATE TABLE landing_contributions (
|
||||
site_id INTEGER NOT NULL REFERENCES landing_sites(id),
|
||||
operator_id INTEGER NOT NULL REFERENCES operators(id),
|
||||
fiber INTEGER NOT NULL DEFAULT 0,
|
||||
hardware INTEGER NOT NULL DEFAULT 0,
|
||||
capital INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (site_id, operator_id)
|
||||
);
|
||||
|
||||
-- The winner and the end of the world. The ranking snapshot is written once, when the world enters status 'ended'.
|
||||
ALTER TABLE worlds ADD COLUMN winner_alliance_id INTEGER;
|
||||
ALTER TABLE worlds ADD COLUMN winner_name TEXT;
|
||||
ALTER TABLE worlds ADD COLUMN winner_tag TEXT;
|
||||
ALTER TABLE worlds ADD COLUMN winner_site_id INTEGER;
|
||||
ALTER TABLE worlds ADD COLUMN won_at INTEGER;
|
||||
|
||||
CREATE TABLE world_rankings (
|
||||
world_id INTEGER PRIMARY KEY REFERENCES worlds(id),
|
||||
created_at INTEGER NOT NULL,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
|
|
@ -72,6 +72,8 @@ function arriveReinforce(ctx, mv, ev) {
|
|||
function arriveTransport(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
// A shipment to a backbone landing site (extra.siteId) feeds the site's stockpile; refused ones ride home like any undeliverable cargo.
|
||||
const siteDelivered = !!(mv.extra && mv.extra.siteId) && require('../endgame').deliverShipment(ctx, mv, now);
|
||||
const target = mv.toTownId ? loadTown(db, mv.toTownId) : null;
|
||||
let lost = {};
|
||||
if (target) {
|
||||
|
|
@ -82,7 +84,7 @@ function arriveTransport(ctx, mv, ev) {
|
|||
if (sender && sender !== receiver) ctx.notify(sender, mv.worldId, 'transport_delivered', { movementId: mv.id, toTownId: target.id, cargo: mv.cargo, cargoLost: lost });
|
||||
for (const fn of M.hooks.transportArrived) fn(ctx, mv, { added: mv.cargo, lost });
|
||||
}
|
||||
const cargoBack = target ? {} : mv.cargo; // no such POP any more: the cargo rides home with the carriers
|
||||
const cargoBack = target || siteDelivered ? {} : mv.cargo; // no such POP any more: the cargo rides home with the carriers
|
||||
// The empty carriers drive back; the link is busy until they are home.
|
||||
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||
if (dest) {
|
||||
|
|
@ -99,12 +101,12 @@ function arriveSettle(ctx, mv, ev) {
|
|||
const world = loadWorld(db, mv.worldId);
|
||||
const op = U.getOperator(db, mv.ownerId);
|
||||
const { x, y } = mv.to;
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
const occupied = !!db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
|
||||
const own = U.operatorTowns(db, op.id);
|
||||
let nearest = Infinity;
|
||||
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||
const chk = R.settleCheck({ tileType: tile.type, occupied, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
|
||||
const chk = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), occupied, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
|
||||
if (!chk.ok) return bounce(ctx, mv, now, chk.code, chk);
|
||||
const wild = R.cleanWild(mv.extra.wild);
|
||||
const name = op.name + ' POP ' + (own.length + 1);
|
||||
|
|
|
|||
|
|
@ -211,7 +211,8 @@ function resolveScanOnTown(ctx, mv, now, s) {
|
|||
function arriveSite(ctx, mv, now, world) {
|
||||
const { db } = ctx;
|
||||
const { x, y } = mv.to;
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
if (tile.type === 'backbone') return require('./landing')(ctx, mv, now, world, tile); // end game: backbone landing site
|
||||
if (tile.type !== 'incumbent' || (mv.type !== 'scan' && mv.type !== 'attack')) return bounce(ctx, mv, now, 'invalid_target');
|
||||
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||
const ageDays = Math.max(0, (now - world.start_at) / DAY * world.speed);
|
||||
|
|
@ -274,6 +275,7 @@ function transferTown(ctx, town, newOp, oldOp, now) {
|
|||
if (home.id === g.hostTownId) U.addHome(db, home.id, g.units); else U.addStationed(db, g.hostTownId, home.id, g.units);
|
||||
}
|
||||
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
||||
require('../trade').onTownTransferred(ctx, town.id, now); // open Internet exchange offers of the old owner end, the escrow stays in the POP
|
||||
const oldUser = U.userOfOperator(db, oldOp.id), newUser = U.userOfOperator(db, newOp.id);
|
||||
if (oldUser) ctx.notify(oldUser, town.worldId, 'town_lost', { townId: town.id, name: town.name, by: opBrief(newOp) });
|
||||
if (newUser) ctx.notify(newUser, town.worldId, 'town_gained', { townId: town.id, name: town.name });
|
||||
|
|
|
|||
67
server/military/landing.js
Normal file
67
server/military/landing.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Arrival of a scan or an attack at a backbone landing site (hooked from combat.arriveSite, runs inside the `arrive` event).
|
||||
* A site is defended by a static value only: rules.backboneDefence(seed, x, y, world age, node level). Beating it as a member
|
||||
* of an alliance makes that alliance the holder (level, stockpile and a running build stay with the site). The site never
|
||||
* loses anything, so there is no loot and no raid; survivors drive home. Re-validates at arrival like every movement.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const U = require('./units');
|
||||
const M = require('./movements');
|
||||
const E = require('../endgame');
|
||||
const { createReport } = require('./reports');
|
||||
const { bounce, townBrief, opBrief } = require('./arrivals');
|
||||
|
||||
const SCAN_STRENGTH = D.ENDGAME.scanStrength; // a landing site counts as this many defending scanners
|
||||
|
||||
function sendHome(ctx, mv, survivors) {
|
||||
if (U.isEmpty(survivors)) return null;
|
||||
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
|
||||
if (!dest) return null;
|
||||
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at: mv.to, to: dest, units: survivors, cargo: {}, parentId: mv.id, extra: {} });
|
||||
}
|
||||
|
||||
module.exports = function arriveLanding(ctx, mv, now, world, tile) {
|
||||
const { db } = ctx;
|
||||
if (mv.type !== 'scan' && mv.type !== 'attack') return bounce(ctx, mv, now, 'invalid_target');
|
||||
const rows = E.ensureSites(db, world, now, ctx);
|
||||
const site = rows.find((r) => r.idx === tile.site);
|
||||
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||
const uid = U.userOfOperator(db, attackerOp.id);
|
||||
const where = { x: site.x, y: site.y, index: site.idx, siteId: site.id, level: site.level, holder: E.allianceInfo(db, site.holder_alliance_id) };
|
||||
const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level);
|
||||
|
||||
if (mv.type === 'scan') {
|
||||
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||
const res = R.resolveScan(sa, SCAN_STRENGTH);
|
||||
const loss = R.applyLoss(mv.units, res.lossFraction);
|
||||
const intel = res.success ? { defence: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null } : null;
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site: Object.assign({ type: 'backbone' }, where) },
|
||||
data: { success: res.success, detail: res.detail, site: Object.assign({ type: 'backbone' }, where), scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
|
||||
recipients: [{ userId: uid, role: 'attacker' }],
|
||||
});
|
||||
sendHome(ctx, mv, loss.survivors);
|
||||
return;
|
||||
}
|
||||
|
||||
// attack: alliance members only, and not against the own alliance or a pact partner (the world may have changed since it left)
|
||||
if (!attackerOp.alliance_id) return bounce(ctx, mv, now, 'no_alliance');
|
||||
try { E.denyIfFriendly(db, attackerOp, site); } catch (e) { return bounce(ctx, mv, now, e.details.reason || 'invalid_target'); }
|
||||
|
||||
const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef });
|
||||
const survivors = Object.assign({}, b.attacker.survivors);
|
||||
const oldHolder = site.holder_alliance_id;
|
||||
if (b.attackerWins) E.transferSite(ctx, site, attackerOp, now);
|
||||
const ret = sendHome(ctx, mv, survivors);
|
||||
const data = {
|
||||
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site: Object.assign({ type: 'backbone' }, where), origin: townBrief(origin),
|
||||
attacker: { operator: opBrief({ id: attackerOp.id, name: attackerOp.name, as_number: attackerOp.as_number }), alliance: E.allianceInfo(db, attackerOp.alliance_id), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
|
||||
power: { attack: b.A, defence: b.D }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null,
|
||||
};
|
||||
const recipients = [{ userId: uid, role: 'attacker' }];
|
||||
if (oldHolder) for (const m of db.all('SELECT o.user_id AS uid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', oldHolder)) recipients.push({ userId: m.uid, role: 'defender' });
|
||||
createReport(ctx, { worldId: mv.worldId, type: 'landing', now, summary: { outcome: data.outcome, site: data.site, attacker: data.attacker.operator, taken: b.attackerWins }, data, recipients });
|
||||
};
|
||||
|
|
@ -46,10 +46,12 @@ function launchReturn(ctx, o) {
|
|||
});
|
||||
}
|
||||
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports.
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports, plus the
|
||||
// open Internet exchange offers it posted (an open offer holds a link in reserve: accepting it sends the escrow on that link).
|
||||
function activeLinks(db, townId) {
|
||||
return db.get(`SELECT COUNT(*) AS n FROM movements WHERE status = 'out' AND
|
||||
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n;
|
||||
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n
|
||||
+ db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", townId).n;
|
||||
}
|
||||
|
||||
// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }).
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ function ownerView(m, names) {
|
|||
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
|
||||
units: j(m.units), cargo: j(m.cargo), departAt: m.depart_at, arriveAt: m.arrive_at,
|
||||
recallableUntil: m.type === 'return' ? null : m.depart_at + D.MILITARY.recallWindowMs,
|
||||
target: extra.target || null, parentId: m.parent_id,
|
||||
target: extra.target || null, parentId: m.parent_id, siteId: extra.siteId || null, // siteId: a shipment to a backbone landing site
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -55,8 +55,27 @@ function movementLists(db, operatorId, townId) {
|
|||
const inc = db.all(`SELECT m.* FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id = ? AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return'
|
||||
${townId ? 'AND m.to_town_id = ?' : ''} ORDER BY m.arrive_at, m.id LIMIT ?`,
|
||||
...(townId ? [operatorId, operatorId, townId, D.MILITARY.maxLists] : [operatorId, operatorId, D.MILITARY.maxLists]));
|
||||
const names = townNames(db, own.concat(inc).flatMap((m) => [m.from_town_id, m.to_town_id]));
|
||||
return { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
|
||||
// Confederation members (own alliance included) see what is heading for each other's POPs: origin and ETA only, the type
|
||||
// stays hidden. Movements of operators who are themselves partners of the target are friendly traffic and left out.
|
||||
// Only in the whole-operator list, not in the per-POP lists.
|
||||
let allied = [];
|
||||
if (!townId) {
|
||||
const partners = require('../alliances').confederatedOperators(db, operatorId);
|
||||
if (partners.length) {
|
||||
allied = db.all(`SELECT m.*, t.owner_id AS target_owner FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id IN (${partners.map(() => '?').join(',')})
|
||||
AND m.owner_id != t.owner_id AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return' ORDER BY m.arrive_at, m.id LIMIT ?`, ...partners, operatorId, D.MILITARY.maxLists)
|
||||
.filter((m) => !U.pactBlocks(db, m.owner_id, m.target_owner));
|
||||
}
|
||||
}
|
||||
const names = townNames(db, own.concat(inc, allied).flatMap((m) => [m.from_town_id, m.to_town_id]));
|
||||
const out = { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
|
||||
if (!townId) {
|
||||
out.alliedIncoming = allied.map((m) => {
|
||||
const o = db.get('SELECT id, name FROM operators WHERE id = ?', m.target_owner);
|
||||
return Object.assign(incomingView(m, names), { ally: true, toOperator: { id: o.id, name: o.name } });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
|
||||
|
|
@ -127,7 +146,7 @@ function createMilitaryQueries({ db, clock, scheduler }) {
|
|||
const now = fresh();
|
||||
const op = operatorFor(userId, worldId);
|
||||
const world = loadWorld(db, op.world_id);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
if (tile.type === 'void') throw new GameError('not_found', { what: 'tile' });
|
||||
const row = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
|
||||
const mine = U.operatorTowns(db, op.id);
|
||||
|
|
@ -140,11 +159,18 @@ function createMilitaryQueries({ db, clock, scheduler }) {
|
|||
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, op.id);
|
||||
out.incumbent = { takenByYou: taken, hardwareBonus: taken ? 0 : D.INCUMBENT.hardwareBonus };
|
||||
}
|
||||
if (tile.type === 'backbone') { // end game: who holds the site, its node level and stockpile, whether you could attack it
|
||||
const E = require('../endgame');
|
||||
const st = E.siteStates(db, world, now).find((s) => s.site.index === tile.site);
|
||||
const v = E.siteView(db, world, st.site, st.row);
|
||||
const holds = !!(op.alliance_id && v.holder && v.holder.allianceId === op.alliance_id);
|
||||
out.backbone = { siteId: v.id, index: v.index, holder: v.holder, level: v.level, maxLevel: v.maxLevel, pool: v.pool, build: v.build, mine: holds, canAttack: !!op.alliance_id && !holds };
|
||||
}
|
||||
const fp = U.operatorFootprint(db, op.id, now);
|
||||
const gate = R.footprintGate(mine.length, fp);
|
||||
let nearest = Infinity;
|
||||
for (const t of mine) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||
const sc = R.settleCheck({ tileType: tile.type, occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp });
|
||||
const sc = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp });
|
||||
out.settle = { possible: sc.ok, code: sc.ok ? null : sc.code, footprint: fp, footprintNeeded: gate.need, maxDistance: D.EXPANSION.maxDistance };
|
||||
return out;
|
||||
}
|
||||
|
|
|
|||
201
server/push.js
Normal file
201
server/push.js
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
'use strict';
|
||||
/*
|
||||
* WebSocket push (stage 6): transport and connection registry only, no game knowledge (that lives in pushHooks.js).
|
||||
* Push is a HINT: small JSON messages saying "something changed, refetch over REST". See docs/PROTOCOL.md.
|
||||
*
|
||||
* const push = createPush({ clock, authenticate, tokenValid, townOwner, opts, log });
|
||||
* httpServer.on('upgrade', push.onUpgrade);
|
||||
* push.toUser(userId, { type: 'town', townId: 7 }); // all sockets of that user
|
||||
* push.toTown(7, { type: 'town', townId: 7 }); // the user who owns POP 7 right now
|
||||
* await push.close(); // 1001 to everybody, resolves when the sockets are gone
|
||||
*
|
||||
* Deps: authenticate(header, now) -> { user, tokenId } | null (auth.authenticate), tokenValid(tokenId) -> bool (re-checked on
|
||||
* every ping tick: revoked token or banned user), townOwner(townId) -> userId | null, opts (the createServer options:
|
||||
* trustProxy, trustedProxies, allowedOrigins, maxConnPerIp, optional wsAuthTimeoutMs / wsPingMs / wsRate / wsBurst / wsBadBudget).
|
||||
*/
|
||||
const { WebSocketServer } = require('ws');
|
||||
const { originAllowed, clientIp, TokenBucket } = require('./net');
|
||||
|
||||
const CLOSE = { SHUTDOWN: 1001, BAD_MESSAGES: 4400, UNAUTHORIZED: 4401, AUTH_TIMEOUT: 4408, RATE_LIMITED: 4429 };
|
||||
const MAX_PAYLOAD = 1024; // bytes per client message
|
||||
const MAX_BUFFERED = 1024 * 1024; // a client that does not read 1 MB of hints is dead weight
|
||||
|
||||
function createPush(deps) {
|
||||
const { clock, authenticate, tokenValid, townOwner, opts } = deps;
|
||||
const log = deps.log || (() => {});
|
||||
const cfg = {
|
||||
authTimeoutMs: opts.wsAuthTimeoutMs || 10000, pingMs: opts.wsPingMs || 30000,
|
||||
rate: opts.wsRate || 5, burst: opts.wsBurst || 15, badBudget: opts.wsBadBudget || 5,
|
||||
maxConnPerIp: opts.maxConnPerIp === undefined ? 40 : opts.maxConnPerIp, closeGraceMs: 1000,
|
||||
};
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false, clientTracking: false });
|
||||
const conns = new Set();
|
||||
const byUser = new Map(); // userId -> Set<conn> (authenticated sockets)
|
||||
const perIp = new Map(); // ip -> open sockets (also not yet authenticated ones)
|
||||
let closing = false;
|
||||
|
||||
// ------------------------------------------------------------ upgrade
|
||||
function refuse(socket, status, text, why) {
|
||||
log('refused ws ' + why);
|
||||
try { socket.write('HTTP/1.1 ' + status + ' ' + text + '\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); } catch (e) { /* gone */ }
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
function onUpgrade(req, socket, head) {
|
||||
socket.on('error', () => {}); // a reset during the handshake must not crash the process
|
||||
let pathname = '';
|
||||
try { pathname = new URL(req.url || '/', 'http://x').pathname; } catch (e) { /* stays '' */ }
|
||||
const ip = clientIp(req, opts.trustProxy, opts.trustedProxies);
|
||||
if (pathname !== '/ws') return refuse(socket, 404, 'Not Found', 'path=' + JSON.stringify(pathname.slice(0, 60)) + ' ip=' + ip);
|
||||
if (closing) return refuse(socket, 503, 'Service Unavailable', 'shutting down ip=' + ip);
|
||||
if (!originAllowed(req, opts)) return refuse(socket, 403, 'Forbidden', 'origin=' + JSON.stringify(String(req.headers.origin).slice(0, 100)) + ' ip=' + ip);
|
||||
if (cfg.maxConnPerIp > 0 && (perIp.get(ip) || 0) >= cfg.maxConnPerIp) return refuse(socket, 429, 'Too Many Requests', 'conn_cap ip=' + ip + ' max=' + cfg.maxConnPerIp);
|
||||
// handleUpgrade calls back synchronously on success and not at all when the handshake is malformed, so the per-IP
|
||||
// count is taken in the callback: nothing can leak it.
|
||||
wss.handleUpgrade(req, socket, head, (ws) => accept(ws, ip));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ connections
|
||||
function accept(ws, ip) {
|
||||
perIp.set(ip, (perIp.get(ip) || 0) + 1);
|
||||
const c = {
|
||||
ws, ip, userId: null, tokenId: null, alive: true, bad: 0, bucket: new TokenBucket(cfg.rate, cfg.burst),
|
||||
out: new Map(), flushing: false, authTimer: null, killTimer: null, gone: false,
|
||||
};
|
||||
conns.add(c);
|
||||
if (ws._socket && ws._socket.setNoDelay) ws._socket.setNoDelay(true);
|
||||
c.authTimer = setTimeout(() => { log('ws closed auth_timeout ip=' + ip); closeConn(c, CLOSE.AUTH_TIMEOUT, 'auth_timeout'); }, cfg.authTimeoutMs);
|
||||
ws.on('message', (data, isBinary) => onMessage(c, data, isBinary));
|
||||
ws.on('pong', () => { c.alive = true; });
|
||||
ws.on('error', (err) => { log('ws error ip=' + ip + ': ' + (err && err.message)); }); // 'close' follows
|
||||
ws.on('close', () => drop(c));
|
||||
}
|
||||
|
||||
function drop(c) {
|
||||
if (c.gone) return;
|
||||
c.gone = true;
|
||||
clearTimeout(c.authTimer); clearTimeout(c.killTimer);
|
||||
conns.delete(c);
|
||||
const n = (perIp.get(c.ip) || 1) - 1;
|
||||
if (n > 0) perIp.set(c.ip, n); else perIp.delete(c.ip);
|
||||
if (c.userId !== null) {
|
||||
const set = byUser.get(c.userId);
|
||||
if (set) { set.delete(c); if (!set.size) byUser.delete(c.userId); }
|
||||
}
|
||||
}
|
||||
|
||||
function closeConn(c, code, reason) {
|
||||
if (c.gone || c.closing) return;
|
||||
c.closing = true;
|
||||
try { c.ws.close(code, reason); } catch (e) { try { c.ws.terminate(); } catch (e2) { /* gone */ } }
|
||||
c.killTimer = setTimeout(() => { try { c.ws.terminate(); } catch (e) { /* gone */ } }, cfg.closeGraceMs);
|
||||
if (c.killTimer.unref) c.killTimer.unref();
|
||||
}
|
||||
|
||||
function sendNow(c, obj) {
|
||||
if (c.gone || c.closing || c.ws.readyState !== 1) return false;
|
||||
if (c.ws.bufferedAmount > MAX_BUFFERED) { log('ws terminated: client not reading ip=' + c.ip); c.ws.terminate(); return false; }
|
||||
c.ws.send(JSON.stringify(obj));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Hints are coalesced: identical messages produced in the same tick (many events of one catch-up) go out once.
|
||||
function queue(c, msg) {
|
||||
if (c.userId === null || c.gone || c.closing) return;
|
||||
c.out.set(JSON.stringify(msg), true);
|
||||
if (!c.flushing) { c.flushing = true; setImmediate(() => flush(c)); }
|
||||
}
|
||||
|
||||
function flush(c) {
|
||||
c.flushing = false;
|
||||
const items = c.out; c.out = new Map();
|
||||
if (c.gone || c.closing || c.ws.readyState !== 1) return;
|
||||
for (const text of items.keys()) {
|
||||
if (c.ws.bufferedAmount > MAX_BUFFERED) { log('ws terminated: client not reading ip=' + c.ip); c.ws.terminate(); return; }
|
||||
c.ws.send(text);
|
||||
}
|
||||
}
|
||||
|
||||
function bad(c, why) {
|
||||
c.bad++;
|
||||
log('ws bad message (' + why + ') ip=' + c.ip + ' user=' + c.userId + ' ' + c.bad + '/' + cfg.badBudget);
|
||||
if (c.bad >= cfg.badBudget) closeConn(c, CLOSE.BAD_MESSAGES, 'too_many_bad_messages');
|
||||
}
|
||||
|
||||
function onMessage(c, data, isBinary) {
|
||||
if (c.gone || c.closing) return;
|
||||
c.alive = true;
|
||||
if (!c.bucket.take()) { log('refused ws rate_limited ip=' + c.ip + ' user=' + c.userId); return closeConn(c, CLOSE.RATE_LIMITED, 'rate_limited'); }
|
||||
let m = null;
|
||||
if (!isBinary) { try { m = JSON.parse(data.toString('utf8')); } catch (e) { m = null; } }
|
||||
const ok = m && typeof m === 'object' && !Array.isArray(m) && typeof m.type === 'string';
|
||||
|
||||
if (c.userId === null) { // the FIRST message must authenticate; anything else is fatal
|
||||
if (!ok || m.type !== 'auth') { log('refused ws unauthorized (first message is not auth) ip=' + c.ip); return closeConn(c, CLOSE.UNAUTHORIZED, 'auth_required'); }
|
||||
const a = typeof m.token === 'string' && m.token.length <= 200 ? authenticate('Bearer ' + m.token, clock.now()) : null;
|
||||
if (!a) { log('refused ws unauthorized (bad token) ip=' + c.ip); return closeConn(c, CLOSE.UNAUTHORIZED, 'invalid_token'); }
|
||||
clearTimeout(c.authTimer); c.authTimer = null;
|
||||
c.userId = a.user.id; c.tokenId = a.tokenId;
|
||||
let set = byUser.get(c.userId);
|
||||
if (!set) { set = new Set(); byUser.set(c.userId, set); }
|
||||
set.add(c);
|
||||
sendNow(c, { type: 'ready', serverTime: clock.now() });
|
||||
return;
|
||||
}
|
||||
if (!ok) return bad(c, isBinary ? 'binary' : 'not a JSON object with a type');
|
||||
if (m.type === 'ping') { sendNow(c, { type: 'pong', serverTime: clock.now() }); return; }
|
||||
return bad(c, 'unknown type ' + JSON.stringify(m.type.slice(0, 20)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ keepalive + revocation
|
||||
function tick() {
|
||||
for (const c of conns) {
|
||||
if (c.gone || c.closing) continue;
|
||||
if (!c.alive) { log('ws dead, terminating ip=' + c.ip + ' user=' + c.userId); try { c.ws.terminate(); } catch (e) { /* gone */ } continue; }
|
||||
if (c.tokenId !== null) {
|
||||
let valid = true;
|
||||
try { valid = tokenValid(c.tokenId); } catch (e) { log('ws token check failed: ' + e.message); }
|
||||
if (!valid) { log('ws closed token_revoked user=' + c.userId); closeConn(c, CLOSE.UNAUTHORIZED, 'token_revoked'); continue; }
|
||||
}
|
||||
c.alive = false;
|
||||
try { c.ws.ping(); } catch (e) { /* closing */ }
|
||||
}
|
||||
}
|
||||
const timer = setInterval(tick, cfg.pingMs);
|
||||
if (timer.unref) timer.unref();
|
||||
|
||||
// ------------------------------------------------------------ public API
|
||||
function toUser(userId, msg) {
|
||||
const set = byUser.get(userId);
|
||||
if (set) for (const c of set) queue(c, msg);
|
||||
}
|
||||
|
||||
function toTown(townId, msg) {
|
||||
if (!byUser.size) return; // nobody connected: no lookup
|
||||
const owner = townOwner(townId);
|
||||
if (owner) toUser(owner, msg);
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (closing) return closing_;
|
||||
closing = true;
|
||||
clearInterval(timer);
|
||||
closing_ = new Promise((resolve) => {
|
||||
for (const c of conns) { if (c.flushing) flush(c); closeConn(c, CLOSE.SHUTDOWN, 'shutdown'); }
|
||||
const done = () => { wss.close(); resolve(); };
|
||||
if (!conns.size) return done();
|
||||
const wait = setInterval(() => { if (!conns.size) { clearInterval(wait); done(); } }, 10);
|
||||
setTimeout(() => { for (const c of conns) { try { c.ws.terminate(); } catch (e) { /* gone */ } } }, cfg.closeGraceMs + 50).unref();
|
||||
});
|
||||
return closing_;
|
||||
}
|
||||
let closing_ = null;
|
||||
|
||||
return {
|
||||
onUpgrade, toUser, toTown, close,
|
||||
stats: () => ({ connections: conns.size, users: byUser.size, ips: perIp.size }),
|
||||
CLOSE,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createPush, CLOSE, MAX_PAYLOAD };
|
||||
84
server/pushHooks.js
Normal file
84
server/pushHooks.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The game-aware half of push: which hint goes to whom. push.js knows sockets; this file knows notifications, events and
|
||||
* commands. Hooks fire only AFTER the transaction that caused them committed (scheduler outbox, commands.run).
|
||||
*
|
||||
* notification row (any kind) -> user: {type:'notification', id, kind}
|
||||
* kind incoming -> user: {type:'incoming', townId, arriveAt}
|
||||
* kind report -> user: {type:'report', id}
|
||||
* kind message | alliance_message -> user: {type:'message', id}
|
||||
* town_lost, town_gained, ... -> user: {type:'town', townId} (ownership changed: the old owner is not
|
||||
* reachable through toTown any more)
|
||||
* event done (build, train, research, arrive, return ...) -> owner of every POP it touched: {type:'town', townId}
|
||||
* command done (build, train, send, ...) -> owner of every POP it touched: {type:'town', townId}
|
||||
* (also the device that issued it: the client may ignore its own echo; other devices of the user learn from it)
|
||||
*
|
||||
* Not a hint source: reading (GET) never pushes.
|
||||
*/
|
||||
|
||||
const isId = (v) => Number.isInteger(v) && v > 0;
|
||||
|
||||
// notification kind -> payload key holding a POP id whose state changed for THAT user (kinds whose event does not already
|
||||
// carry the town in events.town_id, or whose owner changed)
|
||||
const TOWN_KINDS = {
|
||||
town_lost: 'townId', town_gained: 'townId',
|
||||
transport_arrived: 'townId', transport_delivered: 'toTownId',
|
||||
movement_returned: 'townId', reinforcements_sent_home: 'ownerTownId',
|
||||
};
|
||||
|
||||
// Command args that name a POP the command changed (the receiving POP of a movement is NOT listed: the defender gets
|
||||
// an 'incoming' hint, never a plain 'town' one that would give the launch away without its ETA).
|
||||
const COMMAND_TOWN_KEYS = ['townId', 'fromTownId', 'hostTownId', 'ownerTownId'];
|
||||
|
||||
// Deps for createPush that need the database.
|
||||
function pushDeps(db) {
|
||||
const owner = 'SELECT o.user_id AS uid FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?';
|
||||
const valid = 'SELECT 1 AS ok FROM tokens t JOIN users u ON u.id = t.user_id WHERE t.id = ? AND t.revoked_at IS NULL AND u.banned = 0';
|
||||
return {
|
||||
townOwner: (townId) => { const r = db.get(owner, townId); return r ? r.uid : null; },
|
||||
tokenValid: (tokenId) => !!db.get(valid, tokenId),
|
||||
};
|
||||
}
|
||||
|
||||
function bindGame({ push, db, scheduler, commands, log }) {
|
||||
const toTowns = (ids) => { for (const id of ids) push.toTown(id, { type: 'town', townId: id }); };
|
||||
|
||||
function movementTowns(movementId, ids) {
|
||||
if (!isId(movementId)) return;
|
||||
const mv = db.get('SELECT from_town_id AS f, to_town_id AS t FROM movements WHERE id = ?', movementId);
|
||||
if (mv) { if (isId(mv.f)) ids.add(mv.f); if (isId(mv.t)) ids.add(mv.t); }
|
||||
}
|
||||
|
||||
// ---- notifications: written by events and commands via scheduler.notify
|
||||
scheduler.onNotify = (n) => {
|
||||
const p = n.payload || {};
|
||||
push.toUser(n.userId, { type: 'notification', id: n.id, kind: n.type });
|
||||
if (n.type === 'incoming' && isId(p.toTownId)) push.toUser(n.userId, { type: 'incoming', townId: p.toTownId, arriveAt: p.arriveAt });
|
||||
else if (n.type === 'report' && isId(p.reportId)) push.toUser(n.userId, { type: 'report', id: p.reportId });
|
||||
else if ((n.type === 'message' || n.type === 'alliance_message') && isId(p.messageId)) push.toUser(n.userId, { type: 'message', id: p.messageId });
|
||||
const key = TOWN_KINDS[n.type];
|
||||
if (key && isId(p[key])) push.toUser(n.userId, { type: 'town', townId: p[key] });
|
||||
};
|
||||
|
||||
// ---- events: the POPs an event touched (events.town_id, or both ends of a movement)
|
||||
const prevOnEvent = scheduler.onEvent;
|
||||
scheduler.onEvent = (ev) => {
|
||||
if (prevOnEvent) prevOnEvent(ev);
|
||||
const ids = new Set();
|
||||
if (isId(ev.townId)) ids.add(ev.townId);
|
||||
if (ev.type === 'arrive' || ev.type === 'return') movementTowns(ev.payload && ev.payload.movementId, ids);
|
||||
toTowns(ids);
|
||||
};
|
||||
|
||||
// ---- commands
|
||||
commands.hooks.onCommand = (name, args, out) => {
|
||||
const ids = new Set();
|
||||
for (const k of COMMAND_TOWN_KEYS) if (args && isId(args[k])) ids.add(args[k]);
|
||||
if (out && isId(out.townId)) ids.add(out.townId); // joinWorld: the new POP
|
||||
if (name === 'recallMovement') movementTowns(args.movementId, ids); // also tells the target's owner the warning is gone
|
||||
toTowns(ids);
|
||||
};
|
||||
if (log) log('push hooks bound');
|
||||
}
|
||||
|
||||
module.exports = { bindGame, pushDeps, TOWN_KINDS, COMMAND_TOWN_KEYS };
|
||||
|
|
@ -89,10 +89,16 @@ function createQueries({ db, clock, scheduler }) {
|
|||
r = Math.min(r, 40);
|
||||
const x0 = Math.max(-rad, x - r), x1 = Math.min(rad, x + r), y0 = Math.max(-rad, y - r), y1 = Math.min(rad, y + r);
|
||||
const specials = [];
|
||||
const age = R.worldAgeDays(world.start_at, now, world.speed);
|
||||
const sites = new Map(require('./endgame').siteStates(db, world, now).map(({ site, row }) => [site.index, require('./endgame').siteView(db, world, site, row)]));
|
||||
for (let yy = y0; yy <= y1; yy++) {
|
||||
for (let xx = x0; xx <= x1; xx++) {
|
||||
const t = R.tileAt(world.seed, rad, xx, yy);
|
||||
const t = R.tileAt(world.seed, rad, xx, yy, age);
|
||||
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
|
||||
else if (t.type === 'backbone') { // end game: landing site with its holder and node level
|
||||
const v = sites.get(t.site);
|
||||
specials.push({ x: xx, y: yy, type: 'backbone', bonus: null, site: { id: v.id, index: v.index, holder: v.holder, level: v.level, maxLevel: v.maxLevel } });
|
||||
}
|
||||
}
|
||||
}
|
||||
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, a.tag AS atag, a.name AS aname, o.protection_until AS prot
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
'use strict';
|
||||
/* Registers every REST route. One file per resource; each exports register(router, services). */
|
||||
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports')];
|
||||
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports'), require('./sharedReports'), require('./trade'), require('./world')];
|
||||
|
||||
function register(router, services) {
|
||||
for (const f of files) f.register(router, services);
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ const schemas = {
|
|||
}),
|
||||
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
|
||||
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }),
|
||||
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }),
|
||||
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] }, site: { type: 'object', additionalProperties: true } }, ['x', 'y', 'type', 'bonus']),
|
||||
MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }),
|
||||
BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }),
|
||||
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
|
||||
|
|
@ -78,5 +78,6 @@ const schemas = {
|
|||
};
|
||||
|
||||
require('./schemasMilitary')(schemas, { int, num, str, bool, obj, arr });
|
||||
require('./schemasEndgame')(schemas, { int, num, str, bool, obj, arr });
|
||||
|
||||
module.exports = { schemas, int, num, str, bool, obj, arr };
|
||||
|
|
|
|||
45
server/routes/schemasEndgame.js
Normal file
45
server/routes/schemasEndgame.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
'use strict';
|
||||
/* Response schemas of trade, the end game and the shared report folder (merged into routes/schemas.js). Documentation
|
||||
* only, like the others (test helpers can check them with createTestServer({ contract: true })). */
|
||||
module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj, arr }) {
|
||||
const nint = { type: ['integer', 'null'] };
|
||||
const nstr = { type: ['string', 'null'] };
|
||||
const free = { type: 'object', additionalProperties: true };
|
||||
const Cost = { $ref: 'Cost' };
|
||||
Object.assign(schemas, {
|
||||
// ---- trade
|
||||
TradeAmount: obj({ resource: str, amount: int }),
|
||||
TradeOffer: obj({
|
||||
id: int, status: str, worldId: int, townId: int, townName: nstr, x: nint, y: nint, operator: obj({ id: int, name: nstr }),
|
||||
give: { $ref: 'TradeAmount' }, want: { $ref: 'TradeAmount' }, maxDistance: int, createdAt: int, expiresAt: int, acceptedAt: nint, closedAt: nint,
|
||||
role: str, acceptableFrom: arr(obj({ townId: int, distance: num })),
|
||||
}, ['id', 'status', 'townId', 'operator', 'give', 'want', 'maxDistance', 'createdAt', 'expiresAt']),
|
||||
TradeOfferList: obj({ serverTime: int, items: arr({ $ref: 'TradeOffer' }), next: nint, exchangeLevels: arr(obj({ townId: int, level: int, reach: num })) }, ['serverTime', 'items', 'next']),
|
||||
TradeOfferResponse: obj({ serverTime: int, offer: { $ref: 'TradeOffer' } }),
|
||||
TradeCancelled: obj({ serverTime: int, offerId: int, status: str, returned: { $ref: 'TradeAmount' } }),
|
||||
TradeAccepted: obj({ serverTime: int, offerId: int, status: str, goodsMovementId: int, paymentMovementId: int, distance: num, arriveAt: int, give: { $ref: 'TradeAmount' }, want: { $ref: 'TradeAmount' } }),
|
||||
// ---- end game
|
||||
LandingSite: obj({
|
||||
id: nint, index: int, x: int, y: int, holder: { type: ['object', 'null'], properties: { allianceId: int, tag: str, name: str }, additionalProperties: true },
|
||||
takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, level: int, maxLevel: int, progress: num, pool: Cost,
|
||||
build: { type: ['object', 'null'], properties: { toLevel: int, startedAt: int, dueAt: int }, additionalProperties: true },
|
||||
next: { type: ['object', 'null'], properties: { toLevel: int, cost: Cost, durationMs: int }, additionalProperties: true },
|
||||
}),
|
||||
WorldStatus: obj({
|
||||
serverTime: int, worldId: int, name: str, speed: num, status: str, phase: str, ageDays: num, openDay: int, opensAt: int,
|
||||
sites: arr({ $ref: 'LandingSite' }), winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, endedAt: nint,
|
||||
}),
|
||||
WorldResults: obj({ serverTime: int, available: bool, status: str, winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, results: { type: ['object', 'null'], additionalProperties: true } }),
|
||||
LandingSiteResponse: obj({
|
||||
serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool }),
|
||||
contributions: arr(obj({ operatorId: int, name: str, fiber: int, hardware: int, capital: int })),
|
||||
}, ['serverTime', 'site', 'you']),
|
||||
BackboneBuildStarted: obj({ serverTime: int, siteId: int, eventId: int, toLevel: int, startedAt: int, dueAt: int, cost: Cost }),
|
||||
// ---- shared reports
|
||||
ReportShared: obj({ serverTime: int, changed: bool, reportId: int, allianceId: int }),
|
||||
SharedReportItem: obj({ id: int, type: str, createdAt: int, sharedAt: int, sharedBy: obj({ operatorId: int, name: str }), summary: free }),
|
||||
SharedReportList: obj({ serverTime: int, items: arr({ $ref: 'SharedReportItem' }), next: nint }),
|
||||
SharedReport: obj({ id: int, type: str, createdAt: int, expiresAt: int, sharedAt: int, sharedBy: obj({ operatorId: int, name: str }), summary: free, data: free }),
|
||||
SharedReportResponse: obj({ serverTime: int, report: { $ref: 'SharedReport' } }),
|
||||
});
|
||||
};
|
||||
|
|
@ -17,7 +17,7 @@ module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj
|
|||
id: int, type: str, status: str, ownerId: int, from: { $ref: 'MovementEnd' }, to: { $ref: 'MovementEnd' }, units: Units, cargo: free,
|
||||
departAt: int, arriveAt: int, recallableUntil: nint, target: { type: ['string', 'null'] }, parentId: nint, incoming: bool,
|
||||
}, ['id', 'type', 'status', 'from', 'to', 'departAt', 'arriveAt']),
|
||||
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }),
|
||||
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }), alliedIncoming: arr({ $ref: 'Movement' }) }, ['serverTime', 'outgoing', 'incoming']),
|
||||
Marked: obj({ serverTime: int, marked: int }),
|
||||
ReportItem: obj({ id: int, type: str, createdAt: int, role: str, read: bool, summary: free }),
|
||||
ReportList: obj({ serverTime: int, items: arr({ $ref: 'ReportItem' }), next: nint, unread: int }),
|
||||
|
|
|
|||
30
server/routes/sharedReports.js
Normal file
30
server/routes/sharedReports.js
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
'use strict';
|
||||
/* The alliance's shared report folder: share one of your reports, list and read the folder, take one out. */
|
||||
const { createSharedReportQueries } = require('../sharedReports');
|
||||
|
||||
function register(router, services) {
|
||||
const { commands } = services;
|
||||
const folder = createSharedReportQueries(services);
|
||||
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||
|
||||
router.post('/reports/:id/share', {
|
||||
summary: 'Put one of your reports into your alliance\'s shared folder (needs shareReport; keeps the report for another 14 days)', tag: 'reports',
|
||||
response: { $ref: 'ReportShared' }, errors: errs.concat(['not_in_alliance', 'forbidden', 'world_ended']),
|
||||
}, ({ user, params }) => commands.run('reportShare', { userId: user.id, reportId: params.id }));
|
||||
|
||||
router.del('/reports/:id/share', {
|
||||
summary: 'Take a report out of the alliance folder (whoever shared it, or leader/officer)', tag: 'reports',
|
||||
response: { $ref: 'ReportShared' }, errors: errs.concat(['forbidden', 'world_ended']),
|
||||
}, ({ user, params }) => commands.run('reportUnshare', { userId: user.id, reportId: params.id }));
|
||||
|
||||
router.get('/alliances/:id/reports', {
|
||||
summary: 'The alliance\'s shared reports, newest first (cursor: after = id of the last report seen; members only)', tag: 'reports',
|
||||
query: { type: 'object', properties: { after: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 } } },
|
||||
response: { $ref: 'SharedReportList' }, errors: errs.concat(['forbidden']),
|
||||
}, ({ user, params, query }) => folder.list(user.id, params.id, query));
|
||||
|
||||
router.get('/alliances/:id/reports/:reportId', {
|
||||
summary: 'One shared report with its full data (members only)', tag: 'reports', response: { $ref: 'SharedReportResponse' }, errors: errs.concat(['forbidden']),
|
||||
}, ({ user, params }) => folder.get(user.id, params.id, params.reportId));
|
||||
}
|
||||
module.exports = { register };
|
||||
53
server/routes/trade.js
Normal file
53
server/routes/trade.js
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
'use strict';
|
||||
/* Internet exchange: open offers, your offers, create / cancel / accept. Direct transports (to your own POPs or any player)
|
||||
* are POST /movements with type "transport". */
|
||||
const { reply } = require('../http');
|
||||
const { createTradeQueries } = require('../tradeQueries');
|
||||
const D = require('../../public/js/data.js');
|
||||
|
||||
const int1 = { type: 'integer', minimum: 1 };
|
||||
const res = { type: 'string', enum: D.RESOURCES };
|
||||
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
|
||||
|
||||
function register(router, services) {
|
||||
const { commands } = services;
|
||||
const trade = createTradeQueries(services);
|
||||
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||
|
||||
router.get('/trade/offers', {
|
||||
summary: 'Open offers you can take: within the offer\'s max distance and the reach of one of your Internet exchanges (newest first, cursor: after = last id seen)', tag: 'trade',
|
||||
query: { type: 'object', properties: Object.assign({ worldId: int1, townId: int1, give: res, want: res }, page) }, response: { $ref: 'TradeOfferList' }, errors: errs,
|
||||
}, ({ user, query }) => trade.offers(user.id, query));
|
||||
|
||||
router.get('/trade/offers/mine', {
|
||||
summary: 'Offers you posted or accepted, any status (newest first)', tag: 'trade',
|
||||
query: { type: 'object', properties: Object.assign({ worldId: int1, status: { type: 'string', enum: ['open', 'accepted', 'completed', 'cancelled', 'expired', 'void'] } }, page) },
|
||||
response: { $ref: 'TradeOfferList' }, errors: errs,
|
||||
}, ({ user, query }) => trade.mineOffers(user.id, query));
|
||||
|
||||
router.get('/trade/offers/:id', {
|
||||
summary: 'One offer (open ones to every operator of the world, closed ones to the two parties)', tag: 'trade', response: { $ref: 'TradeOfferResponse' }, errors: errs,
|
||||
}, ({ user, params }) => trade.offer(user.id, params.id));
|
||||
|
||||
router.post('/trade/offers', {
|
||||
summary: 'Post an offer from one of your POPs: give X of A for Y of B within a max distance. The offered amount is escrowed and a transport link reserved',
|
||||
tag: 'trade', status: 201,
|
||||
body: {
|
||||
type: 'object', required: ['townId', 'giveRes', 'giveAmount', 'wantRes', 'wantAmount', 'maxDistance'],
|
||||
properties: { townId: int1, giveRes: res, giveAmount: int1, wantRes: res, wantAmount: int1, maxDistance: { type: 'integer', minimum: 1, maximum: D.TRADE.maxDistance } },
|
||||
},
|
||||
response: { $ref: 'TradeOfferResponse' }, errors: errs.concat(['trade_ratio', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, body }) => reply(201, commands.run('tradeOffer', Object.assign({ userId: user.id }, body))));
|
||||
|
||||
router.del('/trade/offers/:id', {
|
||||
summary: 'Cancel your open offer; the escrow returns to the POP', tag: 'trade', response: { $ref: 'TradeCancelled' }, errors: errs.concat(['offer_closed', 'world_ended']),
|
||||
}, ({ user, params }) => commands.run('tradeCancel', { userId: user.id, offerId: params.id }));
|
||||
|
||||
router.post('/trade/offers/:id/accept', {
|
||||
summary: 'Take an open offer with one of your POPs: two transports leave at once (your payment, their goods) and the offer is settled when both arrive', tag: 'trade', status: 201,
|
||||
body: { type: 'object', required: ['townId'], properties: { townId: int1 } },
|
||||
response: { $ref: 'TradeAccepted' },
|
||||
errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, params, body }) => reply(201, commands.run('tradeAccept', { userId: user.id, offerId: params.id, townId: body.townId })));
|
||||
}
|
||||
module.exports = { register };
|
||||
41
server/routes/world.js
Normal file
41
server/routes/world.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
'use strict';
|
||||
/* End game: the race (world status), the final results, landing sites (read, feed the stockpile, build the node). Taking a site is
|
||||
* POST /movements (scan / attack at its x,y). */
|
||||
const { reply } = require('../http');
|
||||
const { createEndgameQueries } = require('../endgameQueries');
|
||||
const D = require('../../public/js/data.js');
|
||||
|
||||
function register(router, services) {
|
||||
const { commands } = services;
|
||||
const eg = createEndgameQueries(services);
|
||||
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||
|
||||
router.get('/worlds/:id/status', {
|
||||
summary: 'The state of the world: phase (running, backbone_open, ended), world age, the landing sites with holder, node level, stockpile and build progress, the winner', tag: 'world',
|
||||
response: { $ref: 'WorldStatus' }, errors: errs,
|
||||
}, ({ user, params }) => eg.status(user.id, params.id));
|
||||
|
||||
router.get('/worlds/:id/results', {
|
||||
summary: 'The final ranking snapshot (operators, alliances, attackers, defenders, winner); available once the world has ended', tag: 'world',
|
||||
response: { $ref: 'WorldResults' }, errors: errs,
|
||||
}, ({ user, params }) => eg.results(user.id, params.id));
|
||||
|
||||
router.get('/backbone/:id', {
|
||||
summary: 'One landing site; members of the holding alliance also see the contribution ledger and what they may do', tag: 'world',
|
||||
response: { $ref: 'LandingSiteResponse' }, errors: errs,
|
||||
}, ({ user, params }) => eg.site(user.id, params.id));
|
||||
|
||||
router.post('/backbone/:id/ship', {
|
||||
summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 500 each)', tag: 'world', status: 201,
|
||||
body: { type: 'object', required: ['fromTownId', 'cargo'], properties: { fromTownId: { type: 'integer', minimum: 1 }, cargo: { type: 'object', additionalProperties: true, description: 'fiber/hardware/capital -> amount' } } },
|
||||
response: { $ref: 'MovementSent' },
|
||||
errors: errs.concat(['forbidden', 'backbone_closed', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, params, body }) => reply(201, commands.run('backboneShip', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, cargo: body.cargo })));
|
||||
|
||||
router.post('/backbone/:id/build', {
|
||||
summary: 'Start the next Backbone node level on a landing site your alliance holds (paid from the site\'s stockpile; one level at a time, up to level ' + D.ENDGAME.maxLevel + ')', tag: 'world', status: 201,
|
||||
response: { $ref: 'BackboneBuildStarted' },
|
||||
errors: errs.concat(['forbidden', 'backbone_closed', 'max_level', 'already_queued', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, params }) => reply(201, commands.run('backboneBuild', { userId: user.id, siteId: params.id })));
|
||||
}
|
||||
module.exports = { register };
|
||||
|
|
@ -19,6 +19,21 @@ class Scheduler {
|
|||
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; }
|
||||
|
|
@ -30,9 +45,13 @@ class Scheduler {
|
|||
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) {
|
||||
this.db.run('INSERT INTO notifications (user_id, world_id, type, payload, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
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"); }
|
||||
|
|
@ -58,6 +77,7 @@ class Scheduler {
|
|||
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);
|
||||
|
|
@ -65,10 +85,12 @@ class Scheduler {
|
|||
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); } }
|
||||
}
|
||||
|
||||
|
|
|
|||
35
server/sharedReports.js
Normal file
35
server/sharedReports.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
'use strict';
|
||||
/* Read model of the alliance's shared report folder. Newest first, `after` = id of the last report you have (older ones
|
||||
* follow), like GET /reports. Members with `viewSharedReports` only. */
|
||||
const { GameError } = require('./errors');
|
||||
const A = require('./alliances');
|
||||
|
||||
const j = (s) => JSON.parse(s || '{}');
|
||||
|
||||
function createSharedReportQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
|
||||
function list(userId, allianceId, { after, limit }) {
|
||||
const now = fresh();
|
||||
A.requireRole(db, userId, allianceId, 'viewSharedReports');
|
||||
const n = limit || 25;
|
||||
const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, s.created_at AS shared_at, s.shared_by, o.name AS shared_name
|
||||
FROM report_shares s JOIN reports r ON r.id = s.report_id JOIN operators o ON o.id = s.shared_by
|
||||
WHERE s.alliance_id = ? ${after ? 'AND r.id < ?' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [allianceId, after, n + 1] : [allianceId, n + 1]));
|
||||
const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, sharedAt: r.shared_at, sharedBy: { operatorId: r.shared_by, name: r.shared_name }, summary: j(r.summary) }));
|
||||
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null };
|
||||
}
|
||||
|
||||
function get(userId, allianceId, reportId) {
|
||||
const now = fresh();
|
||||
A.requireRole(db, userId, allianceId, 'viewSharedReports');
|
||||
const r = db.get(`SELECT r.*, s.created_at AS shared_at, s.shared_by, o.name AS shared_name FROM report_shares s JOIN reports r ON r.id = s.report_id JOIN operators o ON o.id = s.shared_by
|
||||
WHERE s.alliance_id = ? AND r.id = ?`, allianceId, reportId);
|
||||
if (!r) throw new GameError('not_found', { what: 'shared report' });
|
||||
return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, sharedAt: r.shared_at, sharedBy: { operatorId: r.shared_by, name: r.shared_name }, summary: j(r.summary), data: j(r.data) } };
|
||||
}
|
||||
|
||||
return { list, get };
|
||||
}
|
||||
|
||||
module.exports = { createSharedReportQueries };
|
||||
|
|
@ -305,7 +305,7 @@ function createSocialQueries({ db, clock, scheduler }) {
|
|||
|
||||
return {
|
||||
mine, list, get, members, invitesSent, invitesReceived, notes, diplomacy,
|
||||
rankOperators, rankAlliances, rankBattles,
|
||||
rankOperators, rankAlliances, rankBattles, footprints,
|
||||
inbox, outbox, thread, allianceFeed, message, blocks, footprints,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
88
server/trade.js
Normal file
88
server/trade.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Internet exchange trade: shared helpers of the trade commands, the expiry event and the read model.
|
||||
*
|
||||
* Offer life cycle (table trade_offers, status):
|
||||
* open the offered amount is ESCROWED in the row (it left the POP at creation) and one transport link of the poster's POP is
|
||||
* held in reserve (military/movements.activeLinks counts open offers)
|
||||
* accepted two transports are on the road: poster -> acceptor carries the escrow, acceptor -> poster carries the payment
|
||||
* completed both legs were delivered (the `transportArrived` hook below)
|
||||
* cancelled the poster took it back: the escrow is credited to the POP again
|
||||
* expired ttl ran out (event `tradeExpire`): same
|
||||
* void the poster's POP changed hands while the offer was open: the escrow stays in that POP (it goes with the POP)
|
||||
* Nothing is created or lost: escrow is returned WITHOUT the Rack hall cap (an amount above the cap is kept, it only stops
|
||||
* growing); the only loss anywhere is what a delivery cannot store (the existing cargoLost rule of transports).
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { loadTown, settle } = require('./state');
|
||||
const M = require('./military/movements');
|
||||
|
||||
const COL = { fiber: 'fiber', hardware: 'hardware', capital: 'capital' };
|
||||
|
||||
// Credit `amount` of `res` to a POP (settled first, no storage cap: it is a refund of what left the POP).
|
||||
function refund(db, townId, res, amount, at) {
|
||||
const town = loadTown(db, townId);
|
||||
if (!town) return;
|
||||
settle(db, town, at);
|
||||
db.run('UPDATE towns SET ' + COL[res] + ' = ' + COL[res] + ' + ? WHERE id = ?', amount, townId);
|
||||
}
|
||||
|
||||
const getOffer = (db, id) => db.get('SELECT * FROM trade_offers WHERE id = ?', id) || null;
|
||||
|
||||
function expiryMs(speed) { return Math.round(D.TRADE.ttlHours * D.HOUR_MS / (speed || 1)); }
|
||||
|
||||
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
|
||||
|
||||
// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> the offer row (before)
|
||||
function closeOffer(ctx, offer, status, at) {
|
||||
const { db } = ctx;
|
||||
db.run('UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?', status, at, offer.id);
|
||||
if (offer.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", at, offer.expire_event_id);
|
||||
refund(db, offer.town_id, offer.give_res, offer.give_amount, at);
|
||||
return offer;
|
||||
}
|
||||
|
||||
// A POP changed hands (takeover): its open offers end and the escrow stays with the POP. Called from combat.transferTown.
|
||||
function onTownTransferred(ctx, townId, at) {
|
||||
const { db } = ctx;
|
||||
for (const o of db.all("SELECT * FROM trade_offers WHERE town_id = ? AND status = 'open'", townId)) {
|
||||
closeOffer(ctx, o, 'void', at);
|
||||
const uid = userOfOperator(db, o.operator_id);
|
||||
if (uid) ctx.notify(uid, o.world_id, 'trade_void', { offerId: o.id, townId });
|
||||
}
|
||||
}
|
||||
|
||||
// `transportArrived` consumer: both legs of an accepted offer delivered -> completed.
|
||||
function onTransportArrived(ctx, mv, res) {
|
||||
const tradeId = mv.extra && mv.extra.tradeId;
|
||||
if (!tradeId) return;
|
||||
const { db } = ctx;
|
||||
const o = getOffer(db, tradeId);
|
||||
if (!o || o.status !== 'accepted') return;
|
||||
const legs = o.legs_done + 1;
|
||||
if (legs < 2) { db.run('UPDATE trade_offers SET legs_done = ? WHERE id = ?', legs, o.id); return; }
|
||||
db.run("UPDATE trade_offers SET legs_done = ?, status = 'completed', closed_at = ? WHERE id = ?", legs, ctx.now, o.id);
|
||||
const body = { offerId: o.id, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount } };
|
||||
for (const opId of [o.operator_id, o.accepted_by_operator]) {
|
||||
const uid = userOfOperator(db, opId);
|
||||
if (uid) ctx.notify(uid, o.world_id, 'trade_completed', body);
|
||||
}
|
||||
}
|
||||
|
||||
// Registered once, whoever requires this module first (commands and events both do): tests and the server see the same wiring.
|
||||
if (!M.hooks.transportArrived.some((f) => f.name === 'tradeTransportArrived')) {
|
||||
M.hooks.transportArrived.push(function tradeTransportArrived(ctx, mv, res) { return onTransportArrived(ctx, mv, res); });
|
||||
}
|
||||
|
||||
function offerView(db, o, towns) {
|
||||
const t = towns && towns.get(o.town_id);
|
||||
return {
|
||||
id: o.id, status: o.status, worldId: o.world_id, townId: o.town_id, townName: t ? t.name : null, x: t ? t.x : null, y: t ? t.y : null,
|
||||
operator: { id: o.operator_id, name: (db.get('SELECT name FROM operators WHERE id = ?', o.operator_id) || {}).name || null },
|
||||
give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount },
|
||||
maxDistance: o.max_distance, createdAt: o.created_at, expiresAt: o.expires_at, acceptedAt: o.accepted_at, closedAt: o.closed_at,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { refund, getOffer, expiryMs, closeOffer, onTownTransferred, onTransportArrived, offerView, userOfOperator };
|
||||
82
server/tradeQueries.js
Normal file
82
server/tradeQueries.js
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Read models of the Internet exchange: the open offers you can see and take, your own offers, one offer. Reads catch the event
|
||||
* queue up first. Lists are newest first, `after` = id of the last offer you have (older ones follow).
|
||||
* Visibility: an open offer of somebody else is listed when one of your POPs (the one in `townId`, or any) has an Internet
|
||||
* exchange and the poster's POP is within min(the offer's max distance, that exchange's reach). `acceptableFrom` names those POPs.
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const A = require('./alliances');
|
||||
const T = require('./trade');
|
||||
|
||||
function createTradeQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
const townsOf = (ids) => {
|
||||
const m = new Map();
|
||||
for (const id of ids) if (!m.has(id)) m.set(id, db.get('SELECT id, name, x, y FROM towns WHERE id = ?', id));
|
||||
return m;
|
||||
};
|
||||
|
||||
// My POPs with an exchange: [{ id, x, y, level }].
|
||||
function exchanges(operatorId, townId) {
|
||||
const rows = db.all(`SELECT t.id, t.x, t.y, b.level AS level FROM towns t JOIN buildings b ON b.town_id = t.id AND b.type = ? WHERE t.owner_id = ? AND b.level >= 1 ${townId ? 'AND t.id = ?' : ''} ORDER BY t.id`,
|
||||
...[D.TRANSPORT.building, operatorId].concat(townId ? [townId] : []));
|
||||
return rows;
|
||||
}
|
||||
|
||||
function offers(userId, { worldId, townId, give, want, after, limit }) {
|
||||
const now = fresh();
|
||||
const op = A.operatorOf(db, userId, worldId);
|
||||
if (townId && !db.get('SELECT 1 AS x FROM towns WHERE id = ? AND owner_id = ?', townId, op.id)) throw new GameError('not_found', { what: 'town' });
|
||||
const mine = exchanges(op.id, townId);
|
||||
const n = limit || 25;
|
||||
const out = [];
|
||||
let next = null;
|
||||
if (mine.length) {
|
||||
// newest first in chunks: the range filter drops rows, so keep reading until a page is full or the offers are used up
|
||||
let cur = after || 0, done = false;
|
||||
while (!done && !next) {
|
||||
const rows = db.all(`SELECT o.*, t.x AS tx, t.y AS ty FROM trade_offers o JOIN towns t ON t.id = o.town_id WHERE o.world_id = ? AND o.status = 'open' AND o.operator_id != ?
|
||||
${give ? 'AND o.give_res = ?' : ''} ${want ? 'AND o.want_res = ?' : ''} ${cur ? 'AND o.id < ?' : ''} ORDER BY o.id DESC LIMIT ?`,
|
||||
...[op.world_id, op.id].concat(give ? [give] : [], want ? [want] : [], cur ? [cur] : [], [D.TRADE.scanChunk]));
|
||||
const towns = townsOf(rows.map((r) => r.town_id));
|
||||
for (const r of rows) {
|
||||
cur = r.id;
|
||||
const from = mine.map((m) => ({ townId: m.id, distance: R.distance(m.x, m.y, r.tx, r.ty), level: m.level })).filter((m) => R.tradeInRange(m.distance, r.max_distance, m.level));
|
||||
if (!from.length) continue;
|
||||
if (out.length === n) { next = out[out.length - 1].id; break; }
|
||||
out.push(Object.assign(T.offerView(db, r, towns), { acceptableFrom: from.map((m) => ({ townId: m.townId, distance: m.distance })) }));
|
||||
}
|
||||
done = rows.length < D.TRADE.scanChunk;
|
||||
}
|
||||
}
|
||||
return { serverTime: now, items: out, next, exchangeLevels: mine.map((m) => ({ townId: m.id, level: m.level, reach: R.tradeReach(m.level) })) };
|
||||
}
|
||||
|
||||
function mineOffers(userId, { worldId, after, limit, status }) {
|
||||
const now = fresh();
|
||||
const op = A.operatorOf(db, userId, worldId);
|
||||
const n = limit || 25;
|
||||
const rows = db.all(`SELECT * FROM trade_offers WHERE (operator_id = ? OR accepted_by_operator = ?) ${status ? 'AND status = ?' : ''} ${after ? 'AND id < ?' : ''} ORDER BY id DESC LIMIT ?`,
|
||||
...[op.id, op.id].concat(status ? [status] : [], after ? [after] : [], [n + 1]));
|
||||
const towns = townsOf(rows.map((r) => r.town_id));
|
||||
const items = rows.slice(0, n).map((r) => Object.assign(T.offerView(db, r, towns), { role: r.operator_id === op.id ? 'poster' : 'acceptor' }));
|
||||
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null };
|
||||
}
|
||||
|
||||
// One offer: open ones are public inside the world (to operators of it), the rest only to the two parties.
|
||||
function offer(userId, id) {
|
||||
const now = fresh();
|
||||
const o = T.getOffer(db, id);
|
||||
const op = o ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, o.world_id) : null;
|
||||
if (!o || !op) throw new GameError('not_found', { what: 'offer' });
|
||||
if (o.status !== 'open' && o.operator_id !== op.id && o.accepted_by_operator !== op.id) throw new GameError('not_found', { what: 'offer' });
|
||||
return { serverTime: now, offer: Object.assign(T.offerView(db, o, townsOf([o.town_id])), { role: o.operator_id === op.id ? 'poster' : (o.accepted_by_operator === op.id ? 'acceptor' : 'viewer') }) };
|
||||
}
|
||||
|
||||
return { offers, mineOffers, offer };
|
||||
}
|
||||
|
||||
module.exports = { createTradeQueries };
|
||||
Loading…
Add table
Add a link
Reference in a new issue