fix: harden download history and attempt ledger

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 16:45:40 +02:00
1 parent 510fde7afa
commit ba673ad732
19 files changed
+2287 -311

No files matched your search

+166 -17
View File
@@ -5,6 +5,7 @@ import { afterAll, expect, test } from "vitest";
import {
createDownloadDeliveryRepository,
createDownloadHistoryService,
createEditorialDownloadOptionsLoader,
createPostgresDownloadHistoryRepository,
HISTORY_ATTEMPT_PAGE_SIZE,
} from "@/modules/downloads/stream";
@@ -137,11 +138,13 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async
const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database),
});
const repeatIntent = await repeats.createRepeatDownload({
const repeatKey = randomUUID();
const repeatInput = {
editorialId: seed.editorialId,
usageId: seed.usageId,
idempotencyKey: randomUUID(),
});
idempotencyKey: repeatKey,
};
const repeatIntent = await repeats.createRepeatDownload(repeatInput);
const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true });
const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id);
@@ -153,6 +156,101 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async
[repeatIntent.id],
);
expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" });
await expect(repeats.createRepeatDownload(repeatInput)).rejects.toMatchObject({
code: "USAGE_NOT_FOUND",
});
});
test("dialog choices include only owned usages with delivered original bytes", async () => {
const own = await testDb.seedEditorialWithUsage();
const foreign = await testDb.seedEditorialWithUsage();
const billedAssetId = randomUUID();
const reopenedAssetId = randomUUID();
const zeroByteAssetId = randomUUID();
const deliveredOpen = await insertUsage(own.editorialId, own.assetId, "open", "Open geliefert");
const deliveredBilled = await insertUsage(
own.editorialId,
billedAssetId,
"billed",
"Abgerechnet geliefert",
);
const deliveredReopened = await insertUsage(
own.editorialId,
reopenedAssetId,
"reopened",
"Wieder geöffnet geliefert",
);
const zeroByte = await insertUsage(
own.editorialId,
zeroByteAssetId,
"open",
"Null Byte",
);
const eventSeeds = [
{ ...own, usageId: deliveredOpen, id: randomUUID(), bytes: 7, status: "completed" },
{
...own,
usageId: deliveredBilled,
assetId: billedAssetId,
id: randomUUID(),
bytes: 9,
status: "completed",
},
{
...own,
usageId: deliveredReopened,
assetId: reopenedAssetId,
id: randomUUID(),
bytes: 3,
status: "interrupted",
},
{
...own,
usageId: zeroByte,
assetId: zeroByteAssetId,
id: randomUUID(),
bytes: 0,
status: "completed",
},
{ ...foreign, id: randomUUID(), bytes: 11, status: "completed" },
] as const;
for (const event of eventSeeds) {
await testDb.insertDownload({
editorialId: event.editorialId,
usageId: event.usageId,
assetId: event.assetId,
id: event.id,
idempotencyKey: randomUUID(),
});
await testDb.pool.query(
"update download_events set status = $2, started_at = now(), completed_at = now(), transferred_bytes = $3 where id = $1",
[event.id, event.status, event.bytes],
);
}
const loadOptions = createEditorialDownloadOptionsLoader(testDb.database);
const options = await loadOptions(own.editorialId, [
own.assetId,
billedAssetId,
reopenedAssetId,
zeroByteAssetId,
]);
expect(options.priorUsagesByAsset[own.assetId]?.map((usage) => usage.purpose)).toEqual([
"Open geliefert",
]);
expect(options.priorUsagesByAsset[billedAssetId]?.map((usage) => usage.purpose)).toEqual([
"Abgerechnet geliefert",
]);
expect(options.priorUsagesByAsset[reopenedAssetId]?.map((usage) => usage.purpose)).toEqual([
"Wieder geöffnet geliefert",
]);
expect(options.priorUsagesByAsset[zeroByteAssetId]).toBeUndefined();
expect(
Object.values(options.priorUsagesByAsset)
.flat()
.some((usage) => usage.id === foreign.usageId),
).toBe(false);
});
test("a failed repeat attempt never mutates the original usage", async () => {
@@ -200,7 +298,7 @@ test("terminal completion and interruption race to exactly one database transiti
expect(["completed", "interrupted"]).toContain(event.rows[0].status);
});
test("history is editorial-scoped, terminal-only, and paginated by usage", async () => {
test("history keeps the global all-status attempt stream editorial-scoped", async () => {
const own = await testDb.seedEditorialWithUsage();
const foreign = await testDb.seedEditorialWithUsage();
const ownCompleted = randomUUID();
@@ -234,14 +332,14 @@ test("history is editorial-scoped, terminal-only, and paginated by usage", async
expect(page.items).toHaveLength(1);
expect(page.items[0].usageId).toBe(own.usageId);
expect(new Set(page.items[0].attempts.map((attempt) => attempt.downloadId))).toEqual(
new Set([ownInterrupted, ownCompleted]),
expect(new Set(page.attempts.map((attempt) => attempt.downloadId))).toEqual(
new Set([ownAuthorized, ownInterrupted, ownCompleted]),
);
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === ownAuthorized)).toBe(false);
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false);
expect(page.attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false);
expect(page.attempts.every((attempt) => attempt.filename === "bild.jpg")).toBe(true);
});
test("history bounds terminal attempts and exposes every attempt through pagination", async () => {
test("global attempt traversal is independent of usage pages and stable across status changes", async () => {
const own = await testDb.seedEditorialWithUsage();
const attemptIds: string[] = [];
for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) {
@@ -254,26 +352,77 @@ test("history bounds terminal attempts and exposes every attempt through paginat
intentKind: index === 0 ? "new_usage" : "repeat_download",
});
}
await testDb.pool.query(
"update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where usage_id = $1",
[own.usageId],
);
const history = createDownloadHistoryService({
repository: createPostgresDownloadHistoryRepository(testDb.database),
});
const first = await history.listEditorialUsageHistory(own.editorialId, 1, 1);
const first = await history.listEditorialUsageHistory(own.editorialId, 2);
expect(first.nextAttemptCursor).toBeDefined();
expect(first.items).toHaveLength(0);
await testDb.pool.query(
"update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where id = $1",
[first.attempts[0].downloadId],
);
const laterEventId = randomUUID();
await testDb.insertDownload({
...own,
id: laterEventId,
idempotencyKey: randomUUID(),
intentKind: "repeat_download",
});
const second = await history.listEditorialUsageHistory(
own.editorialId,
1,
2,
first.nextAttemptCursor,
);
const firstIds = first.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId));
const secondIds = second.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId));
const firstIds = first.attempts.map((attempt) => attempt.downloadId);
const secondIds = second.attempts.map((attempt) => attempt.downloadId);
expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE);
expect(secondIds).toHaveLength(1);
expect(second.nextAttemptCursor).toBeUndefined();
expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds));
expect([...firstIds, ...secondIds]).not.toContain(laterEventId);
});
test("history ordering queries can use the editorial keyset indexes", async () => {
const own = await testDb.seedEditorialWithUsage();
const client = await testDb.pool.connect();
try {
await client.query("begin");
await client.query("set local enable_seqscan = off");
const events = await client.query(
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc, id desc limit 26",
[own.editorialId],
);
const usageRows = await client.query(
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc, id desc limit 21",
[own.editorialId],
);
const eventPlan = events.rows.map((row) => row["QUERY PLAN"]).join("\n");
const usagePlan = usageRows.rows.map((row) => row["QUERY PLAN"]).join("\n");
expect(eventPlan).toContain("download_events_editorial_authorized_id_idx");
expect(usagePlan).toContain("usages_editorial_created_id_idx");
} finally {
await client.query("rollback");
client.release();
}
});
async function insertUsage(
editorialId: string,
assetId: string,
billingStatus: "open" | "billed" | "reopened",
purpose: string,
): Promise<string> {
const usageId = randomUUID();
await testDb.pool.query(
`insert into usages (
id, editorial_account_id, immich_asset_id, filename_snapshot,
immich_album_id_snapshot, album_name_snapshot, purpose, price_cents, billing_status
) values ($1, $2, $3, 'dialog.jpg', 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'Dialog', $4, 1500, $5)`,
[usageId, editorialId, assetId, purpose, billingStatus],
);
return usageId;
}
@@ -0,0 +1,19 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test } from "vitest";
test("0004 adds both editorial history keyset indexes without rewriting history", async () => {
const migration = await readFile(
path.join(process.cwd(), "drizzle/0004_download_history_indexes.sql"),
"utf8",
);
expect(migration).toContain(
'CREATE INDEX "download_events_editorial_authorized_id_idx" ON "download_events" USING btree ("editorial_account_id","authorized_at" DESC NULLS LAST,"id" DESC NULLS LAST)',
);
expect(migration).toContain(
'CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST)',
);
expect(migration).not.toMatch(/delete\s+from\s+"?(usages|download_events)"?/i);
});
+18 -24
View File
@@ -432,6 +432,7 @@ test("a repeat remains free after a price change and creates no additional usage
const editorialId = await seedEditorial();
const { usageService, downloadService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId));
await markDelivered(first.id);
await database
.update(editorialAccounts)
.set({ currentPriceCents: 2_100 })
@@ -456,6 +457,7 @@ test("same-key repeat concurrency creates one free event", async () => {
const editorialId = await seedEditorial();
const { usageService, downloadService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId));
await markDelivered(first.id);
const repeatInput = {
editorialId,
usageId: first.usageId,
@@ -476,7 +478,7 @@ test("same-key repeat concurrency creates one free event", async () => {
expect(eventCount.value).toBe(1);
});
test("returns a repeat winner committed while waiting before later suspension is checked", async () => {
test("rechecks suspension after an idempotent repeat winner commits", async () => {
const editorialId = await seedEditorial();
const { usageService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId));
@@ -486,20 +488,8 @@ test("returns a repeat winner committed while waiting before later suspension is
note: "Web-Ausgabe",
idempotencyKey: randomUUID(),
};
const realRepository = createRepeatDownloadRepository(database);
let releaseFastMiss!: () => void;
const fastMiss = new Promise<void>((resolve) => {
releaseFastMiss = resolve;
});
const downloadService = createDownloadService({
repository: {
...realRepository,
async findIntent(requestEditorialId, key) {
const intent = await realRepository.findIntent(requestEditorialId, key);
releaseFastMiss();
return intent;
},
},
repository: createRepeatDownloadRepository(database),
});
const eventId = randomUUID();
const authorizedAt = new Date("2026-08-09T11:00:00.000Z");
@@ -509,7 +499,6 @@ test("returns a repeat winner committed while waiting before later suspension is
try {
const pending = downloadService.createRepeatDownload(input);
await fastMiss;
await locker.query(
`insert into download_events (
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
@@ -538,15 +527,7 @@ test("returns a repeat winner committed while waiting before later suspension is
]);
await locker.query("commit");
await expect(pending).resolves.toEqual({
id: eventId,
usageId: first.usageId,
assetId,
priceCents: 0,
billable: false,
status: "authorized",
authorizedAt,
});
await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" });
} finally {
await locker.query("rollback");
locker.release();
@@ -585,3 +566,16 @@ test("repeat ownership is scoped to the active editorial", async () => {
}),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
});
async function markDelivered(downloadId: string): Promise<void> {
const deliveredAt = new Date();
await database
.update(downloadEvents)
.set({
status: "completed",
startedAt: deliveredAt,
completedAt: deliveredAt,
transferredBytes: 1,
})
.where(eq(downloadEvents.id, downloadId));
}