Server-run play, part 1: game prerequisites and shared contracts
Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.
- A new network in two halves (beginState/beginShow), the coach split into
tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
once-per-load toasts, the five text actions take their text as an
argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
the base no longer count as divergences.
This commit is contained in:
parent
e25f843526
commit
d1e127da67
60 changed files with 2200 additions and 105 deletions
|
|
@ -7,17 +7,22 @@
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { JSDOM, VirtualConsole } = require('jsdom');
|
||||
const { assemble } = require('../scripts/lib/page');
|
||||
const { assemble, simId } = require('../scripts/lib/page');
|
||||
|
||||
const PAGE = {};
|
||||
const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html);
|
||||
const page = (dev, mp) => PAGE[dev + '|' + mp] || (PAGE[dev + '|' + mp] = assemble({ dev, mp }).html);
|
||||
// The build id an MP page carries (scripts/lib/page.js simId()), worked out once per test process.
|
||||
let SIM;
|
||||
const simOf = () => SIM || (SIM = simId(assemble({ mp: true }).html));
|
||||
|
||||
// opts.file: a built or older page to load instead (the perf bench, the release build test).
|
||||
// opts.agent: the development page, with src/agent/.
|
||||
// opts.mp: the page with multiplayer on, as MP_API=… npm run build stamps it; opts.fetch: the page's fetch, from the start.
|
||||
// opts.mp: the page with multiplayer on, as MP_API=… npm run build makes it: the server-play client in it, MP_API
|
||||
// stamped (opts.mp's path, or '/api/mp' for true) and SIM_ID too; opts.fetch: the page's fetch, from the start
|
||||
// (fakeFetch() below fakes the session server, streams included).
|
||||
function load(opts = {}) {
|
||||
let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent);
|
||||
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp));
|
||||
let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent, !!opts.mp);
|
||||
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp === true ? '/api/mp' : opts.mp)).replace("/*__SIM_ID__*/''", () => JSON.stringify(simOf()));
|
||||
const errors = [];
|
||||
const vc = new VirtualConsole();
|
||||
vc.on('jsdomError', (e) => {
|
||||
|
|
@ -47,6 +52,8 @@ function load(opts = {}) {
|
|||
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
|
||||
// jsdom has no CompressionStream; {gzip:true} lends the page Node's, the same API browsers have (#176).
|
||||
if (opts.gzip) for (const k of ['CompressionStream', 'DecompressionStream', 'TextEncoder', 'TextDecoder']) window[k] = globalThis[k];
|
||||
// An MP page reads its server's stream through fetch: the decoder and streams it needs, Node's (as browsers have them).
|
||||
if (opts.mp) for (const k of ['TextEncoder', 'TextDecoder', 'ReadableStream']) if (!window[k]) window[k] = globalThis[k];
|
||||
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
|
||||
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
|
||||
const fake = () => { const calls = { n: 0 };
|
||||
|
|
@ -115,4 +122,58 @@ function browser({ locks = true, channel = true } = {}) {
|
|||
}
|
||||
const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); });
|
||||
|
||||
module.exports = { load, seed, browser, flush };
|
||||
/* One server-sent event as it goes over the wire (section 5.1 of the server-sim design): event, optional id, one line
|
||||
of JSON data. */
|
||||
const sse = (event, data, id) => `event: ${event}\n${id === undefined ? '' : `id: ${id}\n`}data: ${JSON.stringify(data)}\n\n`;
|
||||
|
||||
/* A fake session server for an MP page (load({mp: true, fetch: f})). routes: [regexp on "METHOD url", reply |
|
||||
(call) => reply], where a reply is {status, json, headers?}, an Error (the network failed) or a promise of either (an
|
||||
answer still on its way; the page aborting meanwhile rejects it, as fetch does). A GET of …/stream that no route
|
||||
answers opens an event stream the test writes to:
|
||||
f.streams every stream opened, in order; await f.stream(i) the i-th one (0 first), once the page opens it
|
||||
s.send(event, data, id) one event (sse() above); s.comment('hb'); s.close(); s.fail(err)
|
||||
s.aborted the page aborted it (its AbortSignal); s.closed it ended either way; s.call its request
|
||||
Every request is in f.calls: {url, method, path (without MP_API's base), query, headers, raw, body (parsed JSON),
|
||||
keepalive, signal}. Responses are Node's own Headers and ReadableStream, which is what browsers hand a page. */
|
||||
function fakeFetch(routes = [], { base = '/api/mp' } = {}) {
|
||||
const calls = [], streams = [], waiting = [], enc = new TextEncoder();
|
||||
const aborted = () => { const e = new Error('aborted'); e.name = 'AbortError'; return e; };
|
||||
const res = (r) => (r instanceof Error ? Promise.reject(r) : Promise.resolve({ ok: r.status < 400, status: r.status, headers: new Headers(r.headers || { 'content-type': 'application/json' }),
|
||||
body: null, json: () => (r.json === undefined ? Promise.reject(new SyntaxError('no body')) : Promise.resolve(r.json)), text: () => Promise.resolve(r.json === undefined ? '' : JSON.stringify(r.json)) }));
|
||||
function open(c) {
|
||||
let ctl;
|
||||
const s = { call: c, closed: false, aborted: false, sent: [],
|
||||
write(t) { if (!s.closed) ctl.enqueue(enc.encode(t)); return s; },
|
||||
send(event, data, id) { const t = sse(event, data, id); s.sent.push({ event, data, id }); return s.write(t); },
|
||||
comment(text = 'hb') { return s.write(`: ${text}\n\n`); },
|
||||
close() { if (!s.closed) { s.closed = true; ctl.close(); } return s; },
|
||||
fail(e = new Error('network')) { if (!s.closed) { s.closed = true; ctl.error(e); } return s; } };
|
||||
const body = new ReadableStream({ start(k) { ctl = k; }, cancel() { s.closed = true; } });
|
||||
if (c.signal) c.signal.addEventListener('abort', () => { s.aborted = true; s.fail(aborted()); });
|
||||
streams.push(s);
|
||||
for (const w of waiting.filter((x) => x.i < streams.length)) { waiting.splice(waiting.indexOf(w), 1); w.ok(streams[w.i]); }
|
||||
return Promise.resolve({ ok: true, status: 200, headers: new Headers({ 'content-type': 'text/event-stream; charset=utf-8' }), body,
|
||||
json: () => Promise.reject(new SyntaxError('an event stream')), text: () => Promise.reject(new TypeError('an event stream')) });
|
||||
}
|
||||
const f = (url, o = {}) => {
|
||||
const u = new URL(String(url), 'https://tests.invalid/'), method = (o.method || 'GET').toUpperCase();
|
||||
const headers = {}; for (const [k, v] of Object.entries(o.headers || {})) headers[k.toLowerCase()] = v;
|
||||
let body; try { body = typeof o.body === 'string' ? JSON.parse(o.body) : undefined; } catch (e) { body = undefined; }
|
||||
const c = { url: String(url), method, path: u.pathname.startsWith(base) ? u.pathname.slice(base.length) : u.pathname, query: Object.fromEntries(u.searchParams),
|
||||
headers, raw: o.body, body, keepalive: !!o.keepalive, signal: o.signal };
|
||||
calls.push(c);
|
||||
if (o.signal && o.signal.aborted) return Promise.reject(aborted());
|
||||
for (const [re, h] of f.routes) if (re.test(`${method} ${c.url}`)) {
|
||||
const r = typeof h === 'function' ? h(c) : h;
|
||||
if (!r || typeof r.then !== 'function') return res(r);
|
||||
return new Promise((ok, no) => { if (o.signal) o.signal.addEventListener('abort', () => no(aborted())); r.then((x) => res(x).then(ok, no), no); });
|
||||
}
|
||||
if (method === 'GET' && /\/stream$/.test(c.path)) return open(c);
|
||||
return res({ status: 404, json: { error: 'not here' } });
|
||||
};
|
||||
f.routes = routes; f.calls = calls; f.streams = streams;
|
||||
f.stream = (i = 0) => (streams[i] ? Promise.resolve(streams[i]) : new Promise((ok) => waiting.push({ i, ok })));
|
||||
return f;
|
||||
}
|
||||
|
||||
module.exports = { load, seed, browser, flush, sse, fakeFetch };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue