service-sync.test.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import { test } from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import { mkdtemp, readFile, writeFile, rm, cp, realpath } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { dirname, join, resolve } from 'node:path'
  6. import { createServer } from 'node:net'
  7. import { spawn } from 'node:child_process'
  8. import { createHash } from 'node:crypto'
  9. import { _electron as electron } from '@playwright/test'
  10. import { LaunchAgentService, localRequest, synchronizeDesktop } from '../bin/lib/service-update.mjs'
  11. import { sealRuntime, verifyRuntimePackage } from '../bin/lib/runtime-release.mjs'
  12. const root = resolve(import.meta.dirname, '..')
  13. const payloadRoot = process.env.DESKTOP_TEST_EXECUTABLE
  14. ? resolve(dirname(process.env.DESKTOP_TEST_EXECUTABLE), '../Resources/runtime/web-service')
  15. : join(root, '.desktop-build', 'web-service')
  16. async function freePort() {
  17. const server = createServer(); await new Promise(done => server.listen(0, '127.0.0.1', done))
  18. const port = server.address().port; await new Promise(done => server.close(done)); return port
  19. }
  20. async function until(read, accept, timeout = 60000) {
  21. const deadline = Date.now() + timeout
  22. while (Date.now() < deadline) {
  23. try { const value = await read(); if (accept(value)) return value } catch {}
  24. await new Promise(done => setTimeout(done, 200))
  25. }
  26. throw new Error('等待同步服务状态超时')
  27. }
  28. async function nativeQuit(app, menu = false) {
  29. let exited=false;app.process().once('exit',()=>{exited=true})
  30. let output='';app.process().stdout.on('data',bytes=>{output+=bytes})
  31. await app.evaluate(({app,BrowserWindow})=>{
  32. const navigations=[]
  33. BrowserWindow.getAllWindows()[0].webContents.on('did-start-navigation',(_event,url)=>navigations.push(url))
  34. app.once('will-quit',()=>console.log('QUIT_TEST_NAVIGATIONS='+JSON.stringify(navigations)))
  35. })
  36. await app.evaluate(({app,Menu},menu)=>{if(menu)Menu.getApplicationMenu().getMenuItemById('desktop-quit').click();else app.quit()},menu)
  37. await until(()=>exited,Boolean,10000)
  38. const proof=output.match(/QUIT_TEST_NAVIGATIONS=(\[[^\n]*\])/)
  39. assert.ok(proof,'native will-quit must complete')
  40. assert.equal(JSON.parse(proof[1]).some(url=>url.includes('boot.html')),false,'native quit must not navigate to a stopped boot page')
  41. await app.close().catch(()=>{})
  42. }
  43. test('App first launch installs an independent Web; Web remains up after quit and a newer Web is retained', { timeout: 150000 }, async () => {
  44. const home = await realpath(await mkdtemp(join(tmpdir(), 'yaoyao-sync-native-')))
  45. const port = await freePort(), upstreamPort = await freePort()
  46. const releaseRoot = join(home, 'updates', 'fixture-releases')
  47. const label = `cn.samien.yaoyao.sync-test.${createHash('sha256').update(home).digest('hex').slice(0, 16)}`
  48. const driver = new LaunchAgentService({ home, port, releaseRoot, label, plistPath: join(home, 'updates', 'fixture-service.plist') })
  49. const upstream = spawn(process.execPath, [join(root, 'tests/fixtures/fake-hermes.mjs')], {
  50. cwd: root, env: { ...process.env, FAKE_HERMES_PORT: String(upstreamPort), FAKE_HERMES_LOCAL_AUTH: '1' }, stdio: 'ignore',
  51. })
  52. let app
  53. const launch = () => electron.launch({
  54. ...(process.env.DESKTOP_TEST_EXECUTABLE ? { executablePath: process.env.DESKTOP_TEST_EXECUTABLE } : {}),
  55. args: process.env.DESKTOP_TEST_EXECUTABLE ? [] : [root], cwd: root,
  56. env: { ...process.env, HERMES_YAOYAO_DESKTOP_TEST_HOME: home, HERMES_YAOYAO_DESKTOP_PORT: String(port),
  57. HERMES_YAOYAO_DESKTOP_TEST_SYNC: '1', HERMES_YAOYAO_UPSTREAM: `http://127.0.0.1:${upstreamPort}` }, timeout: 30000,
  58. })
  59. try {
  60. await until(() => localRequest(`http://127.0.0.1:${upstreamPort}/api/status`), value => value.status === 200)
  61. app = await launch()
  62. const page = await app.firstWindow()
  63. await page.waitForURL(`http://127.0.0.1:${port}/**`, { timeout: 90000 })
  64. const record = JSON.parse(await readFile(join(home, 'service-instance.json'), 'utf8'))
  65. assert.equal(record.desktopOwned, false)
  66. const identity = await localRequest(`http://127.0.0.1:${port}/desktop/service`, record.token)
  67. const original = verifyRuntimePackage(payloadRoot)
  68. assert.equal(identity.body.build.artifactDigest, original.artifactDigest)
  69. assert.equal(identity.body.quiesced, false)
  70. const support = await page.evaluate(async () => {
  71. const bootstrap = await (await fetch('/api/app/bootstrap')).json()
  72. const setup = await fetch('/api/app/setup', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': bootstrap.csrfToken },
  73. body: JSON.stringify({ username: 'sync-fixture', password: 'sync-fixture-password' }) })
  74. if (!setup.ok) throw new Error('验收账号创建失败')
  75. return (await fetch('/api/app/system/update/status')).json()
  76. })
  77. assert.equal(support.installationMode, 'release'); assert.equal(support.supported, true)
  78. await nativeQuit(app); app = undefined
  79. assert.equal((await localRequest(`http://127.0.0.1:${port}/healthz`)).body.ok, true)
  80. assert.equal(driver.pid(), record.pid, 'quitting the App must leave the independent Web running')
  81. const saved = driver.snapshot().plist
  82. saved.EnvironmentVariables.YAOYAO_TEST_PRESERVE = 'keep-existing-settings'
  83. driver.writePlist(saved)
  84. // Install a later release through the same transaction engine used by Web's updater.
  85. const newer = join(home, 'updates', 'newer-package')
  86. await cp(payloadRoot, newer, { recursive: true })
  87. await writeFile(join(newer, 'release.json'), JSON.stringify({ schemaVersion: 1, releaseVersion: '0.3.33', webVersion: '0.3.33', gitTag: 'v0.3.33' }))
  88. const build = JSON.parse(await readFile(join(newer, 'build-info.json'), 'utf8'))
  89. await writeFile(join(newer, 'build-info.json'), JSON.stringify({ ...build, commit: 'c'.repeat(40), ancestors: [build.commit, ...build.ancestors], dirty: false }))
  90. sealRuntime(newer)
  91. await synchronizeDesktop({ home, runtimeRoot: newer, releaseRoot, driver })
  92. const updated = JSON.parse(await readFile(join(home, 'service-instance.json'), 'utf8'))
  93. assert.equal(updated.version, '0.3.33'); assert.notEqual(updated.pid, record.pid)
  94. assert.equal(driver.snapshot().plist.EnvironmentVariables.YAOYAO_TEST_PRESERVE, 'keep-existing-settings')
  95. app = await launch()
  96. const reopened = await app.firstWindow(); await reopened.waitForURL(`http://127.0.0.1:${port}/**`, { timeout: 90000 })
  97. assert.equal(driver.pid(), updated.pid, 'older App must retain the newer Web without restarting it')
  98. const marker = JSON.parse(await readFile(join(home, 'updates', 'desktop-sync.json'), 'utf8'))
  99. assert.equal(marker.action, 'newer')
  100. assert.equal(marker.artifactDigest, original.artifactDigest)
  101. // Keep an authenticated event stream open. Stop-and-quit must close it,
  102. // unload launchd (not just kill its PID), and exit with one menu action.
  103. await reopened.evaluate(async()=>{
  104. const capabilities=await (await fetch('/api/realtime/capabilities')).json()
  105. const created=await fetch('/api/realtime/channels',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':capabilities.csrfToken},body:JSON.stringify({channel:'chat'})})
  106. if(!created.ok)throw new Error('fixture realtime channel unavailable')
  107. const channel=await created.json()
  108. const response=await fetch(`/api/realtime/channels/${channel.id}/events`)
  109. if(!response.ok)throw new Error('fixture event stream unavailable')
  110. if(!response.headers.get('content-type')?.includes('text/event-stream'))throw new Error('expected a real SSE stream')
  111. window.stopTestStream=response.body.getReader()
  112. void window.stopTestStream.read()
  113. })
  114. let exited=false;app.process().once('exit',()=>{exited=true})
  115. await app.evaluate(({Menu})=>Menu.getApplicationMenu().getMenuItemById('desktop-stop-and-quit').click())
  116. await until(()=>exited,Boolean,30000);app=undefined
  117. assert.equal(driver.pid(),undefined)
  118. assert.equal(driver.listeners().size,0)
  119. await new Promise(done=>setTimeout(done,1000))
  120. assert.equal(driver.pid(),undefined,'launchd must not relaunch a deliberately stopped service')
  121. app = await launch()
  122. const restarted = await app.firstWindow(); await restarted.waitForURL(`http://127.0.0.1:${port}/**`, { timeout: 90000 })
  123. const resumed = JSON.parse(await readFile(join(home, 'service-instance.json'), 'utf8'))
  124. assert.equal(resumed.version, '0.3.33'); assert.equal(resumed.desktopOwned, false)
  125. assert.notEqual(resumed.pid, updated.pid)
  126. await nativeQuit(app,true); app = undefined
  127. } catch (error) {
  128. // Only this fixture's server log, which contains startup diagnostics.
  129. const log = await readFile(join(home, 'service.log'), 'utf8').catch(() => '')
  130. if (log) process.stderr.write(log.slice(-3000))
  131. throw error
  132. } finally {
  133. await app?.close().catch(() => {})
  134. await driver.stop()
  135. upstream.kill('SIGTERM')
  136. await rm(home, { recursive: true, force: true })
  137. }
  138. })