fix: harden usage accounting idempotency

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 10:59:12 +02:00
1 parent 22fe6bf659
commit 3de1530074
14 files changed
+708 -107

No files matched your search

+265 -11
View File
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { and, count, eq } from "drizzle-orm";
import type { PoolClient } from "pg";
import { afterAll, expect, test, vi } from "vitest";
import {
@@ -19,6 +20,7 @@ import {
createDownloadService,
createRepeatDownloadRepository,
} from "@/modules/downloads/service";
import { requestFingerprint } from "@/modules/usages/types";
import { startPostgres } from "./postgres";
const testDb = await startPostgres();
@@ -26,24 +28,28 @@ const database = testDb.database;
afterAll(() => testDb.stop());
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const albumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const otherAlbumId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const asset = {
id: "asset-1",
id: assetId,
type: "IMAGE" as const,
originalFileName: "jubel.jpg",
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "album-1" }],
albums: [{ id: albumId }],
};
function createServices() {
const immich = {
listAlbumsForAsset: vi.fn().mockResolvedValue([
{
id: "album-1",
id: albumId,
albumName: "Presse 2026",
description: null,
albumThumbnailAssetId: "asset-1",
albumThumbnailAssetId: assetId,
assetCount: 1,
},
]),
@@ -64,7 +70,7 @@ function createServices() {
async function seedEditorial({
status = "active",
priceCents = 1_500,
albumId = "album-1",
albumId: grantedAlbumId = albumId,
revoked = false,
}: {
status?: "active" | "suspended" | "pending_approval";
@@ -91,7 +97,7 @@ async function seedEditorial({
});
await database.insert(albumGrants).values({
editorialAccountId: editorialId,
immichAlbumId: albumId,
immichAlbumId: grantedAlbumId,
revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null,
});
return editorialId;
@@ -100,14 +106,59 @@ async function seedEditorial({
function newInput(editorialId: string, idempotencyKey = randomUUID()) {
return {
editorialId,
assetId: "asset-1",
albumId: "album-1",
assetId,
albumId,
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
idempotencyKey,
};
}
async function insertWinner(
client: PoolClient,
input: ReturnType<typeof newInput>,
fingerprint: string,
kind: "new_usage" | "repeat_download" = "new_usage",
) {
const usageId = randomUUID();
const eventId = randomUUID();
const authorizedAt = new Date("2026-08-09T10:00:00.000Z");
await client.query(
`insert into usages (
id, editorial_account_id, immich_asset_id, filename_snapshot,
immich_album_id_snapshot, album_name_snapshot, purpose,
internal_reference, price_cents, billing_status, created_at
) values ($1, $2, $3, 'winner.jpg', $4, 'Presse 2026', $5, $6, 1500, 'open', $7)`,
[
usageId,
input.editorialId,
input.assetId,
input.albumId,
input.purpose,
input.reference,
authorizedAt,
],
);
await client.query(
`insert into download_events (
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
status, request_id, idempotency_key, intent_kind, request_fingerprint
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8, $9)`,
[
eventId,
input.editorialId,
usageId,
input.assetId,
authorizedAt,
randomUUID(),
input.idempotencyKey,
kind,
fingerprint,
],
);
return { eventId, usageId, authorizedAt };
}
test("atomically snapshots price and metadata, authorizes one event, and audits no secrets", async () => {
const editorialId = await seedEditorial();
const { usageService } = createServices();
@@ -123,9 +174,9 @@ test("atomically snapshots price and metadata, authorizes one event, and audits
.where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, intent.usageId)));
expect(usage).toMatchObject({
editorialAccountId: editorialId,
immichAssetId: "asset-1",
immichAssetId: assetId,
filenameSnapshot: "jubel.jpg",
immichAlbumIdSnapshot: "album-1",
immichAlbumIdSnapshot: albumId,
albumNameSnapshot: "Presse 2026",
purpose: "Titelgeschichte",
internalReference: "Ausgabe 8/26",
@@ -165,7 +216,7 @@ test.each([
});
test("requires an active grant for the exact requested album", async () => {
const editorialId = await seedEditorial({ albumId: "album-2" });
const editorialId = await seedEditorial({ albumId: otherAlbumId });
const { usageService } = createServices();
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
@@ -173,6 +224,132 @@ test("requires an active grant for the exact requested album", async () => {
});
});
test("rechecks exact album membership after database locks before inserting", async () => {
const editorialId = await seedEditorial();
const { usageService, immich } = createServices();
immich.listAlbumsForAsset
.mockResolvedValueOnce([
{
id: albumId,
albumName: "Presse 2026",
description: null,
albumThumbnailAssetId: assetId,
assetCount: 1,
},
])
.mockResolvedValueOnce([]);
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
code: "ASSET_NOT_IN_ALBUM",
});
const [usageCount] = await database
.select({ value: count() })
.from(usages)
.where(eq(usages.editorialAccountId, editorialId));
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(2);
expect(usageCount.value).toBe(0);
});
test("returns a winner committed while waiting before later mutable state is checked", async () => {
const editorialId = await seedEditorial();
const input = newInput(editorialId);
const immich = createServices().immich;
const realRepository = createUsageServiceRepository(database);
let releaseFastMiss!: () => void;
const fastMiss = new Promise<void>((resolve) => {
releaseFastMiss = resolve;
});
const usageService = createUsageService({
repository: {
...realRepository,
async findIntent(requestEditorialId, key) {
const intent = await realRepository.findIntent(requestEditorialId, key);
releaseFastMiss();
return intent;
},
},
immich,
});
const locker = await testDb.pool.connect();
await locker.query("begin");
await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]);
try {
const pending = usageService.createNewUsage(input);
await fastMiss;
const winner = await insertWinner(
locker,
input,
requestFingerprint({
kind: "new_usage",
editorialId,
assetId,
albumId,
purpose: input.purpose,
reference: input.reference,
}),
);
await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [
editorialId,
]);
await locker.query("commit");
await expect(pending).resolves.toMatchObject({
id: winner.eventId,
usageId: winner.usageId,
authorizedAt: winner.authorizedAt,
billable: true,
});
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1);
} finally {
await locker.query("rollback");
locker.release();
}
});
test("reports a conflicting winner committed while waiting before later state errors", async () => {
const editorialId = await seedEditorial();
const input = newInput(editorialId);
const { immich } = createServices();
const realRepository = createUsageServiceRepository(database);
let releaseFastMiss!: () => void;
const fastMiss = new Promise<void>((resolve) => {
releaseFastMiss = resolve;
});
const usageService = createUsageService({
repository: {
...realRepository,
async findIntent(requestEditorialId, key) {
const intent = await realRepository.findIntent(requestEditorialId, key);
releaseFastMiss();
return intent;
},
},
immich,
});
const locker = await testDb.pool.connect();
await locker.query("begin");
await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]);
try {
const pending = usageService.createNewUsage(input);
await fastMiss;
await insertWinner(locker, input, "0".repeat(64));
await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [
editorialId,
]);
await locker.query("commit");
await expect(pending).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1);
} finally {
await locker.query("rollback");
locker.release();
}
});
test("same-key concurrency across database clients creates exactly one usage, event, and audit", async () => {
const editorialId = await seedEditorial();
const { usageService } = createServices();
@@ -299,6 +476,83 @@ 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 () => {
const editorialId = await seedEditorial();
const { usageService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId));
const input = {
editorialId,
usageId: first.usageId,
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;
},
},
});
const eventId = randomUUID();
const authorizedAt = new Date("2026-08-09T11:00:00.000Z");
const locker = await testDb.pool.connect();
await locker.query("begin");
await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]);
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,
status, repeat_download_note, request_id, idempotency_key,
intent_kind, request_fingerprint
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8, 'repeat_download', $9)`,
[
eventId,
editorialId,
first.usageId,
assetId,
authorizedAt,
input.note,
randomUUID(),
input.idempotencyKey,
requestFingerprint({
kind: "repeat_download",
editorialId,
usageId: first.usageId,
note: input.note,
}),
],
);
await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [
editorialId,
]);
await locker.query("commit");
await expect(pending).resolves.toEqual({
id: eventId,
usageId: first.usageId,
assetId,
priceCents: 0,
billable: false,
status: "authorized",
authorizedAt,
});
} finally {
await locker.query("rollback");
locker.release();
}
});
test("a suspended owner cannot create a repeat event", async () => {
const editorialId = await seedEditorial();
const { usageService, downloadService } = createServices();