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 { albumGrants, auditEvents, downloadEvents, editorialAccounts, usages, users, } from "@/db/schema"; import { createUsageService, createUsageServiceRepository, } from "@/modules/usages/service"; import { createDownloadService, createRepeatDownloadRepository, } from "@/modules/downloads/service"; import { requestFingerprint } from "@/modules/usages/types"; import { startPostgres } from "./postgres"; const testDb = await startPostgres(); 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: assetId, type: "IMAGE" as const, originalFileName: "jubel.jpg", originalMimeType: "image/jpeg", localDateTime: null, fileCreatedAt: null, albums: [{ id: albumId }], }; function createServices() { const immich = { assetCount: 1, }, ]), getAsset: vi.fn().mockResolvedValue(asset), }; return { usageService: createUsageService({ repository: createUsageServiceRepository(database), immich, }), downloadService: createDownloadService({ repository: createRepeatDownloadRepository(database), }), immich, }; } async function seedEditorial({ status = "active", priceCents = 1_500, albumId: grantedAlbumId = albumId, revoked = false, }: { status?: "active" | "suspended" | "pending_approval"; priceCents?: number | null; albumId?: string; revoked?: boolean; } = {}) { const userId = randomUUID(); const editorialId = randomUUID(); await database.insert(users).values({ id: userId, name: "Test Redaktion", email: `${userId}@example.com`, emailVerified: true, }); await database.insert(editorialAccounts).values({ id: editorialId, userId, name: "Test Redaktion", contactName: "Testkontakt", loginEmail: `${userId}@example.com`, status, currentPriceCents: priceCents, }); await database.insert(albumGrants).values({ editorialAccountId: editorialId, immichAlbumId: grantedAlbumId, revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null, }); return editorialId; } function newInput(editorialId: string, idempotencyKey = randomUUID()) { return { editorialId, assetId, albumId, purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey, }; } async function insertWinner( client: PoolClient, input: ReturnType, 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(); const input = newInput(editorialId); const intent = await usageService.createNewUsage(input); const [usage] = await database.select().from(usages).where(eq(usages.id, intent.usageId)); const [event] = await database.select().from(downloadEvents).where(eq(downloadEvents.id, intent.id)); const [audit] = await database .select() .from(auditEvents) .where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, intent.usageId))); expect(usage).toMatchObject({ editorialAccountId: editorialId, immichAssetId: assetId, filenameSnapshot: "jubel.jpg", immichAlbumIdSnapshot: albumId, albumNameSnapshot: "Presse 2026", purpose: "Titelgeschichte", internalReference: "Ausgabe 8/26", priceCents: 1_500, billingStatus: "open", }); expect(event).toMatchObject({ editorialAccountId: editorialId, usageId: intent.usageId, status: "authorized", intentKind: "new_usage", }); expect(audit).toMatchObject({ actorType: "editorial", entityType: "usage" }); expect(JSON.stringify(audit)).not.toContain(input.idempotencyKey); expect(JSON.stringify(audit)).not.toContain("test-immich-key"); }); test.each([ ["zero price", "active", 0, false, "INVALID_PRICE"], ["missing price", "active", null, false, "INVALID_PRICE"], ["suspended account", "suspended", 1_500, false, "EDITORIAL_NOT_ACTIVE"], ["revoked grant", "active", 1_500, true, "ALBUM_NOT_GRANTED"], ] as const)("rejects %s transactionally without accounting rows", async (_label, status, priceCents, revoked, code) => { const editorialId = await seedEditorial({ status, priceCents, revoked }); const { usageService } = createServices(); await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code }); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorialId)); expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 }); }); test("requires an active grant for the exact requested album", async () => { const editorialId = await seedEditorial({ albumId: otherAlbumId }); const { usageService } = createServices(); await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED", }); }); 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((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((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(); const input = newInput(editorialId); const [first, second] = await Promise.all([ usageService.createNewUsage(input), usageService.createNewUsage(input), ]); expect(second).toEqual(first); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorialId)); const [auditCount] = await database .select({ value: count() }) .from(auditEvents) .where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, first.usageId))); expect({ usages: usageCount.value, events: eventCount.value, audits: auditCount.value }).toEqual({ usages: 1, events: 1, audits: 1, }); }); test("the same key may be reused by a different editorial but not for a different payload", async () => { const firstEditorialId = await seedEditorial(); const secondEditorialId = await seedEditorial(); const { usageService } = createServices(); const key = randomUUID(); await usageService.createNewUsage(newInput(firstEditorialId, key)); await expect( usageService.createNewUsage({ ...newInput(firstEditorialId, key), purpose: "Online-Aufmacher" }), ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); await expect(usageService.createNewUsage(newInput(secondEditorialId, key))).resolves.toMatchObject({ billable: true, }); }); test("an audit failure rolls back both the usage and authorized event", async () => { const editorialId = await seedEditorial(); const { usageService } = createServices(); await testDb.pool.query(` create function reject_billable_usage_audit() returns trigger language plpgsql as $$ begin if new.event_type = 'billable_usage_created' then raise exception 'audit rejected'; end if; return new; end $$ `); await testDb.pool.query(` create trigger reject_billable_usage_audit before insert on audit_events for each row execute function reject_billable_usage_audit() `); try { await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toThrow("audit rejected"); } finally { await testDb.pool.query("drop trigger reject_billable_usage_audit on audit_events"); await testDb.pool.query("drop function reject_billable_usage_audit()"); } const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorialId)); expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 }); }); test("a repeat remains free after a price change and creates no additional usage", async () => { 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 }) .where(eq(editorialAccounts.id, editorialId)); const repeat = await downloadService.createRepeatDownload({ editorialId, usageId: first.usageId, note: "Web-Ausgabe", idempotencyKey: randomUUID(), }); expect(repeat).toMatchObject({ usageId: first.usageId, priceCents: 0, billable: false }); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); expect(usageCount.value).toBe(1); }); 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, note: "Web-Ausgabe", idempotencyKey: randomUUID(), }; const [repeatOne, repeatTwo] = await Promise.all([ downloadService.createRepeatDownload(repeatInput), downloadService.createRepeatDownload(repeatInput), ]); expect(repeatTwo).toEqual(repeatOne); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(and(eq(downloadEvents.usageId, first.usageId), eq(downloadEvents.intentKind, "repeat_download"))); expect(eventCount.value).toBe(1); }); test("rechecks suspension after an idempotent repeat winner commits", 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 downloadService = createDownloadService({ repository: createRepeatDownloadRepository(database), }); 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 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).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); } 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(); const first = await usageService.createNewUsage(newInput(editorialId)); await database .update(editorialAccounts) .set({ status: "suspended" }) .where(eq(editorialAccounts.id, editorialId)); await expect( downloadService.createRepeatDownload({ editorialId, usageId: first.usageId, idempotencyKey: randomUUID(), }), ).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); }); test("repeat ownership is scoped to the active editorial", async () => { const ownerId = await seedEditorial(); const otherEditorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(ownerId)); await expect( downloadService.createRepeatDownload({ editorialId: otherEditorialId, usageId: first.usageId, idempotencyKey: randomUUID(), }), ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); }); async function markDelivered(downloadId: string): Promise { const deliveredAt = new Date(); await database .update(downloadEvents) .set({ status: "completed", startedAt: deliveredAt, completedAt: deliveredAt, transferredBytes: 1, }) .where(eq(downloadEvents.id, downloadId)); }