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 = { 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("idle"); const [left, setLeft] = useState(COUNTDOWN); const [runId, setRunId] = useState(); const [refusal, setRefusal] = useState(); 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 (

Review the restore point before starting.

{snapshot.orbit_name}

{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}

{other && admin && database ? ( ) : ( <>

Restore point

{points.length > 1 ? ( ({ value: p.id, label: p.label }))} /> ) : (

{point?.label ?? "None"}

)}

Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.

{refusal &&

{refusal}

} {admin && database && phase === "idle" && !runId && ( )}
)}
); }