- POST /refresh-runs accepts snapshot_id: restore a snapshot somebody picked (a restorable capture of the relation's own source, never a safety copy or another orbit's) through the same run engine - refresh-relations carries source_orbit_id; snapshots carry kind (capture|safety), and the UI hides safety copies - snapshot detail: Restore replaces Export file on hub (disabled with No restore point without a relation); modal with a restore point selector, a ten second countdown with Abort, and a four step progress view - administrators keep Other registered target; the Refresh menu and refresh-only screen are removed - proven with a real agent and PostgreSQL in the browser: capture, restore to Development, abort, no relation Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
197 lines
10 KiB
TypeScript
197 lines
10 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from "react";
|
|
import { motion } from "motion/react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { cancelRefresh, fetchRefreshRun, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api";
|
|
import { formatBytes, formatWhen } from "../../lib/format";
|
|
import { isFinal, outcomeOf, progressOf, relationLabels, STAGES } 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.",
|
|
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, relations, admin, onBusyChange }: {
|
|
snapshot: Snapshot;
|
|
/** The relations from this snapshot's orbit that the person may restore through. */
|
|
relations: RefreshRelation[];
|
|
admin: boolean;
|
|
onBusyChange: (busy: boolean) => void;
|
|
}) {
|
|
const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]);
|
|
const [pointId, setPointId] = useState(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);
|
|
// 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, 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]);
|
|
|
|
const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2);
|
|
const abort = async () => {
|
|
if (phase === "countdown") {
|
|
setPhase("idle");
|
|
setLeft(COUNTDOWN);
|
|
} else if (runId) {
|
|
try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ }
|
|
}
|
|
};
|
|
const again = () => {
|
|
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined);
|
|
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: formatWhen(snapshot.taken_at) }) : undefined;
|
|
const database = snapshot.capture;
|
|
|
|
return (
|
|
<div className="restore-layout">
|
|
<div className="restore-top">
|
|
<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 ? (
|
|
<DatabaseRestore snapshot={snapshot.id} application={database.application_id} applicationName={snapshot.orbit_name} engine={database.engine} />
|
|
) : (
|
|
<>
|
|
<div className="restore-fields">
|
|
<div>
|
|
<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>
|
|
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.</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"); }}>
|
|
Begin restore
|
|
</Button>
|
|
</div>
|
|
{refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>}
|
|
{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">No restore is running. Begin restore 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">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>
|
|
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button>
|
|
</div>
|
|
)}
|
|
{run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>}
|
|
</>
|
|
)}
|
|
</aside>
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|