import type { CaptureJob, Orbit, RefreshRun, RestoreJob, Snapshot } from "../api"; import { formatBytes, formatWhen } from "./format.ts"; import { undoDepth } from "./restoreRun.ts"; /** Where an entry leads. Restores and exports start from a snapshot, so that is where most entries go. */ export type ActivityTarget = | { kind: "snapshot" | "orbit"; id: string } /** A restore (or undo) that can still be put back: opens the undo (or redo) dialog for this run. */ | { kind: "undo" | "redo"; run: RefreshRun }; export type ActivityEntry = { id: string; kind: "backup" | "restore"; /** Milliseconds since the epoch, or null when the hub does not say when it happened. */ at: number | null; tone: "red" | "amber" | "green" | "grey"; state: string; title: string; meta: string; group: "needs" | "running" | "history"; opens: ActivityTarget | null; /** Position along the five phases of a job in flight, 0 to 4. */ progress?: number; /** Said in place of the link, when the entry leads nowhere on purpose (for instance, its safety backup expired). */ note?: string; /** An undo (a restore put back) or a redo (an undo put back), shown under the restore it reverses. */ variant?: "undo" | "redo"; /** The undo or redo of this restore, oldest first. They are listed under it, not on their own. */ children?: ActivityEntry[]; /** Where the entry sits in the log: its own group and time, or the most urgent and newest of its subtree. */ slotGroup: "needs" | "running" | "history"; slotAt: number | null; }; type Draft = Omit & { children?: Draft[] }; const captureLabels: Record = { queued: "Waiting for outpost", claimed: "Assigned to agent", dumping: "Preparing source", uploading: "Saving backup", dump_failed: "Source preparation failed or timed out", upload_failed: "Backup transfer failed", completed: "Backup completed", }; const captureOrder = ["queued", "claimed", "dumping", "uploading", "completed"]; const restoreLabels: Record = { queued: "Waiting for outpost", claimed: "Assigned to agent", checking: "Verifying archive and target", safety: "Saving a copy of the target", ready: "Safety copy verified", applying: "Applying restore", completed: "Restore complete", wrong_target: "Target identity check failed", invalid_payload: "Archive check failed", safety_failed: "Safety copy could not be verified", rolled_back: "Rolled back", apply_failed: "Apply failed", lease_lost: "Agent disconnected during apply", reconciled: "Recovery verified", cancelled: "Cancelled", }; const restoreOrder: string[][] = [["queued", "claimed"], ["checking"], ["safety"], ["ready", "applying"], ["completed", "reconciled"]]; const EXPIRED = "Safety backup expired"; const shortId = (id: string) => id.slice(0, 8); const inFlight = (status: string) => status === "queued" || status === "running" || status === "applying"; function restoreEntry(job: RestoreJob, snapshots: Map, run: RefreshRun | undefined, runs: Map): Draft { const source = snapshots.get(job.snapshot_id); const from = source ? `${source.orbit_name} · ${formatWhen(source.taken_at)}` : `Snapshot ${shortId(job.snapshot_id)}`; const phase = restoreLabels[job.phase] ?? job.status; const depth = run ? undoDepth(run, runs) : 0; // What this row did (an undo, then a redo of it, then an undo of that) and what opening it offers are opposites. const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const; const where = `${job.target.name} / ${job.target.identity.database}`; // An undo restores the safety copy of an earlier restore, which has no snapshot to open: it opens its own dialog. // A restore whose safety backup retention has forgotten says so, instead of leading anywhere that suggests it is there. const expired = run?.undo_state === "expired"; const opens: ActivityTarget | null = expired ? null : run?.undo_available ? { kind: variant === "undo" ? "redo" : "undo", run } : source ? { kind: "snapshot", id: source.id } : null; const base = { id: `restore-${job.id}`, kind: "restore" as const, variant, at: job.created_at * 1000, title: variant ? `${variant === "redo" ? "Redo" : "Undo"} → ${where}` : `${from} → ${where}`, opens, note: expired ? EXPIRED : undefined, }; if (job.status === "recovery_required") { return { ...base, group: "needs", tone: "red", state: "Recovery required", meta: `Restore · ${phase.toLowerCase()} · ${run?.undo_available ? "roll back available" : "target locked until verified · open the snapshot"}` }; } if (inFlight(job.status)) { const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(job.phase))); return { ...base, group: "running", tone: "amber", state: restoreLabels[job.phase] ?? "Running", progress, meta: `Restore · step ${progress + 1} of 5 · by ${job.actor}` }; } if (job.status === "failed") { return { ...base, group: "history", tone: "red", state: "Failed", meta: `Restore · ${phase.toLowerCase()} · by ${job.actor}` }; } if (job.status === "cancelled") { return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: `Restore · by ${job.actor}` }; } const recovered = job.status === "reconciled"; const rolledBack = job.phase === "rolled_back"; const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore"; const undoable = run?.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : ""; return { ...base, group: "history", tone: "green", state: rolledBack ? "Rolled back" : recovered ? "Recovered" : "Complete", meta: `${noun} · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}${undoable}` }; } /** The id a restore has in the log: its job's when it has one, so a run and its job are one entry. */ const restoreId = (run: RefreshRun) => (run.restore_job_id ? `restore-${run.restore_job_id}` : `restore-run-${run.id}`); const runStopped: Record = { restore_failed: "Failed", blocked: "Stopped", expired: "Expired", capture_failed: "Could not start" }; /** * A restore as the run shows it, for people who may not read restore jobs (those are administrator-only): what was * restored where, how far it got, and whether it can be put back. It carries no database names or who started it. */ function runEntry(run: RefreshRun, runs: Map): Draft { const depth = undoDepth(run, runs); const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const; const taken = run.snapshot_taken_at ? formatWhen(new Date(run.snapshot_taken_at * 1000).toISOString()) : undefined; const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore"; const base = { id: restoreId(run), kind: "restore" as const, variant, at: run.created_at * 1000, title: variant ? `${noun} → ${run.target_name}` : `${run.source_name}${taken ? ` · ${taken}` : ""} → ${run.target_name}`, opens: run.undo_available ? { kind: variant === "undo" ? "redo" as const : "undo" as const, run } : null, // A restore known only by its run has nothing to open unless it can be put back; that is not "removed". note: run.undo_state === "expired" ? EXPIRED : run.undo_available ? undefined : "", }; const phase = (run.restore_phase && restoreLabels[run.restore_phase]) || undefined; if (run.status === "recovery_required") { return { ...base, group: "needs", tone: "red", state: "Recovery required", meta: `${noun} · ${(phase ?? "interrupted").toLowerCase()} · ${run.undo_available ? "roll back available" : "target locked until an administrator verifies it"}` }; } if (run.status === "capturing" || run.status === "restoring") { const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(run.restore_phase ?? "queued"))); return { ...base, group: "running", tone: "amber", state: phase ?? "Running", progress, meta: `${noun} · step ${progress + 1} of 5` }; } if (run.status === "cancelled") return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: noun }; const stopped = runStopped[run.status]; if (stopped) return { ...base, group: "history", tone: "red", state: stopped, meta: `${noun}${phase && run.status === "restore_failed" ? ` · ${phase.toLowerCase()}` : ""}` }; return { ...base, group: "history", tone: "green", state: run.restore_phase === "rolled_back" ? "Rolled back" : run.status === "reconciled" ? "Recovered" : "Complete", meta: `${noun}${run.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : ""}` }; } function captureEntry(job: CaptureJob, orbits: Map): Draft | undefined { const orbit = orbits.get(job.profile.orbit_id); const name = orbit?.name ?? job.profile.application_id; const base = { id: `backup-${job.id}`, kind: "backup" as const, at: job.created_at * 1000, title: name, opens: orbit ? { kind: "orbit" as const, id: orbit.id } : null, }; const phase = captureLabels[job.phase] ?? job.status; if (job.status === "queued" || job.status === "running") { const progress = Math.max(0, captureOrder.indexOf(job.phase)); return { ...base, group: "running", tone: "amber", state: phase, progress, meta: `Backup via Outpost · step ${progress + 1} of 5 · by ${job.actor}` }; } if (job.status === "failed") { return { ...base, group: "history", tone: "red", state: "Failed", meta: `Backup via Outpost · ${phase.toLowerCase()} · nothing was stored` }; } return undefined; } const urgency = { needs: 0, running: 1, history: 2 } as const; /** Entries sit in the log by their own group and time, except a restore, which sits by its most urgent and newest undo. */ function place(entry: Draft): ActivityEntry { const children = entry.children?.map(place); let slotGroup = entry.group; let slotAt = entry.at; for (const child of children ?? []) { if (urgency[child.slotGroup] < urgency[slotGroup]) slotGroup = child.slotGroup; if ((child.slotAt ?? -Infinity) > (slotAt ?? -Infinity)) slotAt = child.slotAt; } return { ...entry, children, slotGroup, slotAt }; } export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, refreshRuns = [], now }: { snapshots: readonly Snapshot[]; orbits: readonly Orbit[]; captureJobs: readonly CaptureJob[]; restoreJobs: readonly RestoreJob[]; /** The hub's restore runs: they say which restore an undo reverses. */ refreshRuns?: readonly RefreshRun[]; now: number; }): ActivityEntry[] { const snapshotById = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot])); const orbitById = new Map(orbits.map((orbit) => [orbit.id, orbit])); const jobForSnapshot = new Map(captureJobs.filter((job) => job.snapshot_id).map((job) => [job.snapshot_id!, job])); const runByJob = new Map(refreshRuns.filter((run) => run.restore_job_id).map((run) => [run.restore_job_id!, run])); const runById = new Map(refreshRuns.map((run) => [run.id, run])); const entries: Draft[] = []; for (const snapshot of snapshots) { const job = jobForSnapshot.get(snapshot.id); entries.push({ id: `snapshot-${snapshot.id}`, kind: "backup", at: Date.parse(snapshot.taken_at) || null, tone: "green", state: "Stored", title: `${snapshot.orbit_name} → ${formatBytes(snapshot.size_bytes)} snapshot`, meta: `Backup${job ? ` via Outpost · by ${job.actor}` : ""} · ${shortId(snapshot.id)}`, group: "history", opens: { kind: "snapshot", id: snapshot.id }, }); } for (const job of captureJobs) { const entry = captureEntry(job, orbitById); if (entry) entries.push(entry); } // Orbits the hub runs itself have no job list, only their last status; an outpost orbit is covered by its jobs above. for (const orbit of orbits) { if (orbit.application_id || orbit.access === "outpost") continue; if (orbit.last_status === "running" || orbit.last_status === "queued" || orbit.last_status === "rehearsing") { entries.push({ id: `orbit-${orbit.id}-running`, kind: "backup", at: now, tone: "amber", state: "Running", title: orbit.name, meta: "Backup via Hub", group: "running", opens: { kind: "orbit", id: orbit.id } }); } else if (orbit.last_status === "failed") { entries.push({ id: `orbit-${orbit.id}-failed`, kind: "backup", at: null, tone: "red", state: "Last backup failed", title: orbit.name, meta: "Backup via Hub · the hub does not record when it failed", group: "needs", opens: { kind: "orbit", id: orbit.id } }); } } // Every restore comes from its run, which anyone with the refresh permission may read; an administrator's restore // job adds the database, the person and the snapshot, and restores started without a run (another registered // target) are only known by their job. const jobById = new Map(restoreJobs.map((job) => [job.id, job])); const parentOf = new Map(); for (const run of refreshRuns) { const job = run.restore_job_id ? jobById.get(run.restore_job_id) : undefined; entries.push(job ? restoreEntry(job, snapshotById, run, runById) : runEntry(run, runById)); const parent = run.undo_of ? runById.get(run.undo_of) : undefined; if (parent) parentOf.set(restoreId(run), restoreId(parent)); } for (const job of restoreJobs) if (!runByJob.has(job.id)) entries.push(restoreEntry(job, snapshotById, undefined, runById)); // An undo hangs under the restore it reverses, and a redo under that undo, when that restore is in the log. const byId = new Map(entries.map((entry) => [entry.id, entry])); const top: Draft[] = []; for (const entry of entries) { const parent = byId.get(parentOf.get(entry.id) ?? ""); if (parent && parent !== entry) (parent.children ??= []).push(entry); else top.push(entry); } const oldestFirst = (entry: Draft) => { entry.children?.sort((x, y) => (x.at ?? 0) - (y.at ?? 0)); entry.children?.forEach(oldestFirst); }; top.forEach(oldestFirst); return top.map(place) .sort((a, b) => urgency[a.slotGroup] - urgency[b.slotGroup] || (b.slotAt ?? -Infinity) - (a.slotAt ?? -Infinity) || a.id.localeCompare(b.id)); } /** Every entry in the log, undos included. */ export function flatten(entries: readonly ActivityEntry[]): ActivityEntry[] { return entries.flatMap((entry) => [entry, ...flatten(entry.children ?? [])]); } export function activityCounts(all: readonly ActivityEntry[]) { const entries = flatten(all); return { running: entries.filter(({ group }) => group === "running").length, needs: entries.filter(({ group }) => group === "needs").length, }; } /** "Today", "Yesterday" or a short date, in the viewer's time zone. */ export function dayLabel(at: number, now: number): string { const day = (time: number) => new Date(time).setHours(0, 0, 0, 0); const gap = Math.round((day(now) - day(at)) / 86_400_000); if (gap <= 0) return "Today"; if (gap === 1) return "Yesterday"; return new Date(at).toLocaleDateString(undefined, { month: "short", day: "numeric", ...(gap > 300 ? { year: "numeric" } : {}) }); } export function clock(at: number): string { return new Date(at).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hour12: false }); }