|
| 1 | +/** |
| 2 | + * Version tracking & one-click self-update. |
| 3 | + * |
| 4 | + * The deployment is a plain git checkout, so the "version" is simply the checked-out commit |
| 5 | + * SHA. We read it at runtime, compare it against the tracked branch on GitHub, and — for |
| 6 | + * admins — kick off an in-place update (git reset + rebuild + PM2 reload) by spawning a |
| 7 | + * detached script that survives the API restart. |
| 8 | + */ |
| 9 | +import { execFile } from 'node:child_process'; |
| 10 | +import { promisify } from 'node:util'; |
| 11 | +import { spawn } from 'node:child_process'; |
| 12 | +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; |
| 13 | +import { dirname, join, resolve } from 'node:path'; |
| 14 | +import type { Env } from '../env.js'; |
| 15 | + |
| 16 | +const exec = promisify(execFile); |
| 17 | + |
| 18 | +export interface LocalVersion { |
| 19 | + sha: string | null; |
| 20 | + shortSha: string | null; |
| 21 | + subject: string | null; |
| 22 | + committedAt: string | null; |
| 23 | + branch: string | null; |
| 24 | + /** True when the checkout is a real git repo we can read/update. */ |
| 25 | + isGit: boolean; |
| 26 | +} |
| 27 | + |
| 28 | +export interface RemoteVersion { |
| 29 | + sha: string; |
| 30 | + shortSha: string; |
| 31 | + subject: string; |
| 32 | + committedAt: string | null; |
| 33 | + htmlUrl: string; |
| 34 | +} |
| 35 | + |
| 36 | +export interface UpdateStatus { |
| 37 | + state: 'idle' | 'running' | 'success' | 'failed'; |
| 38 | + startedAt: string | null; |
| 39 | + finishedAt: string | null; |
| 40 | + message: string | null; |
| 41 | +} |
| 42 | + |
| 43 | +/** Walk up from the API's working directory to the repository root (the dir holding .git). */ |
| 44 | +function findRepoRoot(): string | null { |
| 45 | + let dir = process.cwd(); |
| 46 | + for (let i = 0; i < 8; i += 1) { |
| 47 | + if (existsSync(join(dir, '.git'))) return dir; |
| 48 | + const parent = dirname(dir); |
| 49 | + if (parent === dir) break; |
| 50 | + dir = parent; |
| 51 | + } |
| 52 | + return null; |
| 53 | +} |
| 54 | + |
| 55 | +const repoRoot = findRepoRoot(); |
| 56 | +let cachedLocal: LocalVersion | null = null; |
| 57 | + |
| 58 | +export async function getLocalVersion(): Promise<LocalVersion> { |
| 59 | + if (cachedLocal) return cachedLocal; |
| 60 | + if (!repoRoot) { |
| 61 | + cachedLocal = { sha: null, shortSha: null, subject: null, committedAt: null, branch: null, isGit: false }; |
| 62 | + return cachedLocal; |
| 63 | + } |
| 64 | + try { |
| 65 | + const { stdout } = await exec('git', ['log', '-1', '--format=%H%x1f%h%x1f%cI%x1f%s'], { cwd: repoRoot }); |
| 66 | + const [sha, shortSha, committedAt, subject] = stdout.trim().split('\x1f'); |
| 67 | + let branch: string | null = null; |
| 68 | + try { |
| 69 | + const b = await exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoRoot }); |
| 70 | + branch = b.stdout.trim(); |
| 71 | + } catch { |
| 72 | + /* detached HEAD or no branch — leave null */ |
| 73 | + } |
| 74 | + cachedLocal = { |
| 75 | + sha: sha ?? null, |
| 76 | + shortSha: shortSha ?? null, |
| 77 | + committedAt: committedAt ?? null, |
| 78 | + subject: subject ?? null, |
| 79 | + branch, |
| 80 | + isGit: true, |
| 81 | + }; |
| 82 | + } catch { |
| 83 | + cachedLocal = { sha: null, shortSha: null, subject: null, committedAt: null, branch: null, isGit: false }; |
| 84 | + } |
| 85 | + return cachedLocal; |
| 86 | +} |
| 87 | + |
| 88 | +interface GithubCommit { |
| 89 | + sha: string; |
| 90 | + html_url: string; |
| 91 | + commit: { message: string; committer?: { date?: string } }; |
| 92 | +} |
| 93 | + |
| 94 | +/** Fetch the latest commit of the tracked branch from GitHub. Returns null on any failure. */ |
| 95 | +export async function getRemoteVersion(env: Env): Promise<RemoteVersion | null> { |
| 96 | + const headers: Record<string, string> = { |
| 97 | + Accept: 'application/vnd.github+json', |
| 98 | + 'User-Agent': 'OpenCoperLock', |
| 99 | + 'X-GitHub-Api-Version': '2022-11-28', |
| 100 | + }; |
| 101 | + if (env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`; |
| 102 | + try { |
| 103 | + const res = await fetch( |
| 104 | + `https://api.github.com/repos/${env.GITHUB_REPO}/commits/${encodeURIComponent(env.UPDATE_BRANCH)}`, |
| 105 | + { headers, signal: AbortSignal.timeout(8000) }, |
| 106 | + ); |
| 107 | + if (!res.ok) return null; |
| 108 | + const c = (await res.json()) as GithubCommit; |
| 109 | + return { |
| 110 | + sha: c.sha, |
| 111 | + shortSha: c.sha.slice(0, 7), |
| 112 | + subject: c.commit.message.split('\n')[0] ?? '', |
| 113 | + committedAt: c.commit.committer?.date ?? null, |
| 114 | + htmlUrl: c.html_url, |
| 115 | + }; |
| 116 | + } catch { |
| 117 | + return null; |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +/** How many commits the local checkout is behind `head`, via the GitHub compare API. */ |
| 122 | +export async function commitsBehind(env: Env, base: string, head: string): Promise<number | null> { |
| 123 | + if (base === head) return 0; |
| 124 | + const headers: Record<string, string> = { |
| 125 | + Accept: 'application/vnd.github+json', |
| 126 | + 'User-Agent': 'OpenCoperLock', |
| 127 | + }; |
| 128 | + if (env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`; |
| 129 | + try { |
| 130 | + const res = await fetch( |
| 131 | + `https://api.github.com/repos/${env.GITHUB_REPO}/compare/${base}...${head}`, |
| 132 | + { headers, signal: AbortSignal.timeout(8000) }, |
| 133 | + ); |
| 134 | + if (!res.ok) return null; |
| 135 | + const data = (await res.json()) as { ahead_by?: number }; |
| 136 | + return typeof data.ahead_by === 'number' ? data.ahead_by : null; |
| 137 | + } catch { |
| 138 | + return null; |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +const STATUS_FILE = repoRoot ? resolve(repoRoot, '.update-status.json') : null; |
| 143 | + |
| 144 | +export function readUpdateStatus(): UpdateStatus { |
| 145 | + const idle: UpdateStatus = { state: 'idle', startedAt: null, finishedAt: null, message: null }; |
| 146 | + if (!STATUS_FILE || !existsSync(STATUS_FILE)) return idle; |
| 147 | + try { |
| 148 | + const raw = JSON.parse(readFileSync(STATUS_FILE, 'utf8')) as Partial<UpdateStatus>; |
| 149 | + return { |
| 150 | + state: raw.state ?? 'idle', |
| 151 | + startedAt: raw.startedAt ?? null, |
| 152 | + finishedAt: raw.finishedAt ?? null, |
| 153 | + message: raw.message ?? null, |
| 154 | + }; |
| 155 | + } catch { |
| 156 | + return idle; |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +export interface StartUpdateResult { |
| 161 | + ok: boolean; |
| 162 | + error?: string; |
| 163 | +} |
| 164 | + |
| 165 | +/** Spawn the detached self-update script. It survives the PM2 reload it triggers. */ |
| 166 | +export function startUpdate(env: Env): StartUpdateResult { |
| 167 | + if (!env.SELF_UPDATE_ENABLED) return { ok: false, error: 'Self-update is disabled on this instance.' }; |
| 168 | + if (!repoRoot) return { ok: false, error: 'This deployment is not a git checkout; update it manually.' }; |
| 169 | + if (readUpdateStatus().state === 'running') return { ok: false, error: 'An update is already running.' }; |
| 170 | + |
| 171 | + const script = join(repoRoot, 'scripts', 'self-update.sh'); |
| 172 | + if (!existsSync(script)) return { ok: false, error: 'Update script not found (scripts/self-update.sh).' }; |
| 173 | + |
| 174 | + // Mark running immediately so the UI reflects it before the script writes its own status. |
| 175 | + if (STATUS_FILE) { |
| 176 | + try { |
| 177 | + writeFileSync( |
| 178 | + STATUS_FILE, |
| 179 | + JSON.stringify({ state: 'running', startedAt: new Date().toISOString(), finishedAt: null, message: 'Démarrage…' }), |
| 180 | + ); |
| 181 | + } catch { |
| 182 | + /* best effort */ |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + const child = spawn('bash', [script], { |
| 187 | + cwd: repoRoot, |
| 188 | + detached: true, |
| 189 | + stdio: 'ignore', |
| 190 | + env: { ...process.env, UPDATE_BRANCH: env.UPDATE_BRANCH }, |
| 191 | + }); |
| 192 | + child.unref(); |
| 193 | + return { ok: true }; |
| 194 | +} |
0 commit comments