fix: harden usage accounting idempotency

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 10:59:12 +02:00
1 parent 22fe6bf659
commit 3de1530074
14 files changed
+708 -107

No files matched your search

+23 -5
View File
@@ -8,9 +8,10 @@ import {
} from "./service";
import { UsageAccountingError } from "@/modules/usages/types";
const editorialId = "11111111-1111-4111-8111-111111111111";
const usageId = "44444444-4444-4444-8444-444444444444";
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
const editorialId = "1111111a-1111-4111-8111-11111111111a";
const usageId = "4444444d-4444-4444-8444-44444444444d";
const idempotencyKey = "5555555e-5555-4555-8555-55555555555e";
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
function createService() {
const intents = new Map<string, PersistedRepeatIntent>();
@@ -33,7 +34,7 @@ function createService() {
const intent: PersistedRepeatIntent = {
id: `download-${events.length}`,
usageId: input.usageId,
assetId: "asset-1",
assetId,
priceCents: 0,
billable: false,
status: "authorized",
@@ -77,7 +78,7 @@ test("creates only a free authorized event for an owned prior usage", async () =
expect(intent).toMatchObject({
usageId,
assetId: "asset-1",
assetId,
priceCents: 0,
billable: false,
status: "authorized",
@@ -126,6 +127,23 @@ test("returns the same free intent once for an equivalent retry", async () => {
expect(events).toHaveLength(1);
});
test("treats mixed-case UUID input as the same repeat intent", async () => {
const { service, events } = createService();
const uppercaseInput = {
editorialId: editorialId.toUpperCase(),
usageId: usageId.toUpperCase(),
idempotencyKey: idempotencyKey.toUpperCase(),
};
const first = await service.createRepeatDownload(uppercaseInput);
const second = await service.createRepeatDownload({ editorialId, usageId, idempotencyKey });
expect(second).toEqual(first);
expect(events).toEqual([
expect.objectContaining({ editorialId, usageId, idempotencyKey }),
]);
});
test("rejects reuse of a repeat key with a materially different note", async () => {
const { service, events } = createService();
await service.createRepeatDownload({ editorialId, usageId, note: "Web", idempotencyKey });
+11 -14
View File
@@ -9,10 +9,10 @@ import { db } from "@/db/client";
import { downloadEvents, editorialAccounts, usages } from "@/db/schema";
import type * as schema from "@/db/schema";
import {
assertUuid,
type CreateRepeatDownloadInput,
type DownloadIntent,
normalizeOptionalText,
normalizeUuid,
requestFingerprint,
UsageAccountingError,
} from "@/modules/usages/types";
@@ -71,6 +71,13 @@ export function createRepeatDownloadRepository(
try {
return await database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId);
const existing = await findPersistedIntent(
transaction,
input.editorialId,
input.idempotencyKey,
);
if (existing) return asRepeatIntent(existing);
const [editorial] = await transaction
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
.from(editorialAccounts)
@@ -81,13 +88,6 @@ export function createRepeatDownloadRepository(
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
const existing = await findPersistedIntent(
transaction,
input.editorialId,
input.idempotencyKey,
);
if (existing) return asRepeatIntent(existing);
const [usage] = await transaction
.select({ id: usages.id, assetId: usages.immichAssetId })
.from(usages)
@@ -149,15 +149,12 @@ export function createRepeatDownloadRepository(
function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput {
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
assertUuid(input.editorialId);
assertUuid(input.usageId);
assertUuid(input.idempotencyKey);
const note = normalizeOptionalText(input.note, 200);
return {
editorialId: input.editorialId,
usageId: input.usageId,
editorialId: normalizeUuid(input.editorialId),
usageId: normalizeUuid(input.usageId),
...(note === undefined ? {} : { note }),
idempotencyKey: input.idempotencyKey,
idempotencyKey: normalizeUuid(input.idempotencyKey),
};
}
+118 -23
View File
@@ -8,13 +8,16 @@ import {
} from "./service";
import { UsageAccountingError, type PriorUsage } from "./types";
const editorialId = "11111111-1111-4111-8111-111111111111";
const idempotencyKey = "22222222-2222-4222-8222-222222222222";
const editorialId = "1111111a-1111-4111-8111-11111111111a";
const idempotencyKey = "2222222b-2222-4222-8222-22222222222b";
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const albumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const otherAlbumId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const newUsageInput = {
editorialId,
assetId: "asset-1",
albumId: "album-1",
assetId,
albumId,
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
idempotencyKey,
@@ -31,18 +34,22 @@ function createRepository() {
async findIntent(requestEditorialId, key) {
return intents.get(`${requestEditorialId}:${key}`) ?? null;
},
async createBillableIntent(input) {
async createBillableIntent(
input,
refreshCurrentAsset?: () => Promise<{ albumName: string; filename: string }>,
) {
const key = `${input.editorialId}:${input.idempotencyKey}`;
const existing = intents.get(key);
if (existing) return existing;
if (status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
throw new UsageAccountingError("INVALID_PRICE");
}
const key = `${input.editorialId}:${input.idempotencyKey}`;
const existing = intents.get(key);
if (existing) return existing;
usages.push(input);
const refreshed = await refreshCurrentAsset?.();
usages.push({ ...input, ...refreshed });
const intent: PersistedDownloadIntent = {
id: `download-${intents.size + 1}`,
usageId: `usage-${usages.length}`,
@@ -81,21 +88,21 @@ function createService() {
const immich = {
listAlbumsForAsset: vi.fn().mockResolvedValue([
{
id: "album-1",
id: albumId,
albumName: "Presse 2026",
description: null,
albumThumbnailAssetId: "asset-1",
albumThumbnailAssetId: assetId,
assetCount: 1,
},
]),
getAsset: vi.fn().mockResolvedValue({
id: "asset-1",
id: assetId,
type: "IMAGE" as const,
originalFileName: "jubel.jpg",
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "album-1" }],
albums: [{ id: albumId }],
}),
};
return { ...state, immich, service: createUsageService({ repository: state.repository, immich }) };
@@ -113,8 +120,8 @@ test("snapshots the current editorial price and normalized Immich metadata", asy
expect(intent).toMatchObject({ priceCents: 1_500, billable: true, status: "authorized" });
expect(usages).toEqual([
expect.objectContaining({
assetId: "asset-1",
albumId: "album-1",
assetId,
albumId,
albumName: "Presse 2026",
filename: "jubel.jpg",
purpose: "Titelgeschichte",
@@ -131,7 +138,26 @@ test("returns the exact persisted intent for an equivalent idempotent retry", as
expect(second).toEqual(first);
expect(usages).toHaveLength(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1);
expect(immich.getAsset).toHaveBeenCalledTimes(2);
});
test("canonicalizes every UUID before fingerprinting, lookup, Immich calls, and persistence", async () => {
const { service, usages, immich } = createService();
const uppercaseInput = Object.fromEntries(
Object.entries(newUsageInput).map(([key, value]) => [
key,
key === "purpose" || key === "reference" ? value : value.toUpperCase(),
]),
) as typeof newUsageInput;
const first = await service.createNewUsage(uppercaseInput);
const second = await service.createNewUsage(newUsageInput);
expect(second).toEqual(first);
expect(usages).toHaveLength(1);
expect(usages[0]).toMatchObject({ editorialId, assetId, albumId, idempotencyKey });
expect(immich.listAlbumsForAsset).toHaveBeenCalledWith(assetId);
expect(immich.getAsset).toHaveBeenCalledWith(assetId);
});
test("keeps the original snapshot after a price change while a new key uses the new price", async () => {
@@ -198,7 +224,7 @@ test("rejects an asset outside the exact requested album", async () => {
const { service, immich, usages } = createService();
immich.listAlbumsForAsset.mockResolvedValue([
{
id: "album-2",
id: otherAlbumId,
albumName: "Andere Bilder",
description: null,
albumThumbnailAssetId: null,
@@ -213,6 +239,73 @@ test("rejects an asset outside the exact requested album", async () => {
expect(usages).toHaveLength(0);
});
test("rejects removal from the requested album between preflight and locked refresh", async () => {
const { service, immich, usages } = createService();
immich.listAlbumsForAsset
.mockResolvedValueOnce([
{
id: albumId,
albumName: "Presse 2026",
description: null,
albumThumbnailAssetId: assetId,
assetCount: 1,
},
])
.mockResolvedValueOnce([]);
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "ASSET_NOT_IN_ALBUM",
});
expect(immich.listAlbumsForAsset).toHaveBeenCalledTimes(2);
expect(usages).toHaveLength(0);
});
test("persists metadata from the locked final Immich refresh", async () => {
const { service, immich, usages } = createService();
immich.listAlbumsForAsset
.mockResolvedValueOnce([
{
id: albumId,
albumName: "Presse 2026",
description: null,
albumThumbnailAssetId: assetId,
assetCount: 1,
},
])
.mockResolvedValueOnce([
{
id: albumId,
albumName: "Presse final",
description: null,
albumThumbnailAssetId: assetId,
assetCount: 1,
},
]);
const currentAsset = {
id: assetId,
type: "IMAGE" as const,
originalFileName: "jubel.jpg",
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: albumId }],
};
immich.getAsset.mockResolvedValueOnce({
...currentAsset,
originalFileName: "vorher.jpg",
}).mockResolvedValueOnce({
...currentAsset,
originalFileName: "final.jpg",
});
await service.createNewUsage(newUsageInput);
expect(immich.getAsset).toHaveBeenCalledTimes(2);
expect(usages).toEqual([
expect.objectContaining({ albumName: "Presse final", filename: "final.jpg" }),
]);
});
test("rejects a missing asset immediately before accounting", async () => {
const { service, immich, usages } = createService();
immich.getAsset.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
@@ -226,13 +319,13 @@ test("rejects a missing asset immediately before accounting", async () => {
test("rejects a non-image asset immediately before accounting", async () => {
const { service, immich, usages } = createService();
immich.getAsset.mockResolvedValue({
id: "asset-1",
id: assetId,
type: "VIDEO",
originalFileName: "clip.mp4",
originalMimeType: "video/mp4",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "album-1" }],
albums: [{ id: albumId }],
});
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
@@ -249,16 +342,16 @@ test("rejects reuse of an idempotency key for a materially different new usage",
service.createNewUsage({ ...newUsageInput, purpose: "Online-Aufmacher" }),
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
expect(usages).toHaveLength(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1);
expect(immich.getAsset).toHaveBeenCalledTimes(2);
});
test("lists only the repository's prior usages for the requested editorial asset", async () => {
const { service, priorUsages } = createService();
priorUsages.push({
id: "usage-1",
assetId: "asset-1",
assetId,
filename: "jubel.jpg",
albumId: "album-1",
albumId,
albumName: "Presse 2026",
purpose: "Titelgeschichte",
reference: undefined,
@@ -267,5 +360,7 @@ test("lists only the repository's prior usages for the requested editorial asset
createdAt: new Date("2026-08-09T08:00:00.000Z"),
});
await expect(service.listPriorUsages(editorialId, "asset-1")).resolves.toEqual(priorUsages);
await expect(service.listPriorUsages(editorialId.toUpperCase(), assetId.toUpperCase())).resolves.toEqual(
priorUsages,
);
});
+41 -31
View File
@@ -18,12 +18,11 @@ import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
import {
assertImmichIdentifier,
assertUuid,
type CreateNewUsageInput,
type DownloadIntent,
normalizeOptionalText,
normalizeRequiredText,
normalizeUuid,
type PriorUsage,
requestFingerprint,
UsageAccountingError,
@@ -48,7 +47,10 @@ export type BillableIntentInput = {
export type UsageRepository = {
findIntent(editorialId: string, idempotencyKey: string): Promise<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[]>;
};
@@ -90,14 +92,19 @@ export function createUsageService({
albumName: normalizeUpstreamSnapshot(album.albumName),
filename: normalizeUpstreamSnapshot(asset.originalFileName),
requestFingerprint: fingerprint,
}, async () => {
const currentAlbum = await loadRequestedAlbum(immich, input.assetId, input.albumId);
const currentAsset = await loadImageAsset(immich, input.assetId);
return {
albumName: normalizeUpstreamSnapshot(currentAlbum.albumName),
filename: normalizeUpstreamSnapshot(currentAsset.originalFileName),
};
});
return resolveIntent(persisted, fingerprint, "new_usage");
},
async listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]> {
assertUuid(editorialId);
assertImmichIdentifier(assetId);
return repository.listPriorUsages(editorialId, assetId);
return repository.listPriorUsages(normalizeUuid(editorialId), normalizeUuid(assetId));
},
};
}
@@ -110,10 +117,17 @@ export function createUsageServiceRepository(
return findPersistedIntent(database, editorialId, idempotencyKey);
},
async createBillableIntent(input) {
async createBillableIntent(input, refreshCurrentAsset) {
try {
return await database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId);
const existing = await findPersistedIntentInTransaction(
transaction,
input.editorialId,
input.idempotencyKey,
);
if (existing) return existing;
const [editorial] = await transaction
.select({
id: editorialAccounts.id,
@@ -148,12 +162,10 @@ export function createUsageServiceRepository(
.limit(1);
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
const existing = await findPersistedIntentInTransaction(
transaction,
input.editorialId,
input.idempotencyKey,
);
if (existing) return existing;
// This is the last cross-system authorization snapshot available to the
// portal. Immich may still change after it returns, but no portal work is
// allowed between this refresh and the accounting inserts.
const currentAsset = await refreshCurrentAsset();
const createdAt = new Date();
const [usage] = await transaction
@@ -161,9 +173,9 @@ export function createUsageServiceRepository(
.values({
editorialAccountId: input.editorialId,
immichAssetId: input.assetId,
filenameSnapshot: input.filename,
filenameSnapshot: currentAsset.filename,
immichAlbumIdSnapshot: input.albumId,
albumNameSnapshot: input.albumName,
albumNameSnapshot: currentAsset.albumName,
purpose: input.purpose,
internalReference: input.reference,
priceCents: editorial.currentPriceCents!,
@@ -259,19 +271,15 @@ export function createUsageServiceRepository(
function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput {
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
assertUuid(input.editorialId);
assertImmichIdentifier(input.assetId);
assertImmichIdentifier(input.albumId);
assertUuid(input.idempotencyKey);
const purpose = normalizeRequiredText(input.purpose, 3, 200);
const reference = normalizeOptionalText(input.reference, 200);
return {
editorialId: input.editorialId,
assetId: input.assetId,
albumId: input.albumId,
editorialId: normalizeUuid(input.editorialId),
assetId: normalizeUuid(input.assetId),
albumId: normalizeUuid(input.albumId),
purpose,
...(reference === undefined ? {} : { reference }),
idempotencyKey: input.idempotencyKey,
idempotencyKey: normalizeUuid(input.idempotencyKey),
};
}
@@ -333,18 +341,19 @@ export async function findPersistedIntent(
editorialId: string,
idempotencyKey: string,
): Promise<PersistedDownloadIntent | null> {
const [row] = await database
const rows = await database
.select(intentSelection)
.from(downloadEvents)
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
.where(
and(
eq(downloadEvents.editorialAccountId, editorialId),
eq(downloadEvents.idempotencyKey, idempotencyKey),
sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`,
),
)
.limit(1);
return row ? persistedIntent(row) : null;
.limit(2);
if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
return rows[0] ? persistedIntent(rows[0]) : null;
}
async function findPersistedIntentInTransaction(
@@ -352,18 +361,19 @@ async function findPersistedIntentInTransaction(
editorialId: string,
idempotencyKey: string,
): Promise<PersistedDownloadIntent | null> {
const [row] = await transaction
const rows = await transaction
.select(intentSelection)
.from(downloadEvents)
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
.where(
and(
eq(downloadEvents.editorialAccountId, editorialId),
eq(downloadEvents.idempotencyKey, idempotencyKey),
sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`,
),
)
.limit(1);
return row ? persistedIntent(row) : null;
.limit(2);
if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
return rows[0] ? persistedIntent(rows[0]) : null;
}
const intentSelection = {
+5
View File
@@ -106,6 +106,11 @@ export function assertUuid(value: unknown): asserts value is string {
}
}
export function normalizeUuid(value: unknown): string {
assertUuid(value);
return value.toLowerCase();
}
export function assertImmichIdentifier(value: unknown): asserts value is string {
if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,200}$/.test(value)) {
throw new UsageAccountingError("INVALID_INPUT");