feat: add usage and download intent accounting

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 22:52:27 +02:00
1 parent 846904f3db
commit 22fe6bf659
14 files changed
+3008 -2

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
import { expect, test, vi } from "vitest";
import {
createDownloadService,
type PersistedRepeatIntent,
type RepeatDownloadRepository,
type RepeatIntentInput,
} 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";
function createService() {
const intents = new Map<string, PersistedRepeatIntent>();
const events: RepeatIntentInput[] = [];
let active = true;
let usageOwner = editorialId;
let snapshotPrice = 1_500;
const repository: RepeatDownloadRepository = {
async findIntent(requestEditorialId, key) {
return intents.get(`${requestEditorialId}:${key}`) ?? null;
},
async createRepeatIntent(input) {
if (!active) throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
if (usageOwner !== input.editorialId) throw new UsageAccountingError("USAGE_NOT_FOUND");
const key = `${input.editorialId}:${input.idempotencyKey}`;
const existing = intents.get(key);
if (existing) return existing;
events.push(input);
const intent: PersistedRepeatIntent = {
id: `download-${events.length}`,
usageId: input.usageId,
assetId: "asset-1",
priceCents: 0,
billable: false,
status: "authorized",
authorizedAt: new Date("2026-08-09T09:00:00.000Z"),
requestFingerprint: input.requestFingerprint,
kind: "repeat_download",
};
intents.set(key, intent);
return intent;
},
};
return {
service: createDownloadService({ repository }),
repository,
events,
setActive(value: boolean) {
active = value;
},
setUsageOwner(value: string) {
usageOwner = value;
},
setSnapshotPrice(value: number) {
snapshotPrice = value;
},
getSnapshotPrice() {
return snapshotPrice;
},
};
}
test("creates only a free authorized event for an owned prior usage", async () => {
const { service, events, getSnapshotPrice } = createService();
const intent = await service.createRepeatDownload({
editorialId,
usageId,
note: " erneuter Abruf ",
idempotencyKey,
});
expect(intent).toMatchObject({
usageId,
assetId: "asset-1",
priceCents: 0,
billable: false,
status: "authorized",
});
expect(events).toEqual([expect.objectContaining({ note: "erneuter Abruf" })]);
expect(getSnapshotPrice()).toBe(1_500);
});
test("a changed usage snapshot price never changes the free repeat price", async () => {
const { service, setSnapshotPrice } = createService();
setSnapshotPrice(9_900);
await expect(
service.createRepeatDownload({ editorialId, usageId, idempotencyKey }),
).resolves.toMatchObject({ priceCents: 0, billable: false });
});
test("rejects a usage owned by another editorial without creating an event", async () => {
const { service, events, setUsageOwner } = createService();
setUsageOwner("66666666-6666-4666-8666-666666666666");
await expect(
service.createRepeatDownload({ editorialId, usageId, idempotencyKey }),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
expect(events).toHaveLength(0);
});
test("rejects a repeat for an inactive editorial", async () => {
const { service, events, setActive } = createService();
setActive(false);
await expect(
service.createRepeatDownload({ editorialId, usageId, idempotencyKey }),
).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" });
expect(events).toHaveLength(0);
});
test("returns the same free intent once for an equivalent retry", async () => {
const { service, events } = createService();
const input = { editorialId, usageId, note: "noch einmal", idempotencyKey };
const first = await service.createRepeatDownload(input);
const second = await service.createRepeatDownload(input);
expect(second).toEqual(first);
expect(events).toHaveLength(1);
});
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 });
await expect(
service.createRepeatDownload({ editorialId, usageId, note: "Print", idempotencyKey }),
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
expect(events).toHaveLength(1);
});
test.each([
["x".repeat(201), idempotencyKey],
[undefined, "not-a-uuid"],
] as const)("rejects malformed repeat input before repository side effects", async (note, key) => {
const { service, repository } = createService();
const findIntent = vi.spyOn(repository, "findIntent");
await expect(
service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }),
).rejects.toMatchObject({ code: "INVALID_INPUT" });
expect(findIntent).not.toHaveBeenCalled();
});
+177
View File
@@ -0,0 +1,177 @@
import "server-only";
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
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,
requestFingerprint,
UsageAccountingError,
} from "@/modules/usages/types";
import {
findPersistedIntent,
lockEditorialAccounting,
resolveIntent,
type PersistedDownloadIntent,
} from "@/modules/usages/service";
export type PersistedRepeatIntent = PersistedDownloadIntent & { kind: "repeat_download" };
export type RepeatIntentInput = {
editorialId: string;
usageId: string;
note?: string;
idempotencyKey: string;
requestFingerprint: string;
};
export type RepeatDownloadRepository = {
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
createRepeatIntent(input: RepeatIntentInput): Promise<PersistedRepeatIntent>;
};
export function createDownloadService({ repository }: { repository: RepeatDownloadRepository }) {
return {
async createRepeatDownload(rawInput: CreateRepeatDownloadInput): Promise<DownloadIntent> {
const input = normalizeRepeatInput(rawInput);
const fingerprint = requestFingerprint({
kind: "repeat_download",
editorialId: input.editorialId,
usageId: input.usageId,
note: input.note ?? null,
});
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
if (existing) return resolveIntent(existing, fingerprint, "repeat_download");
const persisted = await repository.createRepeatIntent({
...input,
requestFingerprint: fingerprint,
});
return resolveIntent(persisted, fingerprint, "repeat_download");
},
};
}
export function createRepeatDownloadRepository(
database: NodePgDatabase<typeof schema>,
): RepeatDownloadRepository {
return {
findIntent(editorialId, idempotencyKey) {
return findPersistedIntent(database, editorialId, idempotencyKey);
},
async createRepeatIntent(input) {
try {
return await database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId);
const [editorial] = await transaction
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
.for("update")
.limit(1);
if (!editorial || editorial.status !== "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
.select({ id: usages.id, assetId: usages.immichAssetId })
.from(usages)
.where(
and(
eq(usages.id, input.usageId),
eq(usages.editorialAccountId, input.editorialId),
),
)
.for("update")
.limit(1);
if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND");
const authorizedAt = new Date();
const [event] = await transaction
.insert(downloadEvents)
.values({
editorialAccountId: input.editorialId,
usageId: usage.id,
immichAssetId: usage.assetId,
authorizedAt,
status: "authorized",
repeatDownloadNote: input.note,
requestId: randomUUID(),
idempotencyKey: input.idempotencyKey,
intentKind: "repeat_download",
requestFingerprint: input.requestFingerprint,
})
.onConflictDoNothing({
target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey],
})
.returning({ id: downloadEvents.id });
if (!event) throw new RepeatIdempotencyRaceError();
return {
id: event.id,
usageId: usage.id,
assetId: usage.assetId,
priceCents: 0,
billable: false,
status: "authorized" as const,
authorizedAt,
requestFingerprint: input.requestFingerprint,
kind: "repeat_download" as const,
};
});
} catch (error) {
if (!(error instanceof RepeatIdempotencyRaceError)) throw error;
const existing = await findPersistedIntent(
database,
input.editorialId,
input.idempotencyKey,
);
if (existing) return asRepeatIntent(existing);
throw error;
}
},
};
}
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,
...(note === undefined ? {} : { note }),
idempotencyKey: input.idempotencyKey,
};
}
function asRepeatIntent(intent: PersistedDownloadIntent): PersistedRepeatIntent {
if (intent.kind !== "repeat_download") {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
return { ...intent, kind: "repeat_download" };
}
class RepeatIdempotencyRaceError extends Error {}
export const downloadService = createDownloadService({
repository: createRepeatDownloadRepository(db),
});
export const createRepeatDownload = downloadService.createRepeatDownload;
+13
View File
@@ -6,6 +6,7 @@ import { createImmichClient } from "./client";
import {
immichAlbum,
immichAlbumDetail,
immichAsset,
immichMetadataSearchResponse,
} from "../../../tests/fixtures/immich";
@@ -73,6 +74,18 @@ test("gets album details from the documented album endpoint", async () => {
await expect(client.getAlbum("album-1")).resolves.toEqual(immichAlbumDetail);
});
test("gets current asset metadata immediately before accounting", async () => {
server.use(
http.get(`${baseUrl}/api/assets/asset-1`, ({ request }) => {
expect(request.method).toBe("GET");
expect(request.headers.get("x-api-key")).toBe(apiKey);
return HttpResponse.json(immichAsset);
}),
);
await expect(client.getAsset("asset-1")).resolves.toEqual(immichAsset);
});
test("forces IMAGE and authorized album IDs in metadata search", async () => {
server.use(
http.post(`${baseUrl}/api/search/metadata`, async ({ request }) => {
+13
View File
@@ -8,6 +8,7 @@ import { ImmichClientError, type ImmichErrorCode } from "./errors";
import type {
ImmichAlbum,
ImmichAlbumSummary,
ImmichAsset,
ImmichBinary,
ImmichClient,
ImmichSearchPage,
@@ -27,6 +28,10 @@ const assetSchema = z
})
.passthrough();
const currentAssetSchema = assetSchema.extend({
type: z.enum(["IMAGE", "VIDEO"]),
});
const albumSummarySchema = z
.object({
id: z.string(),
@@ -325,6 +330,14 @@ export function createImmichClient({
signal,
);
},
getAsset(assetId, signal) {
return requestJson<ImmichAsset>(
`/assets/${encodeURIComponent(assetId)}`,
{ method: "GET" },
currentAssetSchema,
signal,
);
},
searchPhotos(input, signal) {
return requestJson<ImmichSearchPage>(
"/search/metadata",
+2 -1
View File
@@ -8,7 +8,7 @@ export type ImmichAlbumSummary = {
export type ImmichAsset = {
id: string;
type: "IMAGE";
type: "IMAGE" | "VIDEO";
originalFileName: string;
originalMimeType: string;
localDateTime: string | null;
@@ -38,6 +38,7 @@ export interface ImmichClient {
listAlbums(signal?: AbortSignal): Promise<ImmichAlbumSummary[]>;
listAlbumsForAsset(assetId: string, signal?: AbortSignal): Promise<ImmichAlbumSummary[]>;
getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>;
getAsset(assetId: string, signal?: AbortSignal): Promise<ImmichAsset>;
searchPhotos(
input: { albumIds: string[]; description?: string; page: number; size: number; type?: "IMAGE" },
signal?: AbortSignal,
+271
View File
@@ -0,0 +1,271 @@
import { expect, test, vi } from "vitest";
import {
createUsageService,
type BillableIntentInput,
type PersistedDownloadIntent,
type UsageRepository,
} from "./service";
import { UsageAccountingError, type PriorUsage } from "./types";
const editorialId = "11111111-1111-4111-8111-111111111111";
const idempotencyKey = "22222222-2222-4222-8222-222222222222";
const newUsageInput = {
editorialId,
assetId: "asset-1",
albumId: "album-1",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
idempotencyKey,
};
function createRepository() {
const intents = new Map<string, PersistedDownloadIntent>();
const usages: BillableIntentInput[] = [];
const priorUsages: PriorUsage[] = [];
let priceCents: number | null = 1_500;
let status = "active";
const repository: UsageRepository = {
async findIntent(requestEditorialId, key) {
return intents.get(`${requestEditorialId}:${key}`) ?? null;
},
async createBillableIntent(input) {
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 intent: PersistedDownloadIntent = {
id: `download-${intents.size + 1}`,
usageId: `usage-${usages.length}`,
assetId: input.assetId,
priceCents: priceCents!,
billable: true,
status: "authorized",
authorizedAt: new Date("2026-08-09T08:00:00.000Z"),
requestFingerprint: input.requestFingerprint,
kind: "new_usage",
};
intents.set(key, intent);
return intent;
},
async listPriorUsages() {
return priorUsages;
},
};
return {
repository,
intents,
usages,
priorUsages,
setPrice(value: number | null) {
priceCents = value;
},
setStatus(value: string) {
status = value;
},
};
}
function createService() {
const state = createRepository();
const immich = {
listAlbumsForAsset: vi.fn().mockResolvedValue([
{
id: "album-1",
albumName: "Presse 2026",
description: null,
albumThumbnailAssetId: "asset-1",
assetCount: 1,
},
]),
getAsset: vi.fn().mockResolvedValue({
id: "asset-1",
type: "IMAGE" as const,
originalFileName: "jubel.jpg",
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "album-1" }],
}),
};
return { ...state, immich, service: createUsageService({ repository: state.repository, immich }) };
}
test("snapshots the current editorial price and normalized Immich metadata", async () => {
const { service, usages } = createService();
const intent = await service.createNewUsage({
...newUsageInput,
purpose: " Titelgeschichte ",
reference: " Ausgabe 8/26 ",
});
expect(intent).toMatchObject({ priceCents: 1_500, billable: true, status: "authorized" });
expect(usages).toEqual([
expect.objectContaining({
assetId: "asset-1",
albumId: "album-1",
albumName: "Presse 2026",
filename: "jubel.jpg",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
}),
]);
});
test("returns the exact persisted intent for an equivalent idempotent retry", async () => {
const { service, usages, immich } = createService();
const first = await service.createNewUsage(newUsageInput);
const second = await service.createNewUsage(newUsageInput);
expect(second).toEqual(first);
expect(usages).toHaveLength(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1);
});
test("keeps the original snapshot after a price change while a new key uses the new price", async () => {
const { service, setPrice } = createService();
const original = await service.createNewUsage(newUsageInput);
setPrice(2_100);
await expect(service.createNewUsage(newUsageInput)).resolves.toEqual(original);
await expect(
service.createNewUsage({
...newUsageInput,
idempotencyKey: "33333333-3333-4333-8333-333333333333",
}),
).resolves.toMatchObject({ priceCents: 2_100 });
});
test.each([
["zero", 0],
["missing", null],
] as const)("rejects a %s current price", async (_label, price) => {
const { service, setPrice } = createService();
setPrice(price);
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "INVALID_PRICE",
});
});
test.each(["suspended", "pending_approval"])("rejects a %s editorial account", async (status) => {
const { service, setStatus } = createService();
setStatus(status);
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "EDITORIAL_NOT_ACTIVE",
});
});
test.each([
["ab", "INVALID_INPUT"],
["x".repeat(201), "INVALID_INPUT"],
["Titelgeschichte", "INVALID_INPUT", "x".repeat(201)],
["Titelgeschichte", "INVALID_INPUT", undefined, "not-a-uuid"],
] as const)(
"rejects malformed purpose, reference, or idempotency input before side effects",
async (purpose: string, code: string, reference?: string, key?: string) => {
const { service, repository, immich } = createService();
const findIntent = vi.spyOn(repository, "findIntent");
await expect(
service.createNewUsage({
...newUsageInput,
purpose,
reference: reference ?? "Ausgabe 8/26",
idempotencyKey: key ?? idempotencyKey,
}),
).rejects.toMatchObject({ code });
expect(findIntent).not.toHaveBeenCalled();
expect(immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(immich.getAsset).not.toHaveBeenCalled();
},
);
test("rejects an asset outside the exact requested album", async () => {
const { service, immich, usages } = createService();
immich.listAlbumsForAsset.mockResolvedValue([
{
id: "album-2",
albumName: "Andere Bilder",
description: null,
albumThumbnailAssetId: null,
assetCount: 1,
},
]);
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "ASSET_NOT_IN_ALBUM",
});
expect(immich.getAsset).not.toHaveBeenCalled();
expect(usages).toHaveLength(0);
});
test("rejects a missing asset immediately before accounting", async () => {
const { service, immich, usages } = createService();
immich.getAsset.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "ASSET_NOT_FOUND",
});
expect(usages).toHaveLength(0);
});
test("rejects a non-image asset immediately before accounting", async () => {
const { service, immich, usages } = createService();
immich.getAsset.mockResolvedValue({
id: "asset-1",
type: "VIDEO",
originalFileName: "clip.mp4",
originalMimeType: "video/mp4",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "album-1" }],
});
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "ASSET_NOT_IMAGE",
});
expect(usages).toHaveLength(0);
});
test("rejects reuse of an idempotency key for a materially different new usage", async () => {
const { service, usages, immich } = createService();
await service.createNewUsage(newUsageInput);
await expect(
service.createNewUsage({ ...newUsageInput, purpose: "Online-Aufmacher" }),
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
expect(usages).toHaveLength(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1);
});
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",
filename: "jubel.jpg",
albumId: "album-1",
albumName: "Presse 2026",
purpose: "Titelgeschichte",
reference: undefined,
priceCents: 1_500,
billingStatus: "open",
createdAt: new Date("2026-08-09T08:00:00.000Z"),
});
await expect(service.listPriorUsages(editorialId, "asset-1")).resolves.toEqual(priorUsages);
});
+422
View File
@@ -0,0 +1,422 @@
import "server-only";
import { randomUUID } from "node:crypto";
import { and, desc, eq, isNull, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import {
albumGrants,
auditEvents,
downloadEvents,
editorialAccounts,
usages,
} from "@/db/schema";
import type * as schema from "@/db/schema";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
import {
assertImmichIdentifier,
assertUuid,
type CreateNewUsageInput,
type DownloadIntent,
normalizeOptionalText,
normalizeRequiredText,
type PriorUsage,
requestFingerprint,
UsageAccountingError,
} from "./types";
export type PersistedDownloadIntent = DownloadIntent & {
requestFingerprint: string;
kind: "new_usage" | "repeat_download";
};
export type BillableIntentInput = {
editorialId: string;
assetId: string;
albumId: string;
albumName: string;
filename: string;
purpose: string;
reference?: string;
idempotencyKey: string;
requestFingerprint: string;
};
export type UsageRepository = {
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
createBillableIntent(input: BillableIntentInput): Promise<PersistedDownloadIntent>;
listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]>;
};
type UsageImmich = {
listAlbumsForAsset(assetId: string): Promise<ImmichAlbumSummary[]>;
getAsset(assetId: string): Promise<{
id: string;
type: string;
originalFileName: string;
}>;
};
export function createUsageService({
repository,
immich,
}: {
repository: UsageRepository;
immich: UsageImmich;
}) {
return {
async createNewUsage(rawInput: CreateNewUsageInput): Promise<DownloadIntent> {
const input = normalizeNewUsageInput(rawInput);
const fingerprint = requestFingerprint({
kind: "new_usage",
editorialId: input.editorialId,
assetId: input.assetId,
albumId: input.albumId,
purpose: input.purpose,
reference: input.reference ?? null,
});
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
if (existing) return resolveIntent(existing, fingerprint, "new_usage");
const album = await loadRequestedAlbum(immich, input.assetId, input.albumId);
const asset = await loadImageAsset(immich, input.assetId);
const persisted = await repository.createBillableIntent({
...input,
albumName: normalizeUpstreamSnapshot(album.albumName),
filename: normalizeUpstreamSnapshot(asset.originalFileName),
requestFingerprint: fingerprint,
});
return resolveIntent(persisted, fingerprint, "new_usage");
},
async listPriorUsages(editorialId: string, assetId: string): Promise<PriorUsage[]> {
assertUuid(editorialId);
assertImmichIdentifier(assetId);
return repository.listPriorUsages(editorialId, assetId);
},
};
}
export function createUsageServiceRepository(
database: NodePgDatabase<typeof schema>,
): UsageRepository {
return {
findIntent(editorialId, idempotencyKey) {
return findPersistedIntent(database, editorialId, idempotencyKey);
},
async createBillableIntent(input) {
try {
return await database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId);
const [editorial] = await transaction
.select({
id: editorialAccounts.id,
status: editorialAccounts.status,
currentPriceCents: editorialAccounts.currentPriceCents,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
.for("update")
.limit(1);
if (!editorial || editorial.status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
if (
!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0
) {
throw new UsageAccountingError("INVALID_PRICE");
}
const [grant] = await transaction
.select({ id: albumGrants.id })
.from(albumGrants)
.where(
and(
eq(albumGrants.editorialAccountId, input.editorialId),
eq(albumGrants.immichAlbumId, input.albumId),
isNull(albumGrants.revokedAt),
),
)
.for("update")
.limit(1);
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
const existing = await findPersistedIntentInTransaction(
transaction,
input.editorialId,
input.idempotencyKey,
);
if (existing) return existing;
const createdAt = new Date();
const [usage] = await transaction
.insert(usages)
.values({
editorialAccountId: input.editorialId,
immichAssetId: input.assetId,
filenameSnapshot: input.filename,
immichAlbumIdSnapshot: input.albumId,
albumNameSnapshot: input.albumName,
purpose: input.purpose,
internalReference: input.reference,
priceCents: editorial.currentPriceCents!,
billingStatus: "open",
createdAt,
})
.returning({ id: usages.id });
const requestId = randomUUID();
const [event] = await transaction
.insert(downloadEvents)
.values({
editorialAccountId: input.editorialId,
usageId: usage.id,
immichAssetId: input.assetId,
authorizedAt: createdAt,
status: "authorized",
requestId,
idempotencyKey: input.idempotencyKey,
intentKind: "new_usage",
requestFingerprint: input.requestFingerprint,
})
.onConflictDoNothing({
target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey],
})
.returning({ id: downloadEvents.id });
if (!event) throw new IdempotencyRaceError();
await transaction.insert(auditEvents).values({
eventType: "billable_usage_created",
actorType: "editorial",
entityType: "usage",
entityId: usage.id,
newValues: {
editorialId: input.editorialId,
assetId: input.assetId,
albumId: input.albumId,
priceCents: editorial.currentPriceCents,
downloadId: event.id,
},
occurredAt: createdAt,
requestId,
});
return {
id: event.id,
usageId: usage.id,
assetId: input.assetId,
priceCents: editorial.currentPriceCents!,
billable: true,
status: "authorized" as const,
authorizedAt: createdAt,
requestFingerprint: input.requestFingerprint,
kind: "new_usage" as const,
};
});
} catch (error) {
if (!(error instanceof IdempotencyRaceError)) throw error;
const existing = await findPersistedIntent(
database,
input.editorialId,
input.idempotencyKey,
);
if (existing) return existing;
throw error;
}
},
async listPriorUsages(editorialId, assetId) {
const rows = await database
.select({
id: usages.id,
assetId: usages.immichAssetId,
filename: usages.filenameSnapshot,
albumId: usages.immichAlbumIdSnapshot,
albumName: usages.albumNameSnapshot,
purpose: usages.purpose,
reference: usages.internalReference,
priceCents: usages.priceCents,
billingStatus: usages.billingStatus,
createdAt: usages.createdAt,
})
.from(usages)
.where(
and(
eq(usages.editorialAccountId, editorialId),
eq(usages.immichAssetId, assetId),
),
)
.orderBy(desc(usages.createdAt));
return rows.map((row) => ({ ...row, reference: row.reference ?? undefined }));
},
};
}
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,
purpose,
...(reference === undefined ? {} : { reference }),
idempotencyKey: input.idempotencyKey,
};
}
async function loadRequestedAlbum(
immich: UsageImmich,
assetId: string,
albumId: string,
): Promise<ImmichAlbumSummary> {
let albums: ImmichAlbumSummary[];
try {
albums = await immich.listAlbumsForAsset(assetId);
} catch {
throw new UsageAccountingError("IMMICH_UNAVAILABLE");
}
const album = albums.find((candidate) => candidate.id === albumId);
if (!album) throw new UsageAccountingError("ASSET_NOT_IN_ALBUM");
return album;
}
async function loadImageAsset(immich: UsageImmich, assetId: string) {
let asset: Awaited<ReturnType<UsageImmich["getAsset"]>>;
try {
asset = await immich.getAsset(assetId);
} catch (error) {
if (hasCode(error, "IMMICH_NOT_FOUND")) throw new UsageAccountingError("ASSET_NOT_FOUND");
throw new UsageAccountingError("IMMICH_UNAVAILABLE");
}
if (asset.id !== assetId) throw new UsageAccountingError("IMMICH_UNAVAILABLE");
if (asset.type !== "IMAGE") throw new UsageAccountingError("ASSET_NOT_IMAGE");
return asset;
}
function normalizeUpstreamSnapshot(value: string): string {
const normalized = value.trim();
if (!normalized) throw new UsageAccountingError("IMMICH_UNAVAILABLE");
return normalized;
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === "object" && error !== null && "code" in error && error.code === code;
}
export function resolveIntent(
persisted: PersistedDownloadIntent,
fingerprint: string,
kind: PersistedDownloadIntent["kind"],
): DownloadIntent {
if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted;
return intent;
}
class IdempotencyRaceError extends Error {}
export async function findPersistedIntent(
database: NodePgDatabase<typeof schema>,
editorialId: string,
idempotencyKey: string,
): Promise<PersistedDownloadIntent | null> {
const [row] = await database
.select(intentSelection)
.from(downloadEvents)
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
.where(
and(
eq(downloadEvents.editorialAccountId, editorialId),
eq(downloadEvents.idempotencyKey, idempotencyKey),
),
)
.limit(1);
return row ? persistedIntent(row) : null;
}
async function findPersistedIntentInTransaction(
transaction: NodePgDatabase<typeof schema>,
editorialId: string,
idempotencyKey: string,
): Promise<PersistedDownloadIntent | null> {
const [row] = await transaction
.select(intentSelection)
.from(downloadEvents)
.innerJoin(usages, eq(usages.id, downloadEvents.usageId))
.where(
and(
eq(downloadEvents.editorialAccountId, editorialId),
eq(downloadEvents.idempotencyKey, idempotencyKey),
),
)
.limit(1);
return row ? persistedIntent(row) : null;
}
const intentSelection = {
id: downloadEvents.id,
usageId: downloadEvents.usageId,
assetId: downloadEvents.immichAssetId,
authorizedAt: downloadEvents.authorizedAt,
intentKind: downloadEvents.intentKind,
requestFingerprint: downloadEvents.requestFingerprint,
usagePriceCents: usages.priceCents,
};
function persistedIntent(row: {
id: string;
usageId: string;
assetId: string;
authorizedAt: Date;
intentKind: string;
requestFingerprint: string;
usagePriceCents: number;
}): PersistedDownloadIntent {
if (
row.intentKind !== "new_usage" &&
row.intentKind !== "repeat_download"
) {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
return {
id: row.id,
usageId: row.usageId,
assetId: row.assetId,
priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0,
billable: row.intentKind === "new_usage",
status: "authorized",
authorizedAt: row.authorizedAt,
requestFingerprint: row.requestFingerprint,
kind: row.intentKind,
};
}
export async function lockEditorialAccounting(
transaction: NodePgDatabase<typeof schema>,
editorialId: string,
): Promise<void> {
await transaction.execute(
sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`,
);
}
export const usageService = createUsageService({
repository: createUsageServiceRepository(db),
immich: immichClient,
});
export const createNewUsage = usageService.createNewUsage;
export const listPriorUsages = usageService.listPriorUsages;
+113
View File
@@ -0,0 +1,113 @@
import { createHash } from "node:crypto";
export type CreateNewUsageInput = {
editorialId: string;
assetId: string;
albumId: string;
purpose: string;
reference?: string;
idempotencyKey: string;
};
export type CreateRepeatDownloadInput = {
editorialId: string;
usageId: string;
note?: string;
idempotencyKey: string;
};
export type DownloadIntent = {
id: string;
usageId: string;
assetId: string;
priceCents: number;
billable: boolean;
status: "authorized";
authorizedAt: Date;
};
export type PriorUsage = {
id: string;
assetId: string;
filename: string;
albumId: string;
albumName: string;
purpose: string;
reference: string | undefined;
priceCents: number;
billingStatus: "open" | "billed" | "reopened";
createdAt: Date;
};
export type UsageAccountingErrorCode =
| "INVALID_INPUT"
| "IDEMPOTENCY_CONFLICT"
| "EDITORIAL_NOT_ACTIVE"
| "INVALID_PRICE"
| "ALBUM_NOT_GRANTED"
| "ASSET_NOT_IN_ALBUM"
| "ASSET_NOT_FOUND"
| "ASSET_NOT_IMAGE"
| "IMMICH_UNAVAILABLE"
| "USAGE_NOT_FOUND";
export class UsageAccountingError extends Error {
readonly name = "UsageAccountingError";
constructor(readonly code: UsageAccountingErrorCode) {
super(code);
}
}
type FingerprintPayload =
| {
kind: "new_usage";
editorialId: string;
assetId: string;
albumId: string;
purpose: string;
reference: string | null;
}
| {
kind: "repeat_download";
editorialId: string;
usageId: string;
note: string | null;
};
export function requestFingerprint(payload: FingerprintPayload): string {
return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
}
export function normalizeRequiredText(value: unknown, minimum: number, maximum: number): string {
if (typeof value !== "string") throw new UsageAccountingError("INVALID_INPUT");
const normalized = value.trim();
const length = [...normalized].length;
if (length < minimum || length > maximum) {
throw new UsageAccountingError("INVALID_INPUT");
}
return normalized;
}
export function normalizeOptionalText(value: unknown, maximum: number): string | undefined {
if (value === undefined) return undefined;
if (typeof value !== "string") throw new UsageAccountingError("INVALID_INPUT");
const normalized = value.trim();
if ([...normalized].length > maximum) throw new UsageAccountingError("INVALID_INPUT");
return normalized || undefined;
}
export function assertUuid(value: unknown): asserts value is string {
if (
typeof value !== "string" ||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
) {
throw new UsageAccountingError("INVALID_INPUT");
}
}
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");
}
}