197 lines
10 KiB
TypeScript
197 lines
10 KiB
TypeScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
|
|
import { ModeHost, GameError } from '../server/game/host.ts';
|
|
import { MatchStore } from '../server/game/store.ts';
|
|
import { ModeDiscovery } from '../server/game/discovery.ts';
|
|
import { stubEngine } from './modes-stub-engine.ts';
|
|
|
|
const mode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, id: 'stub', version: 1, name: 'Stub',
|
|
description: 'Stub mode.', decks: { kind: 'starter' }, ...over });
|
|
const identity = { origin: 'http://node-a.test', operator: 'Alice' };
|
|
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
|
|
const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' };
|
|
|
|
function playOut(host: ModeHost, lobbyId: string, tokens: string[]) {
|
|
for (let guard = 0; guard < 50; guard++) {
|
|
const v0 = host.view(lobbyId, tokens[0]) as any;
|
|
if (v0.phase !== 'playing') return v0;
|
|
for (const t of tokens) {
|
|
const v = host.view(lobbyId, t) as any;
|
|
if (v.legalActions?.length) void host.act(lobbyId, t, v.legalActions[0]);
|
|
}
|
|
}
|
|
throw new Error('did not finish');
|
|
}
|
|
|
|
test('modes host: lobby → match → record → leaderboard and host credit', async () => {
|
|
let now = 1_000_000;
|
|
const store = new MatchStore(null);
|
|
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store, now: () => now });
|
|
const a = host.createLobby('stub', alice);
|
|
assert.equal(host.list().modes[0]!.stats.openLobbies, 1);
|
|
assert.deepEqual(host.openLobbies('stub').map(l => l.host), ['Alice']);
|
|
const b = await host.join(a.lobbyId, bob);
|
|
assert.equal(b.seat, 1);
|
|
assert.equal((host.view(a.lobbyId) as any).state, undefined, 'spectators see no private state');
|
|
const end = playOut(host, a.lobbyId, [a.token, b.token]);
|
|
assert.equal(end.phase, 'finished');
|
|
const list = host.list();
|
|
assert.equal(list.matchesHosted, 1);
|
|
assert.equal(list.host.operator, 'Alice');
|
|
assert.equal(list.modes[0]!.stats.matchesPlayed, 1);
|
|
assert.equal(list.modes[0]!.stats.distinctPlayers, 2);
|
|
const board = host.leaderboard('stub');
|
|
assert.equal(board.entries.length, 2);
|
|
assert.equal(board.key, 'http://node-a.test#stub@1');
|
|
const rec = host.matchRecord(end.matchId);
|
|
assert.equal(rec.actions.length, 6);
|
|
assert.equal(rec.players[0]!.name, 'Alice');
|
|
assert.ok(!JSON.stringify(rec).includes(alice.secret), 'secrets are never stored');
|
|
});
|
|
|
|
test('modes host: actions must be legal and from the right seat', async () => {
|
|
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(null) });
|
|
const a = host.createLobby('stub', alice);
|
|
const b = await host.join(a.lobbyId, bob);
|
|
await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 99 }), /Illegal/);
|
|
await assert.rejects(host.act(a.lobbyId, 'not-a-token-xxxxxxxxxxxx', { type: 'play', card: 0 }), /Not a player/);
|
|
await host.act(a.lobbyId, a.token, { type: 'play', card: 0 });
|
|
await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 0 }), /Illegal/, 'no double play');
|
|
await host.act(a.lobbyId, b.token, { card: 1, type: 'play' }); // key order doesn't matter
|
|
await assert.rejects(host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' }), /no longer open/);
|
|
assert.throws(() => host.createLobby('stub', { name: '<script>', secret: alice.secret }), GameError);
|
|
assert.throws(() => host.createLobby('stub', { name: 'Al', secret: 'short' }), GameError);
|
|
assert.throws(() => host.createLobby('nope', alice), /not hosted/);
|
|
});
|
|
|
|
test('modes host: limits, expiry and turn timeouts', async () => {
|
|
let now = 0;
|
|
const host = new ModeHost({ identity, modes: [mode({ limits: { maxConcurrentMatches: 2, turnSeconds: 10, lobbyMinutes: 1 } })],
|
|
engine: stubEngine, store: new MatchStore(null), now: () => now });
|
|
const l1 = host.createLobby('stub', alice);
|
|
host.createLobby('stub', bob);
|
|
assert.throws(() => host.createLobby('stub', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' }), /match limit/);
|
|
now += 61_000; host.sweep();
|
|
assert.equal((host.view(l1.lobbyId) as any).phase, 'expired');
|
|
const l3 = host.createLobby('stub', alice);
|
|
const t3 = await host.join(l3.lobbyId, bob);
|
|
await host.act(l3.lobbyId, l3.token, { type: 'play', card: 0 }); // Bob now owes a move
|
|
now += 11_000; host.sweep();
|
|
const v = host.view(l3.lobbyId, t3.token) as any;
|
|
assert.deepEqual(v.outcome, { winner: 0, reason: 'timeout' });
|
|
assert.equal(host.list().matchesHosted, 1);
|
|
});
|
|
|
|
test('modes host: snake draft builds both decks from one pool', async () => {
|
|
const host = new ModeHost({ identity, modes: [mode({ decks: { kind: 'draft', poolSize: 8, pickSeconds: 10 } })],
|
|
engine: stubEngine, store: new MatchStore(null) });
|
|
const a = host.createLobby('stub', alice);
|
|
const b = await host.join(a.lobbyId, bob);
|
|
const tok = [a.token, b.token];
|
|
const order: number[] = [];
|
|
for (;;) {
|
|
const v = host.view(a.lobbyId, a.token) as any;
|
|
if (v.phase !== 'drafting') break;
|
|
order.push(v.draft.toPick);
|
|
const free = v.draft.pool.find((c: any) => c.takenBy === null).index;
|
|
await assert.rejects(host.pick(a.lobbyId, tok[1 - v.draft.toPick]!, free), /Not your pick/);
|
|
await host.pick(a.lobbyId, tok[v.draft.toPick]!, free);
|
|
}
|
|
assert.equal(order.length, 8);
|
|
assert.deepEqual(order.slice(0, 4), [order[0], 1 - order[0]!, 1 - order[0]!, order[0]], 'snake order');
|
|
assert.equal((host.view(a.lobbyId, a.token) as any).phase, 'playing');
|
|
assert.throws(() => new ModeHost({ identity, modes: [mode({ decks: { kind: 'draft', poolSize: 8 }, rules: { deckSize: 5 } })],
|
|
engine: stubEngine, store: new MatchStore(null) }), /poolSize/);
|
|
});
|
|
|
|
test('modes host: trending mapping adjusts power from live trends, once, bounded', async () => {
|
|
const seen: number[] = [];
|
|
const host = new ModeHost({ identity, modes: [mode({ cards: { preset: 'trending', percentPerPoint: 10, maxBonus: 2 } })],
|
|
engine: stubEngine, store: new MatchStore(null),
|
|
liveData: async pageId => { seen.push(pageId); return { trendPercent: pageId % 2 ? 1000 : -1000 }; } });
|
|
const a = host.createLobby('stub', alice);
|
|
const b = await host.join(a.lobbyId, bob);
|
|
const base = stubEngine.starterDeck(stubEngine.defaultRuleset, 'x');
|
|
const hand = (host.view(a.lobbyId, a.token) as any).state.hand;
|
|
assert.equal(seen.length, 8);
|
|
for (const c of hand) assert.ok(c.power >= 0 && c.power <= 11);
|
|
void b; void base;
|
|
});
|
|
|
|
test('modes host: bad rules fail at startup, via the engine parser', () => {
|
|
assert.throws(() => new ModeHost({ identity, modes: [mode({ rules: { turns: 99 } })], engine: stubEngine, store: new MatchStore(null) }));
|
|
assert.throws(() => new ModeHost({ identity, modes: [mode(), mode()], engine: stubEngine, store: new MatchStore(null) }), /Duplicate/);
|
|
});
|
|
|
|
test('modes store: records persist and rebuild aggregates; torn lines are skipped', async () => {
|
|
const dir = mkdtempSync(join(tmpdir(), 'modes-store-'));
|
|
try {
|
|
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(dir) });
|
|
const a = host.createLobby('stub', alice);
|
|
const b = await host.join(a.lobbyId, bob);
|
|
playOut(host, a.lobbyId, [a.token, b.token]);
|
|
const file = join(dir, 'matches.jsonl');
|
|
const { appendFileSync } = await import('node:fs');
|
|
appendFileSync(file, '{"torn":');
|
|
const reopened = new MatchStore(dir);
|
|
assert.equal(reopened.total, 1);
|
|
assert.equal(reopened.leaderboard('stub').length, 2);
|
|
assert.ok(readFileSync(file, 'utf8').includes('"modeId":"stub"'));
|
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('modes discovery: peers are fetched as data, origin is pinned, failures are contained', async () => {
|
|
const good = { schema: MODE_SCHEMA_VERSION, host: { origin: 'https://evil.example', operator: 'Bob' }, matchesHosted: 7,
|
|
modes: [{ mode: mode(), stats: { playersOnline: 1, openLobbies: 1, liveMatches: 0, matchesPlayed: 7, distinctPlayers: 3 } }] };
|
|
let calls = 0, now = 0;
|
|
const fetcher = async (url: string) => {
|
|
calls++;
|
|
if (url.startsWith('http://b.test')) return new Response(JSON.stringify(good), { status: 200 });
|
|
if (url.startsWith('http://c.test')) return new Response('x'.repeat(400_000), { status: 200 });
|
|
throw new Error('connect ECONNREFUSED');
|
|
};
|
|
const d = new ModeDiscovery({ peers: ['http://b.test', 'http://c.test', 'http://d.test'], fetcher, now: () => now, ttlMs: 1000 });
|
|
const peers = await d.all();
|
|
assert.equal(peers[0]!.ok, true);
|
|
assert.equal(peers[0]!.list!.host.origin, 'http://b.test', 'claimed origin replaced by the fetched one');
|
|
assert.equal(peers[1]!.ok, false);
|
|
assert.equal(peers[1]!.error, 'response too large');
|
|
assert.equal(peers[2]!.error, 'invalid or unreachable');
|
|
await d.all();
|
|
assert.equal(calls, 3, 'cached within ttl');
|
|
now = 5000; await d.all();
|
|
assert.equal(calls, 6);
|
|
});
|
|
|
|
test('modes trends: cache-only at match time, warmed one page at a time', async () => {
|
|
const { TrendCache } = await import('../server/game/trends.ts');
|
|
const calls: number[] = [];
|
|
let now = 0;
|
|
const t = new TrendCache(async id => { calls.push(id); if (id === 2) throw new Error('rate limited'); return { pageviews: { trendPercent: id * 10 } }; },
|
|
{ now: () => now, ttlMs: 1000 });
|
|
assert.equal(t.get(1), null, 'cold page: no bonus, no fetch in the request path');
|
|
assert.equal(t.get(2), null);
|
|
t.get(1);
|
|
assert.deepEqual(calls, []);
|
|
await t.step(); await t.step();
|
|
assert.deepEqual(calls, [1, 2], 'one fetch per step, deduplicated');
|
|
assert.deepEqual(t.get(1), { trendPercent: 10 });
|
|
assert.equal(t.get(2), null, 'failure stays cold');
|
|
now = 5000; t.get(1); await t.step(); await t.step();
|
|
assert.deepEqual(calls, [1, 2, 2, 1], 'stale entries are refreshed in the background');
|
|
});
|
|
|
|
test('modes host: two concurrent joins cannot both take the second seat', async () => {
|
|
const slow = { ...stubEngine };
|
|
const host = new ModeHost({ identity, modes: [mode({ cards: { preset: 'trending' } })], engine: slow, store: new MatchStore(null),
|
|
liveData: async () => { await new Promise(r => setTimeout(r, 20)); return { trendPercent: 0 }; } });
|
|
const a = host.createLobby('stub', alice);
|
|
const results = await Promise.allSettled([host.join(a.lobbyId, bob), host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' })]);
|
|
assert.equal(results.filter(r => r.status === 'fulfilled').length, 1);
|
|
assert.equal((host.view(a.lobbyId) as any).players.length, 2);
|
|
});
|