mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
Merge branch 'feat/restore-background-job' into release/v1.39.1
This commit is contained in:
commit
934131ee3e
52 files changed
+5684
-2439
No files matched your search
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* What the backups console shows while a restore runs and after it ends.
|
||||
*
|
||||
* The restore runs as a background job; this is the only place an operator
|
||||
* learns how it is going. Pinned here:
|
||||
* 1. a running restore names its phase with the counts and draws a bar
|
||||
* only where the share is known, and says the account still shows its
|
||||
* current data;
|
||||
* 2. a failed restore says what went wrong and that nothing changed, except
|
||||
* for the one failure after the commit, where saying so would be false;
|
||||
* 3. a succeeded restore reports through the outcome module, so an empty
|
||||
* file restored to an empty account is not drawn as a tick;
|
||||
* 4. the panels shown are every active job and the newest finished one not
|
||||
* dismissed;
|
||||
* 5. the copy resolves in more than one locale.
|
||||
*
|
||||
* Mutation check: always print the "nothing was changed" line and case 2's
|
||||
* after-commit test goes red; render the bar in every phase and case 1's
|
||||
* clearing test goes red.
|
||||
*/
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import {
|
||||
RestoreJobStatus,
|
||||
visibleRestoreJobs,
|
||||
} from "@/components/admin/backup-restore-status";
|
||||
import type { BackupRestoreJobView } from "@/lib/jobs/backup-restore";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => "/admin/backups",
|
||||
}));
|
||||
|
||||
function job(overrides: Partial<BackupRestoreJobView>): BackupRestoreJobView {
|
||||
return {
|
||||
id: "job-1",
|
||||
userId: "user-1",
|
||||
username: "alex",
|
||||
backupId: "backup-1",
|
||||
restoreInstanceSettings: false,
|
||||
status: "running",
|
||||
phase: "measurements",
|
||||
progress: {
|
||||
measurementsChecked: 1_250_000,
|
||||
measurementsTotal: 1_250_000,
|
||||
measurementsWritten: 400_000,
|
||||
sectionsDone: 0,
|
||||
sectionsTotal: 17,
|
||||
},
|
||||
result: null,
|
||||
failure: null,
|
||||
attempts: 1,
|
||||
createdAt: "2026-09-25T08:00:00.000Z",
|
||||
startedAt: "2026-09-25T08:00:01.000Z",
|
||||
completedAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function render(view: BackupRestoreJobView, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<RestoreJobStatus job={view} onDismiss={() => {}} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("RestoreJobStatus while it runs", () => {
|
||||
it("names the phase with its counts and draws the share done", () => {
|
||||
const html = render(job({}));
|
||||
expect(html).toContain("Restoring alex");
|
||||
expect(html).toContain("Writing readings: 400,000 of 1,250,000");
|
||||
expect(html).toContain('data-slot="restore-job-progress"');
|
||||
expect(html).toContain("keeps showing its current data");
|
||||
});
|
||||
|
||||
it("draws no bar where the share is not known", () => {
|
||||
const html = render(job({ phase: "clearing" }));
|
||||
expect(html).toContain("Clearing the account");
|
||||
expect(html).not.toContain('data-slot="restore-job-progress"');
|
||||
});
|
||||
|
||||
it("says a queued restore is waiting", () => {
|
||||
const html = render(job({ status: "queued", phase: null, progress: null }));
|
||||
expect(html).toContain("waiting to start");
|
||||
});
|
||||
|
||||
it("says when it was started again after a restart", () => {
|
||||
expect(render(job({ attempts: 2 }))).toContain("Started again");
|
||||
});
|
||||
});
|
||||
|
||||
describe("RestoreJobStatus once it failed", () => {
|
||||
it("says why, and that nothing changed", () => {
|
||||
const html = render(
|
||||
job({
|
||||
status: "failed",
|
||||
phase: null,
|
||||
failure: { code: "interrupted", message: "server text" },
|
||||
}),
|
||||
);
|
||||
expect(html).toContain("did not complete");
|
||||
expect(html).toContain("server restarted");
|
||||
expect(html).toContain("Nothing was changed");
|
||||
expect(html).toContain('data-failure-code="interrupted"');
|
||||
});
|
||||
|
||||
it("does not claim nothing changed when the data was restored", () => {
|
||||
const html = render(
|
||||
job({
|
||||
status: "failed",
|
||||
phase: null,
|
||||
failure: { code: "failed_after_commit", message: "server text" },
|
||||
}),
|
||||
);
|
||||
expect(html).toContain("The data was restored");
|
||||
expect(html).not.toContain("Nothing was changed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("RestoreJobStatus once it succeeded", () => {
|
||||
const result = {
|
||||
summary: { measurements: 1_250_000, medications: 3 },
|
||||
skipped: { links: 0, catalogueKeys: [] },
|
||||
cleared: { measurements: 10 },
|
||||
};
|
||||
|
||||
it("reports the count through the outcome module", () => {
|
||||
const html = render(
|
||||
job({
|
||||
status: "succeeded",
|
||||
phase: null,
|
||||
result,
|
||||
completedAt: "2026-09-25T08:02:00.000Z",
|
||||
}),
|
||||
);
|
||||
expect(html).toContain("Restore of alex finished");
|
||||
expect(html).toContain("1,250,003 records restored");
|
||||
expect(html).toContain('data-outcome="success"');
|
||||
});
|
||||
|
||||
it("does not draw a tick for a file that restored nothing", () => {
|
||||
const html = render(
|
||||
job({
|
||||
status: "succeeded",
|
||||
phase: null,
|
||||
result: { ...result, summary: {} },
|
||||
}),
|
||||
);
|
||||
expect(html).toContain('data-outcome="empty"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("visibleRestoreJobs", () => {
|
||||
it("shows every active job and the newest finished one not dismissed", () => {
|
||||
const jobs = [
|
||||
job({ id: "running", status: "running" }),
|
||||
job({ id: "newest-done", status: "succeeded" }),
|
||||
job({ id: "older-done", status: "failed" }),
|
||||
];
|
||||
expect(visibleRestoreJobs(jobs, new Set()).map((j) => j.id)).toEqual([
|
||||
"running",
|
||||
"newest-done",
|
||||
]);
|
||||
expect(
|
||||
visibleRestoreJobs(jobs, new Set(["newest-done"])).map((j) => j.id),
|
||||
).toEqual(["running", "older-done"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RestoreJobStatus in another language", () => {
|
||||
it("speaks German", () => {
|
||||
const html = render(job({}), "de");
|
||||
expect(html).toContain("alex wird wiederhergestellt");
|
||||
expect(html).toContain("Messwerte werden geschrieben");
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* The server refuses a file whose manifest claims a section the file does not
|
||||
* carry, before it deletes anything. That refusal reaches a person through the
|
||||
* `meta.errorCode` on the error envelope, and a bare "restore failed" toast
|
||||
* `code` on the restore job's failure, and a bare "restore failed" toast
|
||||
* would waste it: the operator on the other end is frequently holding the only
|
||||
* copy of an account, and the two facts they can act on — which section is
|
||||
* missing, and that nothing was changed — have to stay on screen.
|
||||
@@ -14,7 +14,7 @@
|
||||
* 3. no sections means no notice — a panel that appears after every restore
|
||||
* trains the operator to ignore it,
|
||||
* 4. the copy resolves in more than one locale,
|
||||
* 5. `missingSectionsOf` keys on the errorCode and not on the message text,
|
||||
* 5. `missingSectionsOf` keys on the failure code and not on the message text,
|
||||
* so rewording the server's prose cannot silently remove the panel.
|
||||
*
|
||||
* Mutation check: render a count instead of the list and case 1 goes red; drop
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
RestoreRefusalNotice,
|
||||
missingSectionsOf,
|
||||
} from "@/components/admin/backups-section";
|
||||
import { ApiError } from "@/lib/api/api-fetch";
|
||||
import type { MissingBackupSection } from "@/lib/export/restore-skips";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
@@ -79,33 +78,24 @@ describe("RestoreRefusalNotice", () => {
|
||||
});
|
||||
|
||||
describe("missingSectionsOf", () => {
|
||||
it("reads the sections off the refusal envelope", () => {
|
||||
const err = new ApiError("Backup is missing documents", 422, {
|
||||
errorCode: "backup.section.missing",
|
||||
sections: ["documents"],
|
||||
});
|
||||
|
||||
expect(missingSectionsOf(err)).toEqual(["documents"]);
|
||||
it("reads the sections off the failed job", () => {
|
||||
expect(
|
||||
missingSectionsOf({
|
||||
code: "backup.section.missing",
|
||||
sections: ["documents"],
|
||||
}),
|
||||
).toEqual(["documents"]);
|
||||
});
|
||||
|
||||
it("ignores an error whose message merely looks like one", () => {
|
||||
it("ignores a failure whose message merely looks like one", () => {
|
||||
// The message is prose the server may reword. Only the code counts.
|
||||
const err = new ApiError("Backup is missing documents", 422, {
|
||||
errorCode: "something_else",
|
||||
sections: ["documents"],
|
||||
});
|
||||
|
||||
expect(missingSectionsOf(err)).toEqual([]);
|
||||
expect(missingSectionsOf(new Error("Backup is missing documents"))).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(
|
||||
missingSectionsOf({ code: "something_else", sections: ["documents"] }),
|
||||
).toEqual([]);
|
||||
expect(missingSectionsOf(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it("survives a refusal with no section list", () => {
|
||||
const err = new ApiError("Refused", 422, {
|
||||
errorCode: "backup.section.missing",
|
||||
});
|
||||
|
||||
expect(missingSectionsOf(err)).toEqual([]);
|
||||
expect(missingSectionsOf({ code: "backup.section.missing" })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* `<RestoreJobStatus>` — one restore job as the backups console shows it.
|
||||
*
|
||||
* A restore runs on the server as a background job (see
|
||||
* `src/lib/jobs/backup-restore.ts`). The console polls
|
||||
* `GET /api/admin/backups/restores` while a job is queued or running and
|
||||
* renders each one here: what it is doing and how far it has got, then how it
|
||||
* ended. Because the list comes from the server, a reload during a restore
|
||||
* picks it up again where the page left it.
|
||||
*
|
||||
* Three rules, each for a way the synchronous restore misled an operator:
|
||||
*
|
||||
* - A running restore says the account still shows its current data. It
|
||||
* does: nothing the restore writes is visible until it commits.
|
||||
* - A failed restore says whether anything changed, and every failure but
|
||||
* one changed nothing. It also says the backup is kept, because the next
|
||||
* question is "do I have to upload it again", and the answer is no.
|
||||
* - Only the job's own row decides the outcome. A poll that fails on the
|
||||
* network is not a failed restore and is never shown as one.
|
||||
*/
|
||||
import { AlertTriangle, Loader2 } from "lucide-react";
|
||||
|
||||
import { WrittenOutcomeLine } from "@/components/outcome/written-outcome-line";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import type {
|
||||
BackupRestoreFailureCode,
|
||||
BackupRestoreJobView,
|
||||
} from "@/lib/jobs/backup-restore";
|
||||
|
||||
/** Whether a job still holds its account's one restore slot. */
|
||||
export function isActiveRestore(job: BackupRestoreJobView): boolean {
|
||||
return job.status === "queued" || job.status === "running";
|
||||
}
|
||||
|
||||
/**
|
||||
* The jobs worth a panel: every active one, and the newest finished one the
|
||||
* operator has not dismissed.
|
||||
*/
|
||||
export function visibleRestoreJobs(
|
||||
jobs: readonly BackupRestoreJobView[],
|
||||
dismissed: ReadonlySet<string>,
|
||||
): BackupRestoreJobView[] {
|
||||
const active = jobs.filter(isActiveRestore);
|
||||
const finished = jobs.find(
|
||||
(job) => !isActiveRestore(job) && !dismissed.has(job.id),
|
||||
);
|
||||
return finished ? [...active, finished] : active;
|
||||
}
|
||||
|
||||
/** Total records a succeeded restore wrote, from its summary counts. */
|
||||
function restoredCount(job: BackupRestoreJobView): number {
|
||||
let total = 0;
|
||||
for (const value of Object.values(job.result?.summary ?? {})) {
|
||||
if (typeof value === "number") total += value;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* The failure as a sentence in the operator's language.
|
||||
*
|
||||
* Literal `t()` calls, so `i18n-call-site-coverage.test.ts` sees every key.
|
||||
* The `never` at the foot makes the compiler say the chain is exhaustive: a
|
||||
* failure code added on the server without a sentence here stops the build.
|
||||
*/
|
||||
function failureText(
|
||||
code: BackupRestoreFailureCode,
|
||||
t: ReturnType<typeof useTranslations>["t"],
|
||||
): string {
|
||||
switch (code) {
|
||||
case "backup_not_found":
|
||||
return t("admin.section.backups.restoreFailureNotFound");
|
||||
case "backup_changed":
|
||||
return t("admin.section.backups.restoreFailureChanged");
|
||||
case "backup.payload.undecryptable":
|
||||
return t("admin.section.backups.restoreFailureUndecryptable");
|
||||
case "schema_invalid":
|
||||
return t("admin.section.backups.restoreFailureSchema");
|
||||
case "incompatible_schema_version":
|
||||
return t("admin.section.backups.restoreFailureVersion");
|
||||
case "owner_mismatch":
|
||||
return t("admin.section.backups.restoreFailureOwnerMismatch");
|
||||
case "owner_not_found":
|
||||
return t("admin.section.backups.restoreFailureOwnerMissing");
|
||||
case "backup.section.missing":
|
||||
return t("admin.section.backups.restoreFailureSectionMissing");
|
||||
case "document_ciphertext_missing":
|
||||
return t("admin.section.backups.restoreFailureDocument");
|
||||
case "time_budget":
|
||||
return t("admin.section.backups.restoreFailureTimeBudget");
|
||||
case "transaction_failed":
|
||||
return t("admin.section.backups.restoreFailureTransaction");
|
||||
case "interrupted":
|
||||
return t("admin.section.backups.restoreFailureInterrupted");
|
||||
case "not_started":
|
||||
return t("admin.section.backups.restoreFailureNotStarted");
|
||||
case "enqueue_failed":
|
||||
return t("admin.section.backups.restoreFailureEnqueue");
|
||||
case "failed_after_commit":
|
||||
return t("admin.section.backups.restoreFailureAfterCommit");
|
||||
case "unexpected":
|
||||
return t("admin.section.backups.restoreFailureUnexpected");
|
||||
default: {
|
||||
const unhandled: never = code;
|
||||
return unhandled;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What a running job is doing, and the share of it done when that is known. */
|
||||
function runningLine(
|
||||
job: BackupRestoreJobView,
|
||||
t: ReturnType<typeof useTranslations>["t"],
|
||||
fmt: ReturnType<typeof useFormatters>,
|
||||
): { text: string; percent: number | null } {
|
||||
const progress = job.progress;
|
||||
switch (job.phase) {
|
||||
case "clearing":
|
||||
return {
|
||||
text: t("admin.section.backups.restoreJobPhaseClearing"),
|
||||
percent: null,
|
||||
};
|
||||
case "measurements": {
|
||||
const total = progress?.measurementsTotal ?? 0;
|
||||
const done = progress?.measurementsWritten ?? 0;
|
||||
return {
|
||||
text: t("admin.section.backups.restoreJobPhaseMeasurements", {
|
||||
done: fmt.integer(done),
|
||||
total: fmt.integer(total),
|
||||
}),
|
||||
percent: total > 0 ? Math.min(100, (done / total) * 100) : null,
|
||||
};
|
||||
}
|
||||
case "sections": {
|
||||
const total = progress?.sectionsTotal ?? 0;
|
||||
const done = progress?.sectionsDone ?? 0;
|
||||
return {
|
||||
text: t("admin.section.backups.restoreJobPhaseSections", {
|
||||
done: fmt.integer(done),
|
||||
total: fmt.integer(total),
|
||||
}),
|
||||
percent: total > 0 ? Math.min(100, (done / total) * 100) : null,
|
||||
};
|
||||
}
|
||||
case "rebuilding":
|
||||
return {
|
||||
text: t("admin.section.backups.restoreJobPhaseRebuilding"),
|
||||
percent: null,
|
||||
};
|
||||
case "validating":
|
||||
default:
|
||||
return {
|
||||
text: t("admin.section.backups.restoreJobPhaseValidating", {
|
||||
checked: fmt.integer(progress?.measurementsChecked ?? 0),
|
||||
}),
|
||||
percent: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function RestoreJobStatus({
|
||||
job,
|
||||
onDismiss,
|
||||
}: {
|
||||
job: BackupRestoreJobView;
|
||||
onDismiss: () => void;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
const username = job.username ?? job.userId;
|
||||
|
||||
if (isActiveRestore(job)) {
|
||||
const line =
|
||||
job.status === "running"
|
||||
? runningLine(job, t, fmt)
|
||||
: {
|
||||
text: t("admin.section.backups.restoreJobQueuedNote"),
|
||||
percent: null,
|
||||
};
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-slot="restore-job-status"
|
||||
data-status={job.status}
|
||||
className="border-border bg-muted/30 space-y-2 rounded-md border px-3 py-2 text-sm"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<Loader2
|
||||
className="mt-0.5 size-4 shrink-0 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<p className="font-medium">
|
||||
{job.status === "queued"
|
||||
? t("admin.section.backups.restoreJobQueuedTitle", {
|
||||
username,
|
||||
})
|
||||
: t("admin.section.backups.restoreJobRunningTitle", {
|
||||
username,
|
||||
})}
|
||||
</p>
|
||||
<p>{line.text}</p>
|
||||
{line.percent !== null ? (
|
||||
<Progress
|
||||
value={line.percent}
|
||||
aria-label={line.text}
|
||||
data-slot="restore-job-progress"
|
||||
/>
|
||||
) : null}
|
||||
{job.attempts > 1 ? (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("admin.section.backups.restoreJobResumed")}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("admin.section.backups.restoreJobRunningNote")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (job.status === "succeeded") {
|
||||
const count = restoredCount(job);
|
||||
return (
|
||||
<div
|
||||
data-slot="restore-job-status"
|
||||
data-status={job.status}
|
||||
className="border-success/40 bg-success/10 rounded-md border px-3 py-2 text-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">
|
||||
{t("admin.section.backups.restoreJobSucceededTitle", {
|
||||
username,
|
||||
})}
|
||||
</p>
|
||||
{/* An empty file restores to an empty account: honest, and not a
|
||||
tick. The outcome module decides which it looks like. */}
|
||||
<WrittenOutcomeLine
|
||||
outcome={count > 0 ? "success" : "empty"}
|
||||
testId="restore-job-outcome"
|
||||
message={t(
|
||||
"admin.section.backups.restoreJobSucceededDescription",
|
||||
{
|
||||
count: fmt.integer(count),
|
||||
when: job.completedAt ? fmt.dateTime(job.completedAt) : "",
|
||||
},
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onDismiss}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t("common.dismiss")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const code = job.failure?.code ?? "unexpected";
|
||||
const changedNothing = code !== "failed_after_commit";
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
data-slot="restore-job-status"
|
||||
data-status={job.status}
|
||||
data-failure-code={code}
|
||||
className="border-destructive/40 bg-destructive/10 rounded-md border px-3 py-2 text-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle
|
||||
className="mt-0.5 size-4 shrink-0"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{t("admin.section.backups.restoreJobFailedTitle", { username })}
|
||||
</p>
|
||||
<p className="text-xs">{failureText(code, t)}</p>
|
||||
{changedNothing ? (
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{t("admin.section.backups.restoreJobFailedKept")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onDismiss}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t("common.dismiss")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -57,7 +57,13 @@ import type {
|
||||
RestoreSkipSummary,
|
||||
SkippedCatalogue,
|
||||
} from "@/lib/export/restore-skips";
|
||||
import type { BackupRestoreJobView } from "@/lib/jobs/backup-restore";
|
||||
import { getApiErrorMessage } from "./_shared";
|
||||
import {
|
||||
isActiveRestore,
|
||||
RestoreJobStatus,
|
||||
visibleRestoreJobs,
|
||||
} from "./backup-restore-status";
|
||||
import {
|
||||
ApiError,
|
||||
apiFetch,
|
||||
@@ -448,13 +454,41 @@ function missingSectionLabel(
|
||||
* carry, and that nothing was changed — have to survive long enough to be read.
|
||||
*/
|
||||
/**
|
||||
* The refused sections carried on an `ApiError`, or none.
|
||||
* The refused sections a failed restore job names, or none.
|
||||
*
|
||||
* Keyed on `meta.errorCode` and not on the message text: the message is prose
|
||||
* Keyed on the failure's `code` and not on its message: the message is prose
|
||||
* the server may reword, and matching on it would turn a copy edit into a
|
||||
* silent loss of the panel.
|
||||
*/
|
||||
|
||||
const DISMISSED_RESTORES_KEY = "healthlog.admin.backups.dismissedRestores";
|
||||
|
||||
/** Dismissed restore panels, from this browser. Empty when storage is off. */
|
||||
function readDismissedRestores(): string[] {
|
||||
try {
|
||||
if (typeof window === "undefined") return [];
|
||||
const raw = window.localStorage.getItem(DISMISSED_RESTORES_KEY);
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((id): id is string => typeof id === "string")
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeDismissedRestores(ids: string[]): void {
|
||||
try {
|
||||
// The list only ever shows a day of jobs; fifty ids is weeks of them.
|
||||
window.localStorage.setItem(
|
||||
DISMISSED_RESTORES_KEY,
|
||||
JSON.stringify(ids.slice(-50)),
|
||||
);
|
||||
} catch {
|
||||
// A private window: the panel comes back on reload, nothing else breaks.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The upload body for a backup file: the file itself when it is already
|
||||
* gzip, otherwise the file compressed in the browser. The server accepts
|
||||
@@ -468,10 +502,11 @@ async function uploadBody(file: File): Promise<Blob> {
|
||||
).blob();
|
||||
}
|
||||
|
||||
export function missingSectionsOf(err: unknown): MissingBackupSection[] {
|
||||
if (!(err instanceof ApiError)) return [];
|
||||
if (err.meta?.errorCode !== "backup.section.missing") return [];
|
||||
const sections = err.meta?.sections;
|
||||
export function missingSectionsOf(
|
||||
failure: { code: string; sections?: readonly unknown[] } | null | undefined,
|
||||
): MissingBackupSection[] {
|
||||
if (failure?.code !== "backup.section.missing") return [];
|
||||
const sections = failure.sections;
|
||||
if (!Array.isArray(sections)) return [];
|
||||
return sections.filter(
|
||||
(section): section is MissingBackupSection => typeof section === "string",
|
||||
@@ -820,9 +855,77 @@ export function BackupsSection() {
|
||||
MissingBackupSection[]
|
||||
>([]);
|
||||
|
||||
// Restore: typed-confirmation dialog. The mutation is keyed by row id
|
||||
// and used inline by `<RestoreRowDialog>` below — keeping the
|
||||
// mutation here lets the parent invalidate the list query on success.
|
||||
// A job this page watched while it ran, and has now seen finish. Only those
|
||||
// raise a toast and refresh the page's data: a job that had already finished
|
||||
// when the page opened is shown in its panel and nothing more. Read in the
|
||||
// poll's own callback, where each answer arrives, rather than in an effect.
|
||||
const watched = useRef<Map<string, string>>(new Map());
|
||||
function noticeFinishedRestores(jobs: readonly BackupRestoreJobView[]) {
|
||||
for (const job of jobs) {
|
||||
const before = watched.current.get(job.id);
|
||||
watched.current.set(job.id, job.status);
|
||||
if (before !== "queued" && before !== "running") continue;
|
||||
if (job.status === "succeeded") {
|
||||
setRefusedSections([]);
|
||||
const report = job.result?.skipped;
|
||||
if (report && report.links > 0) {
|
||||
setSkipped(report as RestoreSkipSummary);
|
||||
toast.warning(
|
||||
t("admin.section.backups.restoreSkippedToast", {
|
||||
links: String(report.links),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
setSkipped(null);
|
||||
toast.success(t("admin.section.backups.restoreSuccess"));
|
||||
}
|
||||
// Restore touches every personal-data table; nuke the broader cache
|
||||
// so dashboards / lists rebuild against the new state.
|
||||
void queryClient.invalidateQueries();
|
||||
} else if (job.status === "failed") {
|
||||
setRefusedSections(missingSectionsOf(job.failure));
|
||||
toast.error(t("admin.section.backups.restoreFailed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The restore jobs, read from the server so a reload during a restore finds
|
||||
// it again. Polled every two seconds while any is queued or running, and
|
||||
// not at all otherwise. A poll that fails keeps the last answer on screen:
|
||||
// a network blip is not a failed restore.
|
||||
const restores = useQuery({
|
||||
queryKey: queryKeys.adminBackupRestores(),
|
||||
queryFn: async () => {
|
||||
const data = await apiGet<{ jobs: BackupRestoreJobView[] }>(
|
||||
"/api/admin/backups/restores",
|
||||
);
|
||||
noticeFinishedRestores(data.jobs);
|
||||
return data;
|
||||
},
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.jobs.some(isActiveRestore) ? 2000 : false,
|
||||
});
|
||||
const restoreJobs = restores.data?.jobs ?? [];
|
||||
const activeOwners = new Set(
|
||||
restoreJobs.filter(isActiveRestore).map((job) => job.userId),
|
||||
);
|
||||
|
||||
// Finished restores the operator dismissed. Remembered in this browser only,
|
||||
// for convenience; the list itself forgets a job after a day.
|
||||
const [dismissedRestores, setDismissedRestores] = useState<Set<string>>(
|
||||
() => new Set(readDismissedRestores()),
|
||||
);
|
||||
function dismissRestore(id: string) {
|
||||
setDismissedRestores((previous) => {
|
||||
const next = new Set(previous);
|
||||
next.add(id);
|
||||
writeDismissedRestores([...next]);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
// Restore: typed-confirmation dialog. The request only queues the restore;
|
||||
// the panel above the list follows it from there.
|
||||
const restore = useMutation({
|
||||
mutationFn: async ({
|
||||
row,
|
||||
@@ -831,47 +934,35 @@ export function BackupsSection() {
|
||||
row: BackupRow;
|
||||
restoreInstanceSettings: boolean;
|
||||
}) => {
|
||||
// Idempotency-Key prevents a double-click from re-running the
|
||||
// destructive transaction. Include the row id so two different
|
||||
// backups can both be restored independently in the same minute.
|
||||
// Idempotency-Key prevents a double-click from queuing a second
|
||||
// restore. Include the row id so two different backups can both be
|
||||
// restored independently in the same minute.
|
||||
const idempotencyKey = `restore-${row.id}-${randomId()}`;
|
||||
return apiPost<{ restored: true; skipped?: RestoreSkipSummary }>(
|
||||
return apiPost<{ jobId: string; status: "queued" }>(
|
||||
`/api/admin/backups/${row.id}/restore`,
|
||||
{ confirm: "RESTORE", restoreInstanceSettings },
|
||||
// No request timeout: rebuilding a large account takes minutes.
|
||||
{ headers: { "Idempotency-Key": idempotencyKey }, signal: null },
|
||||
{ headers: { "Idempotency-Key": idempotencyKey } },
|
||||
);
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
// A restore that dropped links is not a plain success and must not read
|
||||
// as one. The count and the exact keys go on screen; the same report is
|
||||
// in the audit row for anyone asking later.
|
||||
setRefusedSections([]);
|
||||
const report = data.skipped;
|
||||
if (report && report.links > 0) {
|
||||
setSkipped(report);
|
||||
toast.warning(
|
||||
t("admin.section.backups.restoreSkippedToast", {
|
||||
links: String(report.links),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
setSkipped(null);
|
||||
toast.success(t("admin.section.backups.restoreSuccess"));
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminBackups() });
|
||||
// Restore touches every personal-data table; nuke the broader
|
||||
// cache so dashboards / lists rebuild against the new state.
|
||||
queryClient.invalidateQueries();
|
||||
setSkipped(null);
|
||||
watched.current.set(data.jobId, "queued");
|
||||
// Neutral, not a success: nothing has been restored yet.
|
||||
toast.info(t("admin.section.backups.restoreStarted"));
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.adminBackupRestores(),
|
||||
});
|
||||
},
|
||||
onError: (err) => {
|
||||
// The server refuses an incomplete file before it deletes anything, and
|
||||
// names the sections in `meta`. That is the one restore failure the
|
||||
// operator can act on, so it gets the panel rather than only a toast.
|
||||
const sections = missingSectionsOf(err);
|
||||
if (sections.length > 0) {
|
||||
setRefusedSections(sections);
|
||||
toast.error(t("admin.section.backups.restoreMissingTitle"));
|
||||
if (
|
||||
err instanceof ApiError &&
|
||||
err.meta?.errorCode === "backup.restore.active"
|
||||
) {
|
||||
toast.error(t("admin.section.backups.restoreActive"));
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.adminBackupRestores(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
setRefusedSections([]);
|
||||
@@ -1002,6 +1093,14 @@ export function BackupsSection() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{visibleRestoreJobs(restoreJobs, dismissedRestores).map((job) => (
|
||||
<RestoreJobStatus
|
||||
key={job.id}
|
||||
job={job}
|
||||
onDismiss={() => dismissRestore(job.id)}
|
||||
/>
|
||||
))}
|
||||
|
||||
<RestoreRefusalNotice
|
||||
sections={refusedSections}
|
||||
onDismiss={() => setRefusedSections([])}
|
||||
@@ -1133,8 +1232,9 @@ export function BackupsSection() {
|
||||
<RestoreRowDialog
|
||||
row={row}
|
||||
pending={
|
||||
restore.isPending &&
|
||||
restore.variables?.row.id === row.id
|
||||
(restore.isPending &&
|
||||
restore.variables?.row.id === row.id) ||
|
||||
activeOwners.has(row.userId)
|
||||
}
|
||||
onConfirm={(options) =>
|
||||
restore.mutate({ row, ...options })
|
||||
@@ -1196,8 +1296,9 @@ export function BackupsSection() {
|
||||
<RestoreRowDialog
|
||||
row={row}
|
||||
pending={
|
||||
restore.isPending &&
|
||||
restore.variables?.row.id === row.id
|
||||
(restore.isPending &&
|
||||
restore.variables?.row.id === row.id) ||
|
||||
activeOwners.has(row.userId)
|
||||
}
|
||||
onConfirm={(options) =>
|
||||
restore.mutate({ row, ...options })
|
||||
|
||||
Reference in new issue
Block a user