Files
tessera/web/src/components/restore/RestoreWizard.tsx
Adnan Zahir d356c313ce
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
feat: restore history, undo and redo in the Activity log for everyone who may refresh
- Activity lists restores from refresh runs, so the Refresh permission is enough to see them; an administrator's
  restore jobs add the database, the person and the snapshot
- an undo is listed under the restore it reverses, and a redo under that undo; opening a restore or an undo opens
  its undo or redo dialog
- the dialog has an explicit undo mode: it describes what is put back instead of the snapshot that was open, and
  an interrupted restore offers Roll back
- a restore whose safety backup retention has forgotten shows "Safety backup expired" instead of a link, and the
  dialog says how long a safety copy is kept

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00

257 lines
14 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { motion } from "motion/react";
import { useQuery } from "@tanstack/react-query";
import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format";
import { isFinal, outcomeOf, progressOf, relationLabels, STAGES, undoDepth, undoVerb } from "../../lib/restoreRun";
import { Button } from "../ui/Button";
import { Segmented } from "../ui/Segmented";
import { DatabaseRestore } from "../reconstitute/DatabaseRestore";
/** Seconds between pressing Begin restore and the request being sent. Abort works until then. */
const COUNTDOWN = 10;
const REFUSALS: Record<string, string> = {
run_active: "A restore of this database is already running.",
stale_confirmation: "This restore point was changed while you were looking at it. Close this and open it again.",
relation_unusable: "This restore point cannot be used right now. Ask an administrator.",
too_many_runs: "Too many restores are running at once. Try again in a few minutes.",
snapshot_unusable: "This backup cannot be restored to that database.",
nothing_to_undo: "There is nothing to undo any more: something was restored after it, or its safety copy was removed.",
source_unavailable: "The source cannot be reached right now.",
};
type Phase = "idle" | "countdown" | "running";
/**
* Restore one snapshot onto a staging or development database. The person picks the restore point (shown only
* when there are several), presses Begin restore, has ten seconds to abort, and then follows four steps until the
* target holds the backup. Administrators can still restore to any other registered target.
*/
export function RestoreWizard({ snapshot, undo, relations, admin, onBusyChange, onDone }: {
/** The snapshot to restore. Absent when the dialog was opened from a restore in the Activity log, to undo it. */
snapshot?: Snapshot;
/** The restore (or undo) this dialog was opened to put back. */
undo?: RefreshRun;
/** The relations from this snapshot's orbit that the person may restore through. */
relations: RefreshRelation[];
admin: boolean;
onBusyChange: (busy: boolean) => void;
/** Leave the dialog once a run opened for an undo has finished. */
onDone?: () => void;
}) {
const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]);
const [pointId, setPointId] = useState(undo?.relation_id ?? points[0]?.id ?? "");
const point = points.find((p) => p.id === pointId) ?? points[0];
const [phase, setPhase] = useState<Phase>("idle");
const [left, setLeft] = useState(COUNTDOWN);
const [runId, setRunId] = useState<string>();
const [refusal, setRefusal] = useState<string>();
const [other, setOther] = useState(false);
// Set while an undo is being started or followed: the restore (or undo) being put back. Its presence is the
// wizard's undo mode, which shows what is being put back instead of the snapshot the person opened.
const [undoRun, setUndoRun] = useState<RefreshRun | undefined>(undo);
const undoOf = undoRun?.id;
// One key per attempt: the same press can never start two restores, even if the request is retried.
const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random()));
const run = useQuery({
queryKey: ["restore-run", runId],
queryFn: () => fetchRefreshRun(runId as string),
enabled: !!runId,
refetchInterval: (query) => {
const data = query.state.data as RefreshRun | undefined;
return data && isFinal(data) ? false : 1500;
},
retry: false,
});
const progress = run.data ? progressOf(run.data) : { index: 0, state: "running" as const };
// Finished means the run itself has stopped changing; the steps may all be done a moment before that.
const finished = !!run.data && isFinal(run.data);
const busy = phase === "countdown" || (phase === "running" && !finished);
useEffect(() => { onBusyChange(busy); }, [busy, onBusyChange]);
useEffect(() => {
if (phase !== "countdown") return;
if (left <= 0) {
setPhase("running");
if (!point) return;
startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot!.id })
.then((started) => setRunId(started.id))
.catch((error) => {
setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started.");
setPhase("idle");
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
});
return;
}
const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000);
return () => clearTimeout(timer);
}, [phase, left, point, snapshot?.id, undoOf]);
const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2);
const abort = async () => {
if (phase === "countdown") {
setPhase("idle");
setUndoRun(undo);
setLeft(COUNTDOWN);
} else if (runId) {
try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ }
}
};
const again = () => {
// Opened to undo one restore: once it is done there is nothing left to do here.
if (!snapshot && onDone) { onDone(); return; }
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoRun(undefined);
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
};
// The newest restore on the chosen restore point, if it can still be undone.
const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, retry: false, refetchInterval: 15_000 });
const runsById = new Map((Array.isArray(recent.data) ? recent.data : []).map((r) => [r.id, r]));
const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined;
const beginUndo = (of: RefreshRun) => {
setRefusal(undefined); setRunId(undefined); setUndoRun(of); setLeft(COUNTDOWN); setPhase("countdown");
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
};
const radius = 52;
const circumference = 2 * Math.PI * radius;
const target = point?.label ?? "the database";
const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot?.orbit_name, when: snapshot ? formatWhen(snapshot.taken_at) : undefined }) : undefined;
const database = snapshot?.capture;
const undoing = !!undoRun;
// An undo of an undo puts back what the first undo replaced, so it is a redo.
const verb = (r: RefreshRun) => undoVerb(undoDepth(r, runsById));
// What a run was: a restore, the undo of one, or the redo of that undo.
const what = (r: RefreshRun) => { const depth = undoDepth(r, runsById); return depth === 0 ? "restore" : depth % 2 === 1 ? "undo" : "redo"; };
const undoneAt = undoRun ? formatWhen(new Date(undoRun.updated_at * 1000).toISOString()) : "";
return (
<div className="restore-layout">
<div className="restore-top">
{undoRun ? (
<>
<p className="restore-lead">{verb(undoRun)} the last {what(undoRun)} on {target}.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">↺</span>
<div className="min-w-0">
<p className="restore-snap-name">{target} as it was before {undoneAt}</p>
<p className="restore-snap-meta">From the safety copy taken just before that {what(undoRun)}</p>
</div>
</div>
</>
) : snapshot && (
<>
<p className="restore-lead">Review the restore point before starting.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snapshot.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p>
</div>
</div>
</>
)}
</div>
{other && admin && database && snapshot ? (
<DatabaseRestore snapshot={snapshot!.id} application={database.application_id} applicationName={snapshot?.orbit_name ?? ""} engine={database.engine} />
) : (
<>
<div className="restore-fields">
<div hidden={undoing}>
<p className="field-label mb-1.5">Restore point</p>
{points.length > 1 ? (
<Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId}
options={points.map((p) => ({ value: p.id, label: p.label }))} />
) : (
<p className="field field-mono" aria-label="Restore point">{point?.label ?? "None"}</p>
)}
</div>
<div className="restore-warning" role="note">
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg>
{undoing ? (
<p>This replaces everything on {target} with its state from before {undoneAt}. Whatever changed on {target} since is lost, but its current state is kept as a new safety copy, so this can be reversed too.</p>
) : (
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot?.orbit_name} itself is only read. What {target} holds now is kept as a safety copy first, for at least a week, so the restore can be undone.</p>
)}
</div>
<div className="flex gap-2.5">
<Button variant="danger" className="flex-1" disabled={!abortable} onClick={() => void abort()}>Abort</Button>
<Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}>
{undoRun ? `Begin ${verb(undoRun).toLowerCase()}` : "Begin restore"}
</Button>
</div>
{refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>}
{undoable && !undoRun && phase === "idle" && !runId && (
<div className="restore-undo">
<p>
{undoable.undo ? `${target} was last put back (${what(undoable)}) on` : `${target} was last restored on`} {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}.
{" "}{`${verb(undoable)} returns it to what it held before.`}
{undoable.undo_kept_until ? ` Its safety copy is kept at least until ${formatWhen(new Date(undoable.undo_kept_until * 1000).toISOString())}.` : ""}
</p>
<Button onClick={() => beginUndo(undoable)}>{`${verb(undoable)} last ${what(undoable)}`}</Button>
</div>
)}
{admin && database && phase === "idle" && !runId && (
<button type="button" className="footer-link self-start" onClick={() => setOther(true)}>Other registered target…</button>
)}
</div>
<aside className="restore-status">
<p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p>
{phase === "idle" && <p className="restore-idle">Nothing is running. Begin to start the countdown.</p>}
{phase === "countdown" && (
<motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<div className="restore-ring">
<svg viewBox="0 0 120 120" width="132" height="132" aria-hidden="true">
<circle cx="60" cy="60" r={radius} fill="none" stroke="#2a2218" strokeWidth="5" />
<motion.circle cx="60" cy="60" r={radius} fill="none" stroke="#e8b57e" strokeWidth="5" strokeLinecap="round"
strokeDasharray={circumference} initial={false} animate={{ strokeDashoffset: circumference * (1 - left / COUNTDOWN) }} />
</svg>
<span className="restore-ring-text"><b>{left}</b><i>seconds</i></span>
</div>
<p className="restore-count-note">{undoRun ? `${verb(undoRun)}ing on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p>
</motion.div>
)}
{phase === "running" && (
<>
<ol className="restore-steps" aria-label="Restore progress">
{STAGES.map((name, i) => {
const done = i < progress.index || progress.state === "done";
const now = i === progress.index && progress.state === "running";
const bad = i === progress.index && progress.state === "failed";
return (
<li key={name} className={done ? "done" : now ? "now" : bad ? "bad" : ""} aria-current={now ? "step" : undefined}>
<span aria-hidden="true">{done ? "✓" : bad ? "!" : i + 1}</span>
{name}
</li>
);
})}
</ol>
{!finished && (
<p className="restore-idle" role="status">
{progress.index >= 2 ? "Overwriting has started. This can no longer be cancelled." : `Nothing on ${target} has changed yet. You can still abort.`}
</p>
)}
{outcome && (
<div role="status" className={`restore-outcome ${outcome.tone}`}>
<p>{outcome.title}</p>
<p>{outcome.detail}</p>
<div className="flex flex-wrap gap-2">
{run.data?.undo_available && <Button variant="primary" onClick={() => beginUndo(run.data!)}>{run.data.status === "recovery_required" ? "Roll back" : run.data.undo ? verb(run.data) : "Undo this restore"}</Button>}
<Button onClick={again}>{outcome.tone === "good" ? "Done" : "Try again"}</Button>
</div>
</div>
)}
{run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>}
</>
)}
</aside>
</>
)}
</div>
);
}