service-manager.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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) {
  48. if (value.phase === 'ready' && this.updateNotice) value = { ...value, updateNotice: this.updateNotice, message: `${value.message},Web 同步待完成` }
  49. this.state = value; this.options.onState?.(value)
  50. }
  51. async retrySynchronization() {
  52. if (this.starting) return this.starting
  53. this.state = { phase: 'stopped', message: '正在准备同步 Web…' }
  54. return this.start()
  55. }
  56. async reconnect() {
  57. const generation=this.generation
  58. if (this.state.phase === 'ready' && !this.stopping) {
  59. await this.check()
  60. if(this.stopping||generation!==this.generation)return this.state
  61. }
  62. if (this.state.phase === 'ready' && !this.stopping) return this.state
  63. clearTimeout(this.restartTimer)
  64. return this.start()
  65. }
  66. async readRecord() {
  67. try {
  68. const r = JSON.parse(await readFile(join(this.root, 'service-instance.json'), 'utf8'))
  69. return r.protocol === 1 && r.dataKey === dataKey(this.root) && isAlive(r.pid) ? r : null
  70. } catch { return null }
  71. }
  72. async verify(record) {
  73. if (!record.url) throw new Error('服务尚未监听')
  74. const url = new URL(record.url)
  75. if (url.hostname === '0.0.0.0') url.hostname = '127.0.0.1'
  76. const actual = await localJSON(new URL('/desktop/service', url), { 'x-yaoyao-desktop-token': record.token })
  77. 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))
  78. throw new Error('服务身份与本地数据不匹配')
  79. if (this.child?.pid === actual.pid && actual.version !== this.options.version) throw new Error('App 内置服务版本不匹配,请重新安装完整 App')
  80. return { ...actual, url: url.origin }
  81. }
  82. async legacyService() {
  83. // Old CLI/LaunchAgent builds lack the new descriptor. Prove the listener
  84. // actually holds this directory's SQLite file before reusing its own UI.
  85. if (process.platform !== 'darwin') return null
  86. const pids = async args => {
  87. try { return new Set((await exec('/usr/sbin/lsof', args, { timeout: 3000 })).stdout.trim().split(/\s+/).filter(Boolean)) }
  88. catch { return new Set() }
  89. }
  90. const [holders, listeners] = await Promise.all([
  91. pids(['-t', join(this.root, 'workspace.sqlite3')]),
  92. pids(['-nP', `-iTCP:${this.options.port}`, '-sTCP:LISTEN', '-t']),
  93. ])
  94. if (!holders.size) return null
  95. if (holders.size !== 1 || !listeners.has([...holders][0])) throw new Error('数据目录正在被另一个服务使用,请先确认已有服务。')
  96. const url = `http://127.0.0.1:${this.options.port}`
  97. const status = await localJSON(new URL('/api/status', url))
  98. if (status.server_kind !== 'yaoyao-web') throw new Error('已有端口不是夭夭服务。')
  99. return { url, pid: Number([...holders][0]), external: true, legacy: true, version: '已有服务' }
  100. }
  101. async start() {
  102. if (this.starting) return this.starting
  103. if (this.state.phase === 'ready' && !this.stopping) return this.state
  104. this.stopping = false
  105. this.starting = this.boot().finally(() => { this.starting = null })
  106. return this.starting
  107. }
  108. async boot() {
  109. const generation = ++this.generation
  110. this.publish({ phase: 'starting', message: '正在启动本地服务…' })
  111. try {
  112. await mkdir(this.options.home, { recursive: true, mode: 0o700 })
  113. this.root = await realpath(this.options.home)
  114. this.updateNotice = undefined
  115. if (this.options.synchronize) {
  116. try { await this.options.synchronize(message => this.publish({ phase: 'starting', message })) }
  117. catch (error) {
  118. // Busy is reported before stopping or switching. Other failures still
  119. // fail closed; the existing service must pass the usual identity checks.
  120. if (error.code !== 'service_busy') throw error
  121. this.updateNotice = error.message
  122. }
  123. if (generation !== this.generation || this.stopping) return
  124. }
  125. let record = await this.readRecord()
  126. if (generation !== this.generation || this.stopping) return
  127. if (record?.url) {
  128. const service = await this.verify(record)
  129. if (generation !== this.generation || this.stopping) return
  130. this.publish({ phase: 'ready', message: `已连接已有服务(${service.version})`, ...service, external: !this.child })
  131. return this.state
  132. }
  133. const legacy = !record ? await this.legacyService() : null
  134. if (generation !== this.generation || this.stopping) return
  135. if (legacy) { this.publish({ phase: 'ready', message: '已连接已有后台服务', ...legacy }); return this.state }
  136. if (!record) {
  137. if (this.options.synchronize) throw new Error('独立后台服务尚未就绪,请稍后重试')
  138. const child = this.options.fork({ home: this.root, port: this.options.port })
  139. child.desktopExited = false
  140. this.child = child
  141. child.stdout?.on('data', b => this.options.log?.(String(b)))
  142. child.stderr?.on('data', b => this.options.log?.(String(b)))
  143. child.once('exit', code => {
  144. child.desktopExited = true
  145. if (this.child !== child) return
  146. this.child = null
  147. if (this.stopping || this.state.phase === 'starting') return
  148. this.options.log?.(`服务进程退出:${code}`)
  149. this.scheduleRestart(this.generation)
  150. })
  151. }
  152. const deadline = Date.now() + (this.options.timeoutMs ?? 30_000)
  153. let lastError
  154. while (Date.now() < deadline && !this.stopping && generation === this.generation) {
  155. record = await this.readRecord()
  156. if (record?.url) {
  157. try {
  158. const service = await this.verify(record)
  159. if (this.child && service.pid !== this.child.pid) throw new Error('服务启动期间归属发生变化')
  160. if (generation !== this.generation || this.stopping) return
  161. this.publish({ phase: 'ready', message: '本地服务已就绪', ...service, external: !this.child })
  162. return this.state
  163. } catch (e) { lastError = e }
  164. }
  165. if (!this.child && !record) throw new Error('服务进程未能启动,请查看日志后重试。')
  166. await sleep(100)
  167. }
  168. if (!this.stopping) throw new Error(lastError?.message || '服务启动超时,请查看日志后重试。')
  169. } catch (error) {
  170. if (generation !== this.generation || this.stopping) return
  171. await this.stopChild()
  172. this.publish({ phase: 'error', message: error.message })
  173. throw error
  174. }
  175. }
  176. scheduleRestart(generation) {
  177. const now = Date.now()
  178. this.restarts = this.restarts.filter(time => now - time < 5 * 60_000)
  179. if (this.restarts.length >= (this.options.synchronize ? 12 : 3)) { this.publish({ phase: 'error', message: '服务多次断开,请查看日志后重试。' }); return }
  180. this.restarts.push(now)
  181. this.publish({ phase: 'restarting', message: '服务已断开,正在恢复…' })
  182. this.restartTimer = setTimeout(() => {
  183. if (this.stopping || generation !== this.generation) return
  184. void this.start().catch(() => { if (this.options.synchronize && !this.stopping) this.scheduleRestart(this.generation) })
  185. }, this.options.synchronize ? 5000 : 500 * this.restarts.length)
  186. }
  187. async check() {
  188. if (this.state.phase !== 'ready') return
  189. const generation = this.generation
  190. try {
  191. if (this.state.legacy) {
  192. if (!isAlive(this.state.pid)) throw new Error('已有服务已停止')
  193. await localJSON(new URL('/api/status', this.state.url))
  194. } else {
  195. const record = await this.readRecord()
  196. if (!record) throw new Error('服务已停止')
  197. const service = await this.verify(record)
  198. if (service.pid !== this.state.pid || service.version !== this.state.version || service.build?.commit !== this.state.build?.commit)
  199. this.publish({ phase: 'ready', message: `已连接后台服务(${service.version})`, ...service, external: !this.child })
  200. }
  201. } catch {
  202. if (this.stopping || generation !== this.generation) return
  203. if (this.state.external) this.scheduleRestart(generation)
  204. else this.publish({ phase: 'error', message: '本地服务连接已断开,请重试。' })
  205. }
  206. }
  207. async stopChild() {
  208. const child = this.child
  209. if (!child || child.desktopExited) return
  210. const exited = new Promise(resolve => child.once('exit', resolve))
  211. const record = await this.readRecord()
  212. if (record?.pid === child.pid && record.desktopOwned) {
  213. try { await localJSON(new URL('/desktop/service', record.url), { 'x-yaoyao-desktop-token': record.token }, 'DELETE') }
  214. catch { /* Owned process handle remains authoritative for cleanup. */ }
  215. } else child.kill()
  216. let timer
  217. await Promise.race([exited, new Promise(resolve => { timer = setTimeout(() => { child.kill(); resolve() }, 5000) })])
  218. clearTimeout(timer)
  219. if (!child.desktopExited) {
  220. await Promise.race([exited, sleep(2000)])
  221. if (!child.desktopExited && child.pid) {
  222. try { process.kill(child.pid, 'SIGKILL') } catch (error) { if (error.code !== 'ESRCH') throw error }
  223. await Promise.race([exited, sleep(2000)])
  224. }
  225. if (!child.desktopExited) throw new Error('旧服务进程尚未确认退出,暂不启动替代进程。')
  226. }
  227. if (this.child === child) this.child = null
  228. }
  229. async stop() {
  230. const owned = Boolean(this.child)
  231. this.stopping = true
  232. clearTimeout(this.restartTimer)
  233. ++this.generation
  234. await this.starting?.catch(() => {})
  235. await this.stopChild()
  236. this.publish(owned ? { phase: 'stopped', message: '后台服务已停止' }
  237. : { phase: 'disconnected', message: 'App 已断开后台连接' })
  238. }
  239. async stopBackground() {
  240. this.stopping = true
  241. clearTimeout(this.restartTimer)
  242. ++this.generation
  243. await this.starting?.catch(() => {})
  244. this.publish({phase:'stopping',message:'正在停止后台服务…'})
  245. try {
  246. if(this.options.stopBackground)await this.options.stopBackground(message=>this.publish({phase:'stopping',message}))
  247. else if(this.child)await this.stopChild()
  248. else throw new Error('此后台服务不由本 App 管理,请在它的启动位置停止')
  249. this.publish({phase:'stopped',message:'后台服务已停止'})
  250. } catch(error) {
  251. this.publish({phase:'error',message:'后台服务停止未完成,请重新连接检查'})
  252. throw error
  253. }
  254. }
  255. }