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,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;
|
||||
Reference in new issue
Block a user