import "server-only"; import { randomUUID } from "node:crypto"; import { and, desc, eq, exists, inArray, 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 { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility"; import { type CreateNewUsageInput, type DownloadIntent, normalizeOptionalText, normalizeRequiredText, normalizeUuid, type PriorUsage, requestFingerprint, UsageAccountingError, } from "./types"; export type PersistedDownloadIntent = Omit & { status: typeof downloadEvents.$inferSelect.status; 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; createBillableIntent( input: BillableIntentInput, refreshCurrentAsset: () => Promise<{ albumName: string; filename: string }>, ): Promise; listPriorUsages(editorialId: string, assetId: string): Promise; }; type UsageImmich = { getAlbum(albumId: string): Promise<{ id: string; albumName: string }>; getAsset(assetId: string): Promise<{ id: string; originalFileName: string; originalMimeType: string; type: string; albums: Array<{ id: string }>; }>; }; export function createUsageService({ repository, immich, }: { repository: UsageRepository; immich: UsageImmich; }) { return { async createNewUsage(rawInput: CreateNewUsageInput): Promise { 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 asset = await getValidatedAsset(immich, input.assetId); const album = await loadRequestedAlbum(immich, asset, input.albumId); const persisted = await repository.createBillableIntent({ ...input, albumName: normalizeUpstreamSnapshot(album.albumName), filename: normalizeUpstreamSnapshot(asset.originalFileName), requestFingerprint: fingerprint, }, async () => { const currentAsset = await getValidatedAsset(immich, input.assetId); const currentAlbum = await loadRequestedAlbum(immich, currentAsset, input.albumId); return { albumName: normalizeUpstreamSnapshot(currentAlbum.albumName), filename: normalizeUpstreamSnapshot(currentAsset.originalFileName), }; }); return resolveIntent(persisted, fingerprint, "new_usage"); }, async listPriorUsages(editorialId: string, assetId: string): Promise { return repository.listPriorUsages(normalizeUuid(editorialId), normalizeUuid(assetId)); }, }; } export function createUsageServiceRepository( database: NodePgDatabase, ): UsageRepository { return { findIntent(editorialId, idempotencyKey) { return findPersistedIntent(database, editorialId, idempotencyKey); }, async createBillableIntent(input, refreshCurrentAsset) { try { return await database.transaction(async (transaction) => { await lockEditorialAccounting(transaction, input.editorialId); const existing = await findPersistedIntentInTransaction( transaction, input.editorialId, input.idempotencyKey, ); if (existing) return existing; const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status, currentPriceCents: editorialAccounts.currentPriceCents, flatrateActive: editorialAccounts.flatrateActive, flatrateAssetLimit: editorialAccounts.flatrateAssetLimit, }) .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), sql`lower(${albumGrants.immichAlbumId}) = ${input.albumId}`, isNull(albumGrants.revokedAt), ), ) .for("update") .limit(1); if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED"); let priceCents = editorial.currentPriceCents!; if (editorial.flatrateActive) { if (editorial.flatrateAssetLimit === null) { priceCents = 0; // Unlimited flatrate } else { // Limited flatrate - check how many usages this month const now = new Date(); const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)); const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999)); const [{ count }] = await transaction .select({ count: sql`cast(count(*) as integer)` }) .from(usages) .where( and( eq(usages.editorialAccountId, input.editorialId), sql`${usages.createdAt} >= ${startOfMonth}`, sql`${usages.createdAt} <= ${endOfMonth}`, inArray(usages.billingStatus, ["open", "billed", "reopened"]), // For flatrate, we only count usages that were originally free via the flatrate // so we compare against priceCents = 0. Wait, any usage counts towards the limit? // Yes, any billable usage this month counts towards the limit. eq(usages.priceCents, 0) ) ); if (count < editorial.flatrateAssetLimit) { priceCents = 0; } } } // This is the last cross-system authorization snapshot available to the // portal. Immich may still change after it returns, but no portal work is // allowed between this refresh and the accounting inserts. const currentAsset = await refreshCurrentAsset(); const createdAt = new Date(); const [usage] = await transaction .insert(usages) .values({ editorialAccountId: input.editorialId, immichAssetId: input.assetId, filenameSnapshot: currentAsset.filename, immichAlbumIdSnapshot: input.albumId, albumNameSnapshot: currentAsset.albumName, purpose: input.purpose, internalReference: input.reference, priceCents: priceCents, 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: priceCents, downloadId: event.id, }, occurredAt: createdAt, requestId, }); return { id: event.id, usageId: usage.id, assetId: input.assetId, priceCents: priceCents, 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 deliveredOriginal = database .select({ id: downloadEvents.id }) .from(downloadEvents) .where(deliveredOriginalEventCondition(editorialId, usages.id)); 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), inArray(usages.billingStatus, ["open", "billed", "reopened"]), exists(deliveredOriginal), ), ) .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"); const purpose = normalizeRequiredText(input.purpose, 3, 200); const reference = normalizeOptionalText(input.reference, 200); return { editorialId: normalizeUuid(input.editorialId), assetId: normalizeUuid(input.assetId), albumId: normalizeUuid(input.albumId), purpose, ...(reference === undefined ? {} : { reference }), idempotencyKey: normalizeUuid(input.idempotencyKey), }; } async function loadRequestedAlbum( immich: UsageImmich, asset: { albums: Array<{ id: string }> }, albumId: string, ): Promise<{ id: string; albumName: string }> { if (!asset.albums.some((a) => a.id === albumId)) { throw new UsageAccountingError("ASSET_NOT_IN_ALBUM"); } try { return await immich.getAlbum(albumId); } catch { throw new UsageAccountingError("IMMICH_UNAVAILABLE"); } } async function getValidatedAsset(immich: UsageImmich, assetId: string) { let asset: Awaited>; 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"); } if (persisted.status !== "authorized") { throw new UsageAccountingError("USAGE_NOT_FOUND"); } const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted; return { ...intent, status: "authorized" }; } class IdempotencyRaceError extends Error {} export async function findPersistedIntent( database: NodePgDatabase, editorialId: string, idempotencyKey: string, ): Promise { const rows = await database .select(intentSelection) .from(downloadEvents) .innerJoin(usages, eq(usages.id, downloadEvents.usageId)) .where( and( eq(downloadEvents.editorialAccountId, editorialId), sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`, ), ) .limit(2); if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); return rows[0] ? persistedIntent(rows[0]) : null; } async function findPersistedIntentInTransaction( transaction: NodePgDatabase, editorialId: string, idempotencyKey: string, ): Promise { const rows = await transaction .select(intentSelection) .from(downloadEvents) .innerJoin(usages, eq(usages.id, downloadEvents.usageId)) .where( and( eq(downloadEvents.editorialAccountId, editorialId), sql`lower(${downloadEvents.idempotencyKey}) = ${idempotencyKey}`, ), ) .limit(2); if (rows.length > 1) throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); return rows[0] ? persistedIntent(rows[0]) : null; } const intentSelection = { id: downloadEvents.id, usageId: downloadEvents.usageId, assetId: downloadEvents.immichAssetId, authorizedAt: downloadEvents.authorizedAt, eventStatus: downloadEvents.status, intentKind: downloadEvents.intentKind, requestFingerprint: downloadEvents.requestFingerprint, usagePriceCents: usages.priceCents, }; function persistedIntent(row: { id: string; usageId: string; assetId: string; authorizedAt: Date; eventStatus: PersistedDownloadIntent["status"]; 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: row.eventStatus, authorizedAt: row.authorizedAt, requestFingerprint: row.requestFingerprint, kind: row.intentKind, }; } export async function lockEditorialAccounting( transaction: NodePgDatabase, editorialId: string, ): Promise { 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;