'use strict'; /* End game on the server: sites open at day 100, taking them, shipping, building the node, winning, the end of the world. * Fake clock, in-memory db; the world is moved to day 100 by advancing the clock (nothing else is pending in these worlds). */ const test = require('node:test'); const assert = require('node:assert'); const T = require('./military-helpers'); const A = require('../server/alliances'); const E = require('../server/endgame'); const { createEndgameQueries } = require('../server/endgameQueries'); const { R, D, H } = T; const DAY = 24 * H; function alliance(h, name, leader, members) { const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid); A.addMember(h.db, id, leader.opId, 'leader', h.clock.now()); for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now()); return id; } const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); }; // A world at day `day`, with the sites at fixed positions; operators are created AFTER the clock moved so their POPs are fresh. function world(day, o) { const h = T.setup(Object.assign({ seed: 4242, radius: 50 }, o)); h.advanceTo(h.world.start_at + Math.round(day * DAY / (h.world.speed || 1))); h.eg = createEndgameQueries(h); h.sites = R.backboneSites(h.world.seed, h.world.map_radius); return h; } // An operator next to site `i` with plenty of power so that its units stay online; no production unless asked. function near(h, name, i, o) { const s = h.sites[i]; const op = T.addOperator(h, name, Object.assign({ x: s.x - 4, y: s.y, power: 25 }, o || {})); if (!(o && o.produce)) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%' AND key NOT IN ('f13','f14','f15','f16')", op.townId); return op; } const siteOf = (h, i) => h.db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', h.worldId, i); const attack = (h, who, i, units, type) => h.run('sendMovement', { userId: who.userId, fromTownId: who.townId, type: type || 'attack', x: h.sites[i].x, y: h.sites[i].y, units }); const defenceNow = (h, i, level) => R.backboneDefence(h.world.seed, h.sites[i].x, h.sites[i].y, R.worldAgeDays(h.world.start_at, h.clock.now(), h.world.speed), level || 0); test('before day 100: the sites are plain land - cannot be attacked, settled or seen; status says running', () => { const h = world(99.9); const a = near(h, 'alice', 0, { units: { script_crew: 50 } }); alliance(h, 'Alpha', a); const s0 = h.sites[0]; assert.equal(err(() => attack(h, a, 0, { script_crew: 10 })).code, 'backbone_closed'); assert.equal(err(() => attack(h, a, 0, { script_crew: 10 }, 'raid')).code, 'backbone_closed'); // settling the tile is refused although it looks like land: (the crews would otherwise found a POP on the future site) T.giveUnits(h, a.townId, { rollout_crew: 3 }); h.db.run('UPDATE towns SET footprint = 1e9 WHERE id = ?', a.townId); const e = err(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: s0.x, y: s0.y, units: { rollout_crew: 3 } })); assert.equal(e.code, 'invalid_target'); assert.equal(e.details.reason, 'backbone_site'); const st = h.eg.status(a.userId, h.worldId); assert.equal(st.phase, 'running'); assert.deepEqual(st.sites, []); assert.equal(st.winner, null); assert.equal(st.ageDays < 100, true); assert.equal(h.mq.tileInfo(a.userId, { x: s0.x, y: s0.y }).type, 'land'); assert.equal(h.queries.map(a.userId, { x: s0.x, y: s0.y, r: 2 }).specials.some((s) => s.type === 'backbone'), false); h.advanceTo(h.world.start_at + 100 * DAY); assert.equal(h.eg.status(a.userId, h.worldId).phase, 'backbone_open'); }); test('day 100: 7 sites appear (status, map, tile), held by the incumbent; a scan reports the heavy defence', () => { const h = world(100); const a = near(h, 'alice', 0, { units: { port_scanner: 100 } }); const st = h.eg.status(a.userId, h.worldId); assert.equal(st.phase, 'backbone_open'); assert.equal(st.sites.length, 7); assert.ok(st.sites.every((s) => s.holder === null && s.level === 0 && s.id === null && s.next.toLevel === 1)); assert.deepEqual(st.sites.map((s) => [s.x, s.y]), h.sites.map((s) => [s.x, s.y])); assert.equal(st.opensAt, h.world.start_at + 100 * DAY); const m = h.queries.map(a.userId, { x: h.sites[0].x, y: h.sites[0].y, r: 3 }); const sp = m.specials.find((s) => s.type === 'backbone'); assert.ok(sp && sp.x === h.sites[0].x && sp.site.index === 0 && sp.site.holder === null && sp.site.level === 0); const ti = h.mq.tileInfo(a.userId, { x: h.sites[0].x, y: h.sites[0].y }); assert.equal(ti.type, 'backbone'); assert.equal(ti.backbone.holder, null); assert.equal(ti.backbone.canAttack, false, 'no alliance, no attack'); assert.equal(ti.settle.possible, false); // scan (no alliance needed) const mv = attack(h, a, 0, { port_scanner: 100 }, 'scan'); h.advanceTo(mv.arriveAt); const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'scan'); assert.equal(rep.data.site.type, 'backbone'); assert.equal(rep.data.success, true); assert.equal(rep.data.intel.defence, defenceNow(h, 0, 0), 'the scan shows the exact static defence'); assert.ok(rep.data.intel.defence > 10 * R.incumbentDefence(h.world.seed, h.sites[0].x, h.sites[0].y, 100)); assert.equal(h.db.get('SELECT COUNT(*) AS n FROM landing_sites').n, 7, 'the first touch created the rows'); assert.equal(T.notes(h, a.userId, 'backbone_open').length, 1, 'and told the world once'); }); test('taking a site: alliance members only, heavy defence, the winner holds it; losing attackers change nothing; friends and pacts are refused', () => { const h = world(100); const a = near(h, 'alice', 0, { units: { script_crew: 1200 } }); const a2 = near(h, 'alice2', 0, { x: h.sites[0].x - 4, y: h.sites[0].y + 3 }); const b = near(h, 'bob', 0, { x: h.sites[0].x + 4, y: h.sites[0].y, units: { script_crew: 300 } }); const loner = near(h, 'loner', 0, { x: h.sites[0].x, y: h.sites[0].y - 5, units: { script_crew: 1200 } }); const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b); // an operator without an alliance cannot take a site assert.equal(err(() => attack(h, loner, 0, { script_crew: 1200 })).details.reason, 'no_alliance'); T.giveUnits(h, a.townId, { ma_team: 1 }); assert.equal(err(() => attack(h, a, 0, { script_crew: 10, ma_team: 1 }, 'takeover')).details.reason, 'landing_scan_or_attack_only'); assert.equal(err(() => attack(h, a, 0, { script_crew: 10 }, 'reinforce')).code, 'invalid_target'); // too weak: bob's 300 crews (12 000) against ~40 000: lost, nothing changes const weak = attack(h, b, 0, { script_crew: 300 }); h.advanceTo(weak.arriveAt); assert.equal(siteOf(h, 0).holder_alliance_id, null); const lost = T.reportsOf(h, b.userId).find((r) => r.type === 'landing'); assert.equal(lost.data.outcome, 'defender_won'); assert.equal(lost.data.taken, false); assert.equal(T.units(h, b.townId).script_crew, undefined, 'all lost'); // alice takes it const power = 1200 * 40; assert.ok(power > defenceNow(h, 0, 0) * 1.05); const mv = attack(h, a, 0, { script_crew: 1200 }); h.advanceTo(mv.arriveAt); const site = siteOf(h, 0); assert.equal(site.holder_alliance_id, A1); assert.equal(site.holder_operator_id, a.opId); assert.equal(site.taken_at, mv.arriveAt); assert.equal(site.level, 0); const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'landing'); assert.equal(rep.data.outcome, 'attacker_won'); assert.equal(rep.data.taken, true); assert.equal(rep.data.site.holder, null, 'the report says who held it BEFORE'); assert.equal(T.notes(h, a2.userId, 'backbone_taken').length, 1, 'every member of the new holder hears it'); const surv = h.db.get("SELECT units FROM movements WHERE type = 'return' AND owner_id = ?", a.opId); assert.ok(JSON.parse(surv.units).script_crew > 0 && JSON.parse(surv.units).script_crew < 1200, 'survivors drive home, with losses'); // status and tile now show the holder const st = h.eg.status(a2.userId, h.worldId); assert.equal(st.sites[0].holder.allianceId, A1); assert.equal(st.sites[0].holder.tag, 'ALP'); assert.equal(st.sites[0].takenBy.operatorId, a.opId); assert.equal(h.mq.tileInfo(a2.userId, { x: h.sites[0].x, y: h.sites[0].y }).backbone.mine, true); assert.equal(h.mq.tileInfo(b.userId, { x: h.sites[0].x, y: h.sites[0].y }).backbone.canAttack, true); // the holder's own members cannot attack it; a NAP partner cannot either T.giveUnits(h, a2.townId, { script_crew: 10 }); assert.equal(err(() => attack(h, a2, 0, { script_crew: 10 })).details.reason, 'own_site'); A.setRelation(h.db, h.worldId, A1, B1, 'nap', h.clock.now()); T.giveUnits(h, b.townId, { script_crew: 10 }); assert.equal(err(() => attack(h, b, 0, { script_crew: 10 })).details.reason, 'pact'); A.setRelation(h.db, h.worldId, A1, B1, 'war', h.clock.now()); }); test('re-checked at arrival: a pact signed while the attack is on the road bounces it', () => { const h = world(100); const a = near(h, 'alice', 1, { units: { script_crew: 1200 } }); const b = near(h, 'bob', 1, { x: h.sites[1].x + 4, y: h.sites[1].y }); const A1 = alliance(h, 'Alpha', a), B1 = alliance(h, 'Bravo', b); // bob's alliance holds the site E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 1', B1, b.opId); const mv = attack(h, a, 1, { script_crew: 1200 }); A.setRelation(h.db, h.worldId, A1, B1, 'nap', h.clock.now()); h.advanceTo(mv.arriveAt); assert.equal(siteOf(h, 1).holder_alliance_id, B1, 'not taken'); const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'movement_failed'); assert.equal(rep.data.reason, 'pact'); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM movements WHERE type = 'return' AND owner_id = ?", a.opId).n, 1, 'the units come home'); }); test('shipping: members feed the stockpile by transport; strangers cannot; a shipment that arrives after the site changed hands rides home', () => { const h = world(100); const a = near(h, 'alice', 2); const a2 = near(h, 'alice2', 2, { x: h.sites[2].x - 14, y: h.sites[2].y }); const b = near(h, 'bob', 2, { x: h.sites[2].x + 4, y: h.sites[2].y, units: { script_crew: 1300 } }); const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b); E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 2', A1, a.opId); const site = siteOf(h, 2); const stock = (id) => { const t = T.town(h, id); return t.fiber + t.hardware + t.capital; }; assert.equal(err(() => h.run('backboneShip', { userId: b.userId, siteId: site.id, fromTownId: b.townId, cargo: { fiber: 100 } })).code, 'forbidden'); assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 100 } })).code, 'not_found', "not your POP"); assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 501 } })).code, 'capacity_exceeded'); assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: 9999, fromTownId: a2.townId, cargo: { fiber: 5 } })).code, 'not_found'); const before = stock(a2.townId); const s1 = h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 300, hardware: 200 } }); assert.equal(stock(a2.townId), before - 500, 'it left the POP'); assert.equal(s1.arriveAt - s1.departAt, R.transportMs(R.distance(a2.x, a2.y, site.x, site.y), 1)); h.advanceTo(s1.arriveAt); let row = siteOf(h, 2); assert.deepEqual([row.fiber, row.hardware, row.capital], [300, 200, 0]); assert.deepEqual(h.db.get('SELECT fiber, hardware, capital FROM landing_contributions WHERE site_id = ? AND operator_id = ?', site.id, a2.opId), { fiber: 300, hardware: 200, capital: 0 }); assert.equal(T.notes(h, a2.userId, 'backbone_delivered').length, 1); assert.equal(stock(a2.townId), before - 500, 'nothing came back: it was delivered'); // second shipment is still on the road when bob takes the site const s2 = h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { capital: 400 } }); const mid = stock(a2.townId); const atk = attack(h, b, 2, { script_crew: 1300 }); assert.ok(atk.arriveAt < s2.arriveAt, 'the attack gets there first (a2 lives further away)'); h.advanceTo(s2.arriveAt); assert.equal(siteOf(h, 2).holder_alliance_id, B1, 'bob took it first'); row = siteOf(h, 2); assert.deepEqual([row.fiber, row.hardware, row.capital], [300, 200, 0], 'the late shipment was not added to the new holder\'s stockpile, the old stock stayed with the site'); assert.equal(T.notes(h, a2.userId, 'backbone_ship_bounced').length, 1); assert.equal(stock(a2.townId), mid, 'still on its way home'); h.advance(10 * H); assert.equal(stock(a2.townId), mid + 400, 'back home: nothing lost'); }); test('building the node: from the stockpile, one level at a time, holders only; the level and the build stay with the site when it is taken', () => { const h = world(100); const a = near(h, 'alice', 3); const a2 = near(h, 'alice2', 3, { x: h.sites[3].x - 4, y: h.sites[3].y + 3 }); const b = near(h, 'bob', 3, { x: h.sites[3].x + 4, y: h.sites[3].y, units: { script_crew: 1300 } }); const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b); E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 3', A1, a.opId); const site = siteOf(h, 3); const build = (who) => h.run('backboneBuild', { userId: who.userId, siteId: site.id }); assert.equal(err(() => build(a)).code, 'not_enough_resources'); assert.equal(err(() => build(b)).code, 'forbidden', 'not a holder'); h.db.run('UPDATE landing_sites SET fiber = 5000, hardware = 4200, capital = 4000 WHERE id = ?', site.id); const t0 = h.clock.now(); const q = build(a2); assert.equal(q.toLevel, 1); assert.deepEqual(q.cost, R.backboneCost(1)); assert.equal(q.dueAt, t0 + R.backboneTimeMs(1, 1)); let row = siteOf(h, 3); assert.deepEqual([row.fiber, row.hardware, row.capital], [1000, 200, 0], 'paid from the stockpile at once'); assert.equal(row.build_to, 1); assert.equal(err(() => build(a)).code, 'already_queued'); const view = h.eg.site(a.userId, site.id); assert.equal(view.site.build.toLevel, 1); assert.equal(view.you.canBuild, true); assert.equal(h.eg.site(b.userId, site.id).contributions, undefined, 'the ledger is for holders'); // bob takes the site while level 1 is being built: the level lands on the site for its NEW holder h.advanceTo(q.dueAt - H); const atk = attack(h, b, 3, { script_crew: 1300 }); h.advanceTo(atk.arriveAt); assert.equal(siteOf(h, 3).holder_alliance_id, B1); assert.equal(siteOf(h, 3).build_to, 1, 'the build runs on'); h.advanceTo(q.dueAt); row = siteOf(h, 3); assert.equal(row.level, 1); assert.equal(row.build_to, null); assert.equal(row.holder_alliance_id, B1); assert.equal(err(() => build(a2)).code, 'forbidden', 'alice is a stranger now'); // the node raises the site's defence (level stays with the site) assert.ok(defenceNow(h, 3, 1) > defenceNow(h, 3, 0)); assert.equal(h.eg.status(a.userId, h.worldId).sites[3].level, 1); // the new holder pays the next level from what is left in the stockpile h.db.run('UPDATE landing_sites SET fiber = 9000, hardware = 9000, capital = 9000 WHERE id = ?', site.id); const q2 = build(b); assert.equal(q2.toLevel, 2); assert.deepEqual(q2.cost, R.backboneCost(2)); h.advanceTo(q2.dueAt); assert.equal(siteOf(h, 3).level, 2); assert.equal(T.notes(h, b.userId, 'backbone_level').length, 0, 'only every 10th level is announced'); assert.equal(h.db.all("SELECT 1 FROM events WHERE status = 'failed'").length, 0); }); test('winning: level 100 makes the holder the winner, the world ends two world days later with a ranking, then it is frozen but readable', () => { const h = world(100, { speed: 2 }); const a = near(h, 'alice', 4, { produce: true }); const a2 = near(h, 'alice2', 4, { x: h.sites[4].x - 4, y: h.sites[4].y + 3 }); const b = near(h, 'bob', 4, { x: h.sites[4].x + 4, y: h.sites[4].y, units: { script_crew: 20 } }); const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b); T.giveUnits(h, a.townId, { script_crew: 40 }); h.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 12.5, 3), (?, 40, 1)', a.opId, b.opId); E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, level = 99, fiber = 1e7, hardware = 1e7, capital = 1e7 WHERE idx = 4', A1, a.opId); const site = siteOf(h, 4); const q = h.run('backboneBuild', { userId: a.userId, siteId: site.id }); assert.equal(q.toLevel, 100); assert.equal(h.eg.status(a.userId, h.worldId).winner, null); const wonAt = q.dueAt; h.advanceTo(wonAt); const w = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId); assert.equal(w.winner_alliance_id, A1); assert.equal(w.winner_name, 'Alpha'); assert.equal(w.won_at, wonAt); assert.equal(w.status, 'running', 'the world goes on for two days'); assert.equal(w.end_at, wonAt + DAY, 'two WORLD days at speed 2 = one real day'); assert.equal(T.notes(h, b.userId, 'backbone_won').length, 1, 'everybody hears who won'); assert.equal(T.notes(h, a2.userId, 'backbone_level').length, 1); const st = h.eg.status(b.userId, h.worldId); assert.equal(st.winner.allianceId, A1); assert.equal(st.winner.tag, 'ALP'); assert.equal(st.endsAt, wonAt + DAY); assert.equal(st.endedAt, null); assert.equal(st.phase, 'backbone_open'); assert.equal(h.eg.results(b.userId, h.worldId).available, false); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd' AND status = 'pending'").n, 1); // still playable during the grace period; the winner is fixed even if the site is lost h.run('renameTown', { userId: a.userId, townId: a.townId, name: 'Still Playing' }); assert.equal(err(() => h.run('backboneBuild', { userId: a.userId, siteId: site.id })).code, 'max_level'); h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' }); // something in the queue that the end will cancel const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'capital', giveAmount: 100, wantRes: 'fiber', wantAmount: 100, maxDistance: 30 }).offer; // open at the end h.advanceTo(w.end_at - 1); assert.equal(h.db.get('SELECT status FROM worlds WHERE id = ?', h.worldId).status, 'running'); h.advanceTo(w.end_at); const ended = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId); assert.equal(ended.status, 'ended'); assert.equal(ended.end_at, w.end_at); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", h.worldId).n, 0, 'the world is frozen: nothing pending'); assert.equal(T.notes(h, a.userId, 'world_ended').length, 1); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired', 'open offers end with the world: the escrow is back in its POP'); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE status = 'open'").n, 0); // the snapshot const res = h.eg.results(b.userId, h.worldId); assert.equal(res.available, true); assert.equal(res.status, 'ended'); assert.equal(res.results.winner.name, 'Alpha'); assert.equal(res.results.operators.length, 3); assert.deepEqual(res.results.operators.map((o) => o.rank), [1, 2, 3]); assert.ok(res.results.operators[0].footprint >= res.results.operators[1].footprint); assert.equal(res.results.alliances.length, 2); assert.equal(res.results.alliances[0].members + res.results.alliances[1].members, 3); assert.deepEqual(res.results.attackers.map((o) => o.name), ['bob', 'alice']); assert.deepEqual(res.results.defenders.map((o) => o.name), ['alice', 'bob']); assert.equal(res.results.sites.find((s) => s.index === 4).level, 100); const stored = JSON.parse(h.db.get('SELECT data FROM world_rankings WHERE world_id = ?', h.worldId).data); assert.deepEqual(stored, res.results); // ended: every game command is refused with one stable code ... const refused = (name, args) => assert.equal(err(() => h.run(name, args)).code, 'world_ended', name); refused('build', { userId: a.userId, townId: a.townId, key: 'firewall' }); refused('renameTown', { userId: a.userId, townId: a.townId, name: 'x' }); refused('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', x: b.x, y: b.y, units: { port_scanner: 1 } }); refused('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: a2.townId, cargo: { fiber: 1 } }); refused('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 }); refused('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: 10, wantRes: 'capital', wantAmount: 10, maxDistance: 5 }); refused('tradeAccept', { userId: a.userId, offerId: 1, townId: a.townId }); refused('backboneBuild', { userId: a.userId, siteId: site.id }); refused('backboneShip', { userId: a.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 1 } }); refused('allianceCreate', { userId: a2.userId, worldId: h.worldId, name: 'New', tag: 'NW' }); refused('allianceLeave', { userId: a2.userId, allianceId: A1 }); refused('diploPropose', { userId: a.userId, allianceId: A1, targetId: B1, state: 'war' }); refused('reportShare', { userId: a.userId, reportId: 1 }); refused('recallMovement', { userId: a.userId, movementId: 1 }); refused('joinWorld', { userId: a.userId, worldId: h.worldId }); // ... except reading state and talking h.run('markReportRead', { userId: a.userId, all: true }); assert.equal(h.run('messageSend', { userId: a.userId, toOperatorId: b.opId, text: 'gg' }).recipients, 1); // ... and everything stays readable assert.equal(h.queries.map(a.userId, { x: 0, y: 0, r: 40 }).world.status, 'ended'); assert.ok(h.queries.map(a.userId, { x: 0, y: 0, r: 40 }).specials.some((s) => s.type === 'backbone')); assert.ok(h.mq.reports(a.userId, {}).items.length >= 0); assert.ok(h.queries.town(a.userId, a.townId).town.id === a.townId); assert.equal(h.eg.status(a.userId, h.worldId).phase, 'ended'); assert.equal(h.eg.status(a.userId, h.worldId).endedAt, w.end_at); assert.equal(h.eg.site(a.userId, site.id).site.level, 100); // running it again changes nothing (idempotent) const snap = JSON.stringify(h.db.get('SELECT * FROM world_rankings')); require('../server/events/worldEnd')(Object.assign(h.ctx(), { now: w.end_at }), { id: 0, worldId: h.worldId, dueAt: w.end_at + 5, payload: {} }); assert.equal(JSON.stringify(h.db.get('SELECT * FROM world_rankings')), snap); }); test('winner is fixed at level 100: losing the node during the grace period does not change it; a disbanded holder leaves the site to the incumbent (level stays)', () => { const h = world(100); const a = near(h, 'alice', 5); const b = near(h, 'bob', 5, { x: h.sites[5].x + 4, y: h.sites[5].y, units: { script_crew: 4700 } }); const A1 = alliance(h, 'Alpha', a), B1 = alliance(h, 'Bravo', b); E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, level = 99, fiber = 1e7, hardware = 1e7, capital = 1e7 WHERE idx = 5', A1, a.opId); const site = siteOf(h, 5); const q = h.run('backboneBuild', { userId: a.userId, siteId: site.id }); h.advanceTo(q.dueAt); assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1); const atk = attack(h, b, 5, { script_crew: 4700 }); h.advanceTo(atk.arriveAt); assert.equal(siteOf(h, 5).holder_alliance_id, B1, 'bob took the finished node'); assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1, 'but alice\'s alliance already won'); // the site keeps its level when its holder disbands A.dissolve(Object.assign(h.ctx(), { scheduler: h.scheduler }), B1, 'test'); assert.equal(siteOf(h, 5).holder_alliance_id, null); assert.equal(siteOf(h, 5).level, 100); assert.equal(h.eg.status(a.userId, h.worldId).sites[5].holder, null); }); test('a finished node taken while nobody wins yet completes for the new holder; only one winner per world', () => { const h = world(100); const a = near(h, 'alice', 6, { units: { script_crew: 4700 } }); const A1 = alliance(h, 'Alpha', a); E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET level = 100 WHERE idx = 6'); // finished while its holder was disbanded: nobody won assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, null); const atk = attack(h, a, 6, { script_crew: 4700 }); h.advanceTo(atk.arriveAt); assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd'").n, 1); // a second node reaching 100 does not start a second ending const ctx = h.ctx(); E.ensureSites(h.db, h.world, h.clock.now()); h.db.run('UPDATE landing_sites SET level = 100, holder_alliance_id = ? WHERE idx = 0', A1); assert.equal(E.maybeWin(ctx, siteOf(h, 0), h.clock.now()), false); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd'").n, 1); }); test('ended worlds over HTTP: reads work, writes say world_ended; status and results routes follow their schemas', async () => { const { createTestServer } = require('./helpers'); const t = await createTestServer({ contract: true }); try { const a = await t.signup('alice'); const w = t.srv.db.get('SELECT * FROM worlds'); let r = await t.api('/worlds/' + w.id + '/status', {}, a.token); assert.equal(r.status, 200); assert.equal(r.body.phase, 'running'); assert.equal((await t.api('/worlds/999/status', {}, a.token)).status, 404); assert.equal((await t.api('/worlds/' + w.id + '/status')).status, 401); r = await t.api('/worlds/' + w.id + '/results', {}, a.token); assert.equal(r.body.available, false); // jump to the end t.srv.db.run("UPDATE worlds SET winner_alliance_id = NULL, winner_name = 'Win', winner_tag = 'WIN', won_at = ?, end_at = ?, start_at = ? WHERE id = ?", t.clock.now(), t.clock.now() + 1000, t.clock.now() - 101 * DAY, w.id); t.srv.scheduler.enqueue({ worldId: w.id, dueAt: t.clock.now() + 1000, type: 'worldEnd', payload: {} }); t.clock.advance(1000); r = await t.api('/worlds/' + w.id + '/status', {}, a.token); assert.equal(r.body.phase, 'ended'); assert.equal(r.body.winner.name, 'Win'); assert.equal(r.body.sites.length, 7); r = await t.api('/worlds/' + w.id + '/results', {}, a.token); assert.equal(r.body.available, true); assert.equal(r.body.results.operators[0].name, 'alice'); const build = await t.api('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'firewall' } }, a.token); assert.equal(build.status, 409); assert.equal(build.body.error.code, 'world_ended'); for (const p of ['/me', '/map?x=0&y=0&r=5', '/reports', '/rankings/operators', '/rankings/alliances', '/rankings/battles', '/towns/' + a.townId, '/movements', '/trade/offers', '/notifications', '/map/tile?x=0&y=0']) { const g = await t.api(p, {}, a.token); assert.equal(g.status, 200, p + ' -> ' + JSON.stringify(g.body).slice(0, 200)); } const post = await t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 10, wantRes: 'capital', wantAmount: 10, maxDistance: 5 } }, a.token); assert.equal(post.body.error.code, 'world_ended'); } finally { await t.close(); } }); test('backbone routes over HTTP: site detail, ship, build follow their schemas and permissions', async () => { const { createTestServer } = require('./helpers'); const t = await createTestServer({ contract: true }); try { const lead = await t.signupPeering('lead'), mem = await t.signupPeering('mem'), out = await t.signup('outsider'); t.setBuilding(mem.townId, 'internet_exchange', 2); const w = t.srv.db.get('SELECT * FROM worlds'); assert.equal((await t.api('/backbone/1', {}, lead.token)).status, 404, 'no such site yet'); t.srv.db.run('UPDATE worlds SET start_at = ? WHERE id = ?', t.clock.now() - 101 * DAY, w.id); const mk = await t.api('/alliances', { method: 'POST', body: { name: 'Backers', tag: 'BKR' } }, lead.token); const inv = await t.api('/alliances/' + mk.body.allianceId + '/invite', { method: 'POST', body: { operatorId: mem.operatorId } }, lead.token); await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, mem.token); const world = require('../server/state').loadWorld(t.srv.db, w.id); E.ensureSites(t.srv.db, world, t.clock.now()); t.srv.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 0', mk.body.allianceId, lead.operatorId); const site = t.srv.db.get('SELECT * FROM landing_sites WHERE idx = 0'); let r = await t.api('/worlds/' + w.id + '/status', {}, out.token); assert.equal(r.body.phase, 'backbone_open'); assert.equal(r.body.sites[0].holder.tag, 'BKR'); r = await t.api('/backbone/' + site.id, {}, out.token); assert.equal(r.status, 200); assert.equal(r.body.you.holder, false); assert.equal(r.body.contributions, undefined); r = await t.api('/backbone/' + site.id, {}, mem.token); assert.equal(r.body.you.canBuild, true); assert.deepEqual(r.body.contributions, []); // strangers: 403 on ship and build assert.equal((await t.api('/backbone/' + site.id + '/ship', { method: 'POST', body: { fromTownId: out.townId, cargo: { fiber: 5 } } }, out.token)).status, 403); assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, out.token)).status, 403); assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, mem.token)).body.error.code, 'not_enough_resources'); const ship = await t.api('/backbone/' + site.id + '/ship', { method: 'POST', body: { fromTownId: mem.townId, cargo: { fiber: 100, capital: 50 } } }, mem.token); assert.equal(ship.status, 201); assert.equal(ship.body.siteId, site.id); assert.equal(ship.body.toTownId, null); const mv = await t.api('/movements', {}, mem.token); assert.equal(mv.body.outgoing[0].siteId, site.id, 'the movement list says it is a shipment to a site'); t.clock.advance(ship.body.arriveAt - t.clock.now()); t.srv.scheduler.runDue(); r = await t.api('/backbone/' + site.id, {}, lead.token); assert.deepEqual(r.body.site.pool, { fiber: 100, hardware: 0, capital: 50 }); assert.deepEqual(r.body.contributions.map((c) => [c.name, c.fiber, c.capital]), [['mem', 100, 50]]); t.srv.db.run('UPDATE landing_sites SET fiber = 4000, hardware = 4000, capital = 4000 WHERE id = ?', site.id); const b = await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, lead.token); assert.equal(b.status, 201); assert.equal(b.body.toLevel, 1); assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, lead.token)).body.error.code, 'already_queued'); t.clock.advance(b.body.dueAt - t.clock.now()); t.srv.scheduler.runDue(); r = await t.api('/worlds/' + w.id + '/status', {}, out.token); assert.equal(r.body.sites[0].level, 1); assert.equal(r.body.sites[0].build, null); const map = await t.api('/map?x=' + site.x + '&y=' + site.y + '&r=2', {}, out.token); const sp = map.body.specials.find((x) => x.type === 'backbone'); assert.equal(sp.site.level, 1); assert.equal(sp.site.holder.tag, 'BKR'); const tile = await t.api('/map/tile?x=' + site.x + '&y=' + site.y, {}, lead.token); assert.equal(tile.body.type, 'backbone'); assert.equal(tile.body.backbone.mine, true); } finally { await t.close(); } });