hermes-yaoyao-updater.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env node
  2. import { execFileSync } from 'node:child_process'
  3. import {
  4. existsSync,
  5. lstatSync,
  6. mkdirSync,
  7. readFileSync,
  8. readlinkSync,
  9. renameSync,
  10. rmSync,
  11. symlinkSync,
  12. writeFileSync,
  13. } from 'node:fs'
  14. import { dirname, join, relative, resolve, sep } from 'node:path'
  15. import { fileURLToPath } from 'node:url'
  16. const label = 'com.samien.hermes-yaoyao'
  17. import { LaunchAgentService, updateMutex, recoverTransition, transitionService } from './lib/service-update.mjs'
  18. import { assertRollbackCompatible } from './lib/service-data.mjs'
  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']) {
  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. const COMMAND_OUTPUT_LIMIT = 6_000
  45. function cleanCommandOutput(value) {
  46. if (value === undefined || value === null) return ''
  47. return String(value)
  48. .replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, '')
  49. .replace(/([a-z][a-z0-9+.-]*:\/\/)([^@\s/]+)@/gi, '$1***@')
  50. .replace(/([?&](?:access_token|token|password)=)[^&\s]+/gi, '$1***')
  51. .trim()
  52. }
  53. function outputTail(value) {
  54. if (value.length <= COMMAND_OUTPUT_LIMIT) return value
  55. return `…已省略前面的输出…\n${value.slice(-COMMAND_OUTPUT_LIMIT)}`
  56. }
  57. export function formatCommandFailure(command, args, error) {
  58. const commandLine = cleanCommandOutput([command, ...args].join(' '))
  59. const status = typeof error?.status === 'number'
  60. ? `,退出码 ${error.status}`
  61. : error?.signal ? `,信号 ${error.signal}` : ''
  62. const stdout = cleanCommandOutput(error?.stdout)
  63. const stderr = cleanCommandOutput(error?.stderr)
  64. let detail = [stdout, stderr].filter(Boolean).join('\n')
  65. if (!detail) {
  66. detail = cleanCommandOutput(error instanceof Error ? error.message : error)
  67. .replace(/^Command failed:[^\n]*(?:\n|$)/, '')
  68. .trim()
  69. }
  70. return `${commandLine} 失败${status}${detail ? `\n${outputTail(detail)}` : ''}`
  71. }
  72. function run(command, args, options = {}) {
  73. try {
  74. return execFileSync(command, args, {
  75. cwd: options.cwd,
  76. env: options.env ?? process.env,
  77. encoding: 'utf8',
  78. stdio: 'pipe',
  79. timeout: options.timeout ?? 120_000,
  80. maxBuffer: 8 * 1_024 * 1_024,
  81. })
  82. } catch (error) {
  83. throw new Error(formatCommandFailure(command, args, error))
  84. }
  85. }
  86. function pathInside(path, parent) {
  87. const target = resolve(path)
  88. const root = resolve(parent)
  89. return target.startsWith(`${root}${sep}`)
  90. }
  91. function removeInside(path, parent) {
  92. if (!pathInside(path, parent)) fail(`拒绝清理非预期路径:${path}`)
  93. rmSync(path, { recursive: true, force: true })
  94. }
  95. function loaded() {
  96. try {
  97. run('launchctl', ['print', `${domain}/${label}`])
  98. return true
  99. } catch {
  100. return false
  101. }
  102. }
  103. function stopService() {
  104. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  105. }
  106. export function currentTarget(releaseRoot) {
  107. const current = join(releaseRoot, 'current')
  108. try {
  109. const stat = lstatSync(current)
  110. if (!stat.isSymbolicLink()) fail('发布目录 current 必须是符号链接')
  111. return resolve(releaseRoot, readlinkSync(current))
  112. } catch (error) {
  113. if (error?.code === 'ENOENT') return undefined
  114. throw error
  115. }
  116. }
  117. export function switchCurrent(releaseRoot, target, token) {
  118. mkdirSync(releaseRoot, { recursive: true, mode: 0o700 })
  119. const current = join(releaseRoot, 'current')
  120. const temporary = join(releaseRoot, `.current-${token}`)
  121. removeInside(temporary, releaseRoot)
  122. symlinkSync(relative(releaseRoot, target), temporary, 'dir')
  123. renameSync(temporary, current)
  124. }
  125. function removeCurrent(releaseRoot) {
  126. const current = join(releaseRoot, 'current')
  127. try {
  128. if (!lstatSync(current).isSymbolicLink()) fail('拒绝删除非符号链接 current')
  129. rmSync(current)
  130. } catch (error) {
  131. if (error?.code !== 'ENOENT') throw error
  132. }
  133. }
  134. function serviceEnvironment(serviceRoot, plan) {
  135. return {
  136. ...process.env,
  137. HERMES_YAOYAO_SERVICE_ROOT: serviceRoot,
  138. HERMES_YAOYAO_RELEASE_ROOT: plan.releaseRoot,
  139. HERMES_YAOYAO_RELEASE_SOURCE: plan.source,
  140. HERMES_YAOYAO_HOST: '0.0.0.0',
  141. HERMES_YAOYAO_ALLOW_INSECURE_LAN: '1',
  142. }
  143. }
  144. export function serviceInstallInvocation(
  145. serviceRoot,
  146. plan,
  147. stableRoot = true,
  148. lifecycleRoot = serviceRoot,
  149. ) {
  150. const cli = join(lifecycleRoot, 'bin', 'hermes-yaoyao.mjs')
  151. const env = serviceEnvironment(stableRoot ? join(plan.releaseRoot, 'current') : serviceRoot, plan)
  152. return { cli, env }
  153. }
  154. function startService(serviceRoot, plan, stableRoot = true, lifecycleRoot = serviceRoot) {
  155. const { cli, env } = serviceInstallInvocation(serviceRoot, plan, stableRoot, lifecycleRoot)
  156. if (!existsSync(cli)) fail(`服务入口不存在:${cli}`)
  157. run(process.execPath, [cli, 'service', 'install'], { env, timeout: 30_000 })
  158. }
  159. export function restorePreviousService({
  160. plan,
  161. previousCurrentTarget,
  162. previousServiceRoot,
  163. lifecycleRoot,
  164. token,
  165. switchCurrentCommand = switchCurrent,
  166. removeCurrentCommand = removeCurrent,
  167. startServiceCommand = startService,
  168. }) {
  169. if (!lifecycleRoot) fail('当前发布版本不可用,无法安全执行回滚')
  170. if (previousCurrentTarget) {
  171. switchCurrentCommand(plan.releaseRoot, previousCurrentTarget, token)
  172. startServiceCommand(join(plan.releaseRoot, 'current'), plan, true, lifecycleRoot)
  173. } else {
  174. removeCurrentCommand(plan.releaseRoot)
  175. startServiceCommand(previousServiceRoot, plan, false, lifecycleRoot)
  176. }
  177. }
  178. async function responseJSON(url, fetchImpl) {
  179. const response = await fetchImpl(url, { signal: AbortSignal.timeout(3_000), cache: 'no-store' })
  180. if (!response.ok) fail(`${url} 返回 HTTP ${response.status}`)
  181. return response.json()
  182. }
  183. export async function verifyRuntime(timeoutMs = 45_000, fetchImpl = fetch) {
  184. const deadline = Date.now() + timeoutMs
  185. let lastError = ''
  186. while (Date.now() < deadline) {
  187. try {
  188. // /readyz deliberately includes 9119 reachability. Only the Web's own
  189. // health decides update/rollback success, including older releases.
  190. const health = await responseJSON('http://127.0.0.1:15300/healthz', fetchImpl)
  191. if (health.ok === true) return
  192. lastError = 'Web 服务尚未就绪'
  193. } catch (error) {
  194. lastError = error instanceof Error ? error.message : String(error)
  195. }
  196. await new Promise(resolvePromise => setTimeout(resolvePromise, 500))
  197. }
  198. fail(`升级后健康检查失败:${lastError}`)
  199. }
  200. function stageRelease(job, jobPath) {
  201. const { plan, target, id } = job
  202. if (!target) fail('升级任务缺少目标版本')
  203. const releasesRoot = join(plan.releaseRoot, 'releases')
  204. mkdirSync(releasesRoot, { recursive: true, mode: 0o700 })
  205. const staging = join(releasesRoot, `.staging-${id}`)
  206. removeInside(staging, releasesRoot)
  207. updateJob(jobPath, { state: 'downloading', message: `正在下载 ${target.gitTag}` })
  208. run('git', ['clone', '--quiet', '--depth', '1', '--single-branch', '--branch', target.gitTag, plan.source, staging], { timeout: 600_000 })
  209. const manifest = validateManifest(readJSON(join(staging, 'release.json')))
  210. for (const field of ['schemaVersion', 'releaseVersion', 'webVersion', 'gitTag']) {
  211. if (manifest[field] !== target[field]) fail('下载的发布清单与检查结果不一致')
  212. }
  213. const commit = run('git', ['rev-parse', 'HEAD'], { cwd: staging }).trim()
  214. if (!/^[0-9a-f]{40,64}$/.test(plan.targetCommit || '') || commit !== plan.targetCommit) {
  215. fail('下载提交与检查时锁定的发布提交不一致')
  216. }
  217. updateJob(jobPath, { state: 'building', message: `正在构建 Web ${target.webVersion}` })
  218. const buildEnvironment = { ...process.env, NODE_ENV: 'development' }
  219. run('npm', ['ci', '--include=dev'], { cwd: staging, env: buildEnvironment, timeout: 600_000 })
  220. run('npm', ['run', 'build'], { cwd: staging, env: buildEnvironment, timeout: 600_000 })
  221. const finalRoot = join(releasesRoot, `${target.releaseVersion}-${commit.slice(0, 12)}`)
  222. if (existsSync(finalRoot)) removeInside(staging, releasesRoot)
  223. else renameSync(staging, finalRoot)
  224. return { finalRoot, commit }
  225. }
  226. function serviceOptions(jobPath, job) {
  227. const home = job.plan.home || resolve(dirname(jobPath), '..')
  228. const options = { home, releaseRoot: job.plan.releaseRoot, port: job.plan.port || Number(process.env.HERMES_YAOYAO_PORT || 15300) }
  229. return { ...options, driver: new LaunchAgentService(options), onProgress: message => updateJob(jobPath, { message }) }
  230. }
  231. async function runUpdate(jobPath, job) {
  232. const options = serviceOptions(jobPath, job)
  233. await recoverTransition(options)
  234. const { finalRoot } = stageRelease(job, jobPath)
  235. updateJob(jobPath, { state: 'installing', message: '正在准备切换 Web 服务' })
  236. await transitionService({ ...options, finalRoot })
  237. updateJob(jobPath, { state: 'succeeded', message: `已升级 Web ${job.target.webVersion}` })
  238. }
  239. async function runRollback(jobPath, job) {
  240. const options = serviceOptions(jobPath, job)
  241. await recoverTransition(options)
  242. const recordPath = join(dirname(jobPath), 'last-success.json')
  243. if (!existsSync(recordPath)) fail('没有可回滚的上一版本')
  244. const record = readJSON(recordPath)
  245. // Manual rollback never restores an older snapshot over data written since
  246. // the successful upgrade. Schema-changing releases need a separate recovery.
  247. assertRollbackCompatible(options.home, record)
  248. const finalRoot = record.previousCurrentTarget || record.previousServiceRoot
  249. if (!finalRoot || !existsSync(finalRoot)) fail('上一版本的程序目录已不可用')
  250. updateJob(jobPath, { state: 'rolling_back', message: '正在恢复上一版本' })
  251. await transitionService({ ...options, finalRoot, rollback: true })
  252. rmSync(recordPath)
  253. updateJob(jobPath, { state: 'rolled_back', message: '已回滚 Web 服务,保留现有数据' })
  254. }
  255. async function main() {
  256. const [, , command, flag, jobPathValue] = process.argv
  257. if (command !== 'run' || flag !== '--job' || !jobPathValue) fail('用法:hermes-yaoyao-updater run --job <path>')
  258. const jobPath = resolve(jobPathValue)
  259. const job = readJSON(jobPath)
  260. const unlock = updateMutex(job.plan.home || resolve(dirname(jobPath), '..'))
  261. try {
  262. if (job.operation === 'update') await runUpdate(jobPath, job)
  263. else if (job.operation === 'rollback') await runRollback(jobPath, job)
  264. else fail('未知升级任务类型')
  265. } catch (error) {
  266. updateJob(jobPath, {
  267. state: 'failed',
  268. message: job.operation === 'rollback' ? '回滚失败,需要人工处理' : '升级失败',
  269. error: error instanceof Error ? error.message : String(error),
  270. })
  271. } finally {
  272. const lockPath = join(dirname(jobPath), 'active.lock')
  273. try {
  274. const raw = readFileSync(lockPath, 'utf8').trim()
  275. let lockJobID = raw
  276. try { lockJobID = JSON.parse(raw).jobID } catch { /* legacy lock */ }
  277. if (lockJobID === job.id) rmSync(lockPath)
  278. } catch { /* already released */ }
  279. unlock()
  280. }
  281. }
  282. if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main()