From 3cdca5c82c01308006165b79891669f6320b3d41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Mon, 10 Aug 2026 11:39:44 +0200 Subject: [PATCH] fix: preserve legacy accounting migration data --- drizzle/0002_accounting_intents.sql | 172 +++++++++++---- drizzle/meta/0002_snapshot.json | 34 ++- drizzle/meta/_journal.json | 2 +- src/db/schema/albums.ts | 9 +- src/db/schema/usages.ts | 57 +++-- src/modules/albums/grants.test.ts | 118 ++++++++-- src/modules/albums/grants.ts | 52 +++-- src/modules/usages/service.ts | 2 +- tests/db/accounting-migration-sql.test.ts | 33 +++ tests/db/accounting-migration.test.ts | 257 +++++++++++++++++----- 10 files changed, 559 insertions(+), 177 deletions(-) create mode 100644 tests/db/accounting-migration-sql.test.ts diff --git a/drizzle/0002_accounting_intents.sql b/drizzle/0002_accounting_intents.sql index 095e566..a472b75 100644 --- a/drizzle/0002_accounting_intents.sql +++ b/drizzle/0002_accounting_intents.sql @@ -1,73 +1,149 @@ -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 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. +-- UUID-shaped legacy keys are canonicalized only when doing so is unambiguous. +-- Arbitrary and case-colliding historical keys remain byte-for-byte unchanged. +WITH case_colliding_idempotency_keys AS ( + SELECT "editorial_account_id", lower("idempotency_key") AS canonical_key + FROM "download_events" + GROUP BY "editorial_account_id", lower("idempotency_key") + HAVING count(*) > 1 +) UPDATE "download_events" AS target -SET "idempotency_key" = lower("idempotency_key") +SET "idempotency_key" = lower(target."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 + FROM case_colliding_idempotency_keys AS collision WHERE - sibling."editorial_account_id" = target."editorial_account_id" - AND sibling."id" <> target."id" - AND lower(sibling."idempotency_key") = lower(target."idempotency_key") + collision."editorial_account_id" = target."editorial_account_id" + AND collision.canonical_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 +-- A legacy new usage is reconstructible only when it has one unique earliest, +-- note-free event and every runtime fingerprint field already satisfies the new +-- normalized input contract. A repeat additionally needs a normalized non-null +-- repeat note after that provable initial event. Every other row is explicit legacy. +WITH earliest_event_times AS ( + SELECT "usage_id", min("authorized_at") AS earliest_authorized_at FROM "download_events" + GROUP BY "usage_id" +), +case_colliding_idempotency_keys AS ( + SELECT "editorial_account_id", lower("idempotency_key") AS canonical_key + FROM "download_events" + GROUP BY "editorial_account_id", lower("idempotency_key") + HAVING count(*) > 1 +), +legacy_event_candidates AS ( + SELECT + events."id", + events."usage_id", + events."authorized_at", + earliest.earliest_authorized_at, + ( + events."repeat_download_note" IS NULL + AND events."editorial_account_id" = usage."editorial_account_id" + AND lower(events."immich_asset_id") = lower(usage."immich_asset_id") + AND events."immich_asset_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND usage."immich_asset_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND usage."immich_album_id_snapshot" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND 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}$' + AND usage."purpose" = btrim(usage."purpose") + AND char_length(usage."purpose") BETWEEN 3 AND 200 + AND ( + usage."internal_reference" IS NULL + OR ( + usage."internal_reference" = btrim(usage."internal_reference") + AND usage."internal_reference" <> '' + AND char_length(usage."internal_reference") <= 200 + ) + ) + AND NOT EXISTS ( + SELECT 1 + FROM case_colliding_idempotency_keys AS collision + WHERE + collision."editorial_account_id" = events."editorial_account_id" + AND collision.canonical_key = lower(events."idempotency_key") + ) + ) AS can_be_initial, + ( + events."editorial_account_id" = usage."editorial_account_id" + AND lower(events."immich_asset_id") = lower(usage."immich_asset_id") + AND events."immich_asset_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND 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}$' + AND events."repeat_download_note" = btrim(events."repeat_download_note") + AND events."repeat_download_note" <> '' + AND char_length(events."repeat_download_note") <= 200 + AND NOT EXISTS ( + SELECT 1 + FROM case_colliding_idempotency_keys AS collision + WHERE + collision."editorial_account_id" = events."editorial_account_id" + AND collision.canonical_key = lower(events."idempotency_key") + ) + ) AS can_be_repeat + FROM "download_events" AS events + INNER JOIN "usages" AS usage ON usage."id" = events."usage_id" + INNER JOIN earliest_event_times AS earliest ON earliest."usage_id" = events."usage_id" +), +usage_event_summary AS ( + SELECT + candidate."usage_id", + candidate.earliest_authorized_at, + count(*) FILTER ( + WHERE candidate."authorized_at" = candidate.earliest_authorized_at + ) AS earliest_event_count, + bool_and( + CASE + WHEN candidate."authorized_at" = candidate.earliest_authorized_at + THEN candidate.can_be_initial + ELSE true + END + ) AS earliest_event_is_provable + FROM legacy_event_candidates AS candidate + GROUP BY candidate."usage_id", candidate.earliest_authorized_at ) UPDATE "download_events" AS events SET "intent_kind" = CASE - WHEN ranked.usage_event_number = 1 THEN 'new_usage' - ELSE 'repeat_download' + WHEN + candidate."authorized_at" = summary.earliest_authorized_at + AND summary.earliest_event_count = 1 + AND candidate.can_be_initial + THEN 'new_usage' + WHEN + candidate."authorized_at" > summary.earliest_authorized_at + AND summary.earliest_event_count = 1 + AND summary.earliest_event_is_provable + AND candidate.can_be_repeat + THEN 'repeat_download' + ELSE 'legacy' 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. +FROM legacy_event_candidates AS candidate, usage_event_summary AS summary +WHERE + candidate."id" = events."id" + AND summary."usage_id" = candidate."usage_id";--> statement-breakpoint +-- Runtime-compatible rows receive the exact SHA-256 used by JSON.stringify in the +-- application. Explicit legacy rows receive a deterministic non-runtime hash. 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( + WHEN 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') || + ',"assetId":' || to_json(lower(events."immich_asset_id"))::text || + ',"albumId":' || to_json(lower(usage."immich_album_id_snapshot"))::text || + ',"purpose":' || to_json(usage."purpose")::text || + ',"reference":' || coalesce(to_json(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( + WHEN 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') || + ',"note":' || to_json(events."repeat_download_note")::text || '}', 'UTF8' )), 'hex') - ELSE encode(sha256(convert_to('unprovable-legacy-intent:' || events."id"::text, 'UTF8')), 'hex') + ELSE encode(sha256(convert_to('legacy-intent-v1:' || events."id"::text, 'UTF8')), 'hex') END FROM "usages" AS usage WHERE usage."id" = events."usage_id";--> statement-breakpoint @@ -77,6 +153,10 @@ ALTER TABLE "download_events" ALTER COLUMN "intent_kind" SET NOT NULL;--> statem 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_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download', 'legacy'));--> statement-breakpoint 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}$'); +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}$');--> statement-breakpoint +ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_canonical_immich_album_id_check" CHECK ("album_grants"."immich_album_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint +ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_immich_asset_id_check" CHECK ("download_events"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint +ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_asset_id_check" CHECK ("usages"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint +ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_album_id_check" CHECK ("usages"."immich_album_id_snapshot" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID; diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json index 65a9bc4..006cf5a 100644 --- a/drizzle/meta/0002_snapshot.json +++ b/drizzle/meta/0002_snapshot.json @@ -1,5 +1,5 @@ { - "id": "f650c8ba-ebde-411d-92d0-caf0f9885c44", + "id": "8944c4e7-b3ab-47b5-a05b-91be6fb5c915", "prevId": "cfd5f4d1-55ac-46d9-9667-cd156f26e070", "version": "7", "dialect": "postgresql", @@ -23,7 +23,7 @@ }, "immich_album_id": { "name": "immich_album_id", - "type": "uuid", + "type": "text", "primaryKey": false, "notNull": true }, @@ -110,7 +110,12 @@ "compositePrimaryKeys": {}, "uniqueConstraints": {}, "policies": {}, - "checkConstraints": {}, + "checkConstraints": { + "album_grants_canonical_immich_album_id_check": { + "name": "album_grants_canonical_immich_album_id_check", + "value": "\"album_grants\".\"immich_album_id\" ~ '^[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 }, "public.audit_events": { @@ -1157,7 +1162,7 @@ }, "immich_asset_id": { "name": "immich_asset_id", - "type": "uuid", + "type": "text", "primaryKey": false, "notNull": true }, @@ -1290,7 +1295,7 @@ "checkConstraints": { "download_events_intent_kind_check": { "name": "download_events_intent_kind_check", - "value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download')" + "value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download', 'legacy')" }, "download_events_request_fingerprint_hex_check": { "name": "download_events_request_fingerprint_hex_check", @@ -1299,6 +1304,10 @@ "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}$'" + }, + "download_events_canonical_immich_asset_id_check": { + "name": "download_events_canonical_immich_asset_id_check", + "value": "\"download_events\".\"immich_asset_id\" ~ '^[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 @@ -1322,7 +1331,7 @@ }, "immich_asset_id": { "name": "immich_asset_id", - "type": "uuid", + "type": "text", "primaryKey": false, "notNull": true }, @@ -1334,7 +1343,7 @@ }, "immich_album_id_snapshot": { "name": "immich_album_id_snapshot", - "type": "uuid", + "type": "text", "primaryKey": false, "notNull": true }, @@ -1416,7 +1425,16 @@ "compositePrimaryKeys": {}, "uniqueConstraints": {}, "policies": {}, - "checkConstraints": {}, + "checkConstraints": { + "usages_canonical_immich_asset_id_check": { + "name": "usages_canonical_immich_asset_id_check", + "value": "\"usages\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + }, + "usages_canonical_immich_album_id_check": { + "name": "usages_canonical_immich_album_id_check", + "value": "\"usages\".\"immich_album_id_snapshot\" ~ '^[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 } }, diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 6b7c036..688ba50 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -19,7 +19,7 @@ { "idx": 2, "version": "7", - "when": 1786352073526, + "when": 1786354215684, "tag": "0002_accounting_intents", "breakpoints": true } diff --git a/src/db/schema/albums.ts b/src/db/schema/albums.ts index e35cb6a..e0c1bb8 100644 --- a/src/db/schema/albums.ts +++ b/src/db/schema/albums.ts @@ -1,4 +1,5 @@ -import { index, pgTable, timestamp, uuid } from "drizzle-orm/pg-core"; +import { sql } from "drizzle-orm"; +import { check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { users } from "./auth"; import { editorialAccounts } from "./editorials"; @@ -10,7 +11,7 @@ export const albumGrants = pgTable( editorialAccountId: uuid("editorial_account_id") .notNull() .references(() => editorialAccounts.id, { onDelete: "restrict" }), - immichAlbumId: uuid("immich_album_id").notNull(), + immichAlbumId: text("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, { @@ -20,5 +21,9 @@ export const albumGrants = pgTable( (table) => [ index("album_grants_editorial_account_id_idx").on(table.editorialAccountId), index("album_grants_immich_album_id_idx").on(table.immichAlbumId), + check( + "album_grants_canonical_immich_album_id_check", + sql`${table.immichAlbumId} ~ '^[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/db/schema/usages.ts b/src/db/schema/usages.ts index cf63588..c24dd63 100644 --- a/src/db/schema/usages.ts +++ b/src/db/schema/usages.ts @@ -28,24 +28,37 @@ export const downloadStatuses = [ ] as const; export const downloadStatus = pgEnum("download_status", downloadStatuses); -export const usages = pgTable("usages", { - id: uuid("id").defaultRandom().primaryKey(), - editorialAccountId: uuid("editorial_account_id") - .notNull() - .references(() => editorialAccounts.id, { onDelete: "restrict" }), - immichAssetId: uuid("immich_asset_id").notNull(), - filenameSnapshot: text("filename_snapshot").notNull(), - immichAlbumIdSnapshot: uuid("immich_album_id_snapshot").notNull(), - albumNameSnapshot: text("album_name_snapshot").notNull(), - purpose: text("purpose").notNull(), - internalReference: text("internal_reference"), - priceCents: integer("price_cents").notNull(), - billingStatus: usageBillingStatus("billing_status").notNull().default("open"), - billingReportId: uuid("billing_report_id").references(() => billingReports.id, { - onDelete: "restrict", - }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), -}); +export const usages = pgTable( + "usages", + { + id: uuid("id").defaultRandom().primaryKey(), + editorialAccountId: uuid("editorial_account_id") + .notNull() + .references(() => editorialAccounts.id, { onDelete: "restrict" }), + immichAssetId: text("immich_asset_id").notNull(), + filenameSnapshot: text("filename_snapshot").notNull(), + immichAlbumIdSnapshot: text("immich_album_id_snapshot").notNull(), + albumNameSnapshot: text("album_name_snapshot").notNull(), + purpose: text("purpose").notNull(), + internalReference: text("internal_reference"), + priceCents: integer("price_cents").notNull(), + billingStatus: usageBillingStatus("billing_status").notNull().default("open"), + billingReportId: uuid("billing_report_id").references(() => billingReports.id, { + onDelete: "restrict", + }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + check( + "usages_canonical_immich_asset_id_check", + sql`${table.immichAssetId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`, + ), + check( + "usages_canonical_immich_album_id_check", + sql`${table.immichAlbumIdSnapshot} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`, + ), + ], +); export const downloadEvents = pgTable( "download_events", @@ -57,7 +70,7 @@ export const downloadEvents = pgTable( usageId: uuid("usage_id") .notNull() .references(() => usages.id, { onDelete: "restrict" }), - immichAssetId: uuid("immich_asset_id").notNull(), + immichAssetId: text("immich_asset_id").notNull(), authorizedAt: timestamp("authorized_at", { withTimezone: true }).notNull().defaultNow(), startedAt: timestamp("started_at", { withTimezone: true }), completedAt: timestamp("completed_at", { withTimezone: true }), @@ -77,7 +90,7 @@ export const downloadEvents = pgTable( ), check( "download_events_intent_kind_check", - sql`${table.intentKind} in ('new_usage', 'repeat_download')`, + sql`${table.intentKind} in ('new_usage', 'repeat_download', 'legacy')`, ), check( "download_events_request_fingerprint_hex_check", @@ -87,5 +100,9 @@ export const downloadEvents = pgTable( "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}$'`, ), + check( + "download_events_canonical_immich_asset_id_check", + sql`${table.immichAssetId} ~ '^[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/albums/grants.test.ts b/src/modules/albums/grants.test.ts index ac210b4..a9bd7aa 100644 --- a/src/modules/albums/grants.test.ts +++ b/src/modules/albums/grants.test.ts @@ -18,6 +18,11 @@ type Audit = { newValues: Record; }; +const editorialUuid = "1111111a-1111-4111-8111-11111111111a"; +const albumUuid = "2222222b-2222-4222-8222-22222222222b"; +const adminUuid = "3333333c-3333-4333-8333-33333333333c"; +const unavailableAlbumUuid = "4444444d-4444-4444-8444-44444444444d"; + function createRepository(initial: Grant[] = []) { const grants = [...initial]; const audit: Audit[] = []; @@ -31,7 +36,7 @@ function createRepository(initial: Grant[] = []) { const active = grants.find( (grant) => grant.editorialId === input.editorialId && - grant.albumId === input.immichAlbumId && + grant.albumId.toLowerCase() === input.immichAlbumId && grant.revokedAt === null, ); if (active) return false; @@ -39,7 +44,7 @@ function createRepository(initial: Grant[] = []) { const revoked = grants.find( (grant) => grant.editorialId === input.editorialId && - grant.albumId === input.immichAlbumId && + grant.albumId.toLowerCase() === input.immichAlbumId && grant.revokedAt !== null, ); if (revoked) { @@ -61,7 +66,7 @@ function createRepository(initial: Grant[] = []) { const active = grants.find( (grant) => grant.editorialId === input.editorialId && - grant.albumId === input.immichAlbumId && + grant.albumId.toLowerCase() === input.immichAlbumId && grant.revokedAt === null, ); if (!active) return false; @@ -84,7 +89,7 @@ function createService(initial: Grant[] = []) { const { repository, grants, audit } = createRepository(initial); const immich = { getAlbum: vi.fn().mockResolvedValue({ - id: "album-1", + id: albumUuid, albumName: "Pressefotos", description: null, albumThumbnailAssetId: "cover-1", @@ -93,7 +98,7 @@ function createService(initial: Grant[] = []) { }), listAlbums: vi.fn().mockResolvedValue([ { - id: "album-1", + id: albumUuid, albumName: "Pressefotos", description: null, albumThumbnailAssetId: "cover-1", @@ -114,23 +119,80 @@ test("refuses to grant an album that the service user cannot read", async () => immich.getAlbum.mockRejectedValue({ code: "IMMICH_NOT_FOUND" }); await expect( - service.grantAlbum({ editorialId: "e1", immichAlbumId: "hidden", adminUserId: "a1" }), + service.grantAlbum({ + editorialId: editorialUuid, + immichAlbumId: unavailableAlbumUuid, + adminUserId: adminUuid, + }), ).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" }); }); +test("canonicalizes UUID grant input before Immich and repository side effects", async () => { + const { service, immich, grants } = createService(); + + await service.grantAlbum({ + editorialId: editorialUuid.toUpperCase(), + immichAlbumId: albumUuid.toUpperCase(), + adminUserId: adminUuid.toUpperCase(), + }); + + expect(immich.getAlbum).toHaveBeenCalledWith(albumUuid); + expect(grants).toEqual([ + { editorialId: editorialUuid, albumId: albumUuid, revokedAt: null }, + ]); +}); + +test("treats an uppercase historical album grant as the canonical active grant", async () => { + const { service, grants, audit } = createService([ + { editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null }, + ]); + + await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]); + await service.grantAlbum({ + editorialId: editorialUuid, + immichAlbumId: albumUuid, + adminUserId: adminUuid, + }); + + expect(grants).toHaveLength(1); + expect(audit).toHaveLength(0); +}); + +test("rejects a non-UUID grant before external side effects", async () => { + const { service, immich, grants } = createService(); + + await expect( + service.grantAlbum({ + editorialId: editorialUuid, + immichAlbumId: "legacy-album", + adminUserId: adminUuid, + }), + ).rejects.toMatchObject({ code: "INVALID_ALBUM_GRANT_INPUT" }); + expect(immich.getAlbum).not.toHaveBeenCalled(); + expect(grants).toHaveLength(0); +}); + test("granting an album is idempotent and records one state-change audit event", async () => { const { service, audit } = createService(); - await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); - await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); + await service.grantAlbum({ + editorialId: editorialUuid, + immichAlbumId: albumUuid, + adminUserId: adminUuid, + }); + await service.grantAlbum({ + editorialId: editorialUuid, + immichAlbumId: albumUuid, + adminUserId: adminUuid, + }); - await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]); + await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]); expect(audit).toEqual([ expect.objectContaining({ eventType: "album_granted", - actorUserId: "a1", - editorialId: "e1", - albumId: "album-1", + actorUserId: adminUuid, + editorialId: editorialUuid, + albumId: albumUuid, previousValues: { granted: false }, newValues: { granted: true }, }), @@ -139,29 +201,41 @@ test("granting an album is idempotent and records one state-change audit event", test("a revoked album can be re-granted without creating another current grant", async () => { const { service, grants } = createService([ - { editorialId: "e1", albumId: "album-1", revokedAt: new Date("2026-08-08T00:00:00Z") }, + { + editorialId: editorialUuid, + albumId: albumUuid, + revokedAt: new Date("2026-08-08T00:00:00Z"), + }, ]); - await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); + await service.grantAlbum({ + editorialId: editorialUuid, + immichAlbumId: albumUuid, + adminUserId: adminUuid, + }); expect(grants).toHaveLength(1); - await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]); + await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]); }); test("revocation immediately removes the album from visible IDs and records the actor", async () => { const { service, audit } = createService([ - { editorialId: "e1", albumId: "album-1", revokedAt: null }, + { editorialId: editorialUuid, albumId: albumUuid, revokedAt: null }, ]); - await service.revokeAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); + await service.revokeAlbum({ + editorialId: editorialUuid, + immichAlbumId: albumUuid, + adminUserId: adminUuid, + }); - await expect(service.getGrantedAlbumIds("e1")).resolves.not.toContain("album-1"); + await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.not.toContain(albumUuid); expect(audit).toContainEqual( expect.objectContaining({ eventType: "album_revoked", - actorUserId: "a1", - editorialId: "e1", - albumId: "album-1", + actorUserId: adminUuid, + editorialId: editorialUuid, + albumId: albumUuid, previousValues: { granted: true }, newValues: { granted: false }, }), @@ -176,7 +250,7 @@ test("reports a stable unavailable error when the Immich album list cannot be lo const { service, immich } = createService(); immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" }); - await expect(service.listAssignableAlbums("e1")).rejects.toEqual( + await expect(service.listAssignableAlbums(editorialUuid)).rejects.toEqual( new AlbumGrantError("IMMICH_UNAVAILABLE"), ); }); diff --git a/src/modules/albums/grants.ts b/src/modules/albums/grants.ts index 9e57733..5f2ec56 100644 --- a/src/modules/albums/grants.ts +++ b/src/modules/albums/grants.ts @@ -49,36 +49,38 @@ export function createAlbumGrantService({ }) { return { async listAssignableAlbums(editorialId: string): Promise { - assertIdentifier(editorialId); + const normalizedEditorialId = normalizeIdentifier(editorialId); const [albums, grantedAlbumIds] = await Promise.all([ loadAlbums(immich), - repository.listActiveAlbumIds(editorialId), + repository.listActiveAlbumIds(normalizedEditorialId), ]); - const granted = new Set(grantedAlbumIds); - return albums.map((album) => ({ ...album, isGranted: granted.has(album.id) })); + const granted = new Set(grantedAlbumIds.map(canonicalizeStoredIdentifier)); + return albums.map((album) => ({ + ...album, + isGranted: granted.has(canonicalizeStoredIdentifier(album.id)), + })); }, async grantAlbum(input: AlbumGrantInput): Promise { - assertInput(input); + const normalizedInput = normalizeInput(input); try { - await immich.getAlbum(input.immichAlbumId); + await immich.getAlbum(normalizedInput.immichAlbumId); } catch (error) { if (hasCode(error, "IMMICH_NOT_FOUND")) { throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE"); } throw new AlbumGrantError("IMMICH_UNAVAILABLE"); } - await repository.grant(input); + await repository.grant(normalizedInput); }, async revokeAlbum(input: AlbumGrantInput): Promise { - assertInput(input); - await repository.revoke(input); + await repository.revoke(normalizeInput(input)); }, async getGrantedAlbumIds(editorialId: string): Promise { - assertIdentifier(editorialId); - return repository.listActiveAlbumIds(editorialId); + const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId)); + return albumIds.map(canonicalizeStoredIdentifier); }, }; } @@ -194,16 +196,30 @@ async function loadAlbums(immich: Pick): Promise { + expect(migration).not.toMatch(/ALTER COLUMN "immich_[^"]+" SET DATA TYPE uuid/); + expect(migration).toContain( + 'ADD CONSTRAINT "album_grants_canonical_immich_album_id_check"', + ); + expect(migration).toContain( + 'ADD CONSTRAINT "usages_canonical_immich_asset_id_check"', + ); + expect(migration).toContain( + 'ADD CONSTRAINT "usages_canonical_immich_album_id_check"', + ); + expect(migration).toContain( + 'ADD CONSTRAINT "download_events_canonical_immich_asset_id_check"', + ); + expect(migration.match(/NOT VALID/g)).toHaveLength(4); +}); + +test("0002 uses an explicit legacy kind instead of random UUID ordering for ambiguity", () => { + expect(migration).not.toContain('ORDER BY "authorized_at", "id"'); + expect(migration).toContain("ELSE 'legacy'"); + expect(migration).toContain("in ('new_usage', 'repeat_download', 'legacy')"); + expect(migration).toContain("case_colliding_idempotency_keys"); +}); diff --git a/tests/db/accounting-migration.test.ts b/tests/db/accounting-migration.test.ts index f7fd030..f3d742e 100644 --- a/tests/db/accounting-migration.test.ts +++ b/tests/db/accounting-migration.test.ts @@ -12,17 +12,66 @@ const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sq afterAll(() => testDb.stop()); -test("0002 preserves an equivalent retry of a populated legacy accounting intent", async () => { +const validAssetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; +const validAlbumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; +const cleanKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; +const collidingKey = "dddddddd-dddd-4ddd-8ddd-dddddddddddd"; +const authorizedAt = new Date("2026-08-09T08:00:00.000Z"); + +async function insertLegacyUsage({ + editorialId, + assetId = validAssetId, + albumId = validAlbumId, + purpose = "Titelgeschichte", + reference = "Ausgabe 8/26", +}: { + editorialId: string; + assetId?: string; + albumId?: string; + purpose?: string; + reference?: string | null; +}) { + const usageId = randomUUID(); + 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', $5, $6, 2300, 'open', $7)`, + [usageId, editorialId, assetId, albumId, purpose, reference, authorizedAt], + ); + return usageId; +} + +async function insertLegacyEvent({ + editorialId, + usageId, + assetId = validAssetId, + idempotencyKey = randomUUID(), + note = null, + at = authorizedAt, +}: { + editorialId: string; + usageId: string; + assetId?: string; + idempotencyKey?: string; + note?: string | null; + at?: Date; +}) { + const eventId = randomUUID(); + await testDb.pool.query( + `insert into download_events ( + id, editorial_account_id, usage_id, immich_asset_id, authorized_at, + status, repeat_download_note, request_id, idempotency_key + ) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8)`, + [eventId, editorialId, usageId, assetId, at, note, randomUUID(), idempotencyKey], + ); + return eventId; +} + +test("0002 preserves dirty rows and reconstructs only provable legacy intents", 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)`, @@ -36,33 +85,69 @@ test("0002 preserves an equivalent retry of a populated legacy accounting intent ); await testDb.pool.query( `insert into album_grants (editorial_account_id, immich_album_id) - values ($1, $2)`, - [editorialId, albumId.toUpperCase()], + values ($1, $2), ($1, $3)`, + [editorialId, validAlbumId.toUpperCase(), "legacy album / 2019"], ); - 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, + + const cleanUsageId = await insertLegacyUsage({ + editorialId, + assetId: validAssetId.toUpperCase(), + albumId: validAlbumId.toUpperCase(), + }); + const cleanEventId = await insertLegacyEvent({ + editorialId, + usageId: cleanUsageId, + assetId: validAssetId.toUpperCase(), + idempotencyKey: cleanKey.toUpperCase(), + }); + + const dirtyAssetId = "legacy-asset/not-a-uuid"; + const dirtyAlbumId = "legacy album / 2019"; + const dirtyUsageId = await insertLegacyUsage({ + editorialId, + assetId: dirtyAssetId, + albumId: dirtyAlbumId, + }); + const dirtyEventId = await insertLegacyEvent({ + editorialId, + usageId: dirtyUsageId, + assetId: dirtyAssetId, + idempotencyKey: "legacy-request", + }); + + const equalTimeUsageId = await insertLegacyUsage({ editorialId }); + const equalTimeEventIds = await Promise.all([ + insertLegacyEvent({ editorialId, usageId: equalTimeUsageId }), + insertLegacyEvent({ editorialId, - usageId, - assetId.toUpperCase(), - authorizedAt, - requestId, - idempotencyKey.toUpperCase(), - ], - ); + usageId: equalTimeUsageId, + note: "Wiederholung", + }), + ]); + + const contradictoryUsageId = await insertLegacyUsage({ editorialId }); + const contradictoryEventId = await insertLegacyEvent({ + editorialId, + usageId: contradictoryUsageId, + note: "Als Wiederholung markiert", + }); + + const collisionUsageIds = await Promise.all([ + insertLegacyUsage({ editorialId }), + insertLegacyUsage({ editorialId }), + ]); + const collisionEventIds = await Promise.all([ + insertLegacyEvent({ + editorialId, + usageId: collisionUsageIds[0], + idempotencyKey: collidingKey.toUpperCase(), + }), + insertLegacyEvent({ + editorialId, + usageId: collisionUsageIds[1], + idempotencyKey: collidingKey, + }), + ]); await testDb.applyRemainingMigrations(); @@ -74,19 +159,19 @@ test("0002 preserves an equivalent retry of a populated legacy accounting intent 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, + await expect( + usageService.createNewUsage({ + editorialId: editorialId.toUpperCase(), + assetId: validAssetId.toUpperCase(), + albumId: validAlbumId.toUpperCase(), + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + idempotencyKey: cleanKey.toUpperCase(), + }), + ).resolves.toEqual({ + id: cleanEventId, + usageId: cleanUsageId, + assetId: validAssetId.toUpperCase(), priceCents: 2300, billable: true, status: "authorized", @@ -95,22 +180,76 @@ test("0002 preserves an equivalent retry of a populated legacy accounting intent 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({ + const migratedEvents = await testDb.pool.query<{ + id: string; + idempotency_key: string; + immich_asset_id: string; + intent_kind: string; + request_fingerprint: string; + }>( + `select id, idempotency_key, immich_asset_id, intent_kind, request_fingerprint + from download_events`, + ); + expect(migratedEvents.rows).toHaveLength(7); + const byId = new Map(migratedEvents.rows.map((row) => [row.id, row])); + expect(byId.get(cleanEventId)).toMatchObject({ + idempotency_key: cleanKey, + immich_asset_id: validAssetId.toUpperCase(), + intent_kind: "new_usage", + request_fingerprint: requestFingerprint({ kind: "new_usage", editorialId, - assetId, - albumId, + assetId: validAssetId, + albumId: validAlbumId, purpose: "Titelgeschichte", reference: "Ausgabe 8/26", }), }); + expect(byId.get(dirtyEventId)).toMatchObject({ + idempotency_key: "legacy-request", + immich_asset_id: dirtyAssetId, + intent_kind: "legacy", + }); + for (const id of [ + ...equalTimeEventIds, + contradictoryEventId, + ...collisionEventIds, + ]) { + expect(byId.get(id)?.intent_kind).toBe("legacy"); + expect(byId.get(id)?.request_fingerprint).toMatch(/^[0-9a-f]{64}$/); + } + expect(collisionEventIds.map((id) => byId.get(id)?.idempotency_key).sort()).toEqual( + [collidingKey.toUpperCase(), collidingKey].sort(), + ); + + const dirtySnapshots = await testDb.pool.query<{ + immich_asset_id: string; + immich_album_id_snapshot: string; + }>("select immich_asset_id, immich_album_id_snapshot from usages where id = $1", [dirtyUsageId]); + expect(dirtySnapshots.rows[0]).toEqual({ + immich_asset_id: dirtyAssetId, + immich_album_id_snapshot: dirtyAlbumId, + }); + const dirtyGrant = await testDb.pool.query<{ immich_album_id: string }>( + "select immich_album_id from album_grants where immich_album_id = $1", + [dirtyAlbumId], + ); + expect(dirtyGrant.rows).toEqual([{ immich_album_id: dirtyAlbumId }]); + + await expect( + usageService.createNewUsage({ + editorialId, + assetId: validAssetId, + albumId: validAlbumId, + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + idempotencyKey: collidingKey, + }), + ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); + + const [cleanEvent] = await testDb.database + .select() + .from(downloadEvents) + .where(eq(downloadEvents.id, cleanEventId)); + expect(cleanEvent).toMatchObject({ legacyIntent: true, intentKind: "new_usage" }); });