test(backups): prove the off-host ledger end to end and the card's empty state

The unit tests either side of this mock Prisma, so neither proves the
migration applies or that the writer and the reader agree on a shape. The
integration file runs the real nightly job against real Postgres with an
in-memory bucket, then reads the row back and asks the console's own
classifier what it says: fresh after a run, one row across two runs, stale
once it ages past two nightly periods, gone when the account is.

The component test pins the case an operator most needs stated: a host with
no bucket configured says so, rather than painting an empty list that reads
as "no problems". The accessibility scan's admin-backups response gains one
row in each state, because a card that paints only its header proves nothing
about the rows anybody reads.

Two small corrections ride along, both from writing the tests. The freshness
badge composes its classes through `cn` like every other surface, and the
error-reporting line waits for the settings to arrive instead of asserting
"nothing is sent" while the answer is still loading.
This commit is contained in:
Marc-André Bombeck committed 2026-09-10 09:34:33 +02:00
1 parent 532483e782
commit 34d647a884
5 files changed
+301 -8

No files matched your search

+33
View File
@@ -707,6 +707,39 @@ async function installA11yMocks(page: Page) {
},
],
retentionDays: 30,
// The off-host card, with one row in each state — the scan has to reach
// the status washes, and a card that paints only its header proves
// nothing about the rows an operator actually reads.
offhost: {
configured: true,
periodHours: 24,
rows: [
{
userId: "a11y-user",
username: "a11y-backup-user",
lastSuccessAt: "2026-07-20T03:00:00.000Z",
sizeBytes: 4096,
ageHours: 3,
freshness: "fresh",
},
{
userId: "a11y-user-2",
username: "a11y-backup-user-2",
lastSuccessAt: "2026-07-14T03:00:00.000Z",
sizeBytes: 2048,
ageHours: 150,
freshness: "stale",
},
{
userId: "a11y-user-3",
username: "a11y-backup-user-3",
lastSuccessAt: null,
sizeBytes: null,
ageHours: null,
freshness: "never",
},
],
},
}),
);
}
@@ -0,0 +1,95 @@
/**
* The off-host card paints what the response says, including the case an
* operator most needs stated out loud: this host is not sending anything
* anywhere. A card that renders an empty list on an unconfigured host reads
* as "no problems".
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import type { BackupsList } from "@/types/backups";
const queryResult = vi.hoisted(() => ({
current: {
data: null as BackupsList | null,
isLoading: false,
isError: false,
},
}));
vi.mock("@tanstack/react-query", () => ({
useQuery: () => ({ ...queryResult.current, refetch: vi.fn() }),
}));
import { I18nProvider } from "@/lib/i18n/context";
import { OffhostBackupsSection } from "../offhost-backups-section";
function render(data: BackupsList["offhost"] | null): string {
queryResult.current = {
data:
data === null
? null
: ({
rows: [],
retentionDays: 90,
schedule: null,
offhost: data,
} as unknown as BackupsList),
isLoading: false,
isError: false,
};
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<OffhostBackupsSection />
</I18nProvider>,
);
}
describe("<OffhostBackupsSection>", () => {
it("says off-host backup is not configured rather than showing an empty list", () => {
const html = render({ configured: false, periodHours: 24, rows: [] });
expect(html).toContain("Off-host backup is not configured");
expect(html).not.toContain('data-slot="offhost-backup-rows"');
});
it("paints one row per account with its verdict", () => {
const html = render({
configured: true,
periodHours: 24,
rows: [
{
userId: "u1",
username: "account-one",
lastSuccessAt: "2026-09-10T06:00:00.000Z",
sizeBytes: 4096,
ageHours: 3,
freshness: "fresh",
},
{
userId: "u2",
username: "account-two",
lastSuccessAt: "2026-09-06T06:00:00.000Z",
sizeBytes: 2048,
ageHours: 99,
freshness: "stale",
},
{
userId: "u3",
username: "account-three",
lastSuccessAt: null,
sizeBytes: null,
ageHours: null,
freshness: "never",
},
],
});
expect(html).toContain('data-offhost-freshness="fresh"');
expect(html).toContain('data-offhost-freshness="stale"');
expect(html).toContain('data-offhost-freshness="never"');
expect(html).toContain("account-two");
// The account with no object says so instead of showing a blank cell.
expect(html).toContain("No copy has ever reached the bucket");
// Never the bucket's own coordinates.
expect(html).not.toMatch(/secret|access[- ]key/i);
});
});
+12 -7
View File
@@ -112,13 +112,18 @@ export function GlitchtipSection() {
}
disabled={updateSettings.isPending}
/>
<p className="text-sm" data-slot="glitchtip-target">
{reporting && targetHost
? t("admin.glitchtipTargetOn", { host: targetHost })
: settings?.glitchtipEnabled
? t("admin.glitchtipTargetNoTarget")
: t("admin.glitchtipTargetOff")}
</p>
{/* Only once the settings are in hand: a line that says "nothing is
sent" while the answer is still loading is a claim, not a
placeholder. */}
{settings ? (
<p className="text-sm" data-slot="glitchtip-target">
{reporting && targetHost
? t("admin.glitchtipTargetOn", { host: targetHost })
: settings.glitchtipEnabled
? t("admin.glitchtipTargetNoTarget")
: t("admin.glitchtipTargetOff")}
</p>
) : null}
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="admin-glitchtip-dsn" className="text-xs">
@@ -26,6 +26,7 @@ import { ListRow } from "@/components/ui/list-row";
import { QueryErrorRow } from "@/components/ui/query-error-row";
import { Skeleton } from "@/components/ui/skeleton";
import { apiGet } from "@/lib/api/api-fetch";
import { cn } from "@/lib/utils";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { OffhostBackupFreshness } from "@/lib/jobs/offhost-backup-freshness";
@@ -80,7 +81,7 @@ function AccountRow({ row }: { row: OffhostAccountRow }) {
</span>
<Badge
variant="outline"
className={`shrink-0 ${FRESHNESS_STYLE[row.freshness]}`}
className={cn("shrink-0", FRESHNESS_STYLE[row.freshness])}
>
{freshnessLabel(row.freshness, t)}
</Badge>
@@ -0,0 +1,159 @@
/**
* The off-host ledger, end to end against real Postgres.
*
* Both ends and the pipe: the nightly job is what writes the row, the admin
* console is what reads it, and a unit test that mocks Prisma proves neither
* the migration nor the shape they agree on. Here the real
* `runOffhostBackup()` uploads into an in-memory bucket double, the row lands
* in the real table, and the verdict the console shows is computed from what
* came back out.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { Buffer } from "node:buffer";
import type { Readable } from "node:stream";
import {
classifyOffhostBackup,
OFFHOST_BACKUP_PERIOD_HOURS,
} from "@/lib/jobs/offhost-backup-freshness";
import {
offhostBackupConfigured,
runOffhostBackup,
type S3Like,
} from "@/lib/jobs/offhost-backup";
import { getPrismaClient, truncateAllTables } from "./setup";
const HOUR = 3_600_000;
/** The five variables the job insists on, none of which reach a network here. */
const ENV: Record<string, string> = {
BACKUP_S3_ENDPOINT: "http://bucket.invalid",
BACKUP_S3_BUCKET: "healthlog-test",
BACKUP_S3_ACCESS_KEY: "test-access-key",
BACKUP_S3_SECRET_KEY: "test-secret-key",
BACKUP_ENCRYPTION_KEY:
"1111111111111111111111111111111111111111111111111111111111111111",
};
function makeBucket(): S3Like & { store: Map<string, Buffer> } {
const store = new Map<string, Buffer>();
return {
store,
putObject: async (key, body) => {
store.set(key, Buffer.from(body));
},
putStream: async (key: string, body: Readable) => {
const chunks: Buffer[] = [];
for await (const chunk of body) chunks.push(Buffer.from(chunk));
store.set(key, Buffer.concat(chunks));
},
getObject: async (key) => store.get(key) ?? Buffer.alloc(0),
headObject: async (key) => store.has(key),
listObjects: async () => [],
deleteObject: async (key) => {
store.delete(key);
},
};
}
async function seedUser(id: string): Promise<void> {
await getPrismaClient().user.create({
data: {
id,
username: id,
email: `${id}@example.test`,
timezone: "Europe/Berlin",
},
});
}
beforeEach(async () => {
await truncateAllTables(getPrismaClient());
for (const [name, value] of Object.entries(ENV)) process.env[name] = value;
});
afterEach(() => {
for (const name of Object.keys(ENV)) delete process.env[name];
});
describe("off-host backup ledger (real Postgres)", () => {
it("writes one row per uploaded account and reads back as fresh", async () => {
const prisma = getPrismaClient();
await seedUser("account-one");
await seedUser("account-two");
expect(offhostBackupConfigured()).toBe(true);
const bucket = makeBucket();
const report = await runOffhostBackup(prisma, bucket, new Date());
expect(report.uploaded).toBe(2);
expect(report.failed).toBe(0);
const rows = await prisma.offhostBackupState.findMany({
orderBy: { userId: "asc" },
});
expect(rows.map((row) => row.userId)).toEqual([
"account-one",
"account-two",
]);
for (const row of rows) {
// The size the ledger claims is the size of the object that landed, not
// an estimate: an operator sizing a bucket reads this column.
const object = bucket.store.get(
`${new Date().toISOString().slice(0, 10)}/user-${row.userId}.json.enc`,
);
expect(object).toBeDefined();
expect(row.sizeBytes).toBe(object?.byteLength);
expect(
classifyOffhostBackup({
lastSuccessAt: row.lastSuccessAt,
now: new Date(),
}).freshness,
).toBe("fresh");
}
});
it("keeps one row per account across runs and ages into stale", async () => {
const prisma = getPrismaClient();
await seedUser("account-one");
const bucket = makeBucket();
await runOffhostBackup(prisma, bucket, new Date());
await runOffhostBackup(prisma, bucket, new Date());
expect(await prisma.offhostBackupState.count()).toBe(1);
// Age the row past two nightly runs — the state the console must not miss,
// because the run that skipped this account still reported a success for
// everybody else.
const aged = new Date(
Date.now() - (OFFHOST_BACKUP_PERIOD_HOURS * 2 + 1) * HOUR,
);
await prisma.offhostBackupState.update({
where: { userId: "account-one" },
data: { lastSuccessAt: aged },
});
const row = await prisma.offhostBackupState.findUniqueOrThrow({
where: { userId: "account-one" },
});
expect(
classifyOffhostBackup({
lastSuccessAt: row.lastSuccessAt,
now: new Date(),
}).freshness,
).toBe("stale");
});
it("goes with the account it describes", async () => {
const prisma = getPrismaClient();
await seedUser("account-one");
await runOffhostBackup(prisma, makeBucket(), new Date());
expect(await prisma.offhostBackupState.count()).toBe(1);
await prisma.user.delete({ where: { id: "account-one" } });
expect(await prisma.offhostBackupState.count()).toBe(0);
});
});