fix: harden usage accounting idempotency
This commit is contained in:
1 parent
22fe6bf659
commit
3de1530074
14 files changed
+708
-107
No files matched your search
@@ -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
|
ALTER TABLE "download_events" ADD COLUMN "request_fingerprint" varchar(64);--> statement-breakpoint
|
||||||
UPDATE "download_events"
|
ALTER TABLE "download_events" ADD COLUMN "legacy_intent" boolean;--> statement-breakpoint
|
||||||
SET "request_fingerprint" = md5("editorial_account_id"::text || ':' || "id"::text) || md5("id"::text || ':' || "editorial_account_id"::text);--> 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 "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'));--> 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}$');
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"id": "0cdb7b32-1eb5-4dcf-9949-3862dbbad2b4",
|
"id": "f650c8ba-ebde-411d-92d0-caf0f9885c44",
|
||||||
"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": "text",
|
"type": "uuid",
|
||||||
"primaryKey": false,
|
"primaryKey": false,
|
||||||
"notNull": true
|
"notNull": true
|
||||||
},
|
},
|
||||||
@@ -1157,7 +1157,7 @@
|
|||||||
},
|
},
|
||||||
"immich_asset_id": {
|
"immich_asset_id": {
|
||||||
"name": "immich_asset_id",
|
"name": "immich_asset_id",
|
||||||
"type": "text",
|
"type": "uuid",
|
||||||
"primaryKey": false,
|
"primaryKey": false,
|
||||||
"notNull": true
|
"notNull": true
|
||||||
},
|
},
|
||||||
@@ -1224,6 +1224,13 @@
|
|||||||
"type": "varchar(64)",
|
"type": "varchar(64)",
|
||||||
"primaryKey": false,
|
"primaryKey": false,
|
||||||
"notNull": true
|
"notNull": true
|
||||||
|
},
|
||||||
|
"legacy_intent": {
|
||||||
|
"name": "legacy_intent",
|
||||||
|
"type": "boolean",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"indexes": {
|
"indexes": {
|
||||||
@@ -1288,6 +1295,10 @@
|
|||||||
"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",
|
||||||
"value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'"
|
"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
|
"isRLSEnabled": false
|
||||||
@@ -1311,7 +1322,7 @@
|
|||||||
},
|
},
|
||||||
"immich_asset_id": {
|
"immich_asset_id": {
|
||||||
"name": "immich_asset_id",
|
"name": "immich_asset_id",
|
||||||
"type": "text",
|
"type": "uuid",
|
||||||
"primaryKey": false,
|
"primaryKey": false,
|
||||||
"notNull": true
|
"notNull": true
|
||||||
},
|
},
|
||||||
@@ -1323,7 +1334,7 @@
|
|||||||
},
|
},
|
||||||
"immich_album_id_snapshot": {
|
"immich_album_id_snapshot": {
|
||||||
"name": "immich_album_id_snapshot",
|
"name": "immich_album_id_snapshot",
|
||||||
"type": "text",
|
"type": "uuid",
|
||||||
"primaryKey": false,
|
"primaryKey": false,
|
||||||
"notNull": true
|
"notNull": true
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
{
|
{
|
||||||
"idx": 2,
|
"idx": 2,
|
||||||
"version": "7",
|
"version": "7",
|
||||||
"when": 1786308409516,
|
"when": 1786352073526,
|
||||||
"tag": "0002_accounting_intents",
|
"tag": "0002_accounting_intents",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 { users } from "./auth";
|
||||||
import { editorialAccounts } from "./editorials";
|
import { editorialAccounts } from "./editorials";
|
||||||
@@ -10,7 +10,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: text("immich_album_id").notNull(),
|
immichAlbumId: uuid("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, {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { sql } from "drizzle-orm";
|
import { sql } from "drizzle-orm";
|
||||||
import {
|
import {
|
||||||
bigint,
|
bigint,
|
||||||
|
boolean,
|
||||||
check,
|
check,
|
||||||
integer,
|
integer,
|
||||||
pgEnum,
|
pgEnum,
|
||||||
@@ -32,9 +33,9 @@ export const usages = pgTable("usages", {
|
|||||||
editorialAccountId: uuid("editorial_account_id")
|
editorialAccountId: uuid("editorial_account_id")
|
||||||
.notNull()
|
.notNull()
|
||||||
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
|
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
|
||||||
immichAssetId: text("immich_asset_id").notNull(),
|
immichAssetId: uuid("immich_asset_id").notNull(),
|
||||||
filenameSnapshot: text("filename_snapshot").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(),
|
albumNameSnapshot: text("album_name_snapshot").notNull(),
|
||||||
purpose: text("purpose").notNull(),
|
purpose: text("purpose").notNull(),
|
||||||
internalReference: text("internal_reference"),
|
internalReference: text("internal_reference"),
|
||||||
@@ -56,7 +57,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: text("immich_asset_id").notNull(),
|
immichAssetId: uuid("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 }),
|
||||||
@@ -67,6 +68,7 @@ export const downloadEvents = pgTable(
|
|||||||
idempotencyKey: text("idempotency_key").notNull(),
|
idempotencyKey: text("idempotency_key").notNull(),
|
||||||
intentKind: text("intent_kind").notNull().default("new_usage"),
|
intentKind: text("intent_kind").notNull().default("new_usage"),
|
||||||
requestFingerprint: varchar("request_fingerprint", { length: 64 }).notNull(),
|
requestFingerprint: varchar("request_fingerprint", { length: 64 }).notNull(),
|
||||||
|
legacyIntent: boolean("legacy_intent").notNull().default(false),
|
||||||
},
|
},
|
||||||
(table) => [
|
(table) => [
|
||||||
uniqueIndex("download_events_editorial_idempotency_key_unique").on(
|
uniqueIndex("download_events_editorial_idempotency_key_unique").on(
|
||||||
@@ -81,5 +83,9 @@ export const downloadEvents = pgTable(
|
|||||||
"download_events_request_fingerprint_hex_check",
|
"download_events_request_fingerprint_hex_check",
|
||||||
sql`${table.requestFingerprint} ~ '^[0-9a-f]{64}$'`,
|
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}$'`,
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -8,9 +8,10 @@ import {
|
|||||||
} from "./service";
|
} from "./service";
|
||||||
import { UsageAccountingError } from "@/modules/usages/types";
|
import { UsageAccountingError } from "@/modules/usages/types";
|
||||||
|
|
||||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
const editorialId = "1111111a-1111-4111-8111-11111111111a";
|
||||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
const usageId = "4444444d-4444-4444-8444-44444444444d";
|
||||||
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
const idempotencyKey = "5555555e-5555-4555-8555-55555555555e";
|
||||||
|
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
|
||||||
function createService() {
|
function createService() {
|
||||||
const intents = new Map<string, PersistedRepeatIntent>();
|
const intents = new Map<string, PersistedRepeatIntent>();
|
||||||
@@ -33,7 +34,7 @@ function createService() {
|
|||||||
const intent: PersistedRepeatIntent = {
|
const intent: PersistedRepeatIntent = {
|
||||||
id: `download-${events.length}`,
|
id: `download-${events.length}`,
|
||||||
usageId: input.usageId,
|
usageId: input.usageId,
|
||||||
assetId: "asset-1",
|
assetId,
|
||||||
priceCents: 0,
|
priceCents: 0,
|
||||||
billable: false,
|
billable: false,
|
||||||
status: "authorized",
|
status: "authorized",
|
||||||
@@ -77,7 +78,7 @@ test("creates only a free authorized event for an owned prior usage", async () =
|
|||||||
|
|
||||||
expect(intent).toMatchObject({
|
expect(intent).toMatchObject({
|
||||||
usageId,
|
usageId,
|
||||||
assetId: "asset-1",
|
assetId,
|
||||||
priceCents: 0,
|
priceCents: 0,
|
||||||
billable: false,
|
billable: false,
|
||||||
status: "authorized",
|
status: "authorized",
|
||||||
@@ -126,6 +127,23 @@ test("returns the same free intent once for an equivalent retry", async () => {
|
|||||||
expect(events).toHaveLength(1);
|
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 () => {
|
test("rejects reuse of a repeat key with a materially different note", async () => {
|
||||||
const { service, events } = createService();
|
const { service, events } = createService();
|
||||||
await service.createRepeatDownload({ editorialId, usageId, note: "Web", idempotencyKey });
|
await service.createRepeatDownload({ editorialId, usageId, note: "Web", idempotencyKey });
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ import { db } from "@/db/client";
|
|||||||
import { downloadEvents, editorialAccounts, usages } from "@/db/schema";
|
import { downloadEvents, editorialAccounts, usages } from "@/db/schema";
|
||||||
import type * as schema from "@/db/schema";
|
import type * as schema from "@/db/schema";
|
||||||
import {
|
import {
|
||||||
assertUuid,
|
|
||||||
type CreateRepeatDownloadInput,
|
type CreateRepeatDownloadInput,
|
||||||
type DownloadIntent,
|
type DownloadIntent,
|
||||||
normalizeOptionalText,
|
normalizeOptionalText,
|
||||||
|
normalizeUuid,
|
||||||
requestFingerprint,
|
requestFingerprint,
|
||||||
UsageAccountingError,
|
UsageAccountingError,
|
||||||
} from "@/modules/usages/types";
|
} from "@/modules/usages/types";
|
||||||
@@ -71,6 +71,13 @@ export function createRepeatDownloadRepository(
|
|||||||
try {
|
try {
|
||||||
return await database.transaction(async (transaction) => {
|
return await database.transaction(async (transaction) => {
|
||||||
await lockEditorialAccounting(transaction, input.editorialId);
|
await lockEditorialAccounting(transaction, input.editorialId);
|
||||||
|
const existing = await findPersistedIntent(
|
||||||
|
transaction,
|
||||||
|
input.editorialId,
|
||||||
|
input.idempotencyKey,
|
||||||
|
);
|
||||||
|
if (existing) return asRepeatIntent(existing);
|
||||||
|
|
||||||
const [editorial] = await transaction
|
const [editorial] = await transaction
|
||||||
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
|
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
|
||||||
.from(editorialAccounts)
|
.from(editorialAccounts)
|
||||||
@@ -81,13 +88,6 @@ export function createRepeatDownloadRepository(
|
|||||||
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = await findPersistedIntent(
|
|
||||||
transaction,
|
|
||||||
input.editorialId,
|
|
||||||
input.idempotencyKey,
|
|
||||||
);
|
|
||||||
if (existing) return asRepeatIntent(existing);
|
|
||||||
|
|
||||||
const [usage] = await transaction
|
const [usage] = await transaction
|
||||||
.select({ id: usages.id, assetId: usages.immichAssetId })
|
.select({ id: usages.id, assetId: usages.immichAssetId })
|
||||||
.from(usages)
|
.from(usages)
|
||||||
@@ -149,15 +149,12 @@ export function createRepeatDownloadRepository(
|
|||||||
|
|
||||||
function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput {
|
function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput {
|
||||||
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
|
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);
|
const note = normalizeOptionalText(input.note, 200);
|
||||||
return {
|
return {
|
||||||
editorialId: input.editorialId,
|
editorialId: normalizeUuid(input.editorialId),
|
||||||
usageId: input.usageId,
|
usageId: normalizeUuid(input.usageId),
|
||||||
...(note === undefined ? {} : { note }),
|
...(note === undefined ? {} : { note }),
|
||||||
idempotencyKey: input.idempotencyKey,
|
idempotencyKey: normalizeUuid(input.idempotencyKey),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,13 +8,16 @@ import {
|
|||||||
} from "./service";
|
} from "./service";
|
||||||
import { UsageAccountingError, type PriorUsage } from "./types";
|
import { UsageAccountingError, type PriorUsage } from "./types";
|
||||||
|
|
||||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
const editorialId = "1111111a-1111-4111-8111-11111111111a";
|
||||||
const idempotencyKey = "22222222-2222-4222-8222-222222222222";
|
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 = {
|
const newUsageInput = {
|
||||||
editorialId,
|
editorialId,
|
||||||
assetId: "asset-1",
|
assetId,
|
||||||
albumId: "album-1",
|
albumId,
|
||||||
purpose: "Titelgeschichte",
|
purpose: "Titelgeschichte",
|
||||||
reference: "Ausgabe 8/26",
|
reference: "Ausgabe 8/26",
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
@@ -31,18 +34,22 @@ function createRepository() {
|
|||||||
async findIntent(requestEditorialId, key) {
|
async findIntent(requestEditorialId, key) {
|
||||||
return intents.get(`${requestEditorialId}:${key}`) ?? null;
|
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") {
|
if (status !== "active") {
|
||||||
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
||||||
}
|
}
|
||||||
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
|
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
|
||||||
throw new UsageAccountingError("INVALID_PRICE");
|
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 = {
|
const intent: PersistedDownloadIntent = {
|
||||||
id: `download-${intents.size + 1}`,
|
id: `download-${intents.size + 1}`,
|
||||||
usageId: `usage-${usages.length}`,
|
usageId: `usage-${usages.length}`,
|
||||||
@@ -81,21 +88,21 @@ function createService() {
|
|||||||
const immich = {
|
const immich = {
|
||||||
listAlbumsForAsset: vi.fn().mockResolvedValue([
|
listAlbumsForAsset: vi.fn().mockResolvedValue([
|
||||||
{
|
{
|
||||||
id: "album-1",
|
id: albumId,
|
||||||
albumName: "Presse 2026",
|
albumName: "Presse 2026",
|
||||||
description: null,
|
description: null,
|
||||||
albumThumbnailAssetId: "asset-1",
|
albumThumbnailAssetId: assetId,
|
||||||
assetCount: 1,
|
assetCount: 1,
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
getAsset: vi.fn().mockResolvedValue({
|
getAsset: vi.fn().mockResolvedValue({
|
||||||
id: "asset-1",
|
id: assetId,
|
||||||
type: "IMAGE" as const,
|
type: "IMAGE" as const,
|
||||||
originalFileName: "jubel.jpg",
|
originalFileName: "jubel.jpg",
|
||||||
originalMimeType: "image/jpeg",
|
originalMimeType: "image/jpeg",
|
||||||
localDateTime: null,
|
localDateTime: null,
|
||||||
fileCreatedAt: null,
|
fileCreatedAt: null,
|
||||||
albums: [{ id: "album-1" }],
|
albums: [{ id: albumId }],
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
return { ...state, immich, service: createUsageService({ repository: state.repository, immich }) };
|
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(intent).toMatchObject({ priceCents: 1_500, billable: true, status: "authorized" });
|
||||||
expect(usages).toEqual([
|
expect(usages).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
assetId: "asset-1",
|
assetId,
|
||||||
albumId: "album-1",
|
albumId,
|
||||||
albumName: "Presse 2026",
|
albumName: "Presse 2026",
|
||||||
filename: "jubel.jpg",
|
filename: "jubel.jpg",
|
||||||
purpose: "Titelgeschichte",
|
purpose: "Titelgeschichte",
|
||||||
@@ -131,7 +138,26 @@ test("returns the exact persisted intent for an equivalent idempotent retry", as
|
|||||||
|
|
||||||
expect(second).toEqual(first);
|
expect(second).toEqual(first);
|
||||||
expect(usages).toHaveLength(1);
|
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 () => {
|
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();
|
const { service, immich, usages } = createService();
|
||||||
immich.listAlbumsForAsset.mockResolvedValue([
|
immich.listAlbumsForAsset.mockResolvedValue([
|
||||||
{
|
{
|
||||||
id: "album-2",
|
id: otherAlbumId,
|
||||||
albumName: "Andere Bilder",
|
albumName: "Andere Bilder",
|
||||||
description: null,
|
description: null,
|
||||||
albumThumbnailAssetId: null,
|
albumThumbnailAssetId: null,
|
||||||
@@ -213,6 +239,73 @@ test("rejects an asset outside the exact requested album", async () => {
|
|||||||
expect(usages).toHaveLength(0);
|
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 () => {
|
test("rejects a missing asset immediately before accounting", async () => {
|
||||||
const { service, immich, usages } = createService();
|
const { service, immich, usages } = createService();
|
||||||
immich.getAsset.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
|
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 () => {
|
test("rejects a non-image asset immediately before accounting", async () => {
|
||||||
const { service, immich, usages } = createService();
|
const { service, immich, usages } = createService();
|
||||||
immich.getAsset.mockResolvedValue({
|
immich.getAsset.mockResolvedValue({
|
||||||
id: "asset-1",
|
id: assetId,
|
||||||
type: "VIDEO",
|
type: "VIDEO",
|
||||||
originalFileName: "clip.mp4",
|
originalFileName: "clip.mp4",
|
||||||
originalMimeType: "video/mp4",
|
originalMimeType: "video/mp4",
|
||||||
localDateTime: null,
|
localDateTime: null,
|
||||||
fileCreatedAt: null,
|
fileCreatedAt: null,
|
||||||
albums: [{ id: "album-1" }],
|
albums: [{ id: albumId }],
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
|
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" }),
|
service.createNewUsage({ ...newUsageInput, purpose: "Online-Aufmacher" }),
|
||||||
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
|
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
|
||||||
expect(usages).toHaveLength(1);
|
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 () => {
|
test("lists only the repository's prior usages for the requested editorial asset", async () => {
|
||||||
const { service, priorUsages } = createService();
|
const { service, priorUsages } = createService();
|
||||||
priorUsages.push({
|
priorUsages.push({
|
||||||
id: "usage-1",
|
id: "usage-1",
|
||||||
assetId: "asset-1",
|
assetId,
|
||||||
filename: "jubel.jpg",
|
filename: "jubel.jpg",
|
||||||
albumId: "album-1",
|
albumId,
|
||||||
albumName: "Presse 2026",
|
albumName: "Presse 2026",
|
||||||
purpose: "Titelgeschichte",
|
purpose: "Titelgeschichte",
|
||||||
reference: undefined,
|
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"),
|
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,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
@@ -18,12 +18,11 @@ import { immichClient } from "@/modules/immich/client";
|
|||||||
import type { ImmichAlbumSummary } from "@/modules/immich/types";
|
import type { ImmichAlbumSummary } from "@/modules/immich/types";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
assertImmichIdentifier,
|
|
||||||
assertUuid,
|
|
||||||
type CreateNewUsageInput,
|
type CreateNewUsageInput,
|
||||||
type DownloadIntent,
|
type DownloadIntent,
|
||||||
normalizeOptionalText,
|
normalizeOptionalText,
|
||||||
normalizeRequiredText,
|
normalizeRequiredText,
|
||||||
|
normalizeUuid,
|
||||||
type PriorUsage,
|
type PriorUsage,
|
||||||
requestFingerprint,
|
requestFingerprint,
|
||||||
UsageAccountingError,
|
UsageAccountingError,
|
||||||
@@ -48,7 +47,10 @@ export type BillableIntentInput = {
|
|||||||
|
|
||||||
export type UsageRepository = {
|
export type UsageRepository = {
|
||||||
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
|
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
|
||||||
createBillableIntent(input: BillableIntentInput): Promise<PersistedDownloadIntent>;
|
createBillableIntent(
|
||||||
|
input: BillableIntentInput,
|
||||||
|
refreshCurrentAsset: () => Promise<{ albumName: string; filename: string }>,
|
||||||
|
): Promise<PersistedDownloadIntent>;
|
||||||
listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]>;
|
listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -90,14 +92,19 @@ export function createUsageService({
|
|||||||
albumName: normalizeUpstreamSnapshot(album.albumName),
|
albumName: normalizeUpstreamSnapshot(album.albumName),
|
||||||
filename: normalizeUpstreamSnapshot(asset.originalFileName),
|
filename: normalizeUpstreamSnapshot(asset.originalFileName),
|
||||||
requestFingerprint: fingerprint,
|
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");
|
return resolveIntent(persisted, fingerprint, "new_usage");
|
||||||
},
|
},
|
||||||
|
|
||||||
async listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]> {
|
async listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]> {
|
||||||
assertUuid(editorialId);
|
return repository.listPriorUsages(normalizeUuid(editorialId), normalizeUuid(assetId));
|
||||||
assertImmichIdentifier(assetId);
|
|
||||||
return repository.listPriorUsages(editorialId, assetId);
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -110,10 +117,17 @@ export function createUsageServiceRepository(
|
|||||||
return findPersistedIntent(database, editorialId, idempotencyKey);
|
return findPersistedIntent(database, editorialId, idempotencyKey);
|
||||||
},
|
},
|
||||||
|
|
||||||
async createBillableIntent(input) {
|
async createBillableIntent(input, refreshCurrentAsset) {
|
||||||
try {
|
try {
|
||||||
return await database.transaction(async (transaction) => {
|
return await database.transaction(async (transaction) => {
|
||||||
await lockEditorialAccounting(transaction, input.editorialId);
|
await lockEditorialAccounting(transaction, input.editorialId);
|
||||||
|
const existing = await findPersistedIntentInTransaction(
|
||||||
|
transaction,
|
||||||
|
input.editorialId,
|
||||||
|
input.idempotencyKey,
|
||||||
|
);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
const [editorial] = await transaction
|
const [editorial] = await transaction
|
||||||
.select({
|
.select({
|
||||||
id: editorialAccounts.id,
|
id: editorialAccounts.id,
|
||||||
@@ -148,12 +162,10 @@ export function createUsageServiceRepository(
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
|
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
|
||||||
|
|
||||||
const existing = await findPersistedIntentInTransaction(
|
// This is the last cross-system authorization snapshot available to the
|
||||||
transaction,
|
// portal. Immich may still change after it returns, but no portal work is
|
||||||
input.editorialId,
|
// allowed between this refresh and the accounting inserts.
|
||||||
input.idempotencyKey,
|
const currentAsset = await refreshCurrentAsset();
|
||||||
);
|
|
||||||
if (existing) return existing;
|
|
||||||
|
|
||||||
const createdAt = new Date();
|
const createdAt = new Date();
|
||||||
const [usage] = await transaction
|
const [usage] = await transaction
|
||||||
@@ -161,9 +173,9 @@ export function createUsageServiceRepository(
|
|||||||
.values({
|
.values({
|
||||||
editorialAccountId: input.editorialId,
|
editorialAccountId: input.editorialId,
|
||||||
immichAssetId: input.assetId,
|
immichAssetId: input.assetId,
|
||||||
filenameSnapshot: input.filename,
|
filenameSnapshot: currentAsset.filename,
|
||||||
immichAlbumIdSnapshot: input.albumId,
|
immichAlbumIdSnapshot: input.albumId,
|
||||||
albumNameSnapshot: input.albumName,
|
albumNameSnapshot: currentAsset.albumName,
|
||||||
purpose: input.purpose,
|
purpose: input.purpose,
|
||||||
internalReference: input.reference,
|
internalReference: input.reference,
|
||||||
priceCents: editorial.currentPriceCents!,
|
priceCents: editorial.currentPriceCents!,
|
||||||
@@ -259,19 +271,15 @@ export function createUsageServiceRepository(
|
|||||||
|
|
||||||
function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput {
|
function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput {
|
||||||
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
|
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 purpose = normalizeRequiredText(input.purpose, 3, 200);
|
||||||
const reference = normalizeOptionalText(input.reference, 200);
|
const reference = normalizeOptionalText(input.reference, 200);
|
||||||
return {
|
return {
|
||||||
editorialId: input.editorialId,
|
editorialId: normalizeUuid(input.editorialId),
|
||||||
assetId: input.assetId,
|
assetId: normalizeUuid(input.assetId),
|
||||||
albumId: input.albumId,
|
albumId: normalizeUuid(input.albumId),
|
||||||
purpose,
|
purpose,
|
||||||
...(reference === undefined ? {} : { reference }),
|
...(reference === undefined ? {} : { reference }),
|
||||||
idempotencyKey: input.idempotencyKey,
|
idempotencyKey: normalizeUuid(input.idempotencyKey),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,18 +341,19 @@ export async function findPersistedIntent(
|
|||||||
editorialId: string,
|
editorialId: string,
|
||||||
idempotencyKey: string,
|
idempotencyKey: string,
|
||||||
): Promise<PersistedDownloadIntent | null> {
|
): Promise<PersistedDownloadIntent | null> {
|
||||||
const [row] = await database
|
const rows = await database
|
||||||
.select(intentSelection)
|
.select(intentSelection)
|
||||||
.from(downloadEvents)
|
.from(downloadEvents)
|
||||||
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
|
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(downloadEvents.editorialAccountId, editorialId),
|
eq(downloadEvents.editorialAccountId, editorialId),
|
||||||
eq(downloadEvents.idempotencyKey, idempotencyKey),
|
sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.limit(1);
|
.limit(2);
|
||||||
return row ? persistedIntent(row) : null;
|
if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||||
|
return rows[0] ? persistedIntent(rows[0]) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function findPersistedIntentInTransaction(
|
async function findPersistedIntentInTransaction(
|
||||||
@@ -352,18 +361,19 @@ async function findPersistedIntentInTransaction(
|
|||||||
editorialId: string,
|
editorialId: string,
|
||||||
idempotencyKey: string,
|
idempotencyKey: string,
|
||||||
): Promise<PersistedDownloadIntent | null> {
|
): Promise<PersistedDownloadIntent | null> {
|
||||||
const [row] = await transaction
|
const rows = await transaction
|
||||||
.select(intentSelection)
|
.select(intentSelection)
|
||||||
.from(downloadEvents)
|
.from(downloadEvents)
|
||||||
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
|
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(downloadEvents.editorialAccountId, editorialId),
|
eq(downloadEvents.editorialAccountId, editorialId),
|
||||||
eq(downloadEvents.idempotencyKey, idempotencyKey),
|
sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.limit(1);
|
.limit(2);
|
||||||
return row ? persistedIntent(row) : null;
|
if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||||
|
return rows[0] ? persistedIntent(rows[0]) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const intentSelection = {
|
const intentSelection = {
|
||||||
|
|||||||
@@ -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 {
|
export function assertImmichIdentifier(value: unknown): asserts value is string {
|
||||||
if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,200}$/.test(value)) {
|
if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,200}$/.test(value)) {
|
||||||
throw new UsageAccountingError("INVALID_INPUT");
|
throw new UsageAccountingError("INVALID_INPUT");
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { afterAll, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { downloadEvents } from "@/db/schema";
|
||||||
|
import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service";
|
||||||
|
import { requestFingerprint } from "@/modules/usages/types";
|
||||||
|
import { startPostgres } from "./postgres";
|
||||||
|
|
||||||
|
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
|
||||||
|
|
||||||
|
afterAll(() => testDb.stop());
|
||||||
|
|
||||||
|
test("0002 preserves an equivalent retry of a populated legacy accounting intent", async () => {
|
||||||
|
const userId = randomUUID();
|
||||||
|
const editorialId = randomUUID();
|
||||||
|
const usageId = randomUUID();
|
||||||
|
const eventId = randomUUID();
|
||||||
|
const requestId = randomUUID();
|
||||||
|
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
const albumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||||
|
const idempotencyKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
|
||||||
|
const authorizedAt = new Date("2026-08-09T08:00:00.000Z");
|
||||||
|
|
||||||
|
await testDb.pool.query(
|
||||||
|
`insert into users (id, name, email, email_verified)
|
||||||
|
values ($1, 'Legacy Redaktion', $2, true)`,
|
||||||
|
[userId, `${userId}@example.com`],
|
||||||
|
);
|
||||||
|
await testDb.pool.query(
|
||||||
|
`insert into editorial_accounts (
|
||||||
|
id, user_id, name, contact_name, login_email, status, current_price_cents
|
||||||
|
) values ($1, $2, 'Legacy Redaktion', 'Legacy Kontakt', $3, 'active', 2300)`,
|
||||||
|
[editorialId, userId, `${userId}@example.com`],
|
||||||
|
);
|
||||||
|
await testDb.pool.query(
|
||||||
|
`insert into album_grants (editorial_account_id, immich_album_id)
|
||||||
|
values ($1, $2)`,
|
||||||
|
[editorialId, albumId.toUpperCase()],
|
||||||
|
);
|
||||||
|
await testDb.pool.query(
|
||||||
|
`insert into usages (
|
||||||
|
id, editorial_account_id, immich_asset_id, filename_snapshot,
|
||||||
|
immich_album_id_snapshot, album_name_snapshot, purpose,
|
||||||
|
internal_reference, price_cents, billing_status, created_at
|
||||||
|
) values ($1, $2, $3, 'legacy.jpg', $4, 'Legacy Album',
|
||||||
|
'Titelgeschichte', 'Ausgabe 8/26', 2300, 'open', $5)`,
|
||||||
|
[usageId, editorialId, assetId.toUpperCase(), albumId.toUpperCase(), authorizedAt],
|
||||||
|
);
|
||||||
|
await testDb.pool.query(
|
||||||
|
`insert into download_events (
|
||||||
|
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
|
||||||
|
status, request_id, idempotency_key
|
||||||
|
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7)`,
|
||||||
|
[
|
||||||
|
eventId,
|
||||||
|
editorialId,
|
||||||
|
usageId,
|
||||||
|
assetId.toUpperCase(),
|
||||||
|
authorizedAt,
|
||||||
|
requestId,
|
||||||
|
idempotencyKey.toUpperCase(),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
await testDb.applyRemainingMigrations();
|
||||||
|
|
||||||
|
const immich = {
|
||||||
|
listAlbumsForAsset: vi.fn(),
|
||||||
|
getAsset: vi.fn(),
|
||||||
|
};
|
||||||
|
const usageService = createUsageService({
|
||||||
|
repository: createUsageServiceRepository(testDb.database),
|
||||||
|
immich,
|
||||||
|
});
|
||||||
|
const input = {
|
||||||
|
editorialId: editorialId.toUpperCase(),
|
||||||
|
assetId: assetId.toUpperCase(),
|
||||||
|
albumId: albumId.toUpperCase(),
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
idempotencyKey: idempotencyKey.toUpperCase(),
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(usageService.createNewUsage(input)).resolves.toEqual({
|
||||||
|
id: eventId,
|
||||||
|
usageId,
|
||||||
|
assetId,
|
||||||
|
priceCents: 2300,
|
||||||
|
billable: true,
|
||||||
|
status: "authorized",
|
||||||
|
authorizedAt,
|
||||||
|
});
|
||||||
|
expect(immich.listAlbumsForAsset).not.toHaveBeenCalled();
|
||||||
|
expect(immich.getAsset).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const [migrated] = await testDb.database
|
||||||
|
.select()
|
||||||
|
.from(downloadEvents)
|
||||||
|
.where(eq(downloadEvents.id, eventId));
|
||||||
|
expect(migrated).toMatchObject({
|
||||||
|
immichAssetId: assetId,
|
||||||
|
idempotencyKey,
|
||||||
|
intentKind: "new_usage",
|
||||||
|
legacyIntent: true,
|
||||||
|
requestFingerprint: requestFingerprint({
|
||||||
|
kind: "new_usage",
|
||||||
|
editorialId,
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
+19
-6
@@ -19,10 +19,11 @@ export type PostgresTestDatabase = {
|
|||||||
pool: Pool;
|
pool: Pool;
|
||||||
seedEditorialWithUsage(): Promise<DownloadSeed>;
|
seedEditorialWithUsage(): Promise<DownloadSeed>;
|
||||||
insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise<void>;
|
insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise<void>;
|
||||||
|
applyRemainingMigrations(): Promise<void>;
|
||||||
stop(): Promise<void>;
|
stop(): Promise<void>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function startPostgres(): Promise<PostgresTestDatabase> {
|
export async function startPostgres({ through }: { through?: string } = {}): Promise<PostgresTestDatabase> {
|
||||||
const container = await new PostgreSqlContainer("postgres:17-alpine")
|
const container = await new PostgreSqlContainer("postgres:17-alpine")
|
||||||
.withDatabase("portal")
|
.withDatabase("portal")
|
||||||
.withUsername("portal")
|
.withUsername("portal")
|
||||||
@@ -30,7 +31,11 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
|
|||||||
.start();
|
.start();
|
||||||
const pool = new Pool({ connectionString: container.getConnectionUri() });
|
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 });
|
const db = drizzle({ client: pool, schema });
|
||||||
|
|
||||||
@@ -50,6 +55,10 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
|
|||||||
requestFingerprint: "0".repeat(64),
|
requestFingerprint: "0".repeat(64),
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
async applyRemainingMigrations() {
|
||||||
|
await applyMigrationFiles(pool, migrationFiles.slice(appliedMigrationCount));
|
||||||
|
appliedMigrationCount = migrationFiles.length;
|
||||||
|
},
|
||||||
async stop() {
|
async stop() {
|
||||||
await pool.end();
|
await pool.end();
|
||||||
await stopContainer(container);
|
await stopContainer(container);
|
||||||
@@ -57,11 +66,15 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function applyMigration(pool: Pool) {
|
async function listMigrationFiles() {
|
||||||
const migrationDirectory = path.join(process.cwd(), "drizzle");
|
const migrationDirectory = path.join(process.cwd(), "drizzle");
|
||||||
const migrationFiles = (await readdir(migrationDirectory))
|
return (await readdir(migrationDirectory))
|
||||||
.filter((file) => /^\d+_.*\.sql$/.test(file))
|
.filter((file) => /^\d+_.*\.sql$/.test(file))
|
||||||
.sort();
|
.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyMigrationFiles(pool: Pool, migrationFiles: string[]) {
|
||||||
|
const migrationDirectory = path.join(process.cwd(), "drizzle");
|
||||||
for (const file of migrationFiles) {
|
for (const file of migrationFiles) {
|
||||||
await pool.query(await readFile(path.join(migrationDirectory, file), "utf8"));
|
await pool.query(await readFile(path.join(migrationDirectory, file), "utf8"));
|
||||||
}
|
}
|
||||||
@@ -71,7 +84,7 @@ async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promis
|
|||||||
const userId = randomUUID();
|
const userId = randomUUID();
|
||||||
const editorialId = randomUUID();
|
const editorialId = randomUUID();
|
||||||
const usageId = randomUUID();
|
const usageId = randomUUID();
|
||||||
const assetId = "immich-asset-1";
|
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
|
||||||
await db.insert(schema.users).values({
|
await db.insert(schema.users).values({
|
||||||
id: userId,
|
id: userId,
|
||||||
@@ -93,7 +106,7 @@ async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promis
|
|||||||
editorialAccountId: editorialId,
|
editorialAccountId: editorialId,
|
||||||
immichAssetId: assetId,
|
immichAssetId: assetId,
|
||||||
filenameSnapshot: "bild.jpg",
|
filenameSnapshot: "bild.jpg",
|
||||||
immichAlbumIdSnapshot: "immich-album-1",
|
immichAlbumIdSnapshot: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||||
albumNameSnapshot: "Presse",
|
albumNameSnapshot: "Presse",
|
||||||
purpose: "Artikel",
|
purpose: "Artikel",
|
||||||
priceCents: 1500,
|
priceCents: 1500,
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ afterAll(() => testDb.stop());
|
|||||||
|
|
||||||
test("rejects duplicate download idempotency keys for one editorial", async () => {
|
test("rejects duplicate download idempotency keys for one editorial", async () => {
|
||||||
const seed = await testDb.seedEditorialWithUsage();
|
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(
|
await expect(
|
||||||
testDb.insertDownload({ ...seed, idempotencyKey: "same-request" }),
|
testDb.insertDownload({ ...seed, idempotencyKey }),
|
||||||
).rejects.toThrow();
|
).rejects.toThrow();
|
||||||
});
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import { and, count, eq } from "drizzle-orm";
|
import { and, count, eq } from "drizzle-orm";
|
||||||
|
import type { PoolClient } from "pg";
|
||||||
import { afterAll, expect, test, vi } from "vitest";
|
import { afterAll, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -19,6 +20,7 @@ import {
|
|||||||
createDownloadService,
|
createDownloadService,
|
||||||
createRepeatDownloadRepository,
|
createRepeatDownloadRepository,
|
||||||
} from "@/modules/downloads/service";
|
} from "@/modules/downloads/service";
|
||||||
|
import { requestFingerprint } from "@/modules/usages/types";
|
||||||
import { startPostgres } from "./postgres";
|
import { startPostgres } from "./postgres";
|
||||||
|
|
||||||
const testDb = await startPostgres();
|
const testDb = await startPostgres();
|
||||||
@@ -26,24 +28,28 @@ const database = testDb.database;
|
|||||||
|
|
||||||
afterAll(() => testDb.stop());
|
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 = {
|
const asset = {
|
||||||
id: "asset-1",
|
id: assetId,
|
||||||
type: "IMAGE" as const,
|
type: "IMAGE" as const,
|
||||||
originalFileName: "jubel.jpg",
|
originalFileName: "jubel.jpg",
|
||||||
originalMimeType: "image/jpeg",
|
originalMimeType: "image/jpeg",
|
||||||
localDateTime: null,
|
localDateTime: null,
|
||||||
fileCreatedAt: null,
|
fileCreatedAt: null,
|
||||||
albums: [{ id: "album-1" }],
|
albums: [{ id: albumId }],
|
||||||
};
|
};
|
||||||
|
|
||||||
function createServices() {
|
function createServices() {
|
||||||
const immich = {
|
const immich = {
|
||||||
listAlbumsForAsset: vi.fn().mockResolvedValue([
|
listAlbumsForAsset: vi.fn().mockResolvedValue([
|
||||||
{
|
{
|
||||||
id: "album-1",
|
id: albumId,
|
||||||
albumName: "Presse 2026",
|
albumName: "Presse 2026",
|
||||||
description: null,
|
description: null,
|
||||||
albumThumbnailAssetId: "asset-1",
|
albumThumbnailAssetId: assetId,
|
||||||
assetCount: 1,
|
assetCount: 1,
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
@@ -64,7 +70,7 @@ function createServices() {
|
|||||||
async function seedEditorial({
|
async function seedEditorial({
|
||||||
status = "active",
|
status = "active",
|
||||||
priceCents = 1_500,
|
priceCents = 1_500,
|
||||||
albumId = "album-1",
|
albumId: grantedAlbumId = albumId,
|
||||||
revoked = false,
|
revoked = false,
|
||||||
}: {
|
}: {
|
||||||
status?: "active" | "suspended" | "pending_approval";
|
status?: "active" | "suspended" | "pending_approval";
|
||||||
@@ -91,7 +97,7 @@ async function seedEditorial({
|
|||||||
});
|
});
|
||||||
await database.insert(albumGrants).values({
|
await database.insert(albumGrants).values({
|
||||||
editorialAccountId: editorialId,
|
editorialAccountId: editorialId,
|
||||||
immichAlbumId: albumId,
|
immichAlbumId: grantedAlbumId,
|
||||||
revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null,
|
revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null,
|
||||||
});
|
});
|
||||||
return editorialId;
|
return editorialId;
|
||||||
@@ -100,14 +106,59 @@ async function seedEditorial({
|
|||||||
function newInput(editorialId: string, idempotencyKey = randomUUID()) {
|
function newInput(editorialId: string, idempotencyKey = randomUUID()) {
|
||||||
return {
|
return {
|
||||||
editorialId,
|
editorialId,
|
||||||
assetId: "asset-1",
|
assetId,
|
||||||
albumId: "album-1",
|
albumId,
|
||||||
purpose: "Titelgeschichte",
|
purpose: "Titelgeschichte",
|
||||||
reference: "Ausgabe 8/26",
|
reference: "Ausgabe 8/26",
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function insertWinner(
|
||||||
|
client: PoolClient,
|
||||||
|
input: ReturnType<typeof newInput>,
|
||||||
|
fingerprint: string,
|
||||||
|
kind: "new_usage" | "repeat_download" = "new_usage",
|
||||||
|
) {
|
||||||
|
const usageId = randomUUID();
|
||||||
|
const eventId = randomUUID();
|
||||||
|
const authorizedAt = new Date("2026-08-09T10:00:00.000Z");
|
||||||
|
await client.query(
|
||||||
|
`insert into usages (
|
||||||
|
id, editorial_account_id, immich_asset_id, filename_snapshot,
|
||||||
|
immich_album_id_snapshot, album_name_snapshot, purpose,
|
||||||
|
internal_reference, price_cents, billing_status, created_at
|
||||||
|
) values ($1, $2, $3, 'winner.jpg', $4, 'Presse 2026', $5, $6, 1500, 'open', $7)`,
|
||||||
|
[
|
||||||
|
usageId,
|
||||||
|
input.editorialId,
|
||||||
|
input.assetId,
|
||||||
|
input.albumId,
|
||||||
|
input.purpose,
|
||||||
|
input.reference,
|
||||||
|
authorizedAt,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
await client.query(
|
||||||
|
`insert into download_events (
|
||||||
|
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
|
||||||
|
status, request_id, idempotency_key, intent_kind, request_fingerprint
|
||||||
|
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8, $9)`,
|
||||||
|
[
|
||||||
|
eventId,
|
||||||
|
input.editorialId,
|
||||||
|
usageId,
|
||||||
|
input.assetId,
|
||||||
|
authorizedAt,
|
||||||
|
randomUUID(),
|
||||||
|
input.idempotencyKey,
|
||||||
|
kind,
|
||||||
|
fingerprint,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
return { eventId, usageId, authorizedAt };
|
||||||
|
}
|
||||||
|
|
||||||
test("atomically snapshots price and metadata, authorizes one event, and audits no secrets", async () => {
|
test("atomically snapshots price and metadata, authorizes one event, and audits no secrets", async () => {
|
||||||
const editorialId = await seedEditorial();
|
const editorialId = await seedEditorial();
|
||||||
const { usageService } = createServices();
|
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)));
|
.where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, intent.usageId)));
|
||||||
expect(usage).toMatchObject({
|
expect(usage).toMatchObject({
|
||||||
editorialAccountId: editorialId,
|
editorialAccountId: editorialId,
|
||||||
immichAssetId: "asset-1",
|
immichAssetId: assetId,
|
||||||
filenameSnapshot: "jubel.jpg",
|
filenameSnapshot: "jubel.jpg",
|
||||||
immichAlbumIdSnapshot: "album-1",
|
immichAlbumIdSnapshot: albumId,
|
||||||
albumNameSnapshot: "Presse 2026",
|
albumNameSnapshot: "Presse 2026",
|
||||||
purpose: "Titelgeschichte",
|
purpose: "Titelgeschichte",
|
||||||
internalReference: "Ausgabe 8/26",
|
internalReference: "Ausgabe 8/26",
|
||||||
@@ -165,7 +216,7 @@ test.each([
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("requires an active grant for the exact requested album", async () => {
|
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();
|
const { usageService } = createServices();
|
||||||
|
|
||||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
|
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
|
||||||
@@ -173,6 +224,132 @@ test("requires an active grant for the exact requested album", async () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("rechecks exact album membership after database locks before inserting", async () => {
|
||||||
|
const editorialId = await seedEditorial();
|
||||||
|
const { usageService, immich } = createServices();
|
||||||
|
immich.listAlbumsForAsset
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: albumId,
|
||||||
|
albumName: "Presse 2026",
|
||||||
|
description: null,
|
||||||
|
albumThumbnailAssetId: assetId,
|
||||||
|
assetCount: 1,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.mockResolvedValueOnce([]);
|
||||||
|
|
||||||
|
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
|
||||||
|
code: "ASSET_NOT_IN_ALBUM",
|
||||||
|
});
|
||||||
|
const [usageCount] = await database
|
||||||
|
.select({ value: count() })
|
||||||
|
.from(usages)
|
||||||
|
.where(eq(usages.editorialAccountId, editorialId));
|
||||||
|
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(2);
|
||||||
|
expect(usageCount.value).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns a winner committed while waiting before later mutable state is checked", async () => {
|
||||||
|
const editorialId = await seedEditorial();
|
||||||
|
const input = newInput(editorialId);
|
||||||
|
const immich = createServices().immich;
|
||||||
|
const realRepository = createUsageServiceRepository(database);
|
||||||
|
let releaseFastMiss!: () => void;
|
||||||
|
const fastMiss = new Promise<void>((resolve) => {
|
||||||
|
releaseFastMiss = resolve;
|
||||||
|
});
|
||||||
|
const usageService = createUsageService({
|
||||||
|
repository: {
|
||||||
|
...realRepository,
|
||||||
|
async findIntent(requestEditorialId, key) {
|
||||||
|
const intent = await realRepository.findIntent(requestEditorialId, key);
|
||||||
|
releaseFastMiss();
|
||||||
|
return intent;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
immich,
|
||||||
|
});
|
||||||
|
const locker = await testDb.pool.connect();
|
||||||
|
await locker.query("begin");
|
||||||
|
await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pending = usageService.createNewUsage(input);
|
||||||
|
await fastMiss;
|
||||||
|
const winner = await insertWinner(
|
||||||
|
locker,
|
||||||
|
input,
|
||||||
|
requestFingerprint({
|
||||||
|
kind: "new_usage",
|
||||||
|
editorialId,
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose: input.purpose,
|
||||||
|
reference: input.reference,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [
|
||||||
|
editorialId,
|
||||||
|
]);
|
||||||
|
await locker.query("commit");
|
||||||
|
|
||||||
|
await expect(pending).resolves.toMatchObject({
|
||||||
|
id: winner.eventId,
|
||||||
|
usageId: winner.usageId,
|
||||||
|
authorizedAt: winner.authorizedAt,
|
||||||
|
billable: true,
|
||||||
|
});
|
||||||
|
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
|
||||||
|
expect(immich.getAsset).toHaveBeenCalledTimes(1);
|
||||||
|
} finally {
|
||||||
|
await locker.query("rollback");
|
||||||
|
locker.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports a conflicting winner committed while waiting before later state errors", async () => {
|
||||||
|
const editorialId = await seedEditorial();
|
||||||
|
const input = newInput(editorialId);
|
||||||
|
const { immich } = createServices();
|
||||||
|
const realRepository = createUsageServiceRepository(database);
|
||||||
|
let releaseFastMiss!: () => void;
|
||||||
|
const fastMiss = new Promise<void>((resolve) => {
|
||||||
|
releaseFastMiss = resolve;
|
||||||
|
});
|
||||||
|
const usageService = createUsageService({
|
||||||
|
repository: {
|
||||||
|
...realRepository,
|
||||||
|
async findIntent(requestEditorialId, key) {
|
||||||
|
const intent = await realRepository.findIntent(requestEditorialId, key);
|
||||||
|
releaseFastMiss();
|
||||||
|
return intent;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
immich,
|
||||||
|
});
|
||||||
|
const locker = await testDb.pool.connect();
|
||||||
|
await locker.query("begin");
|
||||||
|
await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pending = usageService.createNewUsage(input);
|
||||||
|
await fastMiss;
|
||||||
|
await insertWinner(locker, input, "0".repeat(64));
|
||||||
|
await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [
|
||||||
|
editorialId,
|
||||||
|
]);
|
||||||
|
await locker.query("commit");
|
||||||
|
|
||||||
|
await expect(pending).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
|
||||||
|
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
|
||||||
|
expect(immich.getAsset).toHaveBeenCalledTimes(1);
|
||||||
|
} finally {
|
||||||
|
await locker.query("rollback");
|
||||||
|
locker.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("same-key concurrency across database clients creates exactly one usage, event, and audit", async () => {
|
test("same-key concurrency across database clients creates exactly one usage, event, and audit", async () => {
|
||||||
const editorialId = await seedEditorial();
|
const editorialId = await seedEditorial();
|
||||||
const { usageService } = createServices();
|
const { usageService } = createServices();
|
||||||
@@ -299,6 +476,83 @@ test("same-key repeat concurrency creates one free event", async () => {
|
|||||||
expect(eventCount.value).toBe(1);
|
expect(eventCount.value).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("returns a repeat winner committed while waiting before later suspension is checked", async () => {
|
||||||
|
const editorialId = await seedEditorial();
|
||||||
|
const { usageService } = createServices();
|
||||||
|
const first = await usageService.createNewUsage(newInput(editorialId));
|
||||||
|
const input = {
|
||||||
|
editorialId,
|
||||||
|
usageId: first.usageId,
|
||||||
|
note: "Web-Ausgabe",
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
};
|
||||||
|
const realRepository = createRepeatDownloadRepository(database);
|
||||||
|
let releaseFastMiss!: () => void;
|
||||||
|
const fastMiss = new Promise<void>((resolve) => {
|
||||||
|
releaseFastMiss = resolve;
|
||||||
|
});
|
||||||
|
const downloadService = createDownloadService({
|
||||||
|
repository: {
|
||||||
|
...realRepository,
|
||||||
|
async findIntent(requestEditorialId, key) {
|
||||||
|
const intent = await realRepository.findIntent(requestEditorialId, key);
|
||||||
|
releaseFastMiss();
|
||||||
|
return intent;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const eventId = randomUUID();
|
||||||
|
const authorizedAt = new Date("2026-08-09T11:00:00.000Z");
|
||||||
|
const locker = await testDb.pool.connect();
|
||||||
|
await locker.query("begin");
|
||||||
|
await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pending = downloadService.createRepeatDownload(input);
|
||||||
|
await fastMiss;
|
||||||
|
await locker.query(
|
||||||
|
`insert into download_events (
|
||||||
|
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
|
||||||
|
status, repeat_download_note, request_id, idempotency_key,
|
||||||
|
intent_kind, request_fingerprint
|
||||||
|
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8, 'repeat_download', $9)`,
|
||||||
|
[
|
||||||
|
eventId,
|
||||||
|
editorialId,
|
||||||
|
first.usageId,
|
||||||
|
assetId,
|
||||||
|
authorizedAt,
|
||||||
|
input.note,
|
||||||
|
randomUUID(),
|
||||||
|
input.idempotencyKey,
|
||||||
|
requestFingerprint({
|
||||||
|
kind: "repeat_download",
|
||||||
|
editorialId,
|
||||||
|
usageId: first.usageId,
|
||||||
|
note: input.note,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [
|
||||||
|
editorialId,
|
||||||
|
]);
|
||||||
|
await locker.query("commit");
|
||||||
|
|
||||||
|
await expect(pending).resolves.toEqual({
|
||||||
|
id: eventId,
|
||||||
|
usageId: first.usageId,
|
||||||
|
assetId,
|
||||||
|
priceCents: 0,
|
||||||
|
billable: false,
|
||||||
|
status: "authorized",
|
||||||
|
authorizedAt,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await locker.query("rollback");
|
||||||
|
locker.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("a suspended owner cannot create a repeat event", async () => {
|
test("a suspended owner cannot create a repeat event", async () => {
|
||||||
const editorialId = await seedEditorial();
|
const editorialId = await seedEditorial();
|
||||||
const { usageService, downloadService } = createServices();
|
const { usageService, downloadService } = createServices();
|
||||||
|
|||||||
Reference in new issue
Block a user