feat: restore inside the Vault; the Refresh page and file export UI are gone

- 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>
This commit is contained in:
2026-11-15 16:13:44 +07:00
parent f52fc1930f
commit 3bd0a1c9a3
20 changed files with 778 additions and 508 deletions

View File

@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import test from "node:test";
import { STAGES, isFinal, outcomeOf, progressOf, relationLabels } from "../src/lib/restoreRun.ts";
const run = (status, restore_phase = null, blocked_reason = null) => ({ status, restore_phase, blocked_reason });
test("the four stages follow the restore job's phase", () => {
assert.deepEqual(STAGES, ["Checking", "Safety copy", "Applying", "Completed"]);
// the run is created first; the restore job appears a moment later
assert.equal(progressOf(run("capturing")).index, 0);
for (const phase of ["queued", "claimed", "checking"]) assert.equal(progressOf(run("restoring", phase)).index, 0, phase);
for (const phase of ["safety", "ready"]) assert.equal(progressOf(run("restoring", phase)).index, 1, phase);
assert.equal(progressOf(run("restoring", "applying")).index, 2);
assert.deepEqual(progressOf(run("completed", "completed")), { index: 4, state: "done" });
assert.equal(progressOf(run("restoring", "applying")).state, "running");
// the restore job finishes a moment before the run is marked completed: that gap must not look like a restart
assert.deepEqual(progressOf(run("restoring", "completed")), { index: 4, state: "done" });
assert.equal(isFinal(run("restoring")), false);
assert.equal(isFinal(run("completed")), true);
});
test("a run that stopped says at which stage and why it counts as failed or merely cancelled", () => {
assert.deepEqual(progressOf(run("restore_failed", "invalid_payload")), { index: 0, state: "failed" });
assert.deepEqual(progressOf(run("restore_failed", "safety_failed")), { index: 1, state: "failed" });
assert.deepEqual(progressOf(run("recovery_required", "apply_failed")), { index: 2, state: "failed" });
assert.deepEqual(progressOf(run("blocked", "checking", "access_revoked")), { index: 0, state: "failed" });
assert.deepEqual(progressOf(run("cancelled", "safety")), { index: 1, state: "cancelled" });
assert.equal(progressOf(run("expired")).state, "failed");
});
test("what the person is told never contains the database's own words", () => {
const done = outcomeOf(run("completed"), { target: "Development", orbit: "broiler", when: "Nov 15, 11:57 AM" });
assert.equal(done.tone, "good");
assert.match(done.detail, /Development now holds broiler as of Nov 15, 11:57 AM/);
assert.match(outcomeOf(run("restore_failed", "apply_failed"), { target: "Development" }).detail, /ask an administrator/i);
assert.match(outcomeOf(run("recovery_required"), { target: "Staging" }).title, /interrupted/i);
assert.match(outcomeOf(run("blocked", null, "access_revoked"), { target: "Staging" }).detail, /access to this restore was removed/);
assert.equal(outcomeOf(run("cancelled"), { target: "Staging" }).tone, "plain");
assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy");
});
test("restore points are named by environment, and by target only when two share one", () => {
const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true });
assert.deepEqual(
relationLabels([rel("a", "staging", "s1"), rel("b", "development", "d1")]).map((r) => r.label),
["Staging", "Development"],
);
assert.deepEqual(
relationLabels([rel("a", "staging", "s1"), rel("b", "staging", "s2")]).map((r) => r.label),
["Staging · s1", "Staging · s2"],
);
assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd");
});

View File

@@ -2,21 +2,20 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchSnapshots, pollReconstitute, savePreferences,
enqueueCapture, runOrbit, startReconstitute, type Orbit,
fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences,
enqueueCapture, runOrbit, type Orbit,
} from "./api";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
import { accessItem, HUDRail, hudItems, refreshItem, relationsItem, type HUDMode } from "./components/hud/HUDRail";
import { accessItem, HUDRail, hudItems, relationsItem, type HUDMode } from "./components/hud/HUDRail";
import { AccessView } from "./components/access/AccessView";
import { RelationsView } from "./components/relations/RelationsView";
import { RefreshView } from "./components/refresh/RefreshView";
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
import { OperatorGate, type Caps } from "./components/operator/OperatorGate";
import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView";
import { ActivityView } from "./components/activity/ActivityView";
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
import { RestoreWizard } from "./components/restore/RestoreWizard";
import { VaultScene } from "./components/scene/VaultScene";
import { EmptyState } from "./components/ui/EmptyState";
import { PanelBoundary } from "./components/ui/PanelBoundary";
@@ -38,7 +37,6 @@ const panelTitles: Record<HUDMode, string> = {
activity: "Activity",
access: "Access",
relations: "Refresh relations",
refresh: "Refresh staging",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
@@ -49,11 +47,10 @@ const panelLabels: Record<HUDMode, string> = {
activity: "Console 04 · Activity",
access: "Console 05 · Access",
relations: "Console 06 · Relations",
refresh: "Console 07 · Refresh",
reconstitute: "Restore from a snapshot",
snapshot: "Recovery point",
};
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, refresh: 760, reconstitute: 760, snapshot: 640 };
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, reconstitute: 760, snapshot: 640 };
const LOOK_KEY = "tessera.look";
@@ -72,34 +69,7 @@ function priority(orbit: Orbit) {
}
export default function App() {
return (
<OperatorGate>
{(operator) =>
// Someone who may only refresh a staging database has no orbits to show: give them that one screen,
// and do not load the vault screens at all (every request they make would be refused).
!operator.caps.admin && !operator.caps.orbits && operator.caps.refresh
? <RefreshOnly actor={operator.actor} onLogout={operator.onLogout} />
: <VaultApp {...operator} />}
</OperatorGate>
);
}
function RefreshOnly({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
return (
<main className="vault-app mx-auto min-h-screen max-w-3xl p-5">
<header className="flex items-center justify-between py-4">
<div>
<p className="instrument-label">Tessera / Refresh</p>
<h1 className="text-2xl font-semibold text-star-100">Refresh staging</h1>
</div>
<div className="flex items-center gap-3 text-sm text-star-300">
{actor && <span>{actor}</span>}
{onLogout && <button type="button" className="console-control" onClick={() => void onLogout()}>Sign out</button>}
</div>
</header>
<RefreshView />
</main>
);
return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
}
function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) {
@@ -270,12 +240,13 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
const activity = useActivity(snaps.data, orbits.data, caps.admin);
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
const railItems = useMemo(
() => {
const base = caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity");
return caps.refresh ? [...base.slice(0, 4), refreshItem, ...base.slice(4)] : base;
},
[caps.admin, caps.refresh],
() => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
[caps.admin],
);
// The staging and development databases this person may restore onto, from the orbit's backups.
const relations = useQuery({ queryKey: ["refresh-relations"], queryFn: fetchRefreshRelations, enabled: caps.refresh, retry: false, refetchInterval: 15_000 });
const restorePoints = Array.isArray(relations.data) ? relations.data : [];
const restoreSnapshot = restoreTarget?.id ? snaps.data?.find(({ id }) => id === restoreTarget.id) : undefined;
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
@@ -314,7 +285,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
}
function openConsole(next: HUDMode, target: string | null = null) {
if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot" && !(next === "refresh" && caps.refresh)) return;
if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot" && !(next === "reconstitute" && caps.refresh)) return;
if (next === "reconstitute" && !restoreBusy &&
(!restoreTarget || (target !== null && target !== restoreTarget.id))) {
setRestoreTarget({ id: target });
@@ -465,9 +436,6 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
{mode === "wormhole" && caps.admin && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "refresh" && caps.refresh && (
<SpringPane key="refresh"><RefreshView /></SpringPane>
)}
{mode === "relations" && caps.admin && (
<SpringPane key="relations"><RelationsView /></SpringPane>
)}
@@ -477,23 +445,26 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
{mode === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} canManage={caps.admin} canDownload={caps.can("snapshot.download", snapshot.orbit_id)} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} canManage={caps.admin} canDownload={caps.can("snapshot.download", snapshot.orbit_id)} onDeleted={() => openConsole("scene")}
restore={snapshot.capture?.restore_ready
? { available: restorePoints.some((r) => r.usable && r.source_orbit_id === snapshot.orbit_id), onOpen: () => openConsole("reconstitute", snapshot.id) }
: undefined} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane>
)}
</AnimatePresence>
<SpringPane active={mode === "reconstitute"}>
{restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard
key={restoreTarget.id ?? "manual"}
snapshots={snaps.data ?? []} selected={restoreTarget.id} scopedExport={!!actor}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy}
/>
) : (
<QueryGate query={snaps} empty={<EmptyState title="No snapshots to restore" body="Capture an orbit to create a recovery point." />}>
{() => null}
</QueryGate>
))}
{restoreSnapshot
? (
<RestoreWizard
key={restoreSnapshot.id}
snapshot={restoreSnapshot}
relations={restorePoints.filter((r) => r.source_orbit_id === restoreSnapshot.orbit_id)}
admin={caps.admin}
onBusyChange={setRestoreBusy}
/>
)
: restoreTarget && <EmptyState title="Snapshot unavailable" body="Pick a snapshot of an orbit to restore it." />}
</SpringPane>
</PanelBoundary>
</HUDPanel>

View File

@@ -5,6 +5,8 @@ export type Snapshot = {
orbit_name: string;
size_bytes: number;
capture?: { job_id: string; application_id: string; engine: "postgres" | "mysql"; format: string; restore_ready: boolean } | null;
/** `safety` is the copy a restore took of its target before overwriting it; it is not a backup of an orbit. */
kind?: "capture" | "safety";
};
export type BackupSource = "filesystem" | "database";
@@ -129,7 +131,7 @@ export const grantRelationAccess = (id: string, grant: { principal_type: "user"
export const revokeRelationAccess = (id: string, grant: string) => api<void>(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" });
export type RefreshRelation = {
id: string; version: number; source_name: string; source_environment: Environment | null;
id: string; version: number; source_orbit_id: string; source_name: string; source_environment: Environment | null;
target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null;
};
export type RefreshRun = {
@@ -140,13 +142,16 @@ export type RefreshRun = {
};
export const fetchRefreshRelations = () => api<RefreshRelation[]>("/api/v1/refresh-relations");
export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs");
export const startRefresh = (relation: RefreshRelation, idempotency_key: string) =>
/** Restore `snapshot_id` onto the relation's target (or, without one, capture first and restore that). */
export const startRefresh = (relation: RefreshRelation, idempotency_key: string, snapshot_id?: string) =>
api<RefreshRun>("/api/v1/refresh-runs", json("POST", {
relation_id: relation.id,
// exactly what the person was shown, so a relation changed in the meantime is refused
confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`,
idempotency_key,
...(snapshot_id ? { snapshot_id } : {}),
}));
export const fetchRefreshRun = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`);
export const cancelRefresh = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`, { method: "DELETE" });
export type Look = "window" | "radar";
@@ -246,7 +251,9 @@ export async function fetchHealth(): Promise<string> {
}
export async function fetchSnapshots(): Promise<Snapshot[]> {
return api("/api/v1/snapshots");
const all = await api<Snapshot[]>("/api/v1/snapshots");
// Safety copies are for rolling a target back, never something to browse or restore from here.
return Array.isArray(all) ? all.filter((snapshot) => snapshot.kind !== "safety") : all;
}
export async function fetchOrbits(): Promise<Orbit[]> {
@@ -278,30 +285,6 @@ export async function runOrbit(id: string): Promise<string | null> {
return response.headers.get("X-Tessera-Snapshot-Id");
}
export async function startReconstitute(
snapshotId: string,
target: string,
): Promise<{
session_id: string;
session: { seconds_remaining: number; state: string };
}> {
return api("/api/v1/reconstitute", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ snapshot_id: snapshotId, target_path: target }),
});
}
export async function abortReconstitute(sessionId: string): Promise<void> {
await api(`/api/v1/reconstitute/${sessionId}`, { method: "DELETE" });
}
export async function pollReconstitute(sessionId: string) {
const response = await fetch(`/api/v1/reconstitute/${sessionId}`);
if (response.status === 404) return { state: "unavailable", seconds_remaining: 0 };
if (!response.ok) throw new Error("Could not read restore status");
return response.json() as Promise<{ state: string; seconds_remaining: number }>;
}
export type CaptureProfile = {

View File

@@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { uiSpring } from "../../lib/motion";
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "refresh" | "reconstitute" | "snapshot";
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "reconstitute" | "snapshot";
export const hudItems = [
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
@@ -20,12 +20,6 @@ export const accessItem: HUDItem = {
icon: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z M9.5 12l2 2 3.5-4",
};
/** Start a refresh of a staging database from its production source. */
export const refreshItem: HUDItem = {
id: "refresh", label: "Refresh",
icon: "M20 12a8 8 0 1 1-2.3-5.6 M20 4v4.5h-4.5",
};
/** Only for administrators: which source may overwrite which target. */
export const relationsItem: HUDItem = {
id: "relations", label: "Relations",

View File

@@ -1,203 +0,0 @@
import { useEffect, useState } from "react";
import { motion } from "motion/react";
import type { Snapshot } from "../../api";
import { DatabaseRestore } from "./DatabaseRestore";
import { formatBytes, formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
import { TelemetryPanel } from "../ui/Telemetry";
import { Segmented } from "../ui/Segmented";
import { Select } from "../ui/Select";
const GRACE = 12;
export function ReconstituteWizard({
snapshots,
selected,
scopedExport,
onStart,
onPoll,
onAbort,
onBusyChange,
}: {
snapshots: Snapshot[];
selected: string | null;
scopedExport?: boolean;
onStart: (snapId: string, target: string) => Promise<{
session_id: string;
session: { seconds_remaining: number; state: string };
}>;
onPoll: (id: string) => Promise<{ state: string; seconds_remaining: number }>;
onAbort: (id: string) => Promise<void>;
onBusyChange: (busy: boolean) => void;
}) {
const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? "");
const [databaseMode, setDatabaseMode] = useState(true);
const [target, setTarget] = useState(scopedExport ? "restored.dump" : "./restore/out");
const [sessionId, setSessionId] = useState<string | null>(null);
const [remaining, setRemaining] = useState(GRACE);
const [state, setState] = useState("idle");
const [action, setAction] = useState<"starting" | "aborting">();
const [error, setError] = useState<string>();
const [reconnecting, setReconnecting] = useState(false);
const snap = snapshots.find((s) => s.id === snapId);
const managed = snap?.capture?.restore_ready ? snap.capture : undefined;
const inCountdown = state === "countdown" || state === "confirming";
const busy = !!action || inCountdown || state === "restoring";
useEffect(() => { onBusyChange(busy); }, [busy, onBusyChange]);
useEffect(() => {
if (!sessionId) return;
let cancelled = false;
let timer: number;
const poll = async () => {
try {
const s = await onPoll(sessionId);
if (cancelled) return;
setReconnecting(false);
setState(s.state);
setRemaining(s.seconds_remaining ?? 0);
if (["completed", "aborted", "failed", "unavailable"].includes(s.state)) {
setAction(undefined);
return;
}
} catch {
if (cancelled) return;
setReconnecting(true);
}
timer = window.setTimeout(poll, 400);
};
timer = window.setTimeout(poll, 400);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [sessionId, onPoll]);
const radius = 52;
const circumference = 2 * Math.PI * radius;
const progress = Math.max(0, Math.min(1, remaining / GRACE));
return (
<div className="restore-layout">
<div className="restore-top">
<p className="restore-lead">Choose a recovery point and a destination.</p>
{snap && (
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snap.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snap.taken_at)} · {formatBytes(snap.size_bytes)} · {snap.id.slice(0, 8)}</p>
</div>
</div>
)}
<label className="block text-sm">
<span className="field-label">Snapshot</span>
<Select
value={snapId}
onChange={(e) => { setSnapId(e.target.value); setDatabaseMode(true); }}
disabled={busy}
>
{snapshots.map((s) => (
<option key={s.id} value={s.id}>
{s.orbit_name} · {formatWhen(s.taken_at)} · {formatBytes(s.size_bytes)}
</option>
))}
</Select>
</label>
{managed && (
<div>
<p className="field-label mb-1.5">Destination</p>
<Segmented label="Recovery destination" value={databaseMode ? "database" : "file"} disabled={busy}
onChange={(value) => setDatabaseMode(value === "database")}
options={[{ value: "database", label: "Restore to database" }, { value: "file", label: "Export file on hub" }]} />
</div>
)}
</div>
{managed && databaseMode ? (
<DatabaseRestore key={snapId} snapshot={snapId} application={managed.application_id} applicationName={snap?.orbit_name} engine={managed.engine} />
) : <>
<div className="restore-fields">
<label className="block text-sm">
<span className="field-label">{scopedExport ? "Export filename on hub" : "Export file path on hub"}</span>
<input className="field field-mono" value={target} onChange={(e) => setTarget(e.target.value)} disabled={busy} />
</label>
<Hint>{scopedExport ? "The hub writes to its exports directory after the countdown." : "The hub writes after the countdown. An existing file at the destination may be overwritten."}</Hint>
<div className="flex gap-2.5">
<Button
variant="danger"
className="flex-1"
disabled={!sessionId || !inCountdown || !!action}
onClick={async () => {
if (!sessionId) return;
setAction("aborting");
setError(undefined);
try {
await onAbort(sessionId);
} catch {
setAction(undefined);
setError("Could not cancel the file export. Check the current session status.");
}
}}
>
Abort
</Button>
<Button
variant="primary"
className="flex-1"
disabled={!snap || !target.trim() || busy}
onClick={async () => {
setAction("starting");
setError(undefined);
try {
const res = await onStart(snapId, target);
setSessionId(res.session_id);
setState(res.session.state);
setRemaining(res.session.seconds_remaining);
} catch {
setError("Could not confirm that the hub started writing to the destination.");
} finally {
setAction(undefined);
}
}}
>
Begin file export
</Button>
</div>
{error && <p role="alert" className="text-orbit-red text-sm">{error}</p>}
</div>
<aside className="restore-status">
<p className="restore-status-label">Countdown</p>
{inCountdown ? (
<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 - progress) }} />
</svg>
<span className="restore-ring-text"><b>{remaining}</b><i>seconds</i></span>
</div>
<p className="restore-count-note">Reconstituting in {remaining}s.<br />Abort restores nothing.</p>
</motion.div>
) : <p className="restore-idle">No export is running. Begin an export to start the countdown.</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the export session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Exporting snapshot…</p>}
{state === "unavailable" && (
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this export session. Check the destination before retrying.</p>
)}
{state === "completed" && <p className="text-orbit-green text-sm">File export complete.</p>}
{state === "aborted" && <p className="text-star-300 text-sm">File export cancelled.</p>}
{state === "failed" && <p className="text-orbit-red text-sm">File export failed. Check telemetry.</p>}
{sessionId && (
<TelemetryPanel label="Session">
{JSON.stringify({ sessionId, state, remaining }, null, 2)}
</TelemetryPanel>
)}
</aside>
</>}
</div>
);
}

View File

@@ -1,184 +0,0 @@
import { useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
cancelRefresh, fetchRefreshRelations, fetchRefreshRuns, refusalReason, startRefresh,
type RefreshRelation, type RefreshRun,
} from "../../api";
import { Button } from "../ui/Button";
const ACTIVE = new Set(["capturing", "restoring"]);
const START_REFUSALS: Record<string, string> = {
run_active: "A refresh of this database is already running.",
stale_confirmation: "This relation was changed while you were looking at it. Reload and check it again.",
source_unavailable: "The source cannot take a backup request right now (its Outpost is not available).",
relation_unusable: "This refresh cannot be used right now. Ask an administrator.",
too_many_runs: "Too many refreshes are running at once. Try again in a few minutes.",
key_reused: "That request was already used. Reload and try again.",
};
const BLOCKED: Record<string, string> = {
access_revoked: "your access to this refresh was removed",
user_disabled: "your account was disabled",
relation_ended: "the relation was ended or replaced",
relation_unusable: "the relation can no longer be used",
target_matches_a_production_source: "the target looks like a production database",
target_rejected: "the target did not match the backup",
snapshot_not_restorable: "the backup could not be restored",
};
const CAPTURE_STEPS: Record<string, string> = {
queued: "waiting for the Outpost", claimed: "the Outpost picked it up", dumping: "reading the database",
uploading: "sending the backup", completed: "done",
};
const RESTORE_STEPS: Record<string, string> = {
queued: "waiting for the Outpost", claimed: "the Outpost picked it up", checking: "checking the backup and the target",
safety: "saving a safety copy of the target", ready: "ready to overwrite", applying: "overwriting the target",
completed: "done",
};
function when(seconds: number | null) {
return seconds ? new Date(seconds * 1000).toLocaleString() : "";
}
/** What happened, in words, and what it means for the target database. */
export function describe(run: RefreshRun): { tone: "busy" | "good" | "bad" | "plain"; title: string; detail: string } {
const target = run.target_name;
switch (run.status) {
case "capturing":
return { tone: "busy", title: "Taking a fresh backup", detail: `Reading ${run.source_name}: ${CAPTURE_STEPS[run.capture_phase ?? "queued"] ?? run.capture_phase}. ${target} is not touched yet.` };
case "restoring": {
const phase = run.restore_phase ?? "queued";
const overwriting = phase === "applying";
return { tone: "busy", title: overwriting ? `Overwriting ${target}` : "Preparing the restore",
detail: `${RESTORE_STEPS[phase] ?? phase}.${overwriting ? " This can no longer be cancelled." : ` ${target} has not been changed yet.`}` };
}
case "completed":
return { tone: "good", title: `${target} was refreshed`, detail: run.snapshot_taken_at ? `It now holds the data of ${run.source_name} as of ${when(run.snapshot_taken_at)}.` : "" };
case "capture_failed":
return { tone: "bad", title: "The backup failed", detail: `${target} was not changed. Try again, or ask an administrator if it keeps failing.` };
case "restore_failed":
return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` };
case "recovery_required":
return { tone: "bad", title: "The restore was interrupted", detail: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.` };
case "blocked":
return { tone: "bad", title: "The refresh was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` };
case "expired":
return { tone: "bad", title: "The refresh took too long to start", detail: `${target} was not changed. Start it again.` };
case "cancelled":
return { tone: "plain", title: "The refresh was cancelled", detail: `${target} was not overwritten.` };
case "reconciled":
return { tone: "plain", title: "An administrator recovered the target", detail: "" };
default:
return { tone: "plain", title: run.status, detail: "" };
}
}
/** Start a refresh of a staging database and follow it. Everyone sees only what their grants allow. */
export function RefreshView() {
const qc = useQueryClient();
const relations = useQuery({ queryKey: ["refresh-relations"], queryFn: fetchRefreshRelations, refetchInterval: 15_000, retry: false });
const runs = useQuery({
queryKey: ["refresh-runs"], queryFn: fetchRefreshRuns, retry: false,
refetchInterval: (query) => (Array.isArray(query.state.data) && query.state.data.some((r) => ACTIVE.has(r.status)) ? 2_000 : 15_000),
});
const list = Array.isArray(relations.data) ? relations.data : [];
const history = Array.isArray(runs.data) ? runs.data : [];
if (relations.isPending) return <p role="status" className="p-6 text-star-300">Loading…</p>;
if (relations.isError) {
return <p role="alert" className="p-6 text-star-300">You have not been given a database to refresh, or this hub does not support it.</p>;
}
return (
<div className="space-y-8 p-6">
<p className="text-sm text-star-300">
A refresh takes a new backup of the source and replaces the contents of its staging database with it. The source is only read.
</p>
{list.length === 0 && <p className="text-star-300">Nothing to refresh yet.</p>}
{list.map((relation) => (
<RelationCard key={relation.id} relation={relation} runs={history.filter((r) => r.relation_id === relation.id)}
onChanged={() => void qc.invalidateQueries({ queryKey: ["refresh-runs"] })} />
))}
</div>
);
}
function RelationCard({ relation, runs, onChanged }: { relation: RefreshRelation; runs: RefreshRun[]; onChanged: () => void }) {
const latest = runs[0];
const running = !!latest && ACTIVE.has(latest.status);
const [confirming, setConfirming] = useState(false);
const [understood, setUnderstood] = useState(false);
// One key per attempt: a double click or a retry after a network error starts a single run.
const key = useRef<string>(crypto.randomUUID());
const start = useMutation({
mutationFn: () => startRefresh(relation, key.current),
onSuccess: () => { setConfirming(false); setUnderstood(false); key.current = crypto.randomUUID(); onChanged(); },
});
const cancel = useMutation({ mutationFn: (id: string) => cancelRefresh(id), onSuccess: onChanged });
const seen = latest ? describe(latest) : undefined;
const overwriting = running && latest?.restore_phase === "applying";
const refusal = start.isError ? START_REFUSALS[refusalReason(start.error) ?? ""] ?? "The refresh could not be started." : undefined;
return (
<section className="rounded-xl border border-space-700 p-5" aria-label={`${relation.source_name} to ${relation.target_name}`}>
<p className="text-xs uppercase tracking-wide text-star-300">Application: {relation.source_name}</p>
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-lg font-semibold text-star-100">
{relation.target_name}
<span className="ml-2 text-sm font-normal text-star-300">({relation.target_environment ?? "?"}) is refreshed from {relation.source_name} ({relation.source_environment ?? "?"})</span>
</h3>
{!relation.usable && <p className="text-sm text-orbit-red">Not available right now. Ask an administrator.</p>}
</div>
{seen && (
<div className="mt-4" role="status" aria-live="polite">
<p className={seen.tone === "bad" ? "font-medium text-orbit-red" : "font-medium text-star-100"}>{seen.title}</p>
{seen.detail && <p className="mt-1 text-sm text-star-300">{seen.detail}</p>}
{running && (
<progress className="mt-3 block h-1 w-full" aria-label="Refresh progress"
value={latest.status === "capturing" ? 1 : latest.restore_phase === "applying" ? 3 : 2} max={4} />
)}
</div>
)}
<div className="mt-4 flex flex-wrap items-center gap-3">
{!confirming && !running && (
<Button variant="primary" disabled={!relation.usable} onClick={() => setConfirming(true)}>Refresh {relation.target_name}</Button>
)}
{running && latest && (
<Button disabled={cancel.isPending || overwriting} onClick={() => cancel.mutate(latest.id)}>
{overwriting ? "Overwriting: cannot cancel" : "Cancel"}
</Button>
)}
</div>
{confirming && !running && (
<form className="mt-4 space-y-3 rounded-lg border border-space-700 p-4" onSubmit={(e) => { e.preventDefault(); if (understood) start.mutate(); }}>
<p className="text-sm text-star-100">
This replaces <strong>everything</strong> in <strong>{relation.target_name}</strong> with a fresh copy of <strong>{relation.source_name}</strong>.
Anything that exists only in {relation.target_name} is lost. {relation.source_name} is only read.
</p>
<label className="flex items-start gap-2 text-sm text-star-300">
<input type="checkbox" checked={understood} onChange={(e) => setUnderstood(e.target.checked)} className="mt-1" />
<span>I understand that {relation.target_name} will be overwritten.</span>
</label>
<div className="flex gap-2">
<Button type="button" onClick={() => { setConfirming(false); setUnderstood(false); }}>Not now</Button>
<Button type="submit" variant="danger" disabled={!understood || start.isPending}>{start.isPending ? "Starting…" : `Overwrite ${relation.target_name}`}</Button>
</div>
</form>
)}
{refusal && <p role="alert" className="mt-3 text-sm text-orbit-red">{refusal}</p>}
{cancel.isError && <p role="alert" className="mt-3 text-sm text-orbit-red">It could not be cancelled: it has already started overwriting.</p>}
{runs.length > 1 && (
<details className="mt-4 text-sm text-star-300">
<summary className="cursor-pointer">Earlier refreshes</summary>
<ul className="mt-2 space-y-1">
{runs.slice(1, 8).map((run) => <li key={run.id}>{when(run.created_at)}: {describe(run).title}</li>)}
</ul>
</details>
)}
</section>
);
}

View File

@@ -0,0 +1,196 @@
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>
);
}

View File

@@ -15,7 +15,7 @@ function signedBytes(delta: number) {
export function SnapshotSheet({
snap,
siblings = [],
onReconstitute,
restore,
onDeleted,
canManage = false,
canDownload = false,
@@ -23,7 +23,8 @@ export function SnapshotSheet({
snap: Snapshot;
/** Every snapshot of the same orbit, newest first, including this one. */
siblings?: Snapshot[];
onReconstitute: () => void;
/** Restore this snapshot onto a staging or development database. Absent when it is not a database backup. */
restore?: { available: boolean; onOpen: () => void };
onDeleted: () => void;
/** Administrators only: restore and delete. */
canManage?: boolean;
@@ -90,7 +91,7 @@ export function SnapshotSheet({
</div>
<div>
<dt>Recovery</dt>
<dd>{database ? "Database ready" : "File export"}</dd>
<dd>{database ? "Database ready" : "Download only"}</dd>
{snap.capture && <dd className="sheet-sub">{snap.capture.engine} · {snap.capture.format}</dd>}
</div>
</dl>
@@ -104,10 +105,20 @@ export function SnapshotSheet({
</div>
<div className="sheet-actions">
{canManage && <Button variant="primary" className="sheet-primary" onClick={onReconstitute}>
{database ? "Database recovery options" : "Export file on hub"}
<span aria-hidden="true">→</span>
</Button>}
{restore && (restore.available ? (
<Button variant="primary" className="sheet-primary" onClick={restore.onOpen}>
Restore
<span aria-hidden="true">→</span>
</Button>
) : (
<>
<Button className="sheet-primary" disabled>
No restore point
<span aria-hidden="true">⊘</span>
</Button>
<p className="mt-1 text-xs text-star-300">An administrator has not connected a staging or development database to this orbit yet.</p>
</>
))}
{canDownload && <a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link">
Download snapshot
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

View File

@@ -1201,3 +1201,21 @@ button.act-row[data-group="needs"]:hover { background: #20161a; }
.big-screen .galaxy-frame { touch-action: none; }
.galaxy-frame[data-turning] { cursor: grabbing; }
.galaxy-frame[data-turning] :is(.scene-labels, .snapshot-marker, .focus-leader, .focus-leader-big) { opacity: 0; }
/* Restore progress: four steps and the outcome, in the modal's right column. */
.restore-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 14px; }
.restore-steps li { display: flex; align-items: center; gap: 12px; font-size: 14px; color: var(--quiet); }
.restore-steps li span { width: 22px; height: 22px; border-radius: 50%; border: 1.5px solid var(--line); display: inline-flex; align-items: center; justify-content: center; font: 600 11px/1 var(--font-mono); flex: none; }
.restore-steps li.done { color: var(--color-star-200, #c4c8d0); }
.restore-steps li.done span { background: var(--color-orbit-green, #8fd0b0); border-color: var(--color-orbit-green, #8fd0b0); color: #0b0d12; }
.restore-steps li.now { color: var(--color-orbit-amber); font-weight: 600; }
.restore-steps li.now span { border-color: var(--color-orbit-amber); color: var(--color-orbit-amber); }
.restore-steps li.bad { color: var(--color-orbit-red); font-weight: 600; }
.restore-steps li.bad span { border-color: var(--color-orbit-red); color: var(--color-orbit-red); }
.restore-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 14px; border: 1px solid var(--line); border-radius: 12px; }
.restore-outcome p { margin: 0; font-size: 13.5px; line-height: 1.5; }
.restore-outcome p:first-child { font-weight: 600; font-size: 14.5px; }
.restore-outcome.good { border-color: #2d5a45; }
.restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); }
.restore-outcome.bad { border-color: #6b2f26; }
.restore-outcome.bad p:first-child { color: var(--color-orbit-red); }

95
web/src/lib/restoreRun.ts Normal file
View File

@@ -0,0 +1,95 @@
/** How a restore run is shown: which of four steps it is at, and what the person is told. Pure, so it is testable. */
export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const;
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null };
const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]);
/** The step a restore job's phase belongs to. */
function stageOfPhase(phase: string | null): number {
switch (phase) {
case "safety": case "ready": case "safety_failed": return 1;
case "applying": case "apply_failed": return 2;
default: return 0; // queued, claimed, checking, invalid_payload, wrong_target, or no job yet
}
}
/** The run has reached a state it will not leave (as opposed to still capturing or restoring). */
export function isFinal(run: { status: string }): boolean {
return run.status !== "capturing" && run.status !== "restoring";
}
/** Where the run is: the index of the step in progress (4 once everything is done) and whether it is still going. */
export function progressOf(run: RunLike): { index: number; state: "running" | "done" | "failed" | "cancelled" } {
if (run.status === "completed" || run.status === "reconciled") return { index: 4, state: "done" };
if (run.status === "cancelled") return { index: stageOfPhase(run.restore_phase), state: "cancelled" };
if (STOPPED.has(run.status)) {
// An interrupted restore stopped while overwriting, whatever phase the job last showed.
const index = run.status === "recovery_required" ? 2 : stageOfPhase(run.restore_phase);
return { index, state: "failed" };
}
// The restore job finishes a moment before the run itself is marked completed.
if (run.restore_phase === "completed") return { index: 4, state: "done" };
return { index: stageOfPhase(run.restore_phase), state: "running" };
}
const BLOCKED: Record<string, string> = {
access_revoked: "your access to this restore was removed",
user_disabled: "your account was disabled",
relation_ended: "the restore point was removed or replaced",
relation_unusable: "the restore point can no longer be used",
target_matches_a_production_source: "the target looks like a production database",
target_rejected: "the target did not match the backup",
snapshot_not_restorable: "the backup could not be restored",
};
export type Outcome = { tone: "busy" | "good" | "bad" | "plain"; title: string; detail: string };
/** What happened, in words, and what it means for the target. Never quotes the database. */
export function outcomeOf(
run: RunLike,
names: { target: string; orbit?: string; when?: string },
): Outcome {
const { target } = names;
switch (run.status) {
case "completed":
case "reconciled":
return {
tone: "good",
title: `${target} was restored`,
detail: names.orbit && names.when
? `${target} now holds ${names.orbit} as of ${names.when}. A safety copy of what it held before was kept.`
: "A safety copy of what it held before was kept.",
};
case "restore_failed":
return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` };
case "recovery_required":
return { tone: "bad", title: "The restore was interrupted", detail: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.` };
case "blocked":
return { tone: "bad", title: "The restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` };
case "expired":
return { tone: "bad", title: "The restore took too long to start", detail: `${target} was not changed. Start it again.` };
case "capture_failed":
return { tone: "bad", title: "The restore could not start", detail: `${target} was not changed.` };
case "cancelled":
return { tone: "plain", title: "The restore was cancelled", detail: `${target} was not overwritten.` };
default:
return { tone: "busy", title: "Restoring", detail: "" };
}
}
type RelationLike = { id: string; target_environment: string | null; target_name: string };
const environmentName = (value: string | null) => (value ? value[0].toUpperCase() + value.slice(1) : null);
/** Names for the restore points of one orbit: the environment, plus the target's name only when two would read the same. */
export function relationLabels<T extends RelationLike>(relations: T[]): (T & { label: string })[] {
const counts = new Map<string, number>();
for (const r of relations) counts.set(environmentName(r.target_environment) ?? r.target_name, (counts.get(environmentName(r.target_environment) ?? r.target_name) ?? 0) + 1);
return relations.map((r) => {
const env = environmentName(r.target_environment);
const base = env ?? r.target_name;
return { ...r, label: env && (counts.get(base) ?? 0) > 1 ? `${env} · ${r.target_name}` : base };
});
}