|
| 1 | +/** |
| 2 | + * /live load-sequence gating — "stopped flashes data then paused" regression |
| 3 | + * |
| 4 | + * Bug: on load, /live painted the dataset (rehydrateFromCache → table rows, and |
| 5 | + * seedLiveStateFromRest → rows) BEFORE/regardless of resolving the run state. |
| 6 | + * The paused overlay is opaque + full-screen but only went up AFTER the async |
| 7 | + * broadcast check, so a STOPPED page showed the last dataset for a beat and then |
| 8 | + * covered it: "first loading the data and showing paused." A second leak: with |
| 9 | + * broadcast left on after a run finished, live-state still returns the last |
| 10 | + * run's results, so seed/rehydrate flashed a stale snapshot behind the overlay. |
| 11 | + * |
| 12 | + * Fix: gate every paint path on there being an ACTIVE run to show — |
| 13 | + * - rehydrateFromCache repaints cached rows ONLY when the cached snapshot was |
| 14 | + * an active run (status running/paused or a live batchId). |
| 15 | + * - seedLiveStateFromRest paints rows ONLY when the seeded status is active. |
| 16 | + * - (DOMContentLoaded resolves broadcast before any paint — covered by the |
| 17 | + * pause-overlay suite; this suite locks the two paint-gate functions.) |
| 18 | + * |
| 19 | + * This runs the REAL rehydrateFromCache + seedLiveStateFromRest extracted from |
| 20 | + * live.html against a fake localStorage / fetch / DOM and counts paints. |
| 21 | + * |
| 22 | + * Run: node test/live-load-gating.test.js |
| 23 | + */ |
| 24 | + |
| 25 | +import { readFileSync } from 'node:fs'; |
| 26 | +import { fileURLToPath } from 'node:url'; |
| 27 | +import { dirname, join } from 'node:path'; |
| 28 | +import vm from 'node:vm'; |
| 29 | + |
| 30 | +const out = { pass: 0, fail: 0, errors: [] }; |
| 31 | +function ok(cond, name) { |
| 32 | + if (cond) { out.pass++; console.log(` PASS ${name}`); } |
| 33 | + else { out.fail++; out.errors.push(name); console.log(` FAIL ${name}`); } |
| 34 | +} |
| 35 | + |
| 36 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 37 | +const html = readFileSync(join(__dirname, '..', 'live.html'), 'utf8'); |
| 38 | + |
| 39 | +function extractFn(src, name) { |
| 40 | + const m = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`).exec(src); |
| 41 | + if (!m) throw new Error(`function ${name} not found in live.html`); |
| 42 | + let depth = 0, started = false, j = m.index; |
| 43 | + for (; j < src.length; j++) { |
| 44 | + const c = src[j]; |
| 45 | + if (c === '{') { depth++; started = true; } |
| 46 | + else if (c === '}') { depth--; if (started && depth === 0) { j++; break; } } |
| 47 | + } |
| 48 | + return src.slice(m.index, j); |
| 49 | +} |
| 50 | + |
| 51 | +const extracted = ['rehydrateFromCache', 'seedLiveStateFromRest'] |
| 52 | + .map(n => extractFn(html, n)).join('\n\n'); |
| 53 | + |
| 54 | +// ─── Fake environment ──────────────────────────────────────────────────────── |
| 55 | +let addSingleRowCount = 0; // rehydrate row paints |
| 56 | +let upsertCount = 0; // seed row paints |
| 57 | + |
| 58 | +function makeSandbox() { |
| 59 | + addSingleRowCount = 0; |
| 60 | + upsertCount = 0; |
| 61 | + const sandbox = { |
| 62 | + // tunables / state the functions close over |
| 63 | + LIVE_CACHE_KEY: 'live:snapshot:v1', |
| 64 | + LIVE_CACHE_TTL_MS: 60 * 60 * 1000, |
| 65 | + _prevActiveRunNumber: null, |
| 66 | + _liveState: {}, |
| 67 | + resultsArr: [], |
| 68 | + _cb: { batchId: null, snapshotSize: 0, tested: 0 }, |
| 69 | + Date, Object, Number, Array, console, |
| 70 | + // localStorage + fetch injected per-case below |
| 71 | + localStorage: null, |
| 72 | + fetch: null, |
| 73 | + // painted-row spies |
| 74 | + addSingleRow: () => { addSingleRowCount++; }, |
| 75 | + upsert: () => { upsertCount++; }, |
| 76 | + // harmless stubs |
| 77 | + cbRender: () => {}, |
| 78 | + applyHeaderStatsFromState: () => {}, |
| 79 | + renderLiveStats: () => {}, |
| 80 | + mergeLiveState: (s) => { sandbox._liveState = { ...sandbox._liveState, ...(s || {}) }; }, |
| 81 | + }; |
| 82 | + vm.createContext(sandbox); |
| 83 | + vm.runInContext(extracted, sandbox); |
| 84 | + return sandbox; |
| 85 | +} |
| 86 | + |
| 87 | +function fakeLocalStorage(snapObj) { |
| 88 | + const store = snapObj == null ? {} : { 'live:snapshot:v1': JSON.stringify(snapObj) }; |
| 89 | + return { |
| 90 | + getItem: (k) => (k in store ? store[k] : null), |
| 91 | + setItem: (k, v) => { store[k] = v; }, |
| 92 | + removeItem: (k) => { delete store[k]; }, |
| 93 | + }; |
| 94 | +} |
| 95 | + |
| 96 | +function fakeFetch(jsonBody, okFlag = true) { |
| 97 | + return () => Promise.resolve({ ok: okFlag, json: () => Promise.resolve(jsonBody) }); |
| 98 | +} |
| 99 | + |
| 100 | +const NOW = Date.now(); |
| 101 | +const activeSnap = (status) => ({ |
| 102 | + ts: NOW, broadcastLive: true, |
| 103 | + state: { status }, cb: { batchId: status ? 7 : null }, |
| 104 | + results: [{ address: 'sent1a' }, { address: 'sent1b' }], |
| 105 | +}); |
| 106 | +const idleSnap = { |
| 107 | + ts: NOW, broadcastLive: true, |
| 108 | + state: { status: 'done' }, cb: { batchId: null }, |
| 109 | + results: [{ address: 'sent1a' }, { address: 'sent1b' }, { address: 'sent1c' }], |
| 110 | +}; |
| 111 | + |
| 112 | +console.log('\n/live load-sequence gating — stopped-flash regression\n'); |
| 113 | + |
| 114 | +// ─── 1. rehydrateFromCache: active cache repaints, idle cache does NOT ──────── |
| 115 | +console.log('[1] rehydrateFromCache gates row paint on a cached ACTIVE run'); |
| 116 | +{ |
| 117 | + const sb = makeSandbox(); |
| 118 | + sb.localStorage = fakeLocalStorage(activeSnap('running')); |
| 119 | + vm.runInContext('rehydrateFromCache()', sb); |
| 120 | + ok(addSingleRowCount === 2, `running cache repaints its 2 rows (got ${addSingleRowCount})`); |
| 121 | +} |
| 122 | +{ |
| 123 | + const sb = makeSandbox(); |
| 124 | + sb.localStorage = fakeLocalStorage(idleSnap); |
| 125 | + vm.runInContext('rehydrateFromCache()', sb); |
| 126 | + ok(addSingleRowCount === 0, `idle/done cache paints NOTHING (got ${addSingleRowCount})`); |
| 127 | +} |
| 128 | +{ |
| 129 | + // A cache with no status but a live batchId is still "active" (mid-run). |
| 130 | + const sb = makeSandbox(); |
| 131 | + sb.localStorage = fakeLocalStorage({ |
| 132 | + ts: NOW, broadcastLive: true, state: {}, cb: { batchId: 42 }, |
| 133 | + results: [{ address: 'sent1x' }], |
| 134 | + }); |
| 135 | + vm.runInContext('rehydrateFromCache()', sb); |
| 136 | + ok(addSingleRowCount === 1, `cache with a live batchId repaints (got ${addSingleRowCount})`); |
| 137 | +} |
| 138 | +{ |
| 139 | + // No cache at all → no paint, no throw. |
| 140 | + const sb = makeSandbox(); |
| 141 | + sb.localStorage = fakeLocalStorage(null); |
| 142 | + vm.runInContext('rehydrateFromCache()', sb); |
| 143 | + ok(addSingleRowCount === 0, 'absent cache paints nothing'); |
| 144 | +} |
| 145 | +{ |
| 146 | + // Expired cache (older than TTL) → discarded, no paint. |
| 147 | + const sb = makeSandbox(); |
| 148 | + const stale = activeSnap('running'); stale.ts = NOW - (2 * 60 * 60 * 1000); |
| 149 | + sb.localStorage = fakeLocalStorage(stale); |
| 150 | + vm.runInContext('rehydrateFromCache()', sb); |
| 151 | + ok(addSingleRowCount === 0, 'expired cache (past TTL) paints nothing'); |
| 152 | +} |
| 153 | + |
| 154 | +// ─── 2. seedLiveStateFromRest: active state paints, idle/done does NOT ──────── |
| 155 | +console.log('[2] seedLiveStateFromRest gates row paint on an ACTIVE run status'); |
| 156 | +async function seedCase(body) { |
| 157 | + const sb = makeSandbox(); |
| 158 | + sb.fetch = fakeFetch(body); |
| 159 | + await vm.runInContext('seedLiveStateFromRest()', sb); |
| 160 | + return sb; |
| 161 | +} |
| 162 | +{ |
| 163 | + const sb = await seedCase({ |
| 164 | + broadcastLive: true, state: { status: 'running' }, activeBatchId: 9, snapshotSize: 100, |
| 165 | + results: [{ address: 'sent1a' }, { address: 'sent1b' }], |
| 166 | + }); |
| 167 | + ok(upsertCount === 2, `running state paints its 2 rows (got ${upsertCount})`); |
| 168 | + ok(sb._cb.batchId === 9, 'running state pins the active batch id'); |
| 169 | +} |
| 170 | +{ |
| 171 | + await seedCase({ |
| 172 | + broadcastLive: true, state: { status: 'done' }, activeBatchId: null, |
| 173 | + results: [{ address: 'sent1a' }, { address: 'sent1b' }, { address: 'sent1c' }], |
| 174 | + }); |
| 175 | + ok(upsertCount === 0, `done state (broadcast still on) paints NOTHING (got ${upsertCount})`); |
| 176 | +} |
| 177 | +{ |
| 178 | + await seedCase({ |
| 179 | + broadcastLive: true, state: { status: 'idle' }, activeBatchId: null, |
| 180 | + results: [{ address: 'sent1a' }], |
| 181 | + }); |
| 182 | + ok(upsertCount === 0, 'idle state paints nothing'); |
| 183 | +} |
| 184 | +{ |
| 185 | + // paused_balance / paused_internet mid-run: a live batchId keeps it active. |
| 186 | + const sb = await seedCase({ |
| 187 | + broadcastLive: true, state: { status: 'paused_balance' }, activeBatchId: 5, |
| 188 | + results: [{ address: 'sent1a' }], |
| 189 | + }); |
| 190 | + ok(upsertCount === 1, `paused_balance + live batchId still paints (got ${upsertCount})`); |
| 191 | + ok(sb._cb.batchId === 5, 'paused_balance mid-run pins the batch id'); |
| 192 | +} |
| 193 | +{ |
| 194 | + // broadcast off → seed bails before any paint (overlay path owns this). |
| 195 | + await seedCase({ broadcastLive: false, state: {}, results: [] }); |
| 196 | + ok(upsertCount === 0, 'broadcast off → seed paints nothing'); |
| 197 | +} |
| 198 | + |
| 199 | +console.log(`\n${'='.repeat(60)}\nRESULTS: ${out.pass} passed, ${out.fail} failed (${out.pass + out.fail} total)`); |
| 200 | +if (out.errors.length) for (const e of out.errors) console.log(` FAIL: ${e}`); |
| 201 | +console.log('='.repeat(60)); |
| 202 | +process.exit(out.fail ? 1 : 0); |
0 commit comments