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"; const KIND_WORDS: Record = { 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 {check.problem}; return ( 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)" : ""}. ); } /** * 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(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(null); const [checks, setChecks] = useState>({}); const [draft, setDraft] = useState(null); const fileRef = useRef(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(what: string, work: () => Promise, 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
{error ? : }
; 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 (

Database backups

e.target.files?.[0] && void upload(e.target.files[0])} />

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 {data.folder}. {" "} A backup does not contain CREDENTIALS_ENCRYPTION_KEY (from .env), 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 BACKUP.md.

{failing && (
The last backup didn't work (): {data.lastAttempt!.error}
)} {data.staged && (
A restore is waiting. The database becomes {data.staged.from} the next time Homelab Manager starts — restart it to finish (with the standard Docker setup: docker compose restart homelab-manager). The database in use now is kept as a backup.
)} {data.lastRestore && (
The database was restored from {data.lastRestore.from} {data.lastRestore.by ? ` (staged by ${data.lastRestore.by})` : ""}. {data.lastRestore.keptAs && ( <> {" "} What was in use before is kept as {data.lastRestore.keptAs}. )}{" "} Servers whose agents were installed after that backup need their token rotated (Servers → Manage servers).
)}
Newest backup
{newest ? <> ({size(newest.sizeBytes)}) : none yet}
Next one
{data.nextRun ? formatDateTime(new Date(data.nextRun)) : daily backups are off}
Kept
{data.snapshots.length} {data.snapshots.length === 1 ? "file" : "files"}
{ e.preventDefault(); void run("settings", () => api.dbBackups.saveSettings(draft), () => "Saved."); }} >
setDraft({ ...draft, time: e.target.value })} />
setDraft({ ...draft, keep: Number(e.target.value) })} />
The time is in the notification time zone (Settings → Notifications). An alert is raised if the newest backup gets more than two days old.
{data.snapshots.length === 0 ? (
No backups yet. Press Back up now to make the first.
) : (
{data.snapshots.map((s) => ( ))}
Backup Kind Taken Size Actions
{s.name} {checks[s.name] &&
}
{KIND_WORDS[s.kind].label} {size(s.sizeBytes)}
Download
)}
); }