diff --git a/drizzle/0002_accounting_intents.sql b/drizzle/0002_accounting_intents.sql index c386136..095e566 100644 --- a/drizzle/0002_accounting_intents.sql +++ b/drizzle/0002_accounting_intents.sql @@ -1,7 +1,82 @@ -ALTER TABLE "download_events" ADD COLUMN "intent_kind" text DEFAULT 'new_usage' NOT NULL;--> statement-breakpoint +ALTER TABLE "album_grants" ALTER COLUMN "immich_album_id" SET DATA TYPE uuid USING lower("immich_album_id")::uuid;--> statement-breakpoint +ALTER TABLE "download_events" ALTER COLUMN "immich_asset_id" SET DATA TYPE uuid USING lower("immich_asset_id")::uuid;--> statement-breakpoint +ALTER TABLE "usages" ALTER COLUMN "immich_asset_id" SET DATA TYPE uuid USING lower("immich_asset_id")::uuid;--> statement-breakpoint +ALTER TABLE "usages" ALTER COLUMN "immich_album_id_snapshot" SET DATA TYPE uuid USING lower("immich_album_id_snapshot")::uuid;--> statement-breakpoint +ALTER TABLE "download_events" ADD COLUMN "intent_kind" text;--> statement-breakpoint ALTER TABLE "download_events" ADD COLUMN "request_fingerprint" varchar(64);--> statement-breakpoint -UPDATE "download_events" -SET "request_fingerprint" = md5("editorial_account_id"::text || ':' || "id"::text) || md5("id"::text || ':' || "editorial_account_id"::text);--> statement-breakpoint +ALTER TABLE "download_events" ADD COLUMN "legacy_intent" boolean;--> statement-breakpoint +-- Preserve arbitrary legacy keys, while canonicalizing every legacy UUID key that +-- can be retried through the new UUID-only API. New rows are protected below. +UPDATE "download_events" AS target +SET "idempotency_key" = lower("idempotency_key") +WHERE + target."idempotency_key" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND NOT EXISTS ( + SELECT 1 + FROM "download_events" AS sibling + WHERE + sibling."editorial_account_id" = target."editorial_account_id" + AND sibling."id" <> target."id" + AND lower(sibling."idempotency_key") = lower(target."idempotency_key") + );--> statement-breakpoint +-- Legacy accounting deterministically treats the earliest event for each usage as +-- its billable creation intent. Later events are repeat downloads. These are the +-- only intent shapes whose original request can be reconstructed from stored data. +WITH ranked_legacy_events AS ( + SELECT + "id", + row_number() OVER ( + PARTITION BY "usage_id" + ORDER BY "authorized_at", "id" + ) AS usage_event_number + FROM "download_events" +) +UPDATE "download_events" AS events +SET "intent_kind" = CASE + WHEN ranked.usage_event_number = 1 THEN 'new_usage' + ELSE 'repeat_download' +END +FROM ranked_legacy_events AS ranked +WHERE ranked."id" = events."id";--> statement-breakpoint +-- The string assembled here deliberately matches JSON.stringify's runtime field +-- order. Valid legacy rows therefore receive the same SHA-256 as an equivalent +-- retry; inconsistent rows receive a deterministic fingerprint no request can use. +UPDATE "download_events" AS events +SET "request_fingerprint" = CASE + WHEN + events."editorial_account_id" = usage."editorial_account_id" + AND events."immich_asset_id" = usage."immich_asset_id" + AND events."intent_kind" = 'new_usage' + THEN encode(sha256(convert_to( + '{"kind":"new_usage","editorialId":' || to_json(events."editorial_account_id"::text)::text || + ',"assetId":' || to_json(events."immich_asset_id"::text)::text || + ',"albumId":' || to_json(usage."immich_album_id_snapshot"::text)::text || + ',"purpose":' || to_json(btrim(usage."purpose"))::text || + ',"reference":' || coalesce(to_json(nullif(btrim(usage."internal_reference"), ''))::text, 'null') || + '}', + 'UTF8' + )), 'hex') + WHEN + events."editorial_account_id" = usage."editorial_account_id" + AND events."immich_asset_id" = usage."immich_asset_id" + AND events."intent_kind" = 'repeat_download' + THEN encode(sha256(convert_to( + '{"kind":"repeat_download","editorialId":' || to_json(events."editorial_account_id"::text)::text || + ',"usageId":' || to_json(events."usage_id"::text)::text || + ',"note":' || coalesce(to_json(nullif(btrim(events."repeat_download_note"), ''))::text, 'null') || + '}', + 'UTF8' + )), 'hex') + ELSE encode(sha256(convert_to('unprovable-legacy-intent:' || events."id"::text, 'UTF8')), 'hex') +END +FROM "usages" AS usage +WHERE usage."id" = events."usage_id";--> statement-breakpoint +UPDATE "download_events" SET "legacy_intent" = true;--> statement-breakpoint +ALTER TABLE "download_events" ALTER COLUMN "intent_kind" SET DEFAULT 'new_usage';--> statement-breakpoint +ALTER TABLE "download_events" ALTER COLUMN "intent_kind" SET NOT NULL;--> statement-breakpoint ALTER TABLE "download_events" ALTER COLUMN "request_fingerprint" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "download_events" ALTER COLUMN "legacy_intent" SET DEFAULT false;--> statement-breakpoint +ALTER TABLE "download_events" ALTER COLUMN "legacy_intent" SET NOT NULL;--> statement-breakpoint ALTER TABLE "download_events" ADD CONSTRAINT "download_events_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download'));--> statement-breakpoint -ALTER TABLE "download_events" ADD CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$'); +ALTER TABLE "download_events" ADD CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$');--> statement-breakpoint +ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_idempotency_key_check" CHECK ("download_events"."legacy_intent" OR "download_events"."idempotency_key" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'); diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json index 6f1926f..65a9bc4 100644 --- a/drizzle/meta/0002_snapshot.json +++ b/drizzle/meta/0002_snapshot.json @@ -1,5 +1,5 @@ { - "id": "0cdb7b32-1eb5-4dcf-9949-3862dbbad2b4", + "id": "f650c8ba-ebde-411d-92d0-caf0f9885c44", "prevId": "cfd5f4d1-55ac-46d9-9667-cd156f26e070", "version": "7", "dialect": "postgresql", @@ -23,7 +23,7 @@ }, "immich_album_id": { "name": "immich_album_id", - "type": "text", + "type": "uuid", "primaryKey": false, "notNull": true }, @@ -1157,7 +1157,7 @@ }, "immich_asset_id": { "name": "immich_asset_id", - "type": "text", + "type": "uuid", "primaryKey": false, "notNull": true }, @@ -1224,6 +1224,13 @@ "type": "varchar(64)", "primaryKey": false, "notNull": true + }, + "legacy_intent": { + "name": "legacy_intent", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false } }, "indexes": { @@ -1288,6 +1295,10 @@ "download_events_request_fingerprint_hex_check": { "name": "download_events_request_fingerprint_hex_check", "value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'" + }, + "download_events_canonical_idempotency_key_check": { + "name": "download_events_canonical_idempotency_key_check", + "value": "\"download_events\".\"legacy_intent\" OR \"download_events\".\"idempotency_key\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" } }, "isRLSEnabled": false @@ -1311,7 +1322,7 @@ }, "immich_asset_id": { "name": "immich_asset_id", - "type": "text", + "type": "uuid", "primaryKey": false, "notNull": true }, @@ -1323,7 +1334,7 @@ }, "immich_album_id_snapshot": { "name": "immich_album_id_snapshot", - "type": "text", + "type": "uuid", "primaryKey": false, "notNull": true }, diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 6a7c747..6b7c036 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -19,7 +19,7 @@ { "idx": 2, "version": "7", - "when": 1786308409516, + "when": 1786352073526, "tag": "0002_accounting_intents", "breakpoints": true } diff --git a/src/db/schema/albums.ts b/src/db/schema/albums.ts index 85a8475..e35cb6a 100644 --- a/src/db/schema/albums.ts +++ b/src/db/schema/albums.ts @@ -1,4 +1,4 @@ -import { index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; +import { index, pgTable, timestamp, uuid } from "drizzle-orm/pg-core"; import { users } from "./auth"; import { editorialAccounts } from "./editorials"; @@ -10,7 +10,7 @@ export const albumGrants = pgTable( editorialAccountId: uuid("editorial_account_id") .notNull() .references(() => editorialAccounts.id, { onDelete: "restrict" }), - immichAlbumId: text("immich_album_id").notNull(), + immichAlbumId: uuid("immich_album_id").notNull(), grantedAt: timestamp("granted_at", { withTimezone: true }).notNull().defaultNow(), revokedAt: timestamp("revoked_at", { withTimezone: true }), grantedByUserId: uuid("granted_by_user_id").references(() => users.id, { diff --git a/src/db/schema/usages.ts b/src/db/schema/usages.ts index bba0bb7..cf63588 100644 --- a/src/db/schema/usages.ts +++ b/src/db/schema/usages.ts @@ -1,6 +1,7 @@ import { sql } from "drizzle-orm"; import { bigint, + boolean, check, integer, pgEnum, @@ -32,9 +33,9 @@ export const usages = pgTable("usages", { editorialAccountId: uuid("editorial_account_id") .notNull() .references(() => editorialAccounts.id, { onDelete: "restrict" }), - immichAssetId: text("immich_asset_id").notNull(), + immichAssetId: uuid("immich_asset_id").notNull(), filenameSnapshot: text("filename_snapshot").notNull(), - immichAlbumIdSnapshot: text("immich_album_id_snapshot").notNull(), + immichAlbumIdSnapshot: uuid("immich_album_id_snapshot").notNull(), albumNameSnapshot: text("album_name_snapshot").notNull(), purpose: text("purpose").notNull(), internalReference: text("internal_reference"), @@ -56,7 +57,7 @@ export const downloadEvents = pgTable( usageId: uuid("usage_id") .notNull() .references(() => usages.id, { onDelete: "restrict" }), - immichAssetId: text("immich_asset_id").notNull(), + immichAssetId: uuid("immich_asset_id").notNull(), authorizedAt: timestamp("authorized_at", { withTimezone: true }).notNull().defaultNow(), startedAt: timestamp("started_at", { withTimezone: true }), completedAt: timestamp("completed_at", { withTimezone: true }), @@ -67,6 +68,7 @@ export const downloadEvents = pgTable( idempotencyKey: text("idempotency_key").notNull(), intentKind: text("intent_kind").notNull().default("new_usage"), requestFingerprint: varchar("request_fingerprint", { length: 64 }).notNull(), + legacyIntent: boolean("legacy_intent").notNull().default(false), }, (table) => [ uniqueIndex("download_events_editorial_idempotency_key_unique").on( @@ -81,5 +83,9 @@ export const downloadEvents = pgTable( "download_events_request_fingerprint_hex_check", sql`${table.requestFingerprint} ~ '^[0-9a-f]{64}$'`, ), + check( + "download_events_canonical_idempotency_key_check", + sql`${table.legacyIntent} OR ${table.idempotencyKey} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`, + ), ], ); diff --git a/src/modules/downloads/service.test.ts b/src/modules/downloads/service.test.ts index 12052fa..edc8e69 100644 --- a/src/modules/downloads/service.test.ts +++ b/src/modules/downloads/service.test.ts @@ -8,9 +8,10 @@ import { } from "./service"; import { UsageAccountingError } from "@/modules/usages/types"; -const editorialId = "11111111-1111-4111-8111-111111111111"; -const usageId = "44444444-4444-4444-8444-444444444444"; -const idempotencyKey = "55555555-5555-4555-8555-555555555555"; +const editorialId = "1111111a-1111-4111-8111-11111111111a"; +const usageId = "4444444d-4444-4444-8444-44444444444d"; +const idempotencyKey = "5555555e-5555-4555-8555-55555555555e"; +const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; function createService() { const intents = new Map(); @@ -33,7 +34,7 @@ function createService() { const intent: PersistedRepeatIntent = { id: `download-${events.length}`, usageId: input.usageId, - assetId: "asset-1", + assetId, priceCents: 0, billable: false, status: "authorized", @@ -77,7 +78,7 @@ test("creates only a free authorized event for an owned prior usage", async () = expect(intent).toMatchObject({ usageId, - assetId: "asset-1", + assetId, priceCents: 0, billable: false, status: "authorized", @@ -126,6 +127,23 @@ test("returns the same free intent once for an equivalent retry", async () => { expect(events).toHaveLength(1); }); +test("treats mixed-case UUID input as the same repeat intent", async () => { + const { service, events } = createService(); + const uppercaseInput = { + editorialId: editorialId.toUpperCase(), + usageId: usageId.toUpperCase(), + idempotencyKey: idempotencyKey.toUpperCase(), + }; + + const first = await service.createRepeatDownload(uppercaseInput); + const second = await service.createRepeatDownload({ editorialId, usageId, idempotencyKey }); + + expect(second).toEqual(first); + expect(events).toEqual([ + expect.objectContaining({ editorialId, usageId, idempotencyKey }), + ]); +}); + test("rejects reuse of a repeat key with a materially different note", async () => { const { service, events } = createService(); await service.createRepeatDownload({ editorialId, usageId, note: "Web", idempotencyKey }); diff --git a/src/modules/downloads/service.ts b/src/modules/downloads/service.ts index d507155..1d61ee7 100644 --- a/src/modules/downloads/service.ts +++ b/src/modules/downloads/service.ts @@ -9,10 +9,10 @@ import { db } from "@/db/client"; import { downloadEvents, editorialAccounts, usages } from "@/db/schema"; import type * as schema from "@/db/schema"; import { - assertUuid, type CreateRepeatDownloadInput, type DownloadIntent, normalizeOptionalText, + normalizeUuid, requestFingerprint, UsageAccountingError, } from "@/modules/usages/types"; @@ -71,6 +71,13 @@ export function createRepeatDownloadRepository( try { return await database.transaction(async (transaction) => { await lockEditorialAccounting(transaction, input.editorialId); + const existing = await findPersistedIntent( + transaction, + input.editorialId, + input.idempotencyKey, + ); + if (existing) return asRepeatIntent(existing); + const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status }) .from(editorialAccounts) @@ -81,13 +88,6 @@ export function createRepeatDownloadRepository( throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); } - const existing = await findPersistedIntent( - transaction, - input.editorialId, - input.idempotencyKey, - ); - if (existing) return asRepeatIntent(existing); - const [usage] = await transaction .select({ id: usages.id, assetId: usages.immichAssetId }) .from(usages) @@ -149,15 +149,12 @@ export function createRepeatDownloadRepository( function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput { if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT"); - assertUuid(input.editorialId); - assertUuid(input.usageId); - assertUuid(input.idempotencyKey); const note = normalizeOptionalText(input.note, 200); return { - editorialId: input.editorialId, - usageId: input.usageId, + editorialId: normalizeUuid(input.editorialId), + usageId: normalizeUuid(input.usageId), ...(note === undefined ? {} : { note }), - idempotencyKey: input.idempotencyKey, + idempotencyKey: normalizeUuid(input.idempotencyKey), }; } diff --git a/src/modules/usages/service.test.ts b/src/modules/usages/service.test.ts index a1360e9..9c31178 100644 --- a/src/modules/usages/service.test.ts +++ b/src/modules/usages/service.test.ts @@ -8,13 +8,16 @@ import { } from "./service"; import { UsageAccountingError, type PriorUsage } from "./types"; -const editorialId = "11111111-1111-4111-8111-111111111111"; -const idempotencyKey = "22222222-2222-4222-8222-222222222222"; +const editorialId = "1111111a-1111-4111-8111-11111111111a"; +const idempotencyKey = "2222222b-2222-4222-8222-22222222222b"; +const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; +const albumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; +const otherAlbumId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; const newUsageInput = { editorialId, - assetId: "asset-1", - albumId: "album-1", + assetId, + albumId, purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey, @@ -31,18 +34,22 @@ function createRepository() { async findIntent(requestEditorialId, key) { return intents.get(`${requestEditorialId}:${key}`) ?? null; }, - async createBillableIntent(input) { + async createBillableIntent( + input, + refreshCurrentAsset?: () => Promise<{ albumName: string; filename: string }>, + ) { + const key = `${input.editorialId}:${input.idempotencyKey}`; + const existing = intents.get(key); + if (existing) return existing; if (status !== "active") { throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); } if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { throw new UsageAccountingError("INVALID_PRICE"); } - const key = `${input.editorialId}:${input.idempotencyKey}`; - const existing = intents.get(key); - if (existing) return existing; - usages.push(input); + const refreshed = await refreshCurrentAsset?.(); + usages.push({ ...input, ...refreshed }); const intent: PersistedDownloadIntent = { id: `download-${intents.size + 1}`, usageId: `usage-${usages.length}`, @@ -81,21 +88,21 @@ function createService() { const immich = { listAlbumsForAsset: vi.fn().mockResolvedValue([ { - id: "album-1", + id: albumId, albumName: "Presse 2026", description: null, - albumThumbnailAssetId: "asset-1", + albumThumbnailAssetId: assetId, assetCount: 1, }, ]), getAsset: vi.fn().mockResolvedValue({ - 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 }], }), }; return { ...state, immich, service: createUsageService({ repository: state.repository, immich }) }; @@ -113,8 +120,8 @@ test("snapshots the current editorial price and normalized Immich metadata", asy expect(intent).toMatchObject({ priceCents: 1_500, billable: true, status: "authorized" }); expect(usages).toEqual([ expect.objectContaining({ - assetId: "asset-1", - albumId: "album-1", + assetId, + albumId, albumName: "Presse 2026", filename: "jubel.jpg", purpose: "Titelgeschichte", @@ -131,7 +138,26 @@ test("returns the exact persisted intent for an equivalent idempotent retry", as expect(second).toEqual(first); expect(usages).toHaveLength(1); - expect(immich.getAsset).toHaveBeenCalledTimes(1); + expect(immich.getAsset).toHaveBeenCalledTimes(2); +}); + +test("canonicalizes every UUID before fingerprinting, lookup, Immich calls, and persistence", async () => { + const { service, usages, immich } = createService(); + const uppercaseInput = Object.fromEntries( + Object.entries(newUsageInput).map(([key, value]) => [ + key, + key === "purpose" || key === "reference" ? value : value.toUpperCase(), + ]), + ) as typeof newUsageInput; + + const first = await service.createNewUsage(uppercaseInput); + const second = await service.createNewUsage(newUsageInput); + + expect(second).toEqual(first); + expect(usages).toHaveLength(1); + expect(usages[0]).toMatchObject({ editorialId, assetId, albumId, idempotencyKey }); + expect(immich.listAlbumsForAsset).toHaveBeenCalledWith(assetId); + expect(immich.getAsset).toHaveBeenCalledWith(assetId); }); test("keeps the original snapshot after a price change while a new key uses the new price", async () => { @@ -198,7 +224,7 @@ test("rejects an asset outside the exact requested album", async () => { const { service, immich, usages } = createService(); immich.listAlbumsForAsset.mockResolvedValue([ { - id: "album-2", + id: otherAlbumId, albumName: "Andere Bilder", description: null, albumThumbnailAssetId: null, @@ -213,6 +239,73 @@ test("rejects an asset outside the exact requested album", async () => { expect(usages).toHaveLength(0); }); +test("rejects removal from the requested album between preflight and locked refresh", async () => { + const { service, immich, usages } = createService(); + immich.listAlbumsForAsset + .mockResolvedValueOnce([ + { + id: albumId, + albumName: "Presse 2026", + description: null, + albumThumbnailAssetId: assetId, + assetCount: 1, + }, + ]) + .mockResolvedValueOnce([]); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "ASSET_NOT_IN_ALBUM", + }); + expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(2); + expect(usages).toHaveLength(0); +}); + +test("persists metadata from the locked final Immich refresh", async () => { + const { service, immich, usages } = createService(); + immich.listAlbumsForAsset + .mockResolvedValueOnce([ + { + id: albumId, + albumName: "Presse 2026", + description: null, + albumThumbnailAssetId: assetId, + assetCount: 1, + }, + ]) + .mockResolvedValueOnce([ + { + id: albumId, + albumName: "Presse final", + description: null, + albumThumbnailAssetId: assetId, + assetCount: 1, + }, + ]); + const currentAsset = { + id: assetId, + type: "IMAGE" as const, + originalFileName: "jubel.jpg", + originalMimeType: "image/jpeg", + localDateTime: null, + fileCreatedAt: null, + albums: [{ id: albumId }], + }; + immich.getAsset.mockResolvedValueOnce({ + ...currentAsset, + originalFileName: "vorher.jpg", + }).mockResolvedValueOnce({ + ...currentAsset, + originalFileName: "final.jpg", + }); + + await service.createNewUsage(newUsageInput); + + expect(immich.getAsset).toHaveBeenCalledTimes(2); + expect(usages).toEqual([ + expect.objectContaining({ albumName: "Presse final", filename: "final.jpg" }), + ]); +}); + test("rejects a missing asset immediately before accounting", async () => { const { service, immich, usages } = createService(); immich.getAsset.mockRejectedValue({ code: "IMMICH_NOT_FOUND" }); @@ -226,13 +319,13 @@ test("rejects a missing asset immediately before accounting", async () => { test("rejects a non-image asset immediately before accounting", async () => { const { service, immich, usages } = createService(); immich.getAsset.mockResolvedValue({ - id: "asset-1", + id: assetId, type: "VIDEO", originalFileName: "clip.mp4", originalMimeType: "video/mp4", localDateTime: null, fileCreatedAt: null, - albums: [{ id: "album-1" }], + albums: [{ id: albumId }], }); await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ @@ -249,16 +342,16 @@ test("rejects reuse of an idempotency key for a materially different new usage", service.createNewUsage({ ...newUsageInput, purpose: "Online-Aufmacher" }), ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); expect(usages).toHaveLength(1); - expect(immich.getAsset).toHaveBeenCalledTimes(1); + expect(immich.getAsset).toHaveBeenCalledTimes(2); }); test("lists only the repository's prior usages for the requested editorial asset", async () => { const { service, priorUsages } = createService(); priorUsages.push({ id: "usage-1", - assetId: "asset-1", + assetId, filename: "jubel.jpg", - albumId: "album-1", + albumId, albumName: "Presse 2026", purpose: "Titelgeschichte", reference: undefined, @@ -267,5 +360,7 @@ test("lists only the repository's prior usages for the requested editorial asset createdAt: new Date("2026-08-09T08:00:00.000Z"), }); - await expect(service.listPriorUsages(editorialId, "asset-1")).resolves.toEqual(priorUsages); + await expect(service.listPriorUsages(editorialId.toUpperCase(), assetId.toUpperCase())).resolves.toEqual( + priorUsages, + ); }); diff --git a/src/modules/usages/service.ts b/src/modules/usages/service.ts index fa8f658..fbf6570 100644 --- a/src/modules/usages/service.ts +++ b/src/modules/usages/service.ts @@ -18,12 +18,11 @@ import { immichClient } from "@/modules/immich/client"; import type { ImmichAlbumSummary } from "@/modules/immich/types"; import { - assertImmichIdentifier, - assertUuid, type CreateNewUsageInput, type DownloadIntent, normalizeOptionalText, normalizeRequiredText, + normalizeUuid, type PriorUsage, requestFingerprint, UsageAccountingError, @@ -48,7 +47,10 @@ export type BillableIntentInput = { export type UsageRepository = { findIntent(editorialId: string, idempotencyKey: string): Promise; - createBillableIntent(input: BillableIntentInput): Promise; + createBillableIntent( + input: BillableIntentInput, + refreshCurrentAsset: () => Promise<{ albumName: string; filename: string }>, + ): Promise; listPriorUsages(editorialId: string, assetId: string): Promise; }; @@ -90,14 +92,19 @@ export function createUsageService({ albumName: normalizeUpstreamSnapshot(album.albumName), filename: normalizeUpstreamSnapshot(asset.originalFileName), requestFingerprint: fingerprint, + }, async () => { + const currentAlbum = await loadRequestedAlbum(immich, input.assetId, input.albumId); + const currentAsset = await loadImageAsset(immich, input.assetId); + return { + albumName: normalizeUpstreamSnapshot(currentAlbum.albumName), + filename: normalizeUpstreamSnapshot(currentAsset.originalFileName), + }; }); return resolveIntent(persisted, fingerprint, "new_usage"); }, async listPriorUsages(editorialId: string, assetId: string): Promise { - assertUuid(editorialId); - assertImmichIdentifier(assetId); - return repository.listPriorUsages(editorialId, assetId); + return repository.listPriorUsages(normalizeUuid(editorialId), normalizeUuid(assetId)); }, }; } @@ -110,10 +117,17 @@ export function createUsageServiceRepository( return findPersistedIntent(database, editorialId, idempotencyKey); }, - async createBillableIntent(input) { + async createBillableIntent(input, refreshCurrentAsset) { try { return await database.transaction(async (transaction) => { await lockEditorialAccounting(transaction, input.editorialId); + const existing = await findPersistedIntentInTransaction( + transaction, + input.editorialId, + input.idempotencyKey, + ); + if (existing) return existing; + const [editorial] = await transaction .select({ id: editorialAccounts.id, @@ -148,12 +162,10 @@ export function createUsageServiceRepository( .limit(1); if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED"); - const existing = await findPersistedIntentInTransaction( - transaction, - input.editorialId, - input.idempotencyKey, - ); - if (existing) return existing; + // This is the last cross-system authorization snapshot available to the + // portal. Immich may still change after it returns, but no portal work is + // allowed between this refresh and the accounting inserts. + const currentAsset = await refreshCurrentAsset(); const createdAt = new Date(); const [usage] = await transaction @@ -161,9 +173,9 @@ export function createUsageServiceRepository( .values({ editorialAccountId: input.editorialId, immichAssetId: input.assetId, - filenameSnapshot: input.filename, + filenameSnapshot: currentAsset.filename, immichAlbumIdSnapshot: input.albumId, - albumNameSnapshot: input.albumName, + albumNameSnapshot: currentAsset.albumName, purpose: input.purpose, internalReference: input.reference, priceCents: editorial.currentPriceCents!, @@ -259,19 +271,15 @@ export function createUsageServiceRepository( function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput { if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT"); - assertUuid(input.editorialId); - assertImmichIdentifier(input.assetId); - assertImmichIdentifier(input.albumId); - assertUuid(input.idempotencyKey); const purpose = normalizeRequiredText(input.purpose, 3, 200); const reference = normalizeOptionalText(input.reference, 200); return { - editorialId: input.editorialId, - assetId: input.assetId, - albumId: input.albumId, + editorialId: normalizeUuid(input.editorialId), + assetId: normalizeUuid(input.assetId), + albumId: normalizeUuid(input.albumId), purpose, ...(reference === undefined ? {} : { reference }), - idempotencyKey: input.idempotencyKey, + idempotencyKey: normalizeUuid(input.idempotencyKey), }; } @@ -333,18 +341,19 @@ export async function findPersistedIntent( editorialId: string, idempotencyKey: string, ): Promise { - const [row] = await database + const rows = await database .select(intentSelection) .from(downloadEvents) .innerJoin(usages, eq(usages.id, downloadEvents.usageId)) .where( and( eq(downloadEvents.editorialAccountId, editorialId), - eq(downloadEvents.idempotencyKey, idempotencyKey), + sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`, ), ) - .limit(1); - return row ? persistedIntent(row) : null; + .limit(2); + if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + return rows[0] ? persistedIntent(rows[0]) : null; } async function findPersistedIntentInTransaction( @@ -352,18 +361,19 @@ async function findPersistedIntentInTransaction( editorialId: string, idempotencyKey: string, ): Promise { - const [row] = await transaction + const rows = await transaction .select(intentSelection) .from(downloadEvents) .innerJoin(usages, eq(usages.id, downloadEvents.usageId)) .where( and( eq(downloadEvents.editorialAccountId, editorialId), - eq(downloadEvents.idempotencyKey, idempotencyKey), + sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`, ), ) - .limit(1); - return row ? persistedIntent(row) : null; + .limit(2); + if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + return rows[0] ? persistedIntent(rows[0]) : null; } const intentSelection = { diff --git a/src/modules/usages/types.ts b/src/modules/usages/types.ts index 53c4d09..d6741f2 100644 --- a/src/modules/usages/types.ts +++ b/src/modules/usages/types.ts @@ -106,6 +106,11 @@ export function assertUuid(value: unknown): asserts value is string { } } +export function normalizeUuid(value: unknown): string { + assertUuid(value); + return value.toLowerCase(); +} + export function assertImmichIdentifier(value: unknown): asserts value is string { if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,200}$/.test(value)) { throw new UsageAccountingError("INVALID_INPUT"); diff --git a/tests/db/accounting-migration.test.ts b/tests/db/accounting-migration.test.ts new file mode 100644 index 0000000..f7fd030 --- /dev/null +++ b/tests/db/accounting-migration.test.ts @@ -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", + }), + }); +}); diff --git a/tests/db/postgres.ts b/tests/db/postgres.ts index f2faefb..6fb3131 100644 --- a/tests/db/postgres.ts +++ b/tests/db/postgres.ts @@ -19,10 +19,11 @@ export type PostgresTestDatabase = { pool: Pool; seedEditorialWithUsage(): Promise; insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise; + applyRemainingMigrations(): Promise; stop(): Promise; }; -export async function startPostgres(): Promise { +export async function startPostgres({ through }: { through?: string } = {}): Promise { const container = await new PostgreSqlContainer("postgres:17-alpine") .withDatabase("portal") .withUsername("portal") @@ -30,7 +31,11 @@ export async function startPostgres(): Promise { .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 { 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 { }; } -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): 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): Promis editorialAccountId: editorialId, immichAssetId: assetId, filenameSnapshot: "bild.jpg", - immichAlbumIdSnapshot: "immich-album-1", + immichAlbumIdSnapshot: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", albumNameSnapshot: "Presse", purpose: "Artikel", priceCents: 1500, diff --git a/tests/db/schema.test.ts b/tests/db/schema.test.ts index 9923674..f16aa99 100644 --- a/tests/db/schema.test.ts +++ b/tests/db/schema.test.ts @@ -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(); }); diff --git a/tests/db/usage-accounting.test.ts b/tests/db/usage-accounting.test.ts index e47d776..e1d5c42 100644 --- a/tests/db/usage-accounting.test.ts +++ b/tests/db/usage-accounting.test.ts @@ -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, + 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((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(); @@ -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((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();