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

+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 = {