hermes-yaoyao-updater.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. #!/usr/bin/env node
  2. import { execFileSync } from 'node:child_process'
  3. import {
  4. copyFileSync,
  5. cpSync,
  6. existsSync,
  7. lstatSync,
  8. mkdirSync,
  9. readFileSync,
  10. readlinkSync,
  11. renameSync,
  12. rmSync,
  13. symlinkSync,
  14. writeFileSync,
  15. } from 'node:fs'
  16. import { dirname, join, relative, resolve, sep } from 'node:path'
  17. import { fileURLToPath } from 'node:url'
  18. const label = 'com.samien.hermes-yaoyao'
  19. const uid = process.getuid?.() ?? 501
  20. const domain = `gui/${uid}`
  21. function fail(message) { throw new Error(message) }
  22. function readJSON(path) { return JSON.parse(readFileSync(path, 'utf8')) }
  23. function writeJSON(path, value) {
  24. const temporary = `${path}.tmp-${process.pid}`
  25. writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
  26. renameSync(temporary, path)
  27. }
  28. export function validateManifest(value) {
  29. if (!value || typeof value !== 'object' || value.schemaVersion !== 1) fail('release.json 格式无效')
  30. for (const key of ['releaseVersion', 'webVersion', 'pluginVersion']) {
  31. if (typeof value[key] !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value[key])) {
  32. fail(`release.json ${key} 无效`)
  33. }
  34. }
  35. if (value.releaseVersion !== value.webVersion || value.gitTag !== `v${value.releaseVersion}`) {
  36. fail('release.json 版本组合不一致')
  37. }
  38. return value
  39. }
  40. function updateJob(jobPath, patch) {
  41. const current = readJSON(jobPath)
  42. writeJSON(jobPath, { ...current, ...patch, updatedAt: new Date().toISOString() })
  43. }
  44. function run(command, args, options = {}) {
  45. return execFileSync(command, args, {
  46. cwd: options.cwd,
  47. env: options.env ?? process.env,
  48. encoding: 'utf8',
  49. stdio: options.inherit ? 'inherit' : 'pipe',
  50. timeout: options.timeout ?? 120_000,
  51. maxBuffer: 8 * 1_024 * 1_024,
  52. })
  53. }
  54. function pathInside(path, parent) {
  55. const target = resolve(path)
  56. const root = resolve(parent)
  57. return target.startsWith(`${root}${sep}`)
  58. }
  59. function removeInside(path, parent) {
  60. if (!pathInside(path, parent)) fail(`拒绝清理非预期路径:${path}`)
  61. rmSync(path, { recursive: true, force: true })
  62. }
  63. function loaded() {
  64. try {
  65. run('launchctl', ['print', `${domain}/${label}`])
  66. return true
  67. } catch {
  68. return false
  69. }
  70. }
  71. function stopService() {
  72. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  73. }
  74. function stopDashboard() {
  75. try { run('hermes', ['dashboard', '--stop'], { timeout: 30_000 }) } catch { /* already stopped */ }
  76. }
  77. function enabledPlugins() {
  78. const raw = run('hermes', ['config', 'get', 'plugins.enabled']).trim()
  79. if (!raw) return []
  80. const value = JSON.parse(raw)
  81. if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
  82. fail('Hermes plugins.enabled 不是字符串数组')
  83. }
  84. return value
  85. }
  86. function setEnabledPlugins(value) {
  87. run('hermes', ['config', 'set', 'plugins.enabled', JSON.stringify(value)])
  88. }
  89. function ensureYaoyaoEnabled(previous) {
  90. if (!previous.includes('yaoyao')) setEnabledPlugins([...previous, 'yaoyao'])
  91. }
  92. function atomicDirectory(source, target, scratchRoot, token) {
  93. const parent = dirname(target)
  94. mkdirSync(parent, { recursive: true })
  95. const incoming = join(parent, `.${token}-incoming`)
  96. const previous = join(parent, `.${token}-previous`)
  97. removeInside(incoming, scratchRoot)
  98. removeInside(previous, scratchRoot)
  99. cpSync(source, incoming, { recursive: true, preserveTimestamps: true })
  100. if (existsSync(target)) renameSync(target, previous)
  101. renameSync(incoming, target)
  102. return previous
  103. }
  104. function atomicFile(source, target, scratchRoot, token) {
  105. const parent = dirname(target)
  106. mkdirSync(parent, { recursive: true })
  107. const incoming = join(parent, `.${token}-incoming.yaml`)
  108. const previous = join(parent, `.${token}-previous.yaml`)
  109. removeInside(incoming, scratchRoot)
  110. removeInside(previous, scratchRoot)
  111. copyFileSync(source, incoming)
  112. if (existsSync(target)) renameSync(target, previous)
  113. renameSync(incoming, target)
  114. return previous
  115. }
  116. export function currentTarget(releaseRoot) {
  117. const current = join(releaseRoot, 'current')
  118. try {
  119. const stat = lstatSync(current)
  120. if (!stat.isSymbolicLink()) fail('发布目录 current 必须是符号链接')
  121. return resolve(releaseRoot, readlinkSync(current))
  122. } catch (error) {
  123. if (error?.code === 'ENOENT') return undefined
  124. throw error
  125. }
  126. }
  127. export function switchCurrent(releaseRoot, target, token) {
  128. mkdirSync(releaseRoot, { recursive: true, mode: 0o700 })
  129. const current = join(releaseRoot, 'current')
  130. const temporary = join(releaseRoot, `.current-${token}`)
  131. removeInside(temporary, releaseRoot)
  132. symlinkSync(relative(releaseRoot, target), temporary, 'dir')
  133. renameSync(temporary, current)
  134. }
  135. function removeCurrent(releaseRoot) {
  136. const current = join(releaseRoot, 'current')
  137. try {
  138. if (!lstatSync(current).isSymbolicLink()) fail('拒绝删除非符号链接 current')
  139. rmSync(current)
  140. } catch (error) {
  141. if (error?.code !== 'ENOENT') throw error
  142. }
  143. }
  144. function serviceEnvironment(serviceRoot, plan) {
  145. return {
  146. ...process.env,
  147. HERMES_YAOYAO_SERVICE_ROOT: serviceRoot,
  148. HERMES_YAOYAO_RELEASE_ROOT: plan.releaseRoot,
  149. HERMES_YAOYAO_RELEASE_SOURCE: plan.source,
  150. }
  151. }
  152. function startService(serviceRoot, plan, stableRoot = true) {
  153. const cli = join(serviceRoot, 'bin', 'hermes-yaoyao.mjs')
  154. if (!existsSync(cli)) fail(`服务入口不存在:${cli}`)
  155. const env = serviceEnvironment(stableRoot ? join(plan.releaseRoot, 'current') : serviceRoot, plan)
  156. if (!stableRoot) delete env.HERMES_YAOYAO_SERVICE_ROOT
  157. run(process.execPath, [cli, 'service', 'install'], { env, timeout: 30_000 })
  158. }
  159. async function responseJSON(url) {
  160. const response = await fetch(url, { signal: AbortSignal.timeout(3_000), cache: 'no-store' })
  161. if (!response.ok) fail(`${url} 返回 HTTP ${response.status}`)
  162. return response.json()
  163. }
  164. async function verifyRuntime(pluginVersion, timeoutMs = 45_000) {
  165. const deadline = Date.now() + timeoutMs
  166. let lastError = ''
  167. while (Date.now() < deadline) {
  168. try {
  169. const health = await responseJSON('http://127.0.0.1:8800/healthz')
  170. const ready = await responseJSON('http://127.0.0.1:8800/readyz')
  171. const plugins = await responseJSON('http://127.0.0.1:9119/api/dashboard/plugins')
  172. const plugin = Array.isArray(plugins) ? plugins.find(item => item?.name === 'yaoyao') : undefined
  173. const pluginMatches = pluginVersion ? plugin?.version === pluginVersion : plugin === undefined
  174. if (health.ok === true && ready.ok === true && pluginMatches) return
  175. lastError = pluginVersion
  176. ? `运行版本不匹配:期望插件 ${pluginVersion}`
  177. : '上一版本未安装夭夭插件,但回滚后仍检测到插件'
  178. } catch (error) {
  179. lastError = error instanceof Error ? error.message : String(error)
  180. }
  181. await new Promise(resolvePromise => setTimeout(resolvePromise, 500))
  182. }
  183. fail(`升级后健康检查失败:${lastError}`)
  184. }
  185. export function backupPlugin(plan, jobID) {
  186. const pluginRoot = join(plan.hermesHome, 'plugins', 'yaoyao')
  187. const backupRoot = join(plan.dataHome, 'backups', 'system-update', jobID)
  188. const pluginPreviouslyInstalled = existsSync(join(pluginRoot, 'dashboard', 'manifest.json'))
  189. mkdirSync(backupRoot, { recursive: true, mode: 0o700 })
  190. if (existsSync(join(pluginRoot, 'dashboard'))) {
  191. cpSync(join(pluginRoot, 'dashboard'), join(backupRoot, 'dashboard'), { recursive: true, preserveTimestamps: true })
  192. }
  193. if (existsSync(join(pluginRoot, 'plugin.yaml'))) copyFileSync(join(pluginRoot, 'plugin.yaml'), join(backupRoot, 'plugin.yaml'))
  194. return { pluginRoot, backupRoot, pluginPreviouslyInstalled }
  195. }
  196. export function restorePlugin(pluginRoot, backupRoot, token, pluginPreviouslyInstalled = true) {
  197. const dashboardBackup = join(backupRoot, 'dashboard')
  198. const manifestBackup = join(backupRoot, 'plugin.yaml')
  199. if (!pluginPreviouslyInstalled) {
  200. removeInside(join(pluginRoot, 'dashboard'), pluginRoot)
  201. removeInside(join(pluginRoot, 'plugin.yaml'), pluginRoot)
  202. return
  203. }
  204. if (!existsSync(dashboardBackup) || !existsSync(manifestBackup)) fail('插件回滚备份不完整')
  205. const oldDashboard = atomicDirectory(dashboardBackup, join(pluginRoot, 'dashboard'), pluginRoot, `${token}-restore-dashboard`)
  206. const oldManifest = atomicFile(manifestBackup, join(pluginRoot, 'plugin.yaml'), pluginRoot, `${token}-restore-manifest`)
  207. removeInside(oldDashboard, pluginRoot)
  208. removeInside(oldManifest, pluginRoot)
  209. }
  210. function backupPluginVersion(backupRoot) {
  211. return String(readJSON(join(backupRoot, 'dashboard', 'manifest.json')).version ?? '')
  212. }
  213. function stageRelease(job, jobPath) {
  214. const { plan, target, id } = job
  215. if (!target) fail('升级任务缺少目标版本')
  216. const releasesRoot = join(plan.releaseRoot, 'releases')
  217. mkdirSync(releasesRoot, { recursive: true, mode: 0o700 })
  218. const staging = join(releasesRoot, `.staging-${id}`)
  219. removeInside(staging, releasesRoot)
  220. updateJob(jobPath, { state: 'downloading', message: `正在下载 ${target.gitTag}` })
  221. run('git', ['clone', '--quiet', '--depth', '1', '--single-branch', '--branch', target.gitTag, plan.source, staging], { timeout: 600_000 })
  222. const manifest = validateManifest(readJSON(join(staging, 'release.json')))
  223. for (const field of ['schemaVersion', 'releaseVersion', 'webVersion', 'pluginVersion', 'gitTag']) {
  224. if (manifest[field] !== target[field]) fail('下载的发布清单与检查结果不一致')
  225. }
  226. const commit = run('git', ['rev-parse', 'HEAD'], { cwd: staging }).trim()
  227. if (!/^[0-9a-f]{40,64}$/.test(plan.targetCommit || '') || commit !== plan.targetCommit) {
  228. fail('下载提交与检查时锁定的发布提交不一致')
  229. }
  230. updateJob(jobPath, { state: 'building', message: `正在构建 Web ${target.webVersion}` })
  231. run('npm', ['ci'], { cwd: staging, inherit: true, timeout: 600_000 })
  232. run('npm', ['run', 'build'], { cwd: staging, inherit: true, timeout: 600_000 })
  233. const finalRoot = join(releasesRoot, `${target.releaseVersion}-${commit.slice(0, 12)}`)
  234. if (existsSync(finalRoot)) removeInside(staging, releasesRoot)
  235. else renameSync(staging, finalRoot)
  236. return { finalRoot, commit }
  237. }
  238. async function runUpdate(jobPath, job) {
  239. const { plan, target, id } = job
  240. if (!target) fail('升级任务缺少目标发布清单')
  241. const { finalRoot, commit } = stageRelease(job, jobPath)
  242. const pluginSource = join(finalRoot, 'hermes-plugins', 'yaoyao')
  243. const pluginManifest = readJSON(join(pluginSource, 'dashboard', 'manifest.json'))
  244. if (pluginManifest.version !== target.pluginVersion) fail('构建产物中的插件版本与发布清单不一致')
  245. const previousCurrentTarget = currentTarget(plan.releaseRoot)
  246. const { pluginRoot, backupRoot, pluginPreviouslyInstalled } = backupPlugin(plan, id)
  247. const previousPluginVersion = pluginPreviouslyInstalled ? backupPluginVersion(backupRoot) : ''
  248. const previousEnabledPlugins = enabledPlugins()
  249. let transitioned = false
  250. let previousDashboard = ''
  251. let previousPluginYaml = ''
  252. try {
  253. updateJob(jobPath, { state: 'installing', message: `正在安装插件 ${target.pluginVersion}` })
  254. stopService()
  255. stopDashboard()
  256. transitioned = true
  257. previousDashboard = atomicDirectory(
  258. join(pluginSource, 'dashboard'), join(pluginRoot, 'dashboard'), pluginRoot, `${id}-dashboard`,
  259. )
  260. previousPluginYaml = atomicFile(
  261. join(pluginSource, 'plugin.yaml'), join(pluginRoot, 'plugin.yaml'), pluginRoot, `${id}-manifest`,
  262. )
  263. ensureYaoyaoEnabled(previousEnabledPlugins)
  264. switchCurrent(plan.releaseRoot, finalRoot, id)
  265. updateJob(jobPath, { state: 'restarting', message: '正在启动新版本服务' })
  266. startService(join(plan.releaseRoot, 'current'), plan, true)
  267. updateJob(jobPath, { state: 'verifying', message: '正在验证 8800、9119 和插件版本' })
  268. await verifyRuntime(target.pluginVersion)
  269. removeInside(previousDashboard, pluginRoot)
  270. removeInside(previousPluginYaml, pluginRoot)
  271. writeJSON(join(dirname(jobPath), 'last-success.json'), {
  272. jobId: id,
  273. previousCurrentTarget,
  274. previousServiceRoot: plan.previousServiceRoot,
  275. previousPluginVersion,
  276. pluginPreviouslyInstalled,
  277. previousEnabledPlugins,
  278. backupRoot,
  279. target,
  280. finalRoot,
  281. commit,
  282. })
  283. updateJob(jobPath, { state: 'succeeded', message: `已升级到 Web ${target.webVersion} + 插件 ${target.pluginVersion}` })
  284. } catch (error) {
  285. const message = error instanceof Error ? error.message : String(error)
  286. if (transitioned) {
  287. updateJob(jobPath, { state: 'rolling_back', message: '升级失败,正在自动恢复上一版本', error: message })
  288. try {
  289. stopService()
  290. stopDashboard()
  291. restorePlugin(pluginRoot, backupRoot, id, pluginPreviouslyInstalled)
  292. setEnabledPlugins(previousEnabledPlugins)
  293. if (previousCurrentTarget) {
  294. switchCurrent(plan.releaseRoot, previousCurrentTarget, `${id}-rollback`)
  295. startService(join(plan.releaseRoot, 'current'), plan, true)
  296. } else {
  297. removeCurrent(plan.releaseRoot)
  298. startService(plan.previousServiceRoot, plan, false)
  299. }
  300. await verifyRuntime(previousPluginVersion)
  301. updateJob(jobPath, { state: 'failed', message: '升级失败,已自动恢复上一版本', error: message })
  302. } catch (rollbackError) {
  303. const rollbackMessage = rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
  304. updateJob(jobPath, { state: 'failed', message: '升级和自动回滚均失败,需要人工处理', error: `${message}; 回滚:${rollbackMessage}` })
  305. }
  306. } else {
  307. updateJob(jobPath, { state: 'failed', message: '升级准备失败,现有服务未被修改', error: message })
  308. }
  309. }
  310. }
  311. async function runRollback(jobPath, job) {
  312. const { plan, id } = job
  313. const recordPath = join(dirname(jobPath), 'last-success.json')
  314. if (!existsSync(recordPath)) fail('没有可回滚的上一版本')
  315. const record = readJSON(recordPath)
  316. updateJob(jobPath, { state: 'rolling_back', message: '正在恢复上一版本' })
  317. stopService()
  318. stopDashboard()
  319. restorePlugin(
  320. join(plan.hermesHome, 'plugins', 'yaoyao'),
  321. record.backupRoot,
  322. id,
  323. record.pluginPreviouslyInstalled !== false,
  324. )
  325. if (Array.isArray(record.previousEnabledPlugins)) setEnabledPlugins(record.previousEnabledPlugins)
  326. if (record.previousCurrentTarget) {
  327. switchCurrent(plan.releaseRoot, record.previousCurrentTarget, id)
  328. startService(join(plan.releaseRoot, 'current'), plan, true)
  329. } else {
  330. removeCurrent(plan.releaseRoot)
  331. startService(record.previousServiceRoot, plan, false)
  332. }
  333. await verifyRuntime(record.previousPluginVersion)
  334. rmSync(recordPath, { force: true })
  335. updateJob(jobPath, { state: 'rolled_back', message: `已回滚到插件 ${record.previousPluginVersion}` })
  336. }
  337. async function main() {
  338. const [, , command, flag, jobPathValue] = process.argv
  339. if (command !== 'run' || flag !== '--job' || !jobPathValue) fail('用法:hermes-yaoyao-updater run --job <path>')
  340. const jobPath = resolve(jobPathValue)
  341. const job = readJSON(jobPath)
  342. try {
  343. if (job.operation === 'update') await runUpdate(jobPath, job)
  344. else if (job.operation === 'rollback') await runRollback(jobPath, job)
  345. else fail('未知升级任务类型')
  346. } catch (error) {
  347. updateJob(jobPath, {
  348. state: 'failed',
  349. message: job.operation === 'rollback' ? '回滚失败,需要人工处理' : '升级失败',
  350. error: error instanceof Error ? error.message : String(error),
  351. })
  352. } finally {
  353. const lockPath = join(dirname(jobPath), 'active.lock')
  354. try {
  355. const raw = readFileSync(lockPath, 'utf8').trim()
  356. let lockJobID = raw
  357. try { lockJobID = JSON.parse(raw).jobID } catch { /* legacy lock */ }
  358. if (lockJobID === job.id) rmSync(lockPath)
  359. } catch { /* already released */ }
  360. }
  361. }
  362. if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main()