feat: add usage and download intent accounting
This commit is contained in:
1 parent
846904f3db
commit
22fe6bf659
14 files changed
+3008
-2
No files matched your search
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE "download_events" ADD COLUMN "intent_kind" text DEFAULT 'new_usage' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "download_events" ADD COLUMN "request_fingerprint" varchar(64);--> statement-breakpoint
|
||||
UPDATE "download_events"
|
||||
SET "request_fingerprint" = md5("editorial_account_id"::text || ':' || "id"::text) || md5("id"::text || ':' || "editorial_account_id"::text);--> statement-breakpoint
|
||||
ALTER TABLE "download_events" ALTER COLUMN "request_fingerprint" 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_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$');
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,6 +15,13 @@
|
||||
"when": 1786303607054,
|
||||
"tag": "0001_editorial_approval_notice",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1786308409516,
|
||||
"tag": "0002_accounting_intents",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
+23
-1
@@ -1,4 +1,16 @@
|
||||
import { integer, pgEnum, pgTable, text, timestamp, uniqueIndex, uuid, bigint } from "drizzle-orm/pg-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
import {
|
||||
bigint,
|
||||
check,
|
||||
integer,
|
||||
pgEnum,
|
||||
pgTable,
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
uuid,
|
||||
varchar,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
import { editorialAccounts } from "./editorials";
|
||||
import { billingReports } from "./billing";
|
||||
@@ -53,11 +65,21 @@ export const downloadEvents = pgTable(
|
||||
repeatDownloadNote: text("repeat_download_note"),
|
||||
requestId: uuid("request_id").notNull(),
|
||||
idempotencyKey: text("idempotency_key").notNull(),
|
||||
intentKind: text("intent_kind").notNull().default("new_usage"),
|
||||
requestFingerprint: varchar("request_fingerprint", { length: 64 }).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("download_events_editorial_idempotency_key_unique").on(
|
||||
table.editorialAccountId,
|
||||
table.idempotencyKey,
|
||||
),
|
||||
check(
|
||||
"download_events_intent_kind_check",
|
||||
sql`${table.intentKind} in ('new_usage', 'repeat_download')`,
|
||||
),
|
||||
check(
|
||||
"download_events_request_fingerprint_hex_check",
|
||||
sql`${table.requestFingerprint} ~ '^[0-9a-f]{64}$'`,
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ type DownloadSeed = {
|
||||
};
|
||||
|
||||
export type PostgresTestDatabase = {
|
||||
database: NodePgDatabase<typeof schema>;
|
||||
pool: Pool;
|
||||
seedEditorialWithUsage(): Promise<DownloadSeed>;
|
||||
insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
@@ -33,6 +35,8 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
|
||||
const db = drizzle({ client: pool, schema });
|
||||
|
||||
return {
|
||||
database: db,
|
||||
pool,
|
||||
async seedEditorialWithUsage() {
|
||||
return seedEditorialWithUsage(db);
|
||||
},
|
||||
@@ -43,6 +47,7 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
|
||||
immichAssetId: input.assetId,
|
||||
requestId: randomUUID(),
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
requestFingerprint: "0".repeat(64),
|
||||
});
|
||||
},
|
||||
async stop() {
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, count, eq } from "drizzle-orm";
|
||||
import { afterAll, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
albumGrants,
|
||||
auditEvents,
|
||||
downloadEvents,
|
||||
editorialAccounts,
|
||||
usages,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import {
|
||||
createUsageService,
|
||||
createUsageServiceRepository,
|
||||
} from "@/modules/usages/service";
|
||||
import {
|
||||
createDownloadService,
|
||||
createRepeatDownloadRepository,
|
||||
} from "@/modules/downloads/service";
|
||||
import { startPostgres } from "./postgres";
|
||||
|
||||
const testDb = await startPostgres();
|
||||
const database = testDb.database;
|
||||
|
||||
afterAll(() => testDb.stop());
|
||||
|
||||
const asset = {
|
||||
id: "asset-1",
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
albums: [{ id: "album-1" }],
|
||||
};
|
||||
|
||||
function createServices() {
|
||||
const immich = {
|
||||
listAlbumsForAsset: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "album-1",
|
||||
albumName: "Presse 2026",
|
||||
description: null,
|
||||
albumThumbnailAssetId: "asset-1",
|
||||
assetCount: 1,
|
||||
},
|
||||
]),
|
||||
getAsset: vi.fn().mockResolvedValue(asset),
|
||||
};
|
||||
return {
|
||||
usageService: createUsageService({
|
||||
repository: createUsageServiceRepository(database),
|
||||
immich,
|
||||
}),
|
||||
downloadService: createDownloadService({
|
||||
repository: createRepeatDownloadRepository(database),
|
||||
}),
|
||||
immich,
|
||||
};
|
||||
}
|
||||
|
||||
async function seedEditorial({
|
||||
status = "active",
|
||||
priceCents = 1_500,
|
||||
albumId = "album-1",
|
||||
revoked = false,
|
||||
}: {
|
||||
status?: "active" | "suspended" | "pending_approval";
|
||||
priceCents?: number | null;
|
||||
albumId?: string;
|
||||
revoked?: boolean;
|
||||
} = {}) {
|
||||
const userId = randomUUID();
|
||||
const editorialId = randomUUID();
|
||||
await database.insert(users).values({
|
||||
id: userId,
|
||||
name: "Test Redaktion",
|
||||
email: `${userId}@example.com`,
|
||||
emailVerified: true,
|
||||
});
|
||||
await database.insert(editorialAccounts).values({
|
||||
id: editorialId,
|
||||
userId,
|
||||
name: "Test Redaktion",
|
||||
contactName: "Testkontakt",
|
||||
loginEmail: `${userId}@example.com`,
|
||||
status,
|
||||
currentPriceCents: priceCents,
|
||||
});
|
||||
await database.insert(albumGrants).values({
|
||||
editorialAccountId: editorialId,
|
||||
immichAlbumId: albumId,
|
||||
revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null,
|
||||
});
|
||||
return editorialId;
|
||||
}
|
||||
|
||||
function newInput(editorialId: string, idempotencyKey = randomUUID()) {
|
||||
return {
|
||||
editorialId,
|
||||
assetId: "asset-1",
|
||||
albumId: "album-1",
|
||||
purpose: "Titelgeschichte",
|
||||
reference: "Ausgabe 8/26",
|
||||
idempotencyKey,
|
||||
};
|
||||
}
|
||||
|
||||
test("atomically snapshots price and metadata, authorizes one event, and audits no secrets", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService } = createServices();
|
||||
const input = newInput(editorialId);
|
||||
|
||||
const intent = await usageService.createNewUsage(input);
|
||||
|
||||
const [usage] = await database.select().from(usages).where(eq(usages.id, intent.usageId));
|
||||
const [event] = await database.select().from(downloadEvents).where(eq(downloadEvents.id, intent.id));
|
||||
const [audit] = await database
|
||||
.select()
|
||||
.from(auditEvents)
|
||||
.where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, intent.usageId)));
|
||||
expect(usage).toMatchObject({
|
||||
editorialAccountId: editorialId,
|
||||
immichAssetId: "asset-1",
|
||||
filenameSnapshot: "jubel.jpg",
|
||||
immichAlbumIdSnapshot: "album-1",
|
||||
albumNameSnapshot: "Presse 2026",
|
||||
purpose: "Titelgeschichte",
|
||||
internalReference: "Ausgabe 8/26",
|
||||
priceCents: 1_500,
|
||||
billingStatus: "open",
|
||||
});
|
||||
expect(event).toMatchObject({
|
||||
editorialAccountId: editorialId,
|
||||
usageId: intent.usageId,
|
||||
status: "authorized",
|
||||
intentKind: "new_usage",
|
||||
});
|
||||
expect(audit).toMatchObject({ actorType: "editorial", entityType: "usage" });
|
||||
expect(JSON.stringify(audit)).not.toContain(input.idempotencyKey);
|
||||
expect(JSON.stringify(audit)).not.toContain("test-immich-key");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["zero price", "active", 0, false, "INVALID_PRICE"],
|
||||
["missing price", "active", null, false, "INVALID_PRICE"],
|
||||
["suspended account", "suspended", 1_500, false, "EDITORIAL_NOT_ACTIVE"],
|
||||
["revoked grant", "active", 1_500, true, "ALBUM_NOT_GRANTED"],
|
||||
] as const)("rejects %s transactionally without accounting rows", async (_label, status, priceCents, revoked, code) => {
|
||||
const editorialId = await seedEditorial({ status, priceCents, revoked });
|
||||
const { usageService } = createServices();
|
||||
|
||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code });
|
||||
const [usageCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(usages)
|
||||
.where(eq(usages.editorialAccountId, editorialId));
|
||||
const [eventCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(downloadEvents)
|
||||
.where(eq(downloadEvents.editorialAccountId, editorialId));
|
||||
expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 });
|
||||
});
|
||||
|
||||
test("requires an active grant for the exact requested album", async () => {
|
||||
const editorialId = await seedEditorial({ albumId: "album-2" });
|
||||
const { usageService } = createServices();
|
||||
|
||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
|
||||
code: "ALBUM_NOT_GRANTED",
|
||||
});
|
||||
});
|
||||
|
||||
test("same-key concurrency across database clients creates exactly one usage, event, and audit", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService } = createServices();
|
||||
const input = newInput(editorialId);
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
usageService.createNewUsage(input),
|
||||
usageService.createNewUsage(input),
|
||||
]);
|
||||
|
||||
expect(second).toEqual(first);
|
||||
const [usageCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(usages)
|
||||
.where(eq(usages.editorialAccountId, editorialId));
|
||||
const [eventCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(downloadEvents)
|
||||
.where(eq(downloadEvents.editorialAccountId, editorialId));
|
||||
const [auditCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(auditEvents)
|
||||
.where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, first.usageId)));
|
||||
expect({ usages: usageCount.value, events: eventCount.value, audits: auditCount.value }).toEqual({
|
||||
usages: 1,
|
||||
events: 1,
|
||||
audits: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test("the same key may be reused by a different editorial but not for a different payload", async () => {
|
||||
const firstEditorialId = await seedEditorial();
|
||||
const secondEditorialId = await seedEditorial();
|
||||
const { usageService } = createServices();
|
||||
const key = randomUUID();
|
||||
await usageService.createNewUsage(newInput(firstEditorialId, key));
|
||||
|
||||
await expect(
|
||||
usageService.createNewUsage({ ...newInput(firstEditorialId, key), purpose: "Online-Aufmacher" }),
|
||||
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
|
||||
await expect(usageService.createNewUsage(newInput(secondEditorialId, key))).resolves.toMatchObject({
|
||||
billable: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("an audit failure rolls back both the usage and authorized event", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService } = createServices();
|
||||
await testDb.pool.query(`
|
||||
create function reject_billable_usage_audit() returns trigger language plpgsql as $$
|
||||
begin
|
||||
if new.event_type = 'billable_usage_created' then raise exception 'audit rejected'; end if;
|
||||
return new;
|
||||
end $$
|
||||
`);
|
||||
await testDb.pool.query(`
|
||||
create trigger reject_billable_usage_audit before insert on audit_events
|
||||
for each row execute function reject_billable_usage_audit()
|
||||
`);
|
||||
|
||||
try {
|
||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toThrow("audit rejected");
|
||||
} finally {
|
||||
await testDb.pool.query("drop trigger reject_billable_usage_audit on audit_events");
|
||||
await testDb.pool.query("drop function reject_billable_usage_audit()");
|
||||
}
|
||||
|
||||
const [usageCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(usages)
|
||||
.where(eq(usages.editorialAccountId, editorialId));
|
||||
const [eventCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(downloadEvents)
|
||||
.where(eq(downloadEvents.editorialAccountId, editorialId));
|
||||
expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 });
|
||||
});
|
||||
|
||||
test("a repeat remains free after a price change and creates no additional usage", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService, downloadService } = createServices();
|
||||
const first = await usageService.createNewUsage(newInput(editorialId));
|
||||
await database
|
||||
.update(editorialAccounts)
|
||||
.set({ currentPriceCents: 2_100 })
|
||||
.where(eq(editorialAccounts.id, editorialId));
|
||||
|
||||
const repeat = await downloadService.createRepeatDownload({
|
||||
editorialId,
|
||||
usageId: first.usageId,
|
||||
note: "Web-Ausgabe",
|
||||
idempotencyKey: randomUUID(),
|
||||
});
|
||||
|
||||
expect(repeat).toMatchObject({ usageId: first.usageId, priceCents: 0, billable: false });
|
||||
const [usageCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(usages)
|
||||
.where(eq(usages.editorialAccountId, editorialId));
|
||||
expect(usageCount.value).toBe(1);
|
||||
});
|
||||
|
||||
test("same-key repeat concurrency creates one free event", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService, downloadService } = createServices();
|
||||
const first = await usageService.createNewUsage(newInput(editorialId));
|
||||
const repeatInput = {
|
||||
editorialId,
|
||||
usageId: first.usageId,
|
||||
note: "Web-Ausgabe",
|
||||
idempotencyKey: randomUUID(),
|
||||
};
|
||||
|
||||
const [repeatOne, repeatTwo] = await Promise.all([
|
||||
downloadService.createRepeatDownload(repeatInput),
|
||||
downloadService.createRepeatDownload(repeatInput),
|
||||
]);
|
||||
|
||||
expect(repeatTwo).toEqual(repeatOne);
|
||||
const [eventCount] = await database
|
||||
.select({ value: count() })
|
||||
.from(downloadEvents)
|
||||
.where(and(eq(downloadEvents.usageId, first.usageId), eq(downloadEvents.intentKind, "repeat_download")));
|
||||
expect(eventCount.value).toBe(1);
|
||||
});
|
||||
|
||||
test("a suspended owner cannot create a repeat event", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService, downloadService } = createServices();
|
||||
const first = await usageService.createNewUsage(newInput(editorialId));
|
||||
await database
|
||||
.update(editorialAccounts)
|
||||
.set({ status: "suspended" })
|
||||
.where(eq(editorialAccounts.id, editorialId));
|
||||
|
||||
await expect(
|
||||
downloadService.createRepeatDownload({
|
||||
editorialId,
|
||||
usageId: first.usageId,
|
||||
idempotencyKey: randomUUID(),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" });
|
||||
});
|
||||
|
||||
test("repeat ownership is scoped to the active editorial", async () => {
|
||||
const ownerId = await seedEditorial();
|
||||
const otherEditorialId = await seedEditorial();
|
||||
const { usageService, downloadService } = createServices();
|
||||
const first = await usageService.createNewUsage(newInput(ownerId));
|
||||
|
||||
await expect(
|
||||
downloadService.createRepeatDownload({
|
||||
editorialId: otherEditorialId,
|
||||
usageId: first.usageId,
|
||||
idempotencyKey: randomUUID(),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
|
||||
});
|
||||
Reference in new issue
Block a user