Files
Homelab-manager/web/src/components/DatabaseBackups.tsx
T
bobbanandClaude Sonnet 5.5 645816d5a8 Add a Swedish interface with a per-person language switch
A small translation system (the English text is its own key, so anything
without a Swedish entry stays English) and a Language switch in the user menu,
saved on the account (users.language) and following the browser when no choice
has been made. Swedish covers the menu, shared parts (search, tables, dialogs,
relative times), the sign-in page and the everyday pages: Dashboard, Alerts,
Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and the
display settings. Server-written messages stay English for now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:49:49 +01:00

269 lines
14 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from "react";
import { api, type DbBackupSettings, type DbBackupsOverview, type DbSnapshot, type DbSnapshotCheck } from "../api/client";
import { confirmDialog } from "../utils/dialogs";
import { formatDateTime } from "../utils/date";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import { BlockSkeleton } from "./Skeleton";
import { ErrorNotice } from "./Notice";
import TimeAgo from "./TimeAgo";
import { t } from "../i18n";
const KIND_WORDS: Record<DbSnapshot["kind"], { label: string; badge: string; hint: string }> = {
scheduled: { label: "daily", badge: "bg-blue-lt text-blue", hint: "Taken by the daily schedule" },
manual: { label: "made by hand", badge: "bg-secondary-lt text-secondary", hint: "Taken with Back up now" },
"pre-restore": { label: "before a restore", badge: "bg-yellow-lt text-yellow", hint: "The database that was in use when a restore took effect — restore this to undo it" },
uploaded: { label: "uploaded", badge: "bg-cyan-lt text-cyan", hint: "A file somebody uploaded" },
};
const size = (bytes: number) => (bytes < 1024 * 1024 ? `${Math.max(1, Math.round(bytes / 1024))} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
function CheckResult({ check }: { check: DbSnapshotCheck }) {
if (!check.ok) return <span className="text-danger">{check.problem}</span>;
return (
<span className="text-success">
Sound (SQLite says {check.integrity}) — {check.counts ? `${check.counts.users} users, ${check.counts.servers} servers, ${check.counts.integrations} integrations` : "readable"}; schema {check.migrations} of {check.appMigrations}
{check.migrations !== null && check.migrations < check.appMigrations ? " (older: brought up to date when restored)" : ""}.
</span>
);
}
/**
* Backups of Homelab Manager's own database: when it was last backed up and when it next will be, a button to make one now, the ones that are
* kept (download, check, restore, delete), uploading one from somewhere else, and the daily schedule. A restore is staged here and takes
* effect when the app next starts.
*/
export default function DatabaseBackups() {
const [data, setData] = useState<DbBackupsOverview | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [checks, setChecks] = useState<Record<string, DbSnapshotCheck>>({});
const [draft, setDraft] = useState<DbBackupSettings | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
return api.dbBackups
.overview()
.then((d) => {
setData(d);
setDraft((before) => before ?? d.settings);
setError(null);
})
.catch((err) => setError(readableError(err)));
}, []);
useEffect(() => {
void load();
}, [load]);
async function run<T>(what: string, work: () => Promise<T>, success?: (r: T) => string) {
setBusy(what);
setError(null);
try {
const result = await work();
if (success) toast.success(success(result));
await load();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(null);
}
}
async function restore(s: DbSnapshot) {
const ok = await confirmDialog({
title: "Restore this backup?",
message: `The database becomes the one in ${s.name}, taken ${formatDateTime(new Date(s.at))}, the next time Homelab Manager starts. Anything changed since then — users, edits, the audit log — is replaced by what that backup has. The database in use now is kept as a "before a restore" backup, so this can be undone. Nothing changes until it is restarted.`,
confirmLabel: "Stage the restore",
danger: true,
});
if (!ok) return;
await run(`restore:${s.name}`, () => api.dbBackups.restore(s.name), () => "The restore is waiting for the next start.");
}
async function remove(s: DbSnapshot) {
if (!(await confirmDialog({ title: "Delete this backup?", message: `${s.name} is deleted for good.`, confirmLabel: "Delete", danger: true }))) return;
await run(`delete:${s.name}`, () => api.dbBackups.remove(s.name), () => "Deleted.");
}
async function upload(file: File) {
await run("upload", () => api.dbBackups.upload(file), (r) => `Kept ${r.snapshot.name}. It can be restored from the list.`);
if (fileRef.current) fileRef.current.value = "";
}
if (!data || !draft) return <div className="card mb-3"><div className="card-body">{error ? <ErrorNotice error={error} /> : <BlockSkeleton lines={4} />}</div></div>;
const newest = data.snapshots.find((s) => s.kind === "scheduled" || s.kind === "manual");
const failing = data.lastAttempt && !data.lastAttempt.ok;
const dirty = draft.enabled !== data.settings.enabled || draft.time !== data.settings.time || draft.keep !== data.settings.keep;
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Database backups</h3>
<div className="card-actions btn-list">
<input ref={fileRef} type="file" accept=".sqlite,.db,application/octet-stream" className="d-none" onChange={(e) => e.target.files?.[0] && void upload(e.target.files[0])} />
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy !== null} onClick={() => fileRef.current?.click()}>
{busy === "upload" ? "Uploading…" : "Upload a backup…"}
</button>
<button type="button" className="btn btn-sm btn-primary" disabled={busy !== null} onClick={() => void run("create", () => api.dbBackups.create(), (r) => `Backed up: ${r.snapshot.name}`)}>
{busy === "create" ? "Backing up…" : "Back up now"}
</button>
</div>
</div>
<div className="card-body">
<p className="text-secondary">
Everything Homelab Manager knows is in one database file. A copy is taken every day, checked as it is made, and the newest few are kept in <code>{data.folder}</code>.
{" "}
<strong>A backup does not contain <code>CREDENTIALS_ENCRYPTION_KEY</code></strong> (from <code>.env</code>), which decrypts the credentials stored in it — keep that somewhere else — and it is still on this machine until you copy it away (Download, or copy the folder). The steps are in <code>BACKUP.md</code>.
</p>
<ErrorNotice error={error} />
{failing && (
<div className="alert alert-danger">
<div>
<strong>The last backup didn't work</strong> (<TimeAgo value={data.lastAttempt!.at} />): {data.lastAttempt!.error}
</div>
</div>
)}
{data.staged && (
<div className="alert alert-warning">
<div className="d-flex flex-wrap align-items-center gap-2 w-100">
<div className="flex-fill">
<strong>A restore is waiting.</strong> The database becomes <code>{data.staged.from}</code> the next time Homelab Manager starts — restart it to finish (with the standard Docker setup: <code>docker compose restart homelab-manager</code>). The database in use now is kept as a backup.
</div>
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy !== null} onClick={() => void run("cancel", () => api.dbBackups.cancelRestore(), () => "The restore was cancelled.")}>
Cancel the restore
</button>
</div>
</div>
)}
{data.lastRestore && (
<div className="alert alert-success">
<div className="d-flex flex-wrap align-items-center gap-2 w-100">
<div className="flex-fill">
<strong>The database was restored</strong> from <code>{data.lastRestore.from}</code> <TimeAgo value={data.lastRestore.restoredAt} />
{data.lastRestore.by ? ` (staged by ${data.lastRestore.by})` : ""}.
{data.lastRestore.keptAs && (
<>
{" "}
What was in use before is kept as <code>{data.lastRestore.keptAs}</code>.
</>
)}{" "}
Servers whose agents were installed after that backup need their token rotated (Servers → Manage servers).
</div>
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => void run("dismiss", () => api.dbBackups.dismissRestoreResult())}>
{t("Dismiss")}
</button>
</div>
</div>
)}
<div className="row g-3 mb-3">
<div className="col-md-4">
<div className="text-secondary small">Newest backup</div>
<div>{newest ? <><TimeAgo value={newest.at} /> <span className="text-secondary">({size(newest.sizeBytes)})</span></> : <span className="text-warning">none yet</span>}</div>
</div>
<div className="col-md-4">
<div className="text-secondary small">Next one</div>
<div>{data.nextRun ? formatDateTime(new Date(data.nextRun)) : <span className="text-secondary">daily backups are off</span>}</div>
</div>
<div className="col-md-4">
<div className="text-secondary small">Kept</div>
<div>{data.snapshots.length} {data.snapshots.length === 1 ? "file" : "files"}</div>
</div>
</div>
<form
className="row g-2 align-items-end mb-3"
onSubmit={(e) => {
e.preventDefault();
void run("settings", () => api.dbBackups.saveSettings(draft), () => "Saved.");
}}
>
<div className="col-auto">
<label className="form-check form-switch mb-2">
<input className="form-check-input" type="checkbox" checked={draft.enabled} onChange={(e) => setDraft({ ...draft, enabled: e.target.checked })} />
<span className="form-check-label">Back up every day</span>
</label>
</div>
<div className="col-auto">
<label className="form-label small mb-1" htmlFor="db-backup-time">
At
</label>
<input id="db-backup-time" type="time" className="form-control form-control-sm" disabled={!draft.enabled} value={draft.time} onChange={(e) => setDraft({ ...draft, time: e.target.value })} />
</div>
<div className="col-auto">
<label className="form-label small mb-1" htmlFor="db-backup-keep">
Keep the newest
</label>
<input id="db-backup-keep" type="number" min={1} max={90} className="form-control form-control-sm" style={{ width: 90 }} disabled={!draft.enabled} value={draft.keep} onChange={(e) => setDraft({ ...draft, keep: Number(e.target.value) })} />
</div>
<div className="col-auto">
<button type="submit" className="btn btn-sm btn-outline-primary" disabled={!dirty || busy !== null}>
{t("Save")}
</button>
</div>
<div className="col-12 text-secondary small">The time is in the notification time zone (Settings → Notifications). An alert is raised if the newest backup gets more than two days old.</div>
</form>
{data.snapshots.length === 0 ? (
<div className="text-secondary">No backups yet. Press Back up now to make the first.</div>
) : (
<div className="table-responsive">
<table className="table table-sm table-vcenter mb-0">
<thead>
<tr>
<th>Backup</th>
<th>Kind</th>
<th>Taken</th>
<th>Size</th>
<th className="w-1">{t("Actions")}</th>
</tr>
</thead>
<tbody>
{data.snapshots.map((s) => (
<tr key={s.name}>
<td>
<code>{s.name}</code>
{checks[s.name] && <div className="small mt-1"><CheckResult check={checks[s.name]} /></div>}
</td>
<td>
<span className={`badge ${KIND_WORDS[s.kind].badge}`} title={KIND_WORDS[s.kind].hint}>
{KIND_WORDS[s.kind].label}
</span>
</td>
<td className="text-nowrap" title={formatDateTime(new Date(s.at))}>
<TimeAgo value={s.at} />
</td>
<td className="text-nowrap">{size(s.sizeBytes)}</td>
<td>
<div className="btn-list flex-nowrap">
<a className="btn btn-sm btn-outline-secondary" href={api.dbBackups.downloadUrl(s.name)} download>
Download
</a>
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy !== null} onClick={() => void run(`check:${s.name}`, () => api.dbBackups.check(s.name).then((r) => setChecks((c) => ({ ...c, [s.name]: r.check }))))}>
{busy === `check:${s.name}` ? "Checking…" : "Check"}
</button>
<button type="button" className="btn btn-sm btn-outline-warning" disabled={busy !== null || data.staged !== null} onClick={() => void restore(s)}>
Restore…
</button>
<button type="button" className="btn btn-sm btn-outline-danger" disabled={busy !== null} onClick={() => void remove(s)}>
{t("Delete")}
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}