import "server-only"; import { and, desc, eq, exists, inArray, sql } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; import { auditEvents, downloadEvents, editorialAccounts, usages } from "@/db/schema"; import type * as schema from "@/db/schema"; import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types"; import { deliveredOriginalEventCondition, hasDeliveredOriginal, isFreeRepeatEligible, } from "./eligibility"; export const HISTORY_PAGE_SIZE = 20; export const HISTORY_MAX_PAGE = 1_000; export const HISTORY_ATTEMPT_PAGE_SIZE = 25; export const DOWNLOAD_OPTIONS_MAX_ASSETS = 60; export const DOWNLOAD_OPTIONS_MAX_USAGES = 300; export type ClaimedDownload = { id: string; usageId: string; assetId: string; albumId: string; filename: string; intentKind: "new_usage" | "repeat_download" | "legacy"; }; export type DownloadClaim = | { outcome: "claimed"; download: ClaimedDownload } | { outcome: "not_found" } | { outcome: "not_authorized" }; export type DownloadDeliveryRepository = { claimAuthorized(editorialId: string, downloadId: string): Promise; failBeforeDelivery( downloadId: string, options: { voidNewUsage: boolean }, ): Promise; markCompleted(downloadId: string, transferredBytes: number): Promise; markInterrupted(downloadId: string, transferredBytes: number): Promise; }; type StreamAccountingRepository = Pick< DownloadDeliveryRepository, "failBeforeDelivery" | "markCompleted" | "markInterrupted" >; export function streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure, repository, }: { downloadId: string; upstream: ReadableStream; voidNewUsageOnFailure: boolean; repository: StreamAccountingRepository; }): ReadableStream { const reader = upstream.getReader(); let transferredBytes = 0; let stopped = false; let released = false; let terminal: Promise | undefined; function releaseReader() { if (released) return; released = true; try { reader.releaseLock(); } catch { // The reader may still have a pending read during a client cancellation. } } function settle(kind: "completed" | "interrupted" | "failed_before_delivery") { terminal ??= (async () => { if (kind === "completed") { await repository.markCompleted(downloadId, transferredBytes); } else if (kind === "interrupted") { await repository.markInterrupted(downloadId, transferredBytes); } else { await repository.failBeforeDelivery(downloadId, { voidNewUsage: voidNewUsageOnFailure, }); } })(); return terminal; } return new ReadableStream({ async pull(controller) { if (stopped) return; try { const { done, value } = await reader.read(); if (stopped) return; if (done) { await settle("completed"); stopped = true; releaseReader(); controller.close(); return; } controller.enqueue(value); transferredBytes += value.byteLength; if (!Number.isSafeInteger(transferredBytes)) { throw new Error("Transferred byte count exceeds the supported range"); } } catch (error) { if (stopped) return; stopped = true; await settle(transferredBytes === 0 ? "failed_before_delivery" : "interrupted").catch( () => undefined, ); releaseReader(); controller.error(error); } }, async cancel(reason) { if (stopped) return; stopped = true; const accounting = settle( transferredBytes === 0 ? "failed_before_delivery" : "interrupted", ); await Promise.allSettled([reader.cancel(reason), accounting]); releaseReader(); }, }); } export function createDownloadDeliveryRepository( database: NodePgDatabase, ): DownloadDeliveryRepository { return { async claimAuthorized(editorialId, downloadId) { return database.transaction(async (transaction) => { const [candidate] = await transaction .select({ id: downloadEvents.id, usageId: downloadEvents.usageId, assetId: downloadEvents.immichAssetId, intentKind: downloadEvents.intentKind, status: downloadEvents.status, }) .from(downloadEvents) .where( and( eq(downloadEvents.id, downloadId), eq(downloadEvents.editorialAccountId, editorialId), ), ) .limit(1); if (!candidate) return { outcome: "not_found" } as const; if (candidate.status !== "authorized") { return { outcome: "not_authorized" } as const; } const [usage] = await transaction .select({ filename: usages.filenameSnapshot, assetId: usages.immichAssetId, albumId: usages.immichAlbumIdSnapshot, billingStatus: usages.billingStatus, }) .from(usages) .where( and( eq(usages.id, candidate.usageId), eq(usages.editorialAccountId, editorialId), ), ) .for("update") .limit(1); if (!usage || usage.assetId !== candidate.assetId) return { outcome: "not_found" } as const; const intentKind = claimedIntentKind(candidate.intentKind); const deliveredOriginal = intentKind === "repeat_download" ? await hasDeliveredOriginal(transaction, editorialId, candidate.usageId) : false; const eligible = intentKind === "repeat_download" ? isFreeRepeatEligible(usage.billingStatus, deliveredOriginal) : usage.billingStatus !== "voided"; if (!eligible) { if (intentKind === "repeat_download") { await invalidateAuthorizedRepeat(transaction, candidate.id, new Date()); } return { outcome: "not_authorized" } as const; } const [claimed] = await transaction .update(downloadEvents) .set({ status: "streaming", startedAt: new Date() }) .where( and( eq(downloadEvents.id, candidate.id), eq(downloadEvents.editorialAccountId, editorialId), eq(downloadEvents.status, "authorized"), ), ) .returning({ id: downloadEvents.id }); if (!claimed) return { outcome: "not_authorized" } as const; return { outcome: "claimed", download: { id: candidate.id, usageId: candidate.usageId, assetId: candidate.assetId, albumId: usage.albumId, filename: usage.filename, intentKind, }, } as const; }); }, async failBeforeDelivery(downloadId, options) { return database.transaction(async (transaction) => { const terminalAt = new Date(); const [candidate] = await transaction .select({ usageId: downloadEvents.usageId, editorialId: downloadEvents.editorialAccountId, intentKind: downloadEvents.intentKind, requestId: downloadEvents.requestId, }) .from(downloadEvents) .where( and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")), ) .limit(1); if (!candidate) return false; const [usage] = await transaction .select({ billingStatus: usages.billingStatus }) .from(usages) .where( and( eq(usages.id, candidate.usageId), eq(usages.editorialAccountId, candidate.editorialId), ), ) .for("update") .limit(1); if (!usage) return false; const [failed] = await transaction .update(downloadEvents) .set({ status: "failed_before_delivery", transferredBytes: 0, completedAt: terminalAt, }) .where( and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")), ) .returning({ id: downloadEvents.id }); if (!failed) return false; if (options.voidNewUsage && candidate.intentKind === "new_usage") { const [voided] = await transaction .update(usages) .set({ billingStatus: "voided" }) .where( and( eq(usages.id, candidate.usageId), eq(usages.editorialAccountId, candidate.editorialId), inArray(usages.billingStatus, ["open", "reopened"]), ), ) .returning({ id: usages.id }); if (!voided) { throw new Error("Billable usage could not be voided before delivery"); } await transaction .update(downloadEvents) .set({ status: "failed_before_delivery", transferredBytes: 0, completedAt: terminalAt, }) .where( and( eq(downloadEvents.editorialAccountId, candidate.editorialId), eq(downloadEvents.usageId, candidate.usageId), eq(downloadEvents.intentKind, "repeat_download"), eq(downloadEvents.status, "authorized"), ), ); await transaction.insert(auditEvents).values({ eventType: "billable_usage_voided_before_delivery", actorType: "system", entityType: "usage", entityId: candidate.usageId, previousValues: { billingStatus: usage.billingStatus }, newValues: { billingStatus: "voided", downloadId, reason: "failed_before_delivery", }, occurredAt: terminalAt, requestId: candidate.requestId, }); } return true; }); }, markCompleted(downloadId, transferredBytes) { return markTerminal(database, downloadId, "completed", transferredBytes); }, markInterrupted(downloadId, transferredBytes) { return markTerminal(database, downloadId, "interrupted", transferredBytes); }, }; } async function invalidateAuthorizedRepeat( transaction: NodePgDatabase, downloadId: string, terminalAt: Date, ) { await transaction .update(downloadEvents) .set({ status: "failed_before_delivery", transferredBytes: 0, completedAt: terminalAt, }) .where( and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "authorized")), ); } async function markTerminal( database: NodePgDatabase, downloadId: string, status: "completed" | "interrupted", transferredBytes: number, ): Promise { assertByteCount(transferredBytes); const [updated] = await database .update(downloadEvents) .set({ status, transferredBytes, completedAt: new Date() }) .where(and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming"))) .returning({ id: downloadEvents.id }); return Boolean(updated); } function assertByteCount(value: number) { if (!Number.isSafeInteger(value) || value < 0) { throw new Error("Invalid transferred byte count"); } } export type UsageHistoryAttempt = { downloadId: string; usageId: string; status: typeof downloadEvents.$inferSelect.status; requestedAt: Date; finishedAt?: Date; transferredBytes: number; repeat: boolean; billableCents: number; filename: string; albumName: string; purpose: string; reference?: string; priceCents: number; }; export type UsageHistoryItem = { usageId: string; filename: string; albumName: string; purpose: string; reference?: string; createdAt: Date; billingStatus: "open" | "billed" | "reopened" | "voided"; priceCents: number; billableCents: number; }; export type UsageHistoryPage = { items: UsageHistoryItem[]; attempts: UsageHistoryAttempt[]; page: number; pageSize: number; hasNext: boolean; attemptPageSize: number; attemptCursor?: string; nextAttemptCursor?: string; }; export type HistoryAttemptCursor = { authorizedAtMicros: string; downloadId: string; }; export type DownloadHistoryRepository = { listEditorialUsageHistory( editorialId: string, page: number, attemptCursor: HistoryAttemptCursor | undefined, ): Promise; }; export function createDownloadHistoryService({ repository, }: { repository: DownloadHistoryRepository; }) { return { async listEditorialUsageHistory( editorialId: string, rawPage: unknown, rawAttemptCursor?: unknown, ) { const attemptCursor = normalizeAttemptCursor(rawAttemptCursor); const result = await repository.listEditorialUsageHistory( normalizeUuid(editorialId), normalizeHistoryPage(rawPage), attemptCursor, ); return attemptCursor ? { ...result, attemptCursor: encodeAttemptCursor(attemptCursor) } : result; }, }; } export function createPostgresDownloadHistoryRepository( database: NodePgDatabase, ): DownloadHistoryRepository { return { async listEditorialUsageHistory(editorialId, page, attemptCursor) { const offset = (page - 1) * HISTORY_PAGE_SIZE; const usageRows = await database .select({ usageId: usages.id, filename: usages.filenameSnapshot, albumName: usages.albumNameSnapshot, purpose: usages.purpose, reference: usages.internalReference, createdAt: usages.createdAt, billingStatus: usages.billingStatus, priceCents: usages.priceCents, }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)) .orderBy(desc(usages.createdAt), desc(usages.id)) .limit(HISTORY_PAGE_SIZE + 1) .offset(offset); const hasNext = usageRows.length > HISTORY_PAGE_SIZE; const pageRows = usageRows.slice(0, HISTORY_PAGE_SIZE); const authorizedAtMicros = sql`floor(extract(epoch from ${downloadEvents.authorizedAt}) * 1000000)::bigint`; const beforeCursor = attemptCursor ? sql`(${downloadEvents.authorizedAt}, ${downloadEvents.id}) < (timestamptz 'epoch' + ${attemptCursor.authorizedAtMicros}::bigint * interval '1 microsecond', ${attemptCursor.downloadId}::uuid)` : undefined; const eventRowsWithNext = await database .select({ downloadId: downloadEvents.id, usageId: downloadEvents.usageId, status: downloadEvents.status, requestedAt: downloadEvents.authorizedAt, finishedAt: downloadEvents.completedAt, transferredBytes: downloadEvents.transferredBytes, intentKind: downloadEvents.intentKind, authorizedAtMicros, filename: usages.filenameSnapshot, albumName: usages.albumNameSnapshot, purpose: usages.purpose, reference: usages.internalReference, priceCents: usages.priceCents, billingStatus: usages.billingStatus, }) .from(downloadEvents) .innerJoin( usages, and( eq(usages.id, downloadEvents.usageId), eq(usages.editorialAccountId, editorialId), ), ) .where( and( eq(downloadEvents.editorialAccountId, editorialId), beforeCursor, ), ) .orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id)) .limit(HISTORY_ATTEMPT_PAGE_SIZE + 1); const hasNextAttempts = eventRowsWithNext.length > HISTORY_ATTEMPT_PAGE_SIZE; const eventRows = eventRowsWithNext.slice(0, HISTORY_ATTEMPT_PAGE_SIZE); const lastEvent = eventRows.at(-1); const nextAttemptCursor = hasNextAttempts && lastEvent ? encodeAttemptCursor({ authorizedAtMicros: lastEvent.authorizedAtMicros, downloadId: lastEvent.downloadId, }) : undefined; return { items: pageRows.map((usage) => { const billableCents = usage.billingStatus === "voided" ? 0 : usage.priceCents; return { usageId: usage.usageId, filename: usage.filename, albumName: usage.albumName, purpose: usage.purpose, ...(usage.reference === null ? {} : { reference: usage.reference }), createdAt: usage.createdAt, billingStatus: usage.billingStatus, priceCents: usage.priceCents, billableCents, }; }), attempts: eventRows.map((event) => ({ downloadId: event.downloadId, usageId: event.usageId, status: event.status, requestedAt: event.requestedAt, ...(event.finishedAt === null ? {} : { finishedAt: event.finishedAt }), transferredBytes: event.transferredBytes ?? 0, repeat: event.intentKind === "repeat_download", billableCents: event.intentKind === "new_usage" && event.billingStatus !== "voided" ? event.priceCents : 0, filename: event.filename, albumName: event.albumName, purpose: event.purpose, ...(event.reference === null ? {} : { reference: event.reference }), priceCents: event.priceCents, })), page, pageSize: HISTORY_PAGE_SIZE, hasNext, attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE, ...(nextAttemptCursor ? { nextAttemptCursor } : {}), }; }, }; } function claimedIntentKind(value: string): ClaimedDownload["intentKind"] { if (value === "new_usage" || value === "repeat_download" || value === "legacy") { return value; } throw new Error("Unsupported download intent kind"); } function normalizeHistoryPage(value: unknown): number { return normalizeBoundedPage(value, HISTORY_MAX_PAGE); } function normalizeBoundedPage(value: unknown, maximum: number): number { let page = 1; if (typeof value === "number" && Number.isSafeInteger(value)) { page = value; } else if (typeof value === "string" && /^\d+$/.test(value)) { const parsed = Number(value); page = Number.isSafeInteger(parsed) ? parsed : maximum; } return Math.min(maximum, Math.max(1, page)); } function normalizeAttemptCursor(value: unknown): HistoryAttemptCursor | undefined { if (typeof value !== "string") return undefined; const match = /^(\d{1,18})\.([0-9a-f-]{36})$/.exec(value); if (!match) return undefined; try { return { authorizedAtMicros: match[1], downloadId: normalizeUuid(match[2]), }; } catch { return undefined; } } function encodeAttemptCursor(cursor: HistoryAttemptCursor): string { return `${cursor.authorizedAtMicros}.${cursor.downloadId}`; } export type DownloadDialogUsage = { id: string; purpose: string; createdAt: string; }; export type EditorialDownloadOptions = { priceCents: number; collabEnabled: boolean; priorUsagesByAsset: Record; }; export function createEditorialDownloadOptionsLoader( database: NodePgDatabase, ) { return async function loadOptions( editorialId: string, assetIds: string[], allowPriorUsage?: (assetId: string, albumId: string) => Promise, ): Promise { const normalizedEditorialId = normalizeUuid(editorialId); const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))]; if (normalizedAssets.length > DOWNLOAD_OPTIONS_MAX_ASSETS) { throw new UsageAccountingError("INVALID_INPUT"); } const [editorial] = await database .select({ currentPriceCents: editorialAccounts.currentPriceCents, collabEnabled: editorialAccounts.collabEnabled, }) .from(editorialAccounts) .where( and( eq(editorialAccounts.id, normalizedEditorialId), eq(editorialAccounts.status, "active"), ), ) .limit(1); const priceCents = editorial?.currentPriceCents; if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { throw new UsageAccountingError("INVALID_PRICE"); } const collabEnabled = editorial?.collabEnabled === true; if (normalizedAssets.length === 0) { return { priceCents: priceCents!, collabEnabled, priorUsagesByAsset: {} }; } const deliveredOriginal = database .select({ id: downloadEvents.id }) .from(downloadEvents) .where(deliveredOriginalEventCondition(normalizedEditorialId, usages.id)); const rows = await database .select({ id: usages.id, assetId: usages.immichAssetId, purpose: usages.purpose, albumId: usages.immichAlbumIdSnapshot, createdAt: usages.createdAt, }) .from(usages) .where( and( eq(usages.editorialAccountId, normalizedEditorialId), inArray(usages.immichAssetId, normalizedAssets), inArray(usages.billingStatus, ["open", "billed", "reopened"]), exists(deliveredOriginal), ), ) .orderBy(desc(usages.createdAt), desc(usages.id)) .limit(DOWNLOAD_OPTIONS_MAX_USAGES); const priorUsagesByAsset: Record = {}; const allowed = new Map(); for (const row of rows) { if (allowPriorUsage) { const scope = `${row.assetId}:${row.albumId}`; if (!allowed.has(scope)) allowed.set(scope, await allowPriorUsage(row.assetId, row.albumId)); if (!allowed.get(scope)) continue; } (priorUsagesByAsset[row.assetId] ??= []).push({ id: row.id, purpose: row.purpose, createdAt: row.createdAt.toISOString(), }); } return { priceCents: priceCents!, collabEnabled, priorUsagesByAsset }; }; } export const loadEditorialDownloadOptions = createEditorialDownloadOptionsLoader(db); const downloadHistoryService = createDownloadHistoryService({ repository: createPostgresDownloadHistoryRepository(db), }); export const listEditorialUsageHistory = downloadHistoryService.listEditorialUsageHistory; export const downloadDeliveryRepository = createDownloadDeliveryRepository(db);