1#!/usr/bin/env node
2/**
3 * smoke.mjs — headless full-cycle smoke test for the game server.
4 * Phase 1: written per contract, not executed yet (server may not exist).
5 * Phase 2: run with `node test/smoke.mjs` from game/ after `npm i -D socket.io-client`.
6 *
7 * Spawns server (node server/index.js, PORT=3210), runs checks via socket.io-client,
8 * prints PASS/FAIL per check and exits 0/1.
9 */
10import { spawn } from 'node:child_process';
11import { setTimeout as delay } from 'node:timers/promises';
12import process from 'node:process';
13import http from 'node:http';
14
15const PORT = Number(process.env.SMOKE_PORT || 3210);
16const BASE_URL = `http://localhost:${PORT}`;
17const TOTAL_TIMEOUT_MS = 120_000;
18const STEP_TIMEOUT_MS = 15_000;
19const TICK_WAIT_MS = 22_000; // ~4 ticks at 5s
20
21// --- minimal assert/reporting helpers (no external deps) ---
22const results = [];
23function record(name, ok, detail = '') {
24 results.push({ name, ok, detail });
25 const mark = ok ? 'PASS' : 'FAIL';
26 const suffix = detail ? ` — ${detail}` : '';
27 console.log(`[${mark}] ${name}${suffix}`);
28}
29function assert(cond, name, detail = '') {
30 record(name, !!cond, cond ? detail : (detail || 'assertion failed'));
31 return !!cond;
32}
33function fail(name, detail) { record(name, false, detail); }
34
35function withTimeout(promise, ms, label) {
36 let t;
37 const timeout = new Promise((_, rej) => {
38 t = setTimeout(() => rej(new Error(`timeout ${ms}ms: ${label}`)), ms);
39 });
40 return Promise.race([promise.finally(() => clearTimeout(t)), timeout]);
41}
42
43async function waitForHealth(url, ms = 20_000) {
44 const start = Date.now();
45 while (Date.now() - start < ms) {
46 try {
47 const ok = await new Promise((resolve) => {
48 const req = http.get(url + '/health', (res) => {
49 let body = '';
50 res.on('data', (c) => (body += c));
51 res.on('end', () => {
52 try { resolve(res.statusCode === 200 && JSON.parse(body).ok === true); }
53 catch { resolve(false); }
54 });
55 });
56 req.on('error', () => resolve(false));
57 req.setTimeout(1000, () => { req.destroy(); resolve(false); });
58 });
59 if (ok) return true;
60 } catch { /* retry */ }
61 await delay(200);
62 }
63 return false;
64}
65
66function onceEvent(socket, event, ms = STEP_TIMEOUT_MS) {
67 return withTimeout(new Promise((resolve, reject) => {
68 const onErr = (e) => { cleanup(); reject(e instanceof Error ? e : new Error(String(e?.message || e))); };
69 const onData = (data) => { cleanup(); resolve(data); };
70 const cleanup = () => {
71 socket.off(event, onData);
72 socket.off('connect_error', onErr);
73 };
74 socket.once(event, onData);
75 socket.once('connect_error', onErr);
76 }), ms, `event ${event}`);
77}
78
79function waitForState(socket, predicate, ms = STEP_TIMEOUT_MS, label = 'state predicate') {
80 return withTimeout(new Promise((resolve) => {
81 const handler = (snap) => {
82 try { if (predicate(snap)) { socket.off('state', handler); resolve(snap); } } catch { /* keep waiting */ }
83 };
84 socket.on('state', handler);
85 }), ms, label);
86}
87
88function collectErrors(socket) {
89 const errors = [];
90 const handler = (e) => errors.push(e);
91 socket.on('error', handler);
92 return { errors, stop: () => socket.off('error', handler) };
93}
94
95async function connectClient(io, name, role, room = '', token) {
96 const socket = io(BASE_URL, { transports: ['websocket'], forceNew: true, reconnection: false });
97 await onceEvent(socket, 'connect', STEP_TIMEOUT_MS);
98 const joinedP = onceEvent(socket, 'joined', STEP_TIMEOUT_MS);
99 socket.emit('join', { room, name, role, ...(token ? { token } : {}) });
100 const joined = await joinedP;
101 return { socket, joined };
102}
103
104function isJsonSerializable(v) {
105 try { JSON.stringify(v); return true; } catch { return false; }
106}
107
108function neighborsOf(tile, width, height) {
109 const { x, y } = tile;
110 const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
111 const out = [];
112 for (const [dx, dy] of dirs) {
113 const nx = x + dx, ny = y + dy;
114 if (nx >= 0 && ny >= 0 && nx < width && ny < height) out.push(ny * width + nx);
115 }
116 return out;
117}
118
119/**
120 * Отправить действие и дождаться его собственного ответа.
121 *
122 * Фактический контракт сервера (server/index.js, обработчик 'action'):
123 * 1) при отказе — событие 'error';
124 * 2) затем ВСЕГДА 'state' (свежий, неизменённый при ошибке снапшот).
125 * Т.е. после каждого действия приходит пара событий. Если следующее действие
126 * отправить сразу по первому событию, его обработчик поймает «хвост» — 'state'
127 * от предыдущего действия — и проверка «invalid -> error» ложно провалится.
128 * Поэтому после первого события выдерживаем DRAIN_MS, чтобы погасить остаток.
129 */
130const DRAIN_MS = 200;
131
132async function sendActionAndWait(socket, action, label) {
133 let cleanup = () => {};
134 try {
135 return await withTimeout(new Promise((resolve) => {
136 let first = null;
137 const onState = (s) => { if (!first) first = { type: 'state', payload: s }; };
138 const onError = (e) => { if (!first) first = { type: 'error', payload: e }; };
139 cleanup = () => { socket.off('state', onState); socket.off('error', onError); };
140 socket.on('state', onState);
141 socket.on('error', onError);
142 socket.emit('action', action);
143
144 const started = Date.now();
145 const poll = () => {
146 if (!first) {
147 // ответа ещё нет — ждём (таймаут отдаст внешний withTimeout)
148 if (Date.now() - started > STEP_TIMEOUT_MS - 1000) { resolve({ type: 'timeout', payload: null }); return; }
149 setTimeout(poll, 25);
150 return;
151 }
152 // ответ получен — гасим «хвост» событий этого действия
153 setTimeout(() => resolve(first), DRAIN_MS);
154 };
155 poll();
156 }), STEP_TIMEOUT_MS, `action ${label}`);
157 } finally {
158 cleanup();
159 }
160}
161
162async function main() {
163 let io;
164 try {
165 ({ io } = await import('socket.io-client'));
166 } catch (e) {
167 console.error('FATAL: socket.io-client not installed. Run: npm i -D socket.io-client');
168 process.exit(2);
169 }
170
171 let serverProc = null;
172 const clients = [];
173 const killServer = () => {
174 if (serverProc && !serverProc.killed) {
175 try { serverProc.kill('SIGTERM'); } catch {}
176 }
177 };
178
179 const globalTimer = setTimeout(() => {
180 fail('global-timeout', `Exceeded ${TOTAL_TIMEOUT_MS}ms`);
181 for (const c of clients) try { c.disconnect(); } catch {}
182 killServer();
183 printSummaryAndExit();
184 }, TOTAL_TIMEOUT_MS);
185
186 try {
187 // 1. Spawn server
188 serverProc = spawn('node', ['server/index.js'], {
189 cwd: process.cwd(),
190 env: { ...process.env, PORT: String(PORT) },
191 stdio: ['ignore', 'pipe', 'pipe'],
192 });
193 serverProc.stdout.on('data', (d) => process.stdout.write(`[server] ${d}`));
194 serverProc.stderr.on('data', (d) => process.stderr.write(`[server:err] ${d}`));
195 const healthy = await waitForHealth(BASE_URL, 20_000);
196 assert(healthy, '1. server /health ok', healthy ? `GET ${BASE_URL}/health -> {ok:true}` : 'server did not become healthy');
197
198 // 2. Host creates room
199 const host = await connectClient(io, 'Host', 'ruler', '');
200 clients.push(host.socket);
201 assert(!!host.joined?.roomCode, '2. host joined & room created', `room=${host.joined?.roomCode}`);
202 assert(!!host.joined?.playerId && !!host.joined?.token, '3. host received playerId+token');
203
204 // 3. Second player joins by code
205 const guest = await connectClient(io, 'Guest', 'treasurer', host.joined.roomCode);
206 clients.push(guest.socket);
207 assert(guest.joined?.roomCode === host.joined.roomCode, '4. guest joined same room');
208
209 // 4. Role change
210 const roleErrs = collectErrors(guest.socket);
211 guest.socket.emit('setRole', { role: 'marshal' });
212 await delay(300);
213 assert(roleErrs.errors.length === 0, '5. guest setRole marshal (no error)', roleErrs.errors[0]?.message || '');
214 roleErrs.stop();
215
216 // 5. Host starts game
217 host.socket.emit('start', {});
218 const playing = await waitForState(host.socket, (s) => s.phase === 'playing', STEP_TIMEOUT_MS, 'phase playing');
219 assert(playing.phase === 'playing', '6. game started (phase playing)', `tick=${playing.tick}`);
220
221 // 6. Map generated
222 const tilesOk = Array.isArray(playing.world?.tiles) &&
223 playing.world.tiles.length === playing.world.width * playing.world.height;
224 assert(tilesOk, '7. map generated', `tiles=${playing.world?.tiles?.length} w*h=${playing.world?.width}*${playing.world?.height}`);
225
226 // 7. My country basics
227 const myCountry = (playing.countries || []).find(c => c.isMe || c.id === playing.me?.countryId);
228 assert(!!myCountry, '8. my country present');
229 if (myCountry) {
230 assert(myCountry.capitalTile != null, '9. my country has capital', `capital=${myCountry.capitalTile}`);
231 assert(typeof myCountry.gold === 'number', '10. my country has gold', `gold=${myCountry.gold}`);
232 assert(!!myCountry.army, '11. my country has army');
233 }
234 const aiCountries = (playing.countries || []).filter(c => c.isAI);
235 assert(aiCountries.length >= 1, '12. AI countries present', `ai=${aiCountries.length}`);
236
237 // 8. JSON serializable state
238 assert(isJsonSerializable(playing), '13. state is JSON-serializable');
239
240 // Helper to get fresh state for host (явный запрос снапшота, чтобы не поймать «хвост»).
241 const getHostState = async () => {
242 const p = waitForState(host.socket, () => true, STEP_TIMEOUT_MS, 'fresh state');
243 host.socket.emit('requestState');
244 return p;
245 };
246
247 // 9. Series of actions (each expects state or error, no crash/silence)
248 const actionChecks = [
249 { label: 'recruit', action: { type: 'recruit', units: { infantry: 1 } } },
250 { label: 'setTaxes', action: { type: 'setTaxes', rate: 0.3 } },
251 { label: 'fundArmy', action: { type: 'fundArmy', percent: 50 } },
252 { label: 'investTreasury', action: { type: 'investTreasury', gold: 10, percent: 10 } },
253 { label: 'setResearch', action: { type: 'setResearch', techId: (playing.catalog?.techs?.[0]?.id || 'agriculture') } },
254 ];
255 // buildBuilding/upgradeFort need a tile we own
256 const myTiles = (playing.world?.tiles || []).filter(t => t.owner === (myCountry?.id));
257 const ownTile = myTiles[0]?.i ?? playing.world?.tiles?.[0]?.i ?? 0;
258 const buildingId = playing.catalog?.buildings?.[0]?.id || 'farm';
259 actionChecks.push({ label: 'buildBuilding', action: { type: 'buildBuilding', buildingId, tile: ownTile } });
260 actionChecks.push({ label: 'upgradeFort', action: { type: 'upgradeFort', tile: ownTile } });
261 const otherCountry = (playing.countries || []).find(c => c.id !== myCountry?.id);
262 if (otherCountry) {
263 actionChecks.push({ label: 'declareWar', action: { type: 'declareWar', countryId: otherCountry.id } });
264 actionChecks.push({ label: 'proposePact', action: { type: 'proposePact', countryId: otherCountry.id, kind: 'trade' } });
265 actionChecks.push({ label: 'gift', action: { type: 'gift', toCountryId: otherCountry.id, gold: 1 } });
266 }
267 // moveArmy by valid adjacent path
268 const myArmy = (playing.armies || []).find(a => a.country === myCountry?.id);
269 if (myArmy) {
270 const armyTile = playing.world.tiles[myArmy.tile];
271 const nbs = armyTile ? neighborsOf(armyTile, playing.world.width, playing.world.height) : [];
272 if (nbs.length) {
273 actionChecks.push({ label: 'moveArmy', action: { type: 'moveArmy', armyId: myArmy.id, path: [nbs[0]] } });
274 actionChecks.push({ label: 'attack', action: { type: 'attack', armyId: myArmy.id, tile: nbs[0] } });
275 }
276 }
277
278 let actionIdx = 14;
279 for (const { label, action } of actionChecks) {
280 try {
281 const res = await sendActionAndWait(host.socket, action, label);
282 const ok = res.type === 'state' || res.type === 'error';
283 const detail = res.type === 'error' ? `expected-error: ${res.payload?.message}` : 'state received';
284 assert(ok, `${actionIdx}. action ${label} -> ${res.type}`, detail);
285 } catch (e) {
286 fail(`${actionIdx}. action ${label} -> response`, e.message);
287 }
288 actionIdx++;
289 }
290
291 // 10. Невалидные действия: сервер обязан ответить 'error' и НЕ менять состояние.
292 //
293 // Фактические ограничения контракта, которые учитывает проверка:
294 // - тик-луп (5000мс) сам меняет золото и двигает армии, поэтому инвариант
295 // "до/после" имеет смысл только внутри одного тика (before.tick === after.tick);
296 // - армии других стран меняются от ИИ, поэтому сравниваем только свои армии
297 // (id + состав юнитов, без tile/moving — их меняет тик);
298 // - в тик попадать нельзя и по логу: мутация любого действия пишет запись в log.
299 const myId = myCountry?.id;
300 const stateSignature = (snap) => {
301 const mine = (snap.countries || []).find(c => c.id === myId) || {};
302 const units = (snap.armies || [])
303 .filter(a => a.country === myId)
304 .map(a => `${a.id}:${JSON.stringify(a.units)}`)
305 .sort()
306 .join('|');
307 return { tick: snap.tick, gold: mine.gold, units };
308 };
309
310 const invalidActions = [
311 { label: 'unknown type', action: { type: '__bogus_type__' } },
312 { label: 'negative numbers', action: { type: 'recruit', units: { infantry: -5 } } },
313 { label: 'foreign army move', action: { type: 'moveArmy', armyId: 'nonexistent-army-id', path: [0] } },
314 { label: 'non-adjacent path', action: { type: 'moveArmy', armyId: myArmy?.id || 'x', path: [0, (playing.world?.tiles?.length || 2) - 1] } },
315 // FIX (регрессия): неизвестные id и прототип-поллюция обязаны давать 'error'.
316 { label: 'build unknown building', action: { type: 'buildBuilding', buildingId: '__proto__', tile: ownTile } },
317 { label: 'research unknown tech', action: { type: 'setResearch', techId: 'no-such-tech' } },
318 { label: 'policy unknown id', action: { type: 'enactPolicy', policyId: 'no-such-policy' } },
319 { label: 'recruit proto units', action: { type: 'recruit', units: JSON.parse('{"__proto__":5}') } },
320 ];
321 if (otherCountry) {
322 invalidActions.push({ label: 'tiny gift', action: { type: 'gift', toCountryId: otherCountry.id, gold: 0.001 } });
323 }
324 let compared = 0;
325 let goldStable = true;
326 let armiesStable = true;
327 for (const { label, action } of invalidActions) {
328 const before = stateSignature(await getHostState());
329 try {
330 const res = await sendActionAndWait(host.socket, action, `invalid:${label}`);
331 assert(res.type === 'error', `${actionIdx}. invalid action '${label}' -> error`, res.type === 'error' ? res.payload?.message : `got ${res.type}`);
332 } catch (e) {
333 fail(`${actionIdx}. invalid action '${label}' -> error`, e.message);
334 }
335 actionIdx++;
336 const after = stateSignature(await getHostState());
337 if (before.tick === after.tick) {
338 compared += 1;
339 if (before.gold !== after.gold) goldStable = false;
340 if (before.units !== after.units) armiesStable = false;
341 }
342 }
343 assert(goldStable && compared > 0, `${actionIdx}. invalid actions did not change gold`, `сравнений в одном тике: ${compared}`);
344 actionIdx++;
345 assert(armiesStable && compared > 0, `${actionIdx}. invalid actions did not change armies`, `сравнений в одном тике: ${compared}`);
346 actionIdx++;
347
348 // guest — маршал, его recruit легитимен; проверяем лишь отсутствие тишины/краша.
349 try {
350 const res = await sendActionAndWait(guest.socket, { type: 'recruit', units: { infantry: 1 } }, 'guest:recruit');
351 assert(res.type === 'error' || res.type === 'state', `${actionIdx}. guest action responded (no silence/crash)`, res.type);
352 } catch (e) {
353 fail(`${actionIdx}. guest action responded`, e.message);
354 }
355 actionIdx++;
356
357 // 11. Wait 3-4 ticks: tick grows, log populates
358 const tickBefore = (await getHostState()).tick;
359 await delay(TICK_WAIT_MS);
360 const afterTicks = await getHostState();
361 assert(afterTicks.tick > tickBefore, `${actionIdx}. tick grows over time`, `before=${tickBefore} after=${afterTicks.tick}`);
362 actionIdx++;
363 assert(Array.isArray(afterTicks.log) && afterTicks.log.length > 0, `${actionIdx}. log populated`, `log=${afterTicks.log?.length}`);
364 actionIdx++;
365
366 // 12. phase/victory consistency
367 const phaseOk = ['lobby', 'playing', 'finished'].includes(afterTicks.phase);
368 assert(phaseOk, `${actionIdx}. phase is valid`, afterTicks.phase);
369 actionIdx++;
370 const victoryOk = afterTicks.victory == null || (typeof afterTicks.victory === 'object' && 'scores' in afterTicks.victory);
371 assert(victoryOk, `${actionIdx}. victory.scores consistent`, JSON.stringify(afterTicks.victory));
372
373 } catch (e) {
374 fail('unhandled-exception', e && e.stack ? e.stack : String(e));
375 } finally {
376 clearTimeout(globalTimer);
377 for (const c of clients) { try { c.disconnect(); } catch {} }
378 killServer();
379 await delay(300);
380 }
381
382 printSummaryAndExit();
383}
384
385function printSummaryAndExit() {
386 const passed = results.filter(r => r.ok).length;
387 const failed = results.filter(r => !r.ok).length;
388 console.log('\n=== SMOKE SUMMARY ===');
389 console.log(`Total: ${results.length} PASS: ${passed} FAIL: ${failed}`);
390 if (failed) {
391 console.log('Failed checks:');
392 for (const r of results.filter(r => !r.ok)) console.log(` - ${r.name}: ${r.detail}`);
393 }
394 process.exit(failed ? 1 : 0);
395}
396
397main();