fix: harden delivery accounting and history

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:44:04 +02:00
1 parent 8871e4794a
commit 510fde7afa
13 files changed
+728 -88

No files matched your search

+130 -3
View File
@@ -6,6 +6,7 @@ import {
createDownloadDeliveryRepository,
createDownloadHistoryService,
createPostgresDownloadHistoryRepository,
HISTORY_ATTEMPT_PAGE_SIZE,
} from "@/modules/downloads/stream";
import { createDownloadService, createRepeatDownloadRepository } from "@/modules/downloads/service";
import { startPostgres } from "./postgres";
@@ -33,6 +34,9 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a
const seed = await testDb.seedEditorialWithUsage();
const id = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id });
await testDb.pool.query("update usages set billing_status = 'reopened' where id = $1", [
seed.usageId,
]);
const repository = createDownloadDeliveryRepository(testDb.database);
await repository.claimAuthorized(seed.editorialId, id);
@@ -49,13 +53,16 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a
[seed.usageId],
);
const audit = await testDb.pool.query(
"select event_type from audit_events where entity_id = $1 order by occurred_at desc",
"select event_type, previous_values from audit_events where entity_id = $1 order by occurred_at desc",
[seed.usageId],
);
expect(event.rows[0]).toMatchObject({ status: "failed_before_delivery" });
expect(Number(event.rows[0].transferred_bytes)).toBe(0);
expect(usage.rows[0]).toEqual({ billing_status: "voided" });
expect(audit.rows[0]).toEqual({ event_type: "billable_usage_voided_before_delivery" });
expect(audit.rows[0]).toEqual({
event_type: "billable_usage_voided_before_delivery",
previous_values: { billingStatus: "reopened" },
});
const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database),
@@ -69,8 +76,92 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
});
test("rejects a free repeat until a new-usage original delivered bytes", async () => {
const seed = await testDb.seedEditorialWithUsage();
const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database),
});
await expect(
repeats.createRepeatDownload({
editorialId: seed.editorialId,
usageId: seed.usageId,
idempotencyKey: randomUUID(),
}),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
});
test.each(["completed", "interrupted"] as const)(
"allows a free repeat after an original %s delivery",
async (terminalStatus) => {
const seed = await testDb.seedEditorialWithUsage();
const originalId = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId });
const delivery = createDownloadDeliveryRepository(testDb.database);
await delivery.claimAuthorized(seed.editorialId, originalId);
if (terminalStatus === "completed") {
await delivery.markCompleted(originalId, 120);
} else {
await delivery.markInterrupted(originalId, 80);
}
const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database),
});
const repeat = await repeats.createRepeatDownload({
editorialId: seed.editorialId,
usageId: seed.usageId,
idempotencyKey: randomUUID(),
});
await expect(delivery.claimAuthorized(seed.editorialId, repeat.id)).resolves.toMatchObject({
outcome: "claimed",
});
},
);
test("a later new-use void invalidates a pre-authorized eligible repeat", async () => {
const seed = await testDb.seedEditorialWithUsage();
const originalId = randomUUID();
const failingNewId = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId });
await testDb.insertDownload({
...seed,
idempotencyKey: randomUUID(),
id: failingNewId,
});
const delivery = createDownloadDeliveryRepository(testDb.database);
await delivery.claimAuthorized(seed.editorialId, originalId);
await delivery.markCompleted(originalId, 120);
await delivery.claimAuthorized(seed.editorialId, failingNewId);
const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database),
});
const repeatIntent = await repeats.createRepeatDownload({
editorialId: seed.editorialId,
usageId: seed.usageId,
idempotencyKey: randomUUID(),
});
const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true });
const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id);
expect(failed).toBe(true);
expect(repeatClaim.outcome).toBe("not_authorized");
const repeatRow = await testDb.pool.query(
"select status from download_events where id = $1",
[repeatIntent.id],
);
expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" });
});
test("a failed repeat attempt never mutates the original usage", async () => {
const seed = await testDb.seedEditorialWithUsage();
const originalId = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId });
const repository = createDownloadDeliveryRepository(testDb.database);
await repository.claimAuthorized(seed.editorialId, originalId);
await repository.markCompleted(originalId, 10);
const id = randomUUID();
await testDb.insertDownload({
...seed,
@@ -78,7 +169,6 @@ test("a failed repeat attempt never mutates the original usage", async () => {
id,
intentKind: "repeat_download",
});
const repository = createDownloadDeliveryRepository(testDb.database);
await repository.claimAuthorized(seed.editorialId, id);
await repository.failBeforeDelivery(id, { voidNewUsage: false });
@@ -150,3 +240,40 @@ test("history is editorial-scoped, terminal-only, and paginated by usage", async
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === ownAuthorized)).toBe(false);
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false);
});
test("history bounds terminal attempts and exposes every attempt through pagination", async () => {
const own = await testDb.seedEditorialWithUsage();
const attemptIds: string[] = [];
for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) {
const id = randomUUID();
attemptIds.push(id);
await testDb.insertDownload({
...own,
id,
idempotencyKey: randomUUID(),
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);
expect(first.nextAttemptCursor).toBeDefined();
const second = await history.listEditorialUsageHistory(
own.editorialId,
1,
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));
expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE);
expect(secondIds).toHaveLength(1);
expect(second.nextAttemptCursor).toBeUndefined();
expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds));
});