fix: preserve legacy accounting migration data

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 11:39:44 +02:00
1 parent 3de1530074
commit 3cdca5c82c
10 files changed
+559 -177

No files matched your search

+126 -46
View File
@@ -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 "intent_kind" text;--> statement-breakpoint
ALTER TABLE "download_events" ADD COLUMN "request_fingerprint" varchar(64);--> 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 ALTER TABLE "download_events" ADD COLUMN "legacy_intent" boolean;--> statement-breakpoint
-- Preserve arbitrary legacy keys, while canonicalizing every legacy UUID key that -- UUID-shaped legacy keys are canonicalized only when doing so is unambiguous.
-- can be retried through the new UUID-only API. New rows are protected below. -- 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 UPDATE "download_events" AS target
SET "idempotency_key" = lower("idempotency_key") SET "idempotency_key" = lower(target."idempotency_key")
WHERE 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}$' 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 ( AND NOT EXISTS (
SELECT 1 SELECT 1
FROM "download_events" AS sibling FROM case_colliding_idempotency_keys AS collision
WHERE WHERE
sibling."editorial_account_id" = target."editorial_account_id" collision."editorial_account_id" = target."editorial_account_id"
AND sibling."id" <> target."id" AND collision.canonical_key = lower(target."idempotency_key")
AND lower(sibling."idempotency_key") = lower(target."idempotency_key")
);--> statement-breakpoint );--> statement-breakpoint
-- Legacy accounting deterministically treats the earliest event for each usage as -- A legacy new usage is reconstructible only when it has one unique earliest,
-- its billable creation intent. Later events are repeat downloads. These are the -- note-free event and every runtime fingerprint field already satisfies the new
-- only intent shapes whose original request can be reconstructed from stored data. -- normalized input contract. A repeat additionally needs a normalized non-null
WITH ranked_legacy_events AS ( -- repeat note after that provable initial event. Every other row is explicit legacy.
SELECT WITH earliest_event_times AS (
"id", SELECT "usage_id", min("authorized_at") AS earliest_authorized_at
row_number() OVER (
PARTITION BY "usage_id"
ORDER BY "authorized_at", "id"
) AS usage_event_number
FROM "download_events" 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 UPDATE "download_events" AS events
SET "intent_kind" = CASE SET "intent_kind" = CASE
WHEN ranked.usage_event_number = 1 THEN 'new_usage' WHEN
ELSE 'repeat_download' 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 END
FROM ranked_legacy_events AS ranked FROM legacy_event_candidates AS candidate, usage_event_summary AS summary
WHERE ranked."id" = events."id";--> statement-breakpoint WHERE
-- The string assembled here deliberately matches JSON.stringify's runtime field candidate."id" = events."id"
-- order. Valid legacy rows therefore receive the same SHA-256 as an equivalent AND summary."usage_id" = candidate."usage_id";--> statement-breakpoint
-- retry; inconsistent rows receive a deterministic fingerprint no request can use. -- 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 UPDATE "download_events" AS events
SET "request_fingerprint" = CASE SET "request_fingerprint" = CASE
WHEN WHEN events."intent_kind" = 'new_usage' THEN encode(sha256(convert_to(
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 || '{"kind":"new_usage","editorialId":' || to_json(events."editorial_account_id"::text)::text ||
',"assetId":' || to_json(events."immich_asset_id"::text)::text || ',"assetId":' || to_json(lower(events."immich_asset_id"))::text ||
',"albumId":' || to_json(usage."immich_album_id_snapshot"::text)::text || ',"albumId":' || to_json(lower(usage."immich_album_id_snapshot"))::text ||
',"purpose":' || to_json(btrim(usage."purpose"))::text || ',"purpose":' || to_json(usage."purpose")::text ||
',"reference":' || coalesce(to_json(nullif(btrim(usage."internal_reference"), ''))::text, 'null') || ',"reference":' || coalesce(to_json(usage."internal_reference")::text, 'null') ||
'}', '}',
'UTF8' 'UTF8'
)), 'hex') )), 'hex')
WHEN WHEN events."intent_kind" = 'repeat_download' THEN encode(sha256(convert_to(
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 || '{"kind":"repeat_download","editorialId":' || to_json(events."editorial_account_id"::text)::text ||
',"usageId":' || to_json(events."usage_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' 'UTF8'
)), 'hex') )), '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 END
FROM "usages" AS usage FROM "usages" AS usage
WHERE usage."id" = events."usage_id";--> statement-breakpoint 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 "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 DEFAULT false;--> statement-breakpoint
ALTER TABLE "download_events" ALTER COLUMN "legacy_intent" SET NOT NULL;--> 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_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;
+26 -8
View File
@@ -1,5 +1,5 @@
{ {
"id": "f650c8ba-ebde-411d-92d0-caf0f9885c44", "id": "8944c4e7-b3ab-47b5-a05b-91be6fb5c915",
"prevId": "cfd5f4d1-55ac-46d9-9667-cd156f26e070", "prevId": "cfd5f4d1-55ac-46d9-9667-cd156f26e070",
"version": "7", "version": "7",
"dialect": "postgresql", "dialect": "postgresql",
@@ -23,7 +23,7 @@
}, },
"immich_album_id": { "immich_album_id": {
"name": "immich_album_id", "name": "immich_album_id",
"type": "uuid", "type": "text",
"primaryKey": false, "primaryKey": false,
"notNull": true "notNull": true
}, },
@@ -110,7 +110,12 @@
"compositePrimaryKeys": {}, "compositePrimaryKeys": {},
"uniqueConstraints": {}, "uniqueConstraints": {},
"policies": {}, "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 "isRLSEnabled": false
}, },
"public.audit_events": { "public.audit_events": {
@@ -1157,7 +1162,7 @@
}, },
"immich_asset_id": { "immich_asset_id": {
"name": "immich_asset_id", "name": "immich_asset_id",
"type": "uuid", "type": "text",
"primaryKey": false, "primaryKey": false,
"notNull": true "notNull": true
}, },
@@ -1290,7 +1295,7 @@
"checkConstraints": { "checkConstraints": {
"download_events_intent_kind_check": { "download_events_intent_kind_check": {
"name": "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": { "download_events_request_fingerprint_hex_check": {
"name": "download_events_request_fingerprint_hex_check", "name": "download_events_request_fingerprint_hex_check",
@@ -1299,6 +1304,10 @@
"download_events_canonical_idempotency_key_check": { "download_events_canonical_idempotency_key_check": {
"name": "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}$'" "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 "isRLSEnabled": false
@@ -1322,7 +1331,7 @@
}, },
"immich_asset_id": { "immich_asset_id": {
"name": "immich_asset_id", "name": "immich_asset_id",
"type": "uuid", "type": "text",
"primaryKey": false, "primaryKey": false,
"notNull": true "notNull": true
}, },
@@ -1334,7 +1343,7 @@
}, },
"immich_album_id_snapshot": { "immich_album_id_snapshot": {
"name": "immich_album_id_snapshot", "name": "immich_album_id_snapshot",
"type": "uuid", "type": "text",
"primaryKey": false, "primaryKey": false,
"notNull": true "notNull": true
}, },
@@ -1416,7 +1425,16 @@
"compositePrimaryKeys": {}, "compositePrimaryKeys": {},
"uniqueConstraints": {}, "uniqueConstraints": {},
"policies": {}, "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 "isRLSEnabled": false
} }
}, },
+1 -1
View File
@@ -19,7 +19,7 @@
{ {
"idx": 2, "idx": 2,
"version": "7", "version": "7",
"when": 1786352073526, "when": 1786354215684,
"tag": "0002_accounting_intents", "tag": "0002_accounting_intents",
"breakpoints": true "breakpoints": true
} }
+7 -2
View File
@@ -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 { users } from "./auth";
import { editorialAccounts } from "./editorials"; import { editorialAccounts } from "./editorials";
@@ -10,7 +11,7 @@ export const albumGrants = pgTable(
editorialAccountId: uuid("editorial_account_id") editorialAccountId: uuid("editorial_account_id")
.notNull() .notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }), .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(), grantedAt: timestamp("granted_at", { withTimezone: true }).notNull().defaultNow(),
revokedAt: timestamp("revoked_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }),
grantedByUserId: uuid("granted_by_user_id").references(() => users.id, { grantedByUserId: uuid("granted_by_user_id").references(() => users.id, {
@@ -20,5 +21,9 @@ export const albumGrants = pgTable(
(table) => [ (table) => [
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId), index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
index("album_grants_immich_album_id_idx").on(table.immichAlbumId), 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}$'`,
),
], ],
); );
+37 -20
View File
@@ -28,24 +28,37 @@ export const downloadStatuses = [
] as const; ] as const;
export const downloadStatus = pgEnum("download_status", downloadStatuses); export const downloadStatus = pgEnum("download_status", downloadStatuses);
export const usages = pgTable("usages", { export const usages = pgTable(
id: uuid("id").defaultRandom().primaryKey(), "usages",
editorialAccountId: uuid("editorial_account_id") {
.notNull() id: uuid("id").defaultRandom().primaryKey(),
.references(() => editorialAccounts.id, { onDelete: "restrict" }), editorialAccountId: uuid("editorial_account_id")
immichAssetId: uuid("immich_asset_id").notNull(), .notNull()
filenameSnapshot: text("filename_snapshot").notNull(), .references(() => editorialAccounts.id, { onDelete: "restrict" }),
immichAlbumIdSnapshot: uuid("immich_album_id_snapshot").notNull(), immichAssetId: text("immich_asset_id").notNull(),
albumNameSnapshot: text("album_name_snapshot").notNull(), filenameSnapshot: text("filename_snapshot").notNull(),
purpose: text("purpose").notNull(), immichAlbumIdSnapshot: text("immich_album_id_snapshot").notNull(),
internalReference: text("internal_reference"), albumNameSnapshot: text("album_name_snapshot").notNull(),
priceCents: integer("price_cents").notNull(), purpose: text("purpose").notNull(),
billingStatus: usageBillingStatus("billing_status").notNull().default("open"), internalReference: text("internal_reference"),
billingReportId: uuid("billing_report_id").references(() => billingReports.id, { priceCents: integer("price_cents").notNull(),
onDelete: "restrict", billingStatus: usageBillingStatus("billing_status").notNull().default("open"),
}), billingReportId: uuid("billing_report_id").references(() => billingReports.id, {
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), 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( export const downloadEvents = pgTable(
"download_events", "download_events",
@@ -57,7 +70,7 @@ export const downloadEvents = pgTable(
usageId: uuid("usage_id") usageId: uuid("usage_id")
.notNull() .notNull()
.references(() => usages.id, { onDelete: "restrict" }), .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(), authorizedAt: timestamp("authorized_at", { withTimezone: true }).notNull().defaultNow(),
startedAt: timestamp("started_at", { withTimezone: true }), startedAt: timestamp("started_at", { withTimezone: true }),
completedAt: timestamp("completed_at", { withTimezone: true }), completedAt: timestamp("completed_at", { withTimezone: true }),
@@ -77,7 +90,7 @@ export const downloadEvents = pgTable(
), ),
check( check(
"download_events_intent_kind_check", "download_events_intent_kind_check",
sql`${table.intentKind} in ('new_usage', 'repeat_download')`, sql`${table.intentKind} in ('new_usage', 'repeat_download', 'legacy')`,
), ),
check( check(
"download_events_request_fingerprint_hex_check", "download_events_request_fingerprint_hex_check",
@@ -87,5 +100,9 @@ export const downloadEvents = pgTable(
"download_events_canonical_idempotency_key_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}$'`, 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}$'`,
),
], ],
); );
+96 -22
View File
@@ -18,6 +18,11 @@ type Audit = {
newValues: Record<string, unknown>; newValues: Record<string, unknown>;
}; };
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[] = []) { function createRepository(initial: Grant[] = []) {
const grants = [...initial]; const grants = [...initial];
const audit: Audit[] = []; const audit: Audit[] = [];
@@ -31,7 +36,7 @@ function createRepository(initial: Grant[] = []) {
const active = grants.find( const active = grants.find(
(grant) => (grant) =>
grant.editorialId === input.editorialId && grant.editorialId === input.editorialId &&
grant.albumId === input.immichAlbumId && grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt === null, grant.revokedAt === null,
); );
if (active) return false; if (active) return false;
@@ -39,7 +44,7 @@ function createRepository(initial: Grant[] = []) {
const revoked = grants.find( const revoked = grants.find(
(grant) => (grant) =>
grant.editorialId === input.editorialId && grant.editorialId === input.editorialId &&
grant.albumId === input.immichAlbumId && grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt !== null, grant.revokedAt !== null,
); );
if (revoked) { if (revoked) {
@@ -61,7 +66,7 @@ function createRepository(initial: Grant[] = []) {
const active = grants.find( const active = grants.find(
(grant) => (grant) =>
grant.editorialId === input.editorialId && grant.editorialId === input.editorialId &&
grant.albumId === input.immichAlbumId && grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt === null, grant.revokedAt === null,
); );
if (!active) return false; if (!active) return false;
@@ -84,7 +89,7 @@ function createService(initial: Grant[] = []) {
const { repository, grants, audit } = createRepository(initial); const { repository, grants, audit } = createRepository(initial);
const immich = { const immich = {
getAlbum: vi.fn().mockResolvedValue({ getAlbum: vi.fn().mockResolvedValue({
id: "album-1", id: albumUuid,
albumName: "Pressefotos", albumName: "Pressefotos",
description: null, description: null,
albumThumbnailAssetId: "cover-1", albumThumbnailAssetId: "cover-1",
@@ -93,7 +98,7 @@ function createService(initial: Grant[] = []) {
}), }),
listAlbums: vi.fn().mockResolvedValue([ listAlbums: vi.fn().mockResolvedValue([
{ {
id: "album-1", id: albumUuid,
albumName: "Pressefotos", albumName: "Pressefotos",
description: null, description: null,
albumThumbnailAssetId: "cover-1", 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" }); immich.getAlbum.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
await expect( await expect(
service.grantAlbum({ editorialId: "e1", immichAlbumId: "hidden", adminUserId: "a1" }), service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: unavailableAlbumUuid,
adminUserId: adminUuid,
}),
).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" }); ).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 () => { test("granting an album is idempotent and records one state-change audit event", async () => {
const { service, audit } = createService(); const { service, audit } = createService();
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); await service.grantAlbum({
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); 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(audit).toEqual([
expect.objectContaining({ expect.objectContaining({
eventType: "album_granted", eventType: "album_granted",
actorUserId: "a1", actorUserId: adminUuid,
editorialId: "e1", editorialId: editorialUuid,
albumId: "album-1", albumId: albumUuid,
previousValues: { granted: false }, previousValues: { granted: false },
newValues: { granted: true }, 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 () => { test("a revoked album can be re-granted without creating another current grant", async () => {
const { service, grants } = createService([ 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); 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 () => { test("revocation immediately removes the album from visible IDs and records the actor", async () => {
const { service, audit } = createService([ 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(audit).toContainEqual(
expect.objectContaining({ expect.objectContaining({
eventType: "album_revoked", eventType: "album_revoked",
actorUserId: "a1", actorUserId: adminUuid,
editorialId: "e1", editorialId: editorialUuid,
albumId: "album-1", albumId: albumUuid,
previousValues: { granted: true }, previousValues: { granted: true },
newValues: { granted: false }, 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(); const { service, immich } = createService();
immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" }); immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" });
await expect(service.listAssignableAlbums("e1")).rejects.toEqual( await expect(service.listAssignableAlbums(editorialUuid)).rejects.toEqual(
new AlbumGrantError("IMMICH_UNAVAILABLE"), new AlbumGrantError("IMMICH_UNAVAILABLE"),
); );
}); });
+34 -18
View File
@@ -49,36 +49,38 @@ export function createAlbumGrantService({
}) { }) {
return { return {
async listAssignableAlbums(editorialId: string): Promise<AssignableAlbum[]> { async listAssignableAlbums(editorialId: string): Promise<AssignableAlbum[]> {
assertIdentifier(editorialId); const normalizedEditorialId = normalizeIdentifier(editorialId);
const [albums, grantedAlbumIds] = await Promise.all([ const [albums, grantedAlbumIds] = await Promise.all([
loadAlbums(immich), loadAlbums(immich),
repository.listActiveAlbumIds(editorialId), repository.listActiveAlbumIds(normalizedEditorialId),
]); ]);
const granted = new Set(grantedAlbumIds); const granted = new Set(grantedAlbumIds.map(canonicalizeStoredIdentifier));
return albums.map((album) => ({ ...album, isGranted: granted.has(album.id) })); return albums.map((album) => ({
...album,
isGranted: granted.has(canonicalizeStoredIdentifier(album.id)),
}));
}, },
async grantAlbum(input: AlbumGrantInput): Promise<void> { async grantAlbum(input: AlbumGrantInput): Promise<void> {
assertInput(input); const normalizedInput = normalizeInput(input);
try { try {
await immich.getAlbum(input.immichAlbumId); await immich.getAlbum(normalizedInput.immichAlbumId);
} catch (error) { } catch (error) {
if (hasCode(error, "IMMICH_NOT_FOUND")) { if (hasCode(error, "IMMICH_NOT_FOUND")) {
throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE"); throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE");
} }
throw new AlbumGrantError("IMMICH_UNAVAILABLE"); throw new AlbumGrantError("IMMICH_UNAVAILABLE");
} }
await repository.grant(input); await repository.grant(normalizedInput);
}, },
async revokeAlbum(input: AlbumGrantInput): Promise<void> { async revokeAlbum(input: AlbumGrantInput): Promise<void> {
assertInput(input); await repository.revoke(normalizeInput(input));
await repository.revoke(input);
}, },
async getGrantedAlbumIds(editorialId: string): Promise<string[]> { async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
assertIdentifier(editorialId); const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId));
return repository.listActiveAlbumIds(editorialId); return albumIds.map(canonicalizeStoredIdentifier);
}, },
}; };
} }
@@ -194,16 +196,30 @@ async function loadAlbums(immich: Pick<ImmichClient, "listAlbums">): Promise<Imm
} }
} }
function assertInput(input: AlbumGrantInput): void { function normalizeInput(input: AlbumGrantInput): AlbumGrantInput {
assertIdentifier(input.editorialId); return {
assertIdentifier(input.immichAlbumId); editorialId: normalizeIdentifier(input.editorialId),
assertIdentifier(input.adminUserId); immichAlbumId: normalizeIdentifier(input.immichAlbumId),
adminUserId: normalizeIdentifier(input.adminUserId),
};
} }
function assertIdentifier(value: string): void { function normalizeIdentifier(value: string): string {
if (!value.trim()) { if (
typeof value !== "string" ||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
) {
throw new AlbumGrantError("INVALID_ALBUM_GRANT_INPUT"); throw new AlbumGrantError("INVALID_ALBUM_GRANT_INPUT");
} }
return value.toLowerCase();
}
function canonicalizeStoredIdentifier(value: string): string {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value,
)
? value.toLowerCase()
: value;
} }
function hasCode(error: unknown, code: string): boolean { function hasCode(error: unknown, code: string): boolean {
@@ -246,7 +262,7 @@ async function lockAlbumGrants(
.where( .where(
and( and(
eq(albumGrants.editorialAccountId, editorialId), eq(albumGrants.editorialAccountId, editorialId),
eq(albumGrants.immichAlbumId, immichAlbumId), sql`lower(${albumGrants.immichAlbumId}) = ${immichAlbumId}`,
), ),
) )
.for("update"); .for("update");
+1 -1
View File
@@ -154,7 +154,7 @@ export function createUsageServiceRepository(
.where( .where(
and( and(
eq(albumGrants.editorialAccountId, input.editorialId), eq(albumGrants.editorialAccountId, input.editorialId),
eq(albumGrants.immichAlbumId, input.albumId), sql`lower(${albumGrants.immichAlbumId}) = ${input.albumId}`,
isNull(albumGrants.revokedAt), isNull(albumGrants.revokedAt),
), ),
) )
+33
View File
@@ -0,0 +1,33 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test } from "vitest";
const migration = await readFile(
path.join(process.cwd(), "drizzle/0002_accounting_intents.sql"),
"utf8",
);
test("0002 retains legacy Immich text and gates only new non-canonical rows", () => {
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");
});
+198 -59
View File
@@ -12,17 +12,66 @@ const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sq
afterAll(() => testDb.stop()); 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 userId = randomUUID();
const editorialId = 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( await testDb.pool.query(
`insert into users (id, name, email, email_verified) `insert into users (id, name, email, email_verified)
values ($1, 'Legacy Redaktion', $2, true)`, 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( await testDb.pool.query(
`insert into album_grants (editorial_account_id, immich_album_id) `insert into album_grants (editorial_account_id, immich_album_id)
values ($1, $2)`, values ($1, $2), ($1, $3)`,
[editorialId, albumId.toUpperCase()], [editorialId, validAlbumId.toUpperCase(), "legacy album / 2019"],
); );
await testDb.pool.query(
`insert into usages ( const cleanUsageId = await insertLegacyUsage({
id, editorial_account_id, immich_asset_id, filename_snapshot, editorialId,
immich_album_id_snapshot, album_name_snapshot, purpose, assetId: validAssetId.toUpperCase(),
internal_reference, price_cents, billing_status, created_at albumId: validAlbumId.toUpperCase(),
) values ($1, $2, $3, 'legacy.jpg', $4, 'Legacy Album', });
'Titelgeschichte', 'Ausgabe 8/26', 2300, 'open', $5)`, const cleanEventId = await insertLegacyEvent({
[usageId, editorialId, assetId.toUpperCase(), albumId.toUpperCase(), authorizedAt], editorialId,
); usageId: cleanUsageId,
await testDb.pool.query( assetId: validAssetId.toUpperCase(),
`insert into download_events ( idempotencyKey: cleanKey.toUpperCase(),
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)`, const dirtyAssetId = "legacy-asset/not-a-uuid";
[ const dirtyAlbumId = "legacy album / 2019";
eventId, 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, editorialId,
usageId, usageId: equalTimeUsageId,
assetId.toUpperCase(), note: "Wiederholung",
authorizedAt, }),
requestId, ]);
idempotencyKey.toUpperCase(),
], 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(); await testDb.applyRemainingMigrations();
@@ -74,19 +159,19 @@ test("0002 preserves an equivalent retry of a populated legacy accounting intent
repository: createUsageServiceRepository(testDb.database), repository: createUsageServiceRepository(testDb.database),
immich, immich,
}); });
const input = { await expect(
editorialId: editorialId.toUpperCase(), usageService.createNewUsage({
assetId: assetId.toUpperCase(), editorialId: editorialId.toUpperCase(),
albumId: albumId.toUpperCase(), assetId: validAssetId.toUpperCase(),
purpose: "Titelgeschichte", albumId: validAlbumId.toUpperCase(),
reference: "Ausgabe 8/26", purpose: "Titelgeschichte",
idempotencyKey: idempotencyKey.toUpperCase(), reference: "Ausgabe 8/26",
}; idempotencyKey: cleanKey.toUpperCase(),
}),
await expect(usageService.createNewUsage(input)).resolves.toEqual({ ).resolves.toEqual({
id: eventId, id: cleanEventId,
usageId, usageId: cleanUsageId,
assetId, assetId: validAssetId.toUpperCase(),
priceCents: 2300, priceCents: 2300,
billable: true, billable: true,
status: "authorized", 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.listAlbumsForAsset).not.toHaveBeenCalled();
expect(immich.getAsset).not.toHaveBeenCalled(); expect(immich.getAsset).not.toHaveBeenCalled();
const [migrated] = await testDb.database const migratedEvents = await testDb.pool.query<{
.select() id: string;
.from(downloadEvents) idempotency_key: string;
.where(eq(downloadEvents.id, eventId)); immich_asset_id: string;
expect(migrated).toMatchObject({ intent_kind: string;
immichAssetId: assetId, request_fingerprint: string;
idempotencyKey, }>(
intentKind: "new_usage", `select id, idempotency_key, immich_asset_id, intent_kind, request_fingerprint
legacyIntent: true, from download_events`,
requestFingerprint: requestFingerprint({ );
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", kind: "new_usage",
editorialId, editorialId,
assetId, assetId: validAssetId,
albumId, albumId: validAlbumId,
purpose: "Titelgeschichte", purpose: "Titelgeschichte",
reference: "Ausgabe 8/26", 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" });
}); });