gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/tests/jb23.mjs

8.1 KB

  1. // tests/jb23.mjs — JB23 (mission 015): a tap whose server emit fails must still play once the connection is back.
  2. // 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,
  3. // 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),
  4. // 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.
  5. // Own server on a generated database of 6 songs (one 1.5 s tone, ffmpeg), headless Chrome at 390 px.
  6. // 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_MS
  7. import { spawn, execFileSync } from 'node:child_process'
  8. import { createServer as netServer, connect as netConnect } from 'node:net'
  9. import { rmSync, mkdirSync, readFileSync } from 'node:fs'
  10. import { dirname, join } from 'node:path'
  11. import { fileURLToPath } from 'node:url'
  12. process.env.HL_CHROME = process.env.HL_CHROME || '/opt/google/chrome/chrome'
  13. process.env.HL_PORT_BASE = process.env.HL_PORT_BASE || '8630'
  14. const { launchBrowser, sleep } = await import('./cdp.mjs')
  15. const root = process.env.JB23_ROOT || join(dirname(fileURLToPath(import.meta.url)), '..')
  16. const dir = process.env.JB23_DIR || '/tmp/jb23-gate'
  17. const port = Number(process.env.JB23_PORT || 8826)
  18. const BASE = `http://127.0.0.1:${port}`
  19. 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)
  20. const COLD_MS = Number(process.env.JUKEBOX_COLD_MS || 150000)
  21. const TONE = 1.5
  22. let pass = 0, fail = 0
  23. const check = (name, ok, detail = '') => { console.log((ok ? 'ok ' : 'FAIL ') + name + (ok ? '' : ' — ' + detail)); if (ok) pass++; else fail++ }
  24. mkdirSync(dir, { recursive: true })
  25. process.env.TMPDIR = dir
  26. let server = null, browser = null, log = ''
  27. async function stop() {
  28. if (browser) { try { await browser.close() } catch {} browser = null }
  29. try { proxy.close() } catch {}
  30. if (server) { try { server.kill('SIGTERM') } catch {} await sleep(500); server = null }
  31. }
  32. process.on('SIGINT', async () => { await stop(); process.exit(1) })
  33. const storage = join(dir, 'storage')
  34. const tone = join(dir, 'tone.mp3')
  35. rmSync(storage, { recursive: true, force: true })
  36. execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', `sine=frequency=440:duration=${TONE}`, '-q:a', '9', tone])
  37. const cover = join(root, 'tests/fixtures/withcover/folder.jpg')
  38. 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 })
  39. 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'] })
  40. console.log('server pid ' + server.pid)
  41. let hole = false, socks = new Set()
  42. const proxy = netServer((c) => {
  43. if (hole) { c.destroy(); return } // a new connection while the network is dead: refused at once (the POST fallback fails)
  44. const u = netConnect(realPort, '127.0.0.1'); const mine = { c, u, dead: hole }; socks.add(mine)
  45. c.on('data', (d) => { if (!mine.dead) u.write(d) }); u.on('data', (d) => { if (!mine.dead) c.write(d) })
  46. const end = () => { socks.delete(mine); c.destroy(); u.destroy() }
  47. c.on('close', end); u.on('close', end); c.on('error', end); u.on('error', end)
  48. })
  49. await new Promise((r) => proxy.listen(port, '127.0.0.1', r))
  50. 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 reset
  51. server.stdout.on('data', (d) => { log += d }); server.stderr.on('data', (d) => { log += d })
  52. try {
  53. for (const t0 = Date.now(); ; ) {
  54. try { if ((await fetch(`http://127.0.0.1:${realPort}/`)).ok) break } catch {}
  55. if (Date.now() - t0 > COLD_MS) { console.log(log); throw new Error('the server did not come up') }
  56. await sleep(500)
  57. }
  58. 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))
  59. console.log('list order (artist): ' + order.join(' '))
  60. browser = await launchBrowser()
  61. console.log('chrome pid ' + browser.proc?.pid)
  62. const page = await browser.newPage()
  63. const ev = (e) => page.evaluate(e)
  64. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true })
  65. await page.goto(BASE + '/')
  66. await page.waitForSelector('virtual-list .vl-row:not(.blank)')
  67. await sleep(800)
  68. const playing = () => ev(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc && !a.paused ? a.currentSrc.split('/').pop() : '' })()`)
  69. const tap = (id) => page.click(`virtual-list .vl-row[data-id="${id}"]`)
  70. const pause = () => ev(`document.querySelector('media-player audio').pause(); 1`)
  71. // a normal tap plays at once
  72. await tap(order[1])
  73. 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(() => {})
  74. check('a normal tap plays at once', (await playing()) === order[1], await playing())
  75. await pause(); await sleep(500)
  76. // the network dies, the page does not know yet; a tap 3 s later
  77. setHole(true); await page.setOffline(true)
  78. await sleep(3000)
  79. await tap(order[3])
  80. 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 null
  81. check('while the network is dead nothing plays', (await playing()) === '', await playing())
  82. await page.setOffline(false); setHole(false)
  83. let got = ''
  84. 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() }
  85. check('the tapped song plays after the network is back, without another tap', got === order[3], 'playing=' + JSON.stringify(got) + ' wanted ' + order[3])
  86. // the page works after that: another normal tap
  87. await pause(); await tap(order[4])
  88. try { await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc.endsWith('/${order[4]}') && !a.paused })()`, { timeout: 15000 }) } catch {}
  89. check('a normal tap after the reconnect plays at once', (await playing()) === order[4], await playing())
  90. // 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 back
  91. await pause(); await sleep(500)
  92. setHole(true); await page.setOffline(true)
  93. await sleep(3000)
  94. await ev(`window.__srcs = []; (a => { a.addEventListener('loadstart', () => window.__srcs.push(a.currentSrc.split('/').pop())); a.addEventListener('emptied', () => {}) })(document.querySelector('media-player audio')); 1`)
  95. await tap(order[2])
  96. await sleep(500)
  97. await page.click('.jb-bar .jb-next')
  98. await sleep(Number(process.env.JB23_DEAD_MS || 45000))
  99. await page.setOffline(false); setHole(false)
  100. await sleep(12000)
  101. const srcs = await ev(`window.__srcs`)
  102. check('Next advanced during the outage (its song was loaded)', srcs.includes(order[5]), JSON.stringify(srcs))
  103. check('the superseded tap is never selected during the recovery', !srcs.includes(order[2]), JSON.stringify(srcs))
  104. } finally {
  105. await stop()
  106. }
  107. console.log(`${pass} passed, ${fail} failed`)
  108. 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