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