|
| 1 | +/** |
| 2 | + * /live single-poll gate — paused page makes ONE network call |
| 3 | + * |
| 4 | + * Request: "When showing paused it should only make one network call to check |
| 5 | + * whether there is an active run or no. If [active] then make the necessary |
| 6 | + * calls and show the live page." |
| 7 | + * |
| 8 | + * Before: while paused, /live fired /stats, /runs/last, /events (SSE), /status, |
| 9 | + * /live-state and /logs on every load — six requests for a page showing nothing |
| 10 | + * but the paused overlay. Root cause: DOMContentLoaded fanned out to every work |
| 11 | + * endpoint whenever broadcast was on, regardless of whether a run was in flight. |
| 12 | + * |
| 13 | + * Fix: /api/broadcast now returns { broadcastLive, activeRun }. checkBroadcastState |
| 14 | + * polls ONLY that endpoint; it calls connectLiveWork() (SSE + logs + live-state + |
| 15 | + * batch + stats) exactly once on a paused→active transition, and nothing else |
| 16 | + * while paused. This runs the REAL checkBroadcastState + connectLiveWork extracted |
| 17 | + * from live.html against a fake fetch/DOM and counts the calls. |
| 18 | + * |
| 19 | + * Run: node test/live-single-poll-gate.test.js |
| 20 | + */ |
| 21 | + |
| 22 | +import { readFileSync } from 'node:fs'; |
| 23 | +import { fileURLToPath } from 'node:url'; |
| 24 | +import { dirname, join } from 'node:path'; |
| 25 | +import vm from 'node:vm'; |
| 26 | + |
| 27 | +const out = { pass: 0, fail: 0, errors: [] }; |
| 28 | +function ok(cond, name) { |
| 29 | + if (cond) { out.pass++; console.log(` PASS ${name}`); } |
| 30 | + else { out.fail++; out.errors.push(name); console.log(` FAIL ${name}`); } |
| 31 | +} |
| 32 | + |
| 33 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 34 | +const html = readFileSync(join(__dirname, '..', 'live.html'), 'utf8'); |
| 35 | + |
| 36 | +function extractFn(src, name) { |
| 37 | + const m = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`).exec(src); |
| 38 | + if (!m) throw new Error(`function ${name} not found in live.html`); |
| 39 | + let depth = 0, started = false, j = m.index; |
| 40 | + for (; j < src.length; j++) { |
| 41 | + const c = src[j]; |
| 42 | + if (c === '{') { depth++; started = true; } |
| 43 | + else if (c === '}') { depth--; if (started && depth === 0) { j++; break; } } |
| 44 | + } |
| 45 | + return src.slice(m.index, j); |
| 46 | +} |
| 47 | + |
| 48 | +const extracted = ['connectLiveWork', 'checkBroadcastState'] |
| 49 | + .map(n => extractFn(html, n)).join('\n\n'); |
| 50 | + |
| 51 | +function makeSandbox(broadcastResponses) { |
| 52 | + // broadcastResponses: array of { broadcastLive, activeRun } returned in order. |
| 53 | + const calls = { fetchUrls: [], work: 0, sseConnect: 0, sseClose: 0, paused: [] }; |
| 54 | + let idx = 0; |
| 55 | + const sandbox = { |
| 56 | + console, |
| 57 | + _broadcastLive: false, |
| 58 | + _activeRun: false, |
| 59 | + _liveWorkConnected: false, |
| 60 | + _sse: null, |
| 61 | + // The single allowed poll endpoint: |
| 62 | + fetch: (url) => { |
| 63 | + calls.fetchUrls.push(url); |
| 64 | + const body = broadcastResponses[Math.min(idx, broadcastResponses.length - 1)]; |
| 65 | + idx++; |
| 66 | + return Promise.resolve({ ok: true, json: () => Promise.resolve(body) }); |
| 67 | + }, |
| 68 | + document: { getElementById: () => null }, |
| 69 | + // Work-endpoint spies — every one of these is a network call we must NOT |
| 70 | + // make while paused. |
| 71 | + rehydrateFromCache: () => {}, |
| 72 | + renderTable: () => {}, |
| 73 | + renderLiveStats: () => {}, |
| 74 | + connectSSE: () => { calls.sseConnect++; sandbox._sse = { close: () => { calls.sseClose++; } }; }, |
| 75 | + seedLogsFromRest: () => { calls.work++; }, |
| 76 | + seedLiveStateFromRest: () => { calls.work++; return Promise.resolve(); }, |
| 77 | + loadCurrentBatch: () => { calls.work++; }, |
| 78 | + loadHeaderStats: () => { calls.work++; }, |
| 79 | + applyPauseFromState: () => {}, |
| 80 | + showPaused: (on) => { calls.paused.push(on); }, |
| 81 | + }; |
| 82 | + vm.createContext(sandbox); |
| 83 | + vm.runInContext(extracted, sandbox); |
| 84 | + return { sandbox, calls }; |
| 85 | +} |
| 86 | + |
| 87 | +console.log('\n/live single-poll gate — paused page makes ONE network call\n'); |
| 88 | + |
| 89 | +// ─── 1. Paused: exactly one call to /api/broadcast, no work endpoints ──────── |
| 90 | +console.log('[1] paused (activeRun=false) → only /api/broadcast'); |
| 91 | +{ |
| 92 | + const { sandbox, calls } = makeSandbox([{ broadcastLive: true, activeRun: false }]); |
| 93 | + await vm.runInContext('checkBroadcastState()', sandbox); |
| 94 | + ok(calls.fetchUrls.length === 1 && /\/api\/broadcast/.test(calls.fetchUrls[0]), |
| 95 | + `one fetch, to /api/broadcast (got ${calls.fetchUrls.length}: ${calls.fetchUrls.join(',')})`); |
| 96 | + ok(calls.work === 0, `no work-endpoint calls while paused (got ${calls.work})`); |
| 97 | + ok(calls.sseConnect === 0, 'no SSE connection while paused'); |
| 98 | + ok(calls.paused.length && calls.paused[calls.paused.length - 1] === true, |
| 99 | + 'overlay shown while paused'); |
| 100 | + ok(sandbox._liveWorkConnected === false, 'work stays disconnected while paused'); |
| 101 | +} |
| 102 | + |
| 103 | +// ─── 2. Broadcast off entirely → still only the one poll, overlay up ───────── |
| 104 | +console.log('[2] broadcast off → one poll, overlay up, no work'); |
| 105 | +{ |
| 106 | + const { sandbox, calls } = makeSandbox([{ broadcastLive: false, activeRun: false }]); |
| 107 | + await vm.runInContext('checkBroadcastState()', sandbox); |
| 108 | + ok(calls.fetchUrls.length === 1, 'exactly one fetch when broadcast off'); |
| 109 | + ok(calls.work === 0 && calls.sseConnect === 0, 'no work / SSE when broadcast off'); |
| 110 | + ok(sandbox._broadcastLive === false, '_broadcastLive reflects off'); |
| 111 | +} |
| 112 | + |
| 113 | +// ─── 3. paused→active transition fans out EXACTLY once ─────────────────────── |
| 114 | +console.log('[3] paused→active → connectLiveWork fires the full fan-out once'); |
| 115 | +{ |
| 116 | + const { sandbox, calls } = makeSandbox([{ broadcastLive: true, activeRun: true }]); |
| 117 | + await vm.runInContext('checkBroadcastState()', sandbox); |
| 118 | + ok(calls.fetchUrls.length === 1, 'broadcast poll itself is still one call'); |
| 119 | + ok(calls.sseConnect === 1, 'SSE connected once on activation'); |
| 120 | + ok(calls.work === 4, `all four work endpoints hit once (logs+live-state+batch+stats) (got ${calls.work})`); |
| 121 | + ok(sandbox._liveWorkConnected === true, 'work marked connected'); |
| 122 | +} |
| 123 | + |
| 124 | +// ─── 4. staying active across polls does NOT re-fan-out ────────────────────── |
| 125 | +console.log('[4] active→active second poll does not reconnect'); |
| 126 | +{ |
| 127 | + const { sandbox, calls } = makeSandbox([ |
| 128 | + { broadcastLive: true, activeRun: true }, |
| 129 | + { broadcastLive: true, activeRun: true }, |
| 130 | + ]); |
| 131 | + await vm.runInContext('checkBroadcastState()', sandbox); |
| 132 | + await vm.runInContext('checkBroadcastState()', sandbox); |
| 133 | + ok(calls.fetchUrls.length === 2, 'two broadcast polls'); |
| 134 | + ok(calls.sseConnect === 1, 'SSE connected only once across both polls'); |
| 135 | + ok(calls.work === 4, `work endpoints hit only once total (got ${calls.work})`); |
| 136 | +} |
| 137 | + |
| 138 | +// ─── 5. active→paused tears down the stream and re-arms ────────────────────── |
| 139 | +console.log('[5] active→paused closes SSE and re-arms for the next run'); |
| 140 | +{ |
| 141 | + const { sandbox, calls } = makeSandbox([ |
| 142 | + { broadcastLive: true, activeRun: true }, |
| 143 | + { broadcastLive: true, activeRun: false }, |
| 144 | + { broadcastLive: true, activeRun: true }, |
| 145 | + ]); |
| 146 | + await vm.runInContext('checkBroadcastState()', sandbox); // active: connect |
| 147 | + await vm.runInContext('checkBroadcastState()', sandbox); // paused: teardown |
| 148 | + ok(calls.sseClose === 1, 'SSE closed on active→paused'); |
| 149 | + ok(sandbox._liveWorkConnected === false, 're-armed (disconnected) while paused'); |
| 150 | + await vm.runInContext('checkBroadcastState()', sandbox); // active again: reconnect |
| 151 | + ok(calls.sseConnect === 2, 'SSE reconnects on the next activation'); |
| 152 | + ok(calls.work === 8, `full fan-out runs again on re-activation (got ${calls.work})`); |
| 153 | +} |
| 154 | + |
| 155 | +console.log(`\n${'='.repeat(60)}\nRESULTS: ${out.pass} passed, ${out.fail} failed (${out.pass + out.fail} total)`); |
| 156 | +if (out.errors.length) for (const e of out.errors) console.log(` FAIL: ${e}`); |
| 157 | +console.log('='.repeat(60)); |
| 158 | +process.exit(out.fail ? 1 : 0); |
0 commit comments