'use strict'; /* Which hint goes to whom (server/pushHooks.js), end to end: REST commands and the event queue on a fake clock, real * WebSocket clients. Push is only a hint: every assertion on a hint is paired with the REST/DB truth it points at. */ const test = require('node:test'); const assert = require('node:assert'); const { createTestServer } = require('./helpers'); const { login, sleep } = require('./push-helpers'); const D = require('../public/js/data.js'); const H = D.HOUR_MS; const post = (body) => ({ method: 'POST', body }); test('build: command hint on all devices of the owner, then town + notification when it finishes; nothing for others', async () => { const t = await createTestServer(); try { const alice = await t.signup('alice'), bob = await t.signup('bobby'); const login2 = await t.api('/auth/login', post({ username: 'alice', password: 'correct horse battery' })); const a1 = await login(t.srv, alice.token), a2 = await login(t.srv, login2.body.token), b = await login(t.srv, bob.token); const r = await t.api('/towns/' + alice.townId + '/build', post({ key: 'f1' }), alice.token); assert.equal(r.status, 201, JSON.stringify(r.body)); for (const c of [a1, a2]) await c.waitFor((m) => m.type === 'town' && m.townId === alice.townId); await sleep(50); for (const c of [a1, a2]) c.msgs.length = 0; t.clock.advance(r.body.dueAt - t.clock.now()); t.srv.scheduler.runDue(); // the buildDone event fires for (const c of [a1, a2]) { const town = await c.waitFor((m) => m.type === 'town' && m.townId === alice.townId); assert.deepEqual(town, { type: 'town', townId: alice.townId }); const n = await c.waitFor((m) => m.type === 'notification'); assert.equal(n.kind, 'build_done'); const row = t.srv.db.get('SELECT type FROM notifications WHERE id = ?', n.id); assert.equal(row.type, 'build_done', 'the id points at a real notification row'); } assert.deepEqual((await b.settle(100)).filter((m) => m.type !== 'ready'), [], 'another player hears nothing'); const poll = await t.api('/notifications', {}, alice.token); assert.ok(poll.body.items.some((x) => x.id === a1.msgs.find((m) => m.type === 'notification').id), 'and REST agrees'); } finally { await t.close(); } }); test('train done: town + notification (train_done)', async () => { const t = await createTestServer(); try { const a = await t.signup('alice'); t.clock.advance(73 * H); for (const [k, lv] of [['ops_lab', 3], ['noc', 2]]) t.srv.db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, k, k, lv); t.srv.db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId); const c = await login(t.srv, a.token); const r = await t.api('/towns/' + a.townId + '/train', post({ unit: 'script_crew', count: 5 }), a.token); assert.equal(r.status, 201, JSON.stringify(r.body)); await c.waitFor((m) => m.type === 'town'); // command hint await c.settle(50); c.msgs.length = 0; t.clock.set(r.body.dueAt); t.srv.scheduler.runDue(); await c.waitFor((m) => m.type === 'town' && m.townId === a.townId); const n = await c.waitFor((m) => m.type === 'notification'); assert.equal(n.kind, 'train_done'); } finally { await t.close(); } }); // alice raids bobby: bobby gets 'incoming' (only him), a report lands for both async function raidSetup(t) { const a = await t.signup('alice'), b = await t.signup('bobby'); const db = t.srv.db; t.clock.advance(73 * H); // beginner protection over for (const [k, lv] of [['ops_lab', 3], ['research_lab', 3], ['noc', 2]]) db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, k, k, lv); db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId); let r = await t.api('/towns/' + a.townId + '/train', post({ unit: 'script_crew', count: 20 }), a.token); assert.equal(r.status, 201, JSON.stringify(r.body)); t.clock.advance(3 * H); t.srv.scheduler.runDue(); return { a, b }; } test('incoming attack: defender gets incoming (+ notification), attacker does not; then report hints for both', async () => { const t = await createTestServer(); try { const { a, b } = await raidSetup(t); const ca = await login(t.srv, a.token), cb = await login(t.srv, b.token); await sleep(30); ca.msgs.length = 0; cb.msgs.length = 0; const r = await t.api('/movements', post({ fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } }), a.token); assert.equal(r.status, 201, JSON.stringify(r.body)); const inc = await cb.waitFor((m) => m.type === 'incoming'); assert.deepEqual(inc, { type: 'incoming', townId: b.townId, arriveAt: r.body.arriveAt }, 'town and ETA only, no type, no origin'); const note = await cb.waitFor((m) => m.type === 'notification' && m.kind === 'incoming'); assert.ok(t.srv.db.get('SELECT 1 AS x FROM notifications WHERE id = ? AND user_id = ?', note.id, b.userId)); const mine = await ca.settle(100); assert.ok(!mine.some((m) => m.type === 'incoming' || m.type === 'notification'), 'the attacker gets no warning: ' + JSON.stringify(mine)); assert.ok(mine.some((m) => m.type === 'town' && m.townId === a.townId), 'but a town hint for the POP that sent the units'); assert.ok(!cb.msgs.some((m) => m.type === 'town'), 'no plain town hint for the target at launch (the warning carries the ETA)'); ca.msgs.length = 0; cb.msgs.length = 0; t.clock.set(r.body.arriveAt); t.srv.scheduler.runDue(); // combat resolves const rep = t.srv.db.get('SELECT id FROM reports ORDER BY id DESC LIMIT 1'); assert.ok(rep); for (const c of [ca, cb]) { const m = await c.waitFor((x) => x.type === 'report'); assert.deepEqual(m, { type: 'report', id: rep.id }); await c.waitFor((x) => x.type === 'notification' && x.kind === 'report'); } await cb.waitFor((m) => m.type === 'town' && m.townId === b.townId); // the attacked POP changed const view = await t.api('/reports/' + rep.id, {}, b.token); assert.equal(view.status, 200, 'the id in the hint is fetchable over REST'); } finally { await t.close(); } }); test('recall: the target owner learns the warning is gone (town hint), the sender gets his POP hint', async () => { const t = await createTestServer(); try { const { a, b } = await raidSetup(t); const ca = await login(t.srv, a.token), cb = await login(t.srv, b.token); const r = await t.api('/movements', post({ fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } }), a.token); await cb.waitFor((m) => m.type === 'incoming'); await sleep(50); cb.msgs.length = 0; ca.msgs.length = 0; const rc = await t.api('/movements/' + r.body.movementId + '/recall', post({}), a.token); assert.equal(rc.status, 200, JSON.stringify(rc.body)); await cb.waitFor((m) => m.type === 'town' && m.townId === b.townId); await ca.waitFor((m) => m.type === 'town' && m.townId === a.townId); } finally { await t.close(); } }); test('messages and alliance invites: message hint with id, notification with kind alliance_invite', async () => { const t = await createTestServer(); try { const lead = await t.signupPeering('leader'), bob = await t.signup('bobby'); const cl = await login(t.srv, lead.token), cb = await login(t.srv, bob.token); let r = await t.api('/messages', post({ toOperatorId: bob.operatorId, text: 'hello there' }), lead.token); assert.equal(r.status, 201, JSON.stringify(r.body)); const m = await cb.waitFor((x) => x.type === 'message'); assert.deepEqual(m, { type: 'message', id: r.body.messageId }); assert.equal((await cb.waitFor((x) => x.type === 'notification' && x.kind === 'message')).kind, 'message'); assert.ok(!(await cl.settle(50)).some((x) => x.type === 'message'), 'the sender gets no message hint'); r = await t.api('/alliances', post({ name: 'Pushers', tag: 'PSH' }), lead.token); assert.equal(r.status, 201, JSON.stringify(r.body)); const inv = await t.api('/alliances/' + r.body.allianceId + '/invite', post({ operatorId: bob.operatorId }), lead.token); assert.equal(inv.status, 201, JSON.stringify(inv.body)); const n = await cb.waitFor((x) => x.type === 'notification' && x.kind === 'alliance_invite'); assert.ok(t.srv.db.get("SELECT 1 AS x FROM notifications WHERE id = ? AND type = 'alliance_invite'", n.id)); } finally { await t.close(); } }); test('hints are coalesced: identical hints produced in one tick go out once, distinct ones all arrive in order', async () => { const t = await createTestServer(); try { const a = await t.signup('alice'); const c = await login(t.srv, a.token); for (let i = 0; i < 50; i++) t.srv.push.toTown(a.townId, { type: 'town', townId: a.townId }); // e.g. a long catch-up t.srv.push.toUser(a.userId, { type: 'notification', id: 1, kind: 'x' }); t.srv.push.toUser(a.userId, { type: 'notification', id: 2, kind: 'x' }); t.srv.push.toUser(a.userId, { type: 'notification', id: 1, kind: 'x' }); await c.waitFor((m) => m.type === 'notification' && m.id === 2); await c.settle(50); const got = c.msgs.filter((m) => m.type !== 'ready'); assert.deepEqual(got, [{ type: 'town', townId: a.townId }, { type: 'notification', id: 1, kind: 'x' }, { type: 'notification', id: 2, kind: 'x' }]); t.srv.push.toUser(999999, { type: 'town', townId: 1 }); // unknown user: silently nothing t.srv.push.toTown(999999, { type: 'town', townId: 999999 }); // unknown POP: silently nothing } finally { await t.close(); } }); test('rollback: a notification written by an event or command that then fails is never pushed (hints follow the commit)', async () => { const t = await createTestServer(); try { const a = await t.signup('alice'); const c = await login(t.srv, a.token); const sc = t.srv.scheduler; sc.register('boom', (ctx, ev) => { ctx.notify(a.userId, ev.worldId, 'ghost', {}); throw new Error('handler failed'); }); sc.register('fine', (ctx, ev) => { ctx.notify(a.userId, ev.worldId, 'real', {}); }); t.srv.commands.handlers.boomCmd = (ctx) => { ctx.scheduler.notify(a.userId, null, 'ghost_cmd', {}); throw new Error('command failed'); }; t.srv.commands.handlers.fineCmd = (ctx) => { ctx.scheduler.notify(a.userId, null, 'real_cmd', {}); return {}; }; const worldId = t.srv.db.get('SELECT id FROM worlds').id; const now = t.clock.now(); sc.enqueue({ worldId, dueAt: now + 10, type: 'boom', payload: {} }); sc.enqueue({ worldId, dueAt: now + 20, type: 'fine', payload: {} }); t.clock.advance(100); sc.runDue(); assert.throws(() => t.srv.commands.run('boomCmd', {}), /command failed/); t.srv.commands.run('fineCmd', {}); await c.waitFor((m) => m.kind === 'real_cmd'); const kinds = (await c.settle(60)).filter((m) => m.type === 'notification').map((m) => m.kind); assert.deepEqual(kinds, ['real', 'real_cmd']); assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM notifications WHERE type IN ('ghost', 'ghost_cmd')").n, 0, 'the rows rolled back too'); assert.equal(sc.outbox.length, 0); } finally { await t.close(); } });