jukebox
All repositories: gitoria
8.1 KB
// tests/jb23.mjs — JB23 (mission 015): a tap whose server emit fails must still play once the connection is back.// The case: the network dies (a TCP proxy: open connections go silent, new ones are refused) but the page does not know yet; a song is tapped ~3 s later, the jbQueue emit never arrives (value-form emit, answers null,// the POST fallback fails too), and nothing plays. The app keeps the tapped request and runs it when the server answers again (on client reachability / reconnected),// so the song plays after the network is back WITHOUT another tap. Also: a normal tap plays at once. Red on 04f5d9d (no retry), green on the branch.// Own server on a generated database of 6 songs (one 1.5 s tone, ffmpeg), headless Chrome at 390 px.// node tests/jb23.mjs env: JB23_PORT (what the page uses: a TCP proxy, default 8826; the server runs on JB23_PORT+1), JB23_DIR (scratch, default a tmp dir), JB23_ROOT (checkout to test), HL_PORT_BASE (Chrome debug ports base+200, default 8630), JUKEBOX_COLD_MSimport { spawn, execFileSync } from 'node:child_process'import { createServer as netServer, connect as netConnect } from 'node:net'import { rmSync, mkdirSync, readFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'process.env.HL_CHROME = process.env.HL_CHROME || '/opt/google/chrome/chrome'process.env.HL_PORT_BASE = process.env.HL_PORT_BASE || '8630'const { launchBrowser, sleep } = await import('./cdp.mjs')const root = process.env.JB23_ROOT || join(dirname(fileURLToPath(import.meta.url)), '..')const dir = process.env.JB23_DIR || '/tmp/jb23-gate'const port = Number(process.env.JB23_PORT || 8826)const BASE = `http://127.0.0.1:${port}`const realPort = port + 1 // the server; the page talks to `port`, a TCP proxy that can go silent (a half-open connection: nothing arrives, nothing closes)const COLD_MS = Number(process.env.JUKEBOX_COLD_MS || 150000)const TONE = 1.5let pass = 0, fail = 0const check = (name, ok, detail = '') => { console.log((ok ? 'ok ' : 'FAIL ') + name + (ok ? '' : ' — ' + detail)); if (ok) pass++; else fail++ }mkdirSync(dir, { recursive: true })process.env.TMPDIR = dirlet server = null, browser = null, log = ''async function stop() {if (browser) { try { await browser.close() } catch {} browser = null }try { proxy.close() } catch {}if (server) { try { server.kill('SIGTERM') } catch {} await sleep(500); server = null }}process.on('SIGINT', async () => { await stop(); process.exit(1) })const storage = join(dir, 'storage')const tone = join(dir, 'tone.mp3')rmSync(storage, { recursive: true, force: true })execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', `sine=frequency=440:duration=${TONE}`, '-q:a', '9', tone])const cover = join(root, 'tests/fixtures/withcover/folder.jpg')execFileSync(join(root, 'bin/hybriel'), [join(root, 'tools/make-test-db.hl'), tone, cover, '6'], { env: { ...process.env, JUKEBOX_STORAGE: storage }, encoding: 'utf8', timeout: 600000 })server = spawn(join(root, 'bin/hybriel'), ['project.hl'], { cwd: root, env: { ...process.env, JUKEBOX_PORT: String(realPort), JUKEBOX_STORAGE: storage, JUKEBOX_AUTOSCAN: '0', JUKEBOX_WATCH: '0', HL_HOST: '127.0.0.1' }, stdio: ['ignore', 'pipe', 'pipe'] })console.log('server pid ' + server.pid)let hole = false, socks = new Set()const proxy = netServer((c) => {if (hole) { c.destroy(); return } // a new connection while the network is dead: refused at once (the POST fallback fails)const u = netConnect(realPort, '127.0.0.1'); const mine = { c, u, dead: hole }; socks.add(mine)c.on('data', (d) => { if (!mine.dead) u.write(d) }); u.on('data', (d) => { if (!mine.dead) c.write(d) })const end = () => { socks.delete(mine); c.destroy(); u.destroy() }c.on('close', end); u.on('close', end); c.on('error', end); u.on('error', end)})await new Promise((r) => proxy.listen(port, '127.0.0.1', r))const setHole = (on) => { hole = on; for (const m of [...socks]) { if (on) m.dead = true; else if (m.dead) { m.c.destroy(); m.u.destroy() } } } // the network comes back: the half-open connections get their resetserver.stdout.on('data', (d) => { log += d }); server.stderr.on('data', (d) => { log += d })try {for (const t0 = Date.now(); ; ) {try { if ((await fetch(`http://127.0.0.1:${realPort}/`)).ok) break } catch {}if (Date.now() - t0 > COLD_MS) { console.log(log); throw new Error('the server did not come up') }await sleep(500)}const order = (await (await fetch(`http://127.0.0.1:${realPort}` + '/api/songs?sort=artist&offset=0&limit=100')).json()).items.map((s) => String(s.id))console.log('list order (artist): ' + order.join(' '))browser = await launchBrowser()console.log('chrome pid ' + browser.proc?.pid)const page = await browser.newPage()const ev = (e) => page.evaluate(e)await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true })await page.goto(BASE + '/')await page.waitForSelector('virtual-list .vl-row:not(.blank)')await sleep(800)const playing = () => ev(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc && !a.paused ? a.currentSrc.split('/').pop() : '' })()`)const tap = (id) => page.click(`virtual-list .vl-row[data-id="${id}"]`)const pause = () => ev(`document.querySelector('media-player audio').pause(); 1`)// a normal tap plays at onceawait tap(order[1])await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc.endsWith('/${order[1]}') && !a.paused })()`, { timeout: 15000, label: 'baseline tap plays' }).catch(() => {})check('a normal tap plays at once', (await playing()) === order[1], await playing())await pause(); await sleep(500)// the network dies, the page does not know yet; a tap 3 s latersetHole(true); await page.setOffline(true)await sleep(3000)await tap(order[3])await sleep(Number(process.env.JB23_DEAD_MS || 45000)) // the dead socket is noticed (ping + pong window), the new connections are refused, the POST fallback fails, the emit answers nullcheck('while the network is dead nothing plays', (await playing()) === '', await playing())await page.setOffline(false); setHole(false)let got = ''try { await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc.endsWith('/${order[3]}') && !a.paused })()`, { timeout: 40000, label: 'song plays after the network is back' }); got = await playing() } catch { got = await playing() }check('the tapped song plays after the network is back, without another tap', got === order[3], 'playing=' + JSON.stringify(got) + ' wanted ' + order[3])// the page works after that: another normal tapawait pause(); await tap(order[4])try { await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc.endsWith('/${order[4]}') && !a.paused })()`, { timeout: 15000 }) } catch {}check('a normal tap after the reconnect plays at once', (await playing()) === order[4], await playing())// GUARD (green on the old code too: here Next is handled at once, so the late failure never reinstated the tap): a newer action wins: a tap is lost to the dead network, then Next is pressed (cached queue); when the first emit finally fails it must not come backawait pause(); await sleep(500)setHole(true); await page.setOffline(true)await sleep(3000)await ev(`window.__srcs = []; (a => { a.addEventListener('loadstart', () => window.__srcs.push(a.currentSrc.split('/').pop())); a.addEventListener('emptied', () => {}) })(document.querySelector('media-player audio')); 1`)await tap(order[2])await sleep(500)await page.click('.jb-bar .jb-next')await sleep(Number(process.env.JB23_DEAD_MS || 45000))await page.setOffline(false); setHole(false)await sleep(12000)const srcs = await ev(`window.__srcs`)check('Next advanced during the outage (its song was loaded)', srcs.includes(order[5]), JSON.stringify(srcs))check('the superseded tap is never selected during the recovery', !srcs.includes(order[2]), JSON.stringify(srcs))} finally {await stop()}console.log(`${pass} passed, ${fail} failed`)process.exit(fail ? 1 : 0)
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre