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

+116
View File
@@ -0,0 +1,116 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, expect, test, vi } from "vitest";
import { downloadEvents } from "@/db/schema";
import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service";
import { requestFingerprint } from "@/modules/usages/types";
import { startPostgres } from "./postgres";
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
afterAll(() => testDb.stop());
test("0002 preserves an equivalent retry of a populated legacy accounting intent", async () => {
const userId = randomUUID();
const editorialId = randomUUID();
const usageId = randomUUID();
const eventId = randomUUID();
const requestId = randomUUID();
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const albumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const idempotencyKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const authorizedAt = new Date("2026-08-09T08:00:00.000Z");
await testDb.pool.query(
`insert into users (id, name, email, email_verified)
values ($1, 'Legacy Redaktion', $2, true)`,
[userId, `${userId}@example.com`],
);
await testDb.pool.query(
`insert into editorial_accounts (
id, user_id, name, contact_name, login_email, status, current_price_cents
) values ($1, $2, 'Legacy Redaktion', 'Legacy Kontakt', $3, 'active', 2300)`,
[editorialId, userId, `${userId}@example.com`],
);
await testDb.pool.query(
`insert into album_grants (editorial_account_id, immich_album_id)
values ($1, $2)`,
[editorialId, albumId.toUpperCase()],
);
await testDb.pool.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, 'legacy.jpg', $4, 'Legacy Album',
'Titelgeschichte', 'Ausgabe 8/26', 2300, 'open', $5)`,
[usageId, editorialId, assetId.toUpperCase(), albumId.toUpperCase(), authorizedAt],
);
await testDb.pool.query(
`insert into download_events (
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
status, request_id, idempotency_key
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7)`,
[
eventId,
editorialId,
usageId,
assetId.toUpperCase(),
authorizedAt,
requestId,
idempotencyKey.toUpperCase(),
],
);
await testDb.applyRemainingMigrations();
const immich = {
listAlbumsForAsset: vi.fn(),
getAsset: vi.fn(),
};
const usageService = createUsageService({
repository: createUsageServiceRepository(testDb.database),
immich,
});
const input = {
editorialId: editorialId.toUpperCase(),
assetId: assetId.toUpperCase(),
albumId: albumId.toUpperCase(),
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
idempotencyKey: idempotencyKey.toUpperCase(),
};
await expect(usageService.createNewUsage(input)).resolves.toEqual({
id: eventId,
usageId,
assetId,
priceCents: 2300,
billable: true,
status: "authorized",
authorizedAt,
});
expect(immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(immich.getAsset).not.toHaveBeenCalled();
const [migrated] = await testDb.database
.select()
.from(downloadEvents)
.where(eq(downloadEvents.id, eventId));
expect(migrated).toMatchObject({
immichAssetId: assetId,
idempotencyKey,
intentKind: "new_usage",
legacyIntent: true,
requestFingerprint: requestFingerprint({
kind: "new_usage",
editorialId,
assetId,
albumId,
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
}),
});
});
+19 -6
View File
@@ -19,10 +19,11 @@ export type PostgresTestDatabase = {
pool: Pool;
seedEditorialWithUsage(): Promise<DownloadSeed>;
insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise<void>;
applyRemainingMigrations(): Promise<void>;
stop(): Promise<void>;
};
export async function startPostgres(): Promise<PostgresTestDatabase> {
export async function startPostgres({ through }: { through?: string } = {}): Promise<PostgresTestDatabase> {
const container = await new PostgreSqlContainer("postgres:17-alpine")
.withDatabase("portal")
.withUsername("portal")
@@ -30,7 +31,11 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
.start();
const pool = new Pool({ connectionString: container.getConnectionUri() });
await applyMigration(pool);
const migrationFiles = await listMigrationFiles();
const throughIndex = through ? migrationFiles.indexOf(through) : migrationFiles.length - 1;
if (through && throughIndex < 0) throw new Error(`Unknown migration: ${through}`);
let appliedMigrationCount = throughIndex + 1;
await applyMigrationFiles(pool, migrationFiles.slice(0, appliedMigrationCount));
const db = drizzle({ client: pool, schema });
@@ -50,6 +55,10 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
requestFingerprint: "0".repeat(64),
});
},
async applyRemainingMigrations() {
await applyMigrationFiles(pool, migrationFiles.slice(appliedMigrationCount));
appliedMigrationCount = migrationFiles.length;
},
async stop() {
await pool.end();
await stopContainer(container);
@@ -57,11 +66,15 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
};
}
async function applyMigration(pool: Pool) {
async function listMigrationFiles() {
const migrationDirectory = path.join(process.cwd(), "drizzle");
const migrationFiles = (await readdir(migrationDirectory))
return (await readdir(migrationDirectory))
.filter((file) => /^\d+_.*\.sql$/.test(file))
.sort();
}
async function applyMigrationFiles(pool: Pool, migrationFiles: string[]) {
const migrationDirectory = path.join(process.cwd(), "drizzle");
for (const file of migrationFiles) {
await pool.query(await readFile(path.join(migrationDirectory, file), "utf8"));
}
@@ -71,7 +84,7 @@ async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promis
const userId = randomUUID();
const editorialId = randomUUID();
const usageId = randomUUID();
const assetId = "immich-asset-1";
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
await db.insert(schema.users).values({
id: userId,
@@ -93,7 +106,7 @@ async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promis
editorialAccountId: editorialId,
immichAssetId: assetId,
filenameSnapshot: "bild.jpg",
immichAlbumIdSnapshot: "immich-album-1",
immichAlbumIdSnapshot: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
albumNameSnapshot: "Presse",
purpose: "Artikel",
priceCents: 1500,
+3 -2
View File
@@ -7,10 +7,11 @@ afterAll(() => testDb.stop());
test("rejects duplicate download idempotency keys for one editorial", async () => {
const seed = await testDb.seedEditorialWithUsage();
const idempotencyKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
await testDb.insertDownload({ ...seed, idempotencyKey: "same-request" });
await testDb.insertDownload({ ...seed, idempotencyKey });
await expect(
testDb.insertDownload({ ...seed, idempotencyKey: "same-request" }),
testDb.insertDownload({ ...seed, idempotencyKey }),
).rejects.toThrow();
});
+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();