service-manager.mjs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { readFile, realpath, mkdir } from 'node:fs/promises'
  2. import { join } from 'node:path'
  3. import { createHash } from 'node:crypto'
  4. import { request as httpRequest } from 'node:http'
  5. import { request as httpsRequest } from 'node:https'
  6. import { execFile } from 'node:child_process'
  7. import { promisify } from 'node:util'
  8. const exec = promisify(execFile)
  9. const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
  10. export const dataKey = root => createHash('sha256').update(root).digest('hex')
  11. export function localJSON(url, headers = {}, method = 'GET', timeout = 1500) {
  12. const target = new URL(url)
  13. if (!['http:', 'https:'].includes(target.protocol) || !['127.0.0.1', '[::1]'].includes(target.hostname) || target.username || target.password)
  14. return Promise.reject(new Error('桌面服务必须使用本机回环地址。'))
  15. return new Promise((resolve, reject) => {
  16. const req = (target.protocol === 'https:' ? httpsRequest : httpRequest)(target, { method, headers, agent: false }, res => {
  17. let body = '', bytes = 0
  18. res.on('data', chunk => {
  19. bytes += chunk.length
  20. if (bytes > 64 * 1024) req.destroy(new Error('服务身份响应过大'))
  21. else body += chunk
  22. })
  23. res.on('end', () => {
  24. if (res.statusCode !== 200) { reject(new Error(`服务返回 HTTP ${res.statusCode}`)); return }
  25. try { resolve(JSON.parse(body)) } catch { reject(new Error('服务返回了无效响应')) }
  26. })
  27. })
  28. req.setTimeout(timeout, () => req.destroy(new Error('服务连接超时')))
  29. req.on('error', reject); req.end()
  30. })
  31. }
  32. function isAlive(pid) {
  33. if (!Number.isSafeInteger(pid) || pid < 1) return false
  34. try { process.kill(pid, 0); return true } catch (e) { return e.code !== 'ESRCH' }
  35. }
  36. /** One owner for a packaged service child. Existing services are connected to,
  37. * never stopped. All callbacks are fenced to their exact child generation. */
  38. export class DesktopServiceManager {
  39. constructor(options) {
  40. this.options = options
  41. this.state = { phase: 'stopped', message: '本地服务尚未启动' }
  42. this.child = null
  43. this.generation = 0
  44. this.stopping = false
  45. this.restarts = []
  46. }
  47. publish(value) { this.state = value; this.options.onState?.(value) }
  48. async readRecord() {
  49. try {
  50. const r = JSON.parse(await readFile(join(this.root, 'service-instance.json'), 'utf8'))
  51. return r.protocol === 1 && r.dataKey === dataKey(this.root) && isAlive(r.pid) ? r : null
  52. } catch { return null }
  53. }
  54. async verify(record) {
  55. if (!record.url) throw new Error('服务尚未监听')
  56. const url = new URL(record.url)
  57. if (url.hostname === '0.0.0.0') url.hostname = '127.0.0.1'
  58. const actual = await localJSON(new URL('/desktop/service', url), { 'x-yaoyao-desktop-token': record.token })
  59. if (actual.protocol !== 1 || actual.instanceId !== record.instanceId || actual.pid !== record.pid || actual.dataKey !== dataKey(this.root) || actual.version !== record.version || typeof actual.version !== 'string' || !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/.test(actual.version))
  60. throw new Error('服务身份与本地数据不匹配')
  61. if (this.child?.pid === actual.pid && actual.version !== this.options.version) throw new Error('App 内置服务版本不匹配,请重新安装完整 App')
  62. return { ...actual, url: url.origin }
  63. }
  64. async legacyService() {
  65. // Old CLI/LaunchAgent builds lack the new descriptor. Prove the listener
  66. // actually holds this directory's SQLite file before reusing its own UI.
  67. if (process.platform !== 'darwin') return null
  68. const pids = async args => {
  69. try { return new Set((await exec('/usr/sbin/lsof', args, { timeout: 3000 })).stdout.trim().split(/\s+/).filter(Boolean)) }
  70. catch { return new Set() }
  71. }
  72. const [holders, listeners] = await Promise.all([
  73. pids(['-t', join(this.root, 'workspace.sqlite3')]),
  74. pids(['-nP', `-iTCP:${this.options.port}`, '-sTCP:LISTEN', '-t']),
  75. ])
  76. if (!holders.size) return null
  77. if (holders.size !== 1 || !listeners.has([...holders][0])) throw new Error('数据目录正在被另一个服务使用,请先确认已有服务。')
  78. const url = `http://127.0.0.1:${this.options.port}`
  79. const status = await localJSON(new URL('/api/status', url))
  80. if (status.server_kind !== 'yaoyao-web') throw new Error('已有端口不是夭夭服务。')
  81. return { url, pid: Number([...holders][0]), external: true, legacy: true, version: '已有服务' }
  82. }
  83. async start() {
  84. if (this.starting) return this.starting
  85. if (this.state.phase === 'ready') return this.state
  86. this.stopping = false
  87. this.starting = this.boot().finally(() => { this.starting = null })
  88. return this.starting
  89. }
  90. async boot() {
  91. const generation = ++this.generation
  92. this.publish({ phase: 'starting', message: '正在启动本地服务…' })
  93. try {
  94. await mkdir(this.options.home, { recursive: true, mode: 0o700 })
  95. this.root = await realpath(this.options.home)
  96. let record = await this.readRecord()
  97. if (generation !== this.generation || this.stopping) return
  98. if (record?.url) {
  99. const service = await this.verify(record)
  100. if (generation !== this.generation || this.stopping) return
  101. this.publish({ phase: 'ready', message: `已连接已有服务(${service.version})`, ...service, external: !this.child })
  102. return this.state
  103. }
  104. const legacy = !record ? await this.legacyService() : null
  105. if (generation !== this.generation || this.stopping) return
  106. if (legacy) { this.publish({ phase: 'ready', message: '已连接已有后台服务', ...legacy }); return this.state }
  107. if (!record) {
  108. const child = this.options.fork({ home: this.root, port: this.options.port })
  109. child.desktopExited = false
  110. this.child = child
  111. child.stdout?.on('data', b => this.options.log?.(String(b)))
  112. child.stderr?.on('data', b => this.options.log?.(String(b)))
  113. child.once('exit', code => {
  114. child.desktopExited = true
  115. if (this.child !== child) return
  116. this.child = null
  117. if (this.stopping || this.state.phase === 'starting') return
  118. this.options.log?.(`服务进程退出:${code}`)
  119. this.scheduleRestart(this.generation)
  120. })
  121. }
  122. const deadline = Date.now() + (this.options.timeoutMs ?? 30_000)
  123. let lastError
  124. while (Date.now() < deadline && !this.stopping && generation === this.generation) {
  125. record = await this.readRecord()
  126. if (record?.url) {
  127. try {
  128. const service = await this.verify(record)
  129. if (this.child && service.pid !== this.child.pid) throw new Error('服务启动期间归属发生变化')
  130. if (generation !== this.generation || this.stopping) return
  131. this.publish({ phase: 'ready', message: '本地服务已就绪', ...service, external: !this.child })
  132. return this.state
  133. } catch (e) { lastError = e }
  134. }
  135. if (!this.child && !record) throw new Error('服务进程未能启动,请查看日志后重试。')
  136. await sleep(100)
  137. }
  138. if (!this.stopping) throw new Error(lastError?.message || '服务启动超时,请查看日志后重试。')
  139. } catch (error) {
  140. if (generation !== this.generation || this.stopping) return
  141. await this.stopChild()
  142. this.publish({ phase: 'error', message: error.message })
  143. throw error
  144. }
  145. }
  146. scheduleRestart(generation) {
  147. const now = Date.now()
  148. this.restarts = this.restarts.filter(time => now - time < 5 * 60_000)
  149. if (this.restarts.length >= 3) { this.publish({ phase: 'error', message: '服务多次退出,已停止自动重启。请查看日志后重试。' }); return }
  150. this.restarts.push(now)
  151. this.publish({ phase: 'restarting', message: '服务已断开,正在恢复…' })
  152. this.restartTimer = setTimeout(() => {
  153. if (this.stopping || generation !== this.generation) return
  154. void this.start().catch(() => {})
  155. }, 500 * this.restarts.length)
  156. }
  157. async check() {
  158. if (this.state.phase !== 'ready') return
  159. const generation = this.generation
  160. try {
  161. if (this.state.legacy) {
  162. if (!isAlive(this.state.pid)) throw new Error('已有服务已停止')
  163. await localJSON(new URL('/api/status', this.state.url))
  164. } else {
  165. const record = await this.readRecord()
  166. if (!record) throw new Error('服务已停止')
  167. await this.verify(record)
  168. }
  169. } catch {
  170. if (this.stopping || generation !== this.generation) return
  171. this.publish({ phase: 'error', message: '本地服务连接已断开,请重试。' })
  172. }
  173. }
  174. async stopChild() {
  175. const child = this.child
  176. if (!child || child.desktopExited) return
  177. const exited = new Promise(resolve => child.once('exit', resolve))
  178. const record = await this.readRecord()
  179. if (record?.pid === child.pid && record.desktopOwned) {
  180. try { await localJSON(new URL('/desktop/service', record.url), { 'x-yaoyao-desktop-token': record.token }, 'DELETE') }
  181. catch { /* Owned process handle remains authoritative for cleanup. */ }
  182. } else child.kill()
  183. let timer
  184. await Promise.race([exited, new Promise(resolve => { timer = setTimeout(() => { child.kill(); resolve() }, 5000) })])
  185. clearTimeout(timer)
  186. if (!child.desktopExited) {
  187. await Promise.race([exited, sleep(2000)])
  188. if (!child.desktopExited && child.pid) {
  189. try { process.kill(child.pid, 'SIGKILL') } catch (error) { if (error.code !== 'ESRCH') throw error }
  190. await Promise.race([exited, sleep(2000)])
  191. }
  192. if (!child.desktopExited) throw new Error('旧服务进程尚未确认退出,暂不启动替代进程。')
  193. }
  194. if (this.child === child) this.child = null
  195. }
  196. async stop() {
  197. this.stopping = true
  198. clearTimeout(this.restartTimer)
  199. ++this.generation
  200. await this.starting?.catch(() => {})
  201. await this.stopChild()
  202. this.publish({ phase: 'stopped', message: '本地服务已停止' })
  203. }
  204. }