import { mkdir, rm, writeFile } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { destOfKind, type ArtifactKind } from '../config.js'; import { db } from '../db/index.js'; import { emit } from '../pipeline/bus.js'; import { recordScript, removeScript } from './inventory.js'; import { getVersion } from './scripts.js'; // Roll a promoted deployment back to whatever versions were current before // the promote landed. Reads deployment_scripts as the source of truth for // which scripts were involved (and their prior versions); falls back to the // deprecated deployments.script_id/version_id/prior_version_id columns for // pre-multi-script legacy rows. export class RollbackError extends Error { constructor(message: string, public readonly kind: 'no-such-deployment' | 'not-promote' | 'already-rolled-back') { super(message); } } interface DeploymentRow { id: string; action: string; script_id: number | null; script_version_id: number | null; prior_version_id: number | null; rolled_back_by: string | null; } interface DepScriptRow { deployment_id: string; script_id: number; script_version_id: number; prior_version_id: number | null; kind: ArtifactKind; } interface FileRow { id: number; server: string; verb: 'added' | 'updated' | 'removed'; rel_path: string; sha256_before: string | null; sha256_after: string | null; content_before: Buffer | null; content_after: Buffer | null; } interface ScriptTargetRow { id: number; target_rel_path: string; kind: ArtifactKind; } function nowIso(): string { return new Date().toISOString(); } function rollbackDeploymentId(promoteId: string): string { const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z'); return `dep-${stamp}-rollback-${promoteId}`; } export interface RollbackDeploymentResult { deploymentId: string; // the new rollback deployment reverses: string; // the promote deployment id scriptIds: number[]; // scripts whose current_version_id got reverted affectedServers: string[]; } export async function rollbackPromoteDeployment(promoteId: string): Promise { const dep = db() .prepare(`SELECT id, action, script_id, script_version_id, prior_version_id, rolled_back_by FROM deployments WHERE id = ?`) .get(promoteId) as DeploymentRow | undefined; if (!dep) throw new RollbackError(`no such deployment ${promoteId}`, 'no-such-deployment'); if (dep.action !== 'promote') { throw new RollbackError(`deployment ${promoteId} is action='${dep.action}', not 'promote'`, 'not-promote'); } if (dep.rolled_back_by) { throw new RollbackError(`deployment ${promoteId} already rolled back by ${dep.rolled_back_by}`, 'already-rolled-back'); } // Source of truth for which scripts (and prior versions) this promote // touched. Prefer deployment_scripts; fall back to the deprecated // singular columns for legacy single-script deployments. let scripts = db() .prepare(`SELECT * FROM deployment_scripts WHERE deployment_id = ? ORDER BY script_id`) .all(promoteId) as DepScriptRow[]; if (scripts.length === 0 && dep.script_id !== null && dep.script_version_id !== null) { scripts = [{ deployment_id: promoteId, script_id: dep.script_id, script_version_id: dep.script_version_id, prior_version_id: dep.prior_version_id, kind: 'script' }]; } const fileRows = db() .prepare( `SELECT id, server, verb, rel_path, sha256_before, sha256_after, content_before, content_after FROM deployment_files WHERE deployment_id = ? ORDER BY server, rel_path` ) .all(promoteId) as FileRow[]; // Map rel_path → scriptId (and prior_version_id) so we can restore the // inventory row's script_version_id correctly during file restore. const scriptByTarget = new Map(); const kindByScriptId = new Map(); if (scripts.length > 0) { const placeholders = scripts.map(() => '?').join(','); const targetRows = db() .prepare(`SELECT id, target_rel_path, kind FROM scripts WHERE id IN (${placeholders})`) .all(...scripts.map((s) => s.script_id)) as ScriptTargetRow[]; const targetById = new Map(); for (const t of targetRows) { targetById.set(t.id, t.target_rel_path); kindByScriptId.set(t.id, t.kind); } for (const s of scripts) { const t = targetById.get(s.script_id); if (t) scriptByTarget.set(t, s); } } const kindForRelPath = (relPath: string): ArtifactKind => { const owner = scriptByTarget.get(relPath); if (owner) return owner.kind ?? kindByScriptId.get(owner.script_id) ?? 'script'; // Config/baseline aggregate rows have no per-artifact target_rel_path // mapping — the deployment_files row is keyed on the shared cfg name. // Any script/baseline in this deployment tagged as config/baseline // means the rollback for that path lives under the config destination. for (const s of scripts) if (s.kind === 'config' || s.kind === 'baseline') return 'config'; return 'script'; }; const newDepId = rollbackDeploymentId(promoteId); const startedAt = nowIso(); // Group files by server so each server gets exactly one deployment_servers row. const perServer = new Map(); for (const f of fileRows) { const arr = perServer.get(f.server); if (arr) arr.push(f); else perServer.set(f.server, [f]); } const affectedServers: string[] = []; const perServerFailures = new Map(); for (const [server, files] of perServer) { try { for (const f of files) { const kind = kindForRelPath(f.rel_path); const dest = destOfKind(server, kind); const abs = join(dest, f.rel_path); await mkdir(join(dest, dirname(f.rel_path)), { recursive: true }); const owningScript = scriptByTarget.get(f.rel_path); if (f.verb === 'added') { if (existsSync(abs)) await rm(abs, { force: true }); removeScript(server, f.rel_path); } else if (f.verb === 'updated' && f.content_before) { await writeFile(abs, f.content_before); const priorVer = owningScript?.prior_version_id ? getVersion(owningScript.prior_version_id) : null; recordScript( server, f.rel_path, priorVer?.id ?? null, f.sha256_before!, f.content_before.byteLength, `rollback:${newDepId}` ); } else if (f.verb === 'removed' && f.content_before) { await writeFile(abs, f.content_before); recordScript(server, f.rel_path, null, f.sha256_before!, f.content_before.byteLength, `rollback:${newDepId}`); } } affectedServers.push(server); } catch (err) { perServerFailures.set(server, (err as Error).message); } } // Write the new rollback deployment + mark the original. const insertDep = db().prepare( `INSERT INTO deployments (id, action, started_at, triggered_by, script_id, script_version_id, prior_version_id, beta_id) VALUES (?, 'rollback', ?, 'ui', NULL, NULL, NULL, NULL)` ); const insertDepScript = db().prepare( `INSERT INTO deployment_scripts (deployment_id, script_id, script_version_id, prior_version_id, kind) VALUES (?, ?, ?, ?, ?)` ); const insertDepServer = db().prepare( `INSERT INTO deployment_servers (deployment_id, server, files_changed, restart_state, players, checked_at, restarted_at, attempts, error) VALUES (?, ?, ?, ?, NULL, NULL, NULL, 0, ?)` ); const insertDepFile = db().prepare( `INSERT INTO deployment_files (deployment_id, server, verb, rel_path, sha256_before, sha256_after, content_before, content_after) VALUES (?, ?, ?, ?, ?, ?, ?, ?)` ); db().transaction(() => { insertDep.run(newDepId, startedAt); // Mirror the promote's script list — swapped: the "current" version // after rollback is the promote's prior; the "prior" of the rollback // is what was current up until this call (i.e. the promote's version). for (const s of scripts) { insertDepScript.run( newDepId, s.script_id, s.prior_version_id ?? s.script_version_id, s.script_version_id, s.kind ?? 'script' ); } for (const [server, files] of perServer) { if (perServerFailures.has(server)) { insertDepServer.run(newDepId, server, 0, 'failed', perServerFailures.get(server)!); continue; } insertDepServer.run(newDepId, server, files.length, 'pending', null); for (const f of files) { const invertedVerb = f.verb === 'added' ? 'removed' : f.verb === 'removed' ? 'added' : 'updated'; insertDepFile.run( newDepId, server, invertedVerb, f.rel_path, f.sha256_after, f.sha256_before, f.content_after, f.content_before ); } } db().prepare(`UPDATE deployments SET rolled_back_by = ? WHERE id = ?`).run(newDepId, promoteId); // Restore each affected script's current_version_id. for (const s of scripts) { db().prepare(`UPDATE scripts SET current_version_id = ? WHERE id = ?`).run(s.prior_version_id, s.script_id); } })(); emit({ type: 'deployment-opened', deploymentId: newDepId, action: 'rollback', servers: affectedServers }); return { deploymentId: newDepId, reverses: promoteId, scriptIds: scripts.map((s) => s.script_id), affectedServers }; }