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

{verb(undoRun)} the last {what(undoRun)} on {target}.

{target} as it was before {undoneAt}

From the safety copy taken just before that {what(undoRun)}

) : snapshot && ( <>

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 && snapshot ? ( ) : ( <>
{undoing ? (

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.

) : (

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.

)}
{refusal &&

{refusal}

} {undoable && !undoRun && phase === "idle" && !runId && (

{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())}.` : ""}

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