feat: stream originals with download accounting

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:10:13 +02:00
1 parent c400167b8f
commit 8871e4794a
28 files changed
+4081 -8

No files matched your search

+510
View File
@@ -0,0 +1,510 @@
import "server-only";
import { and, desc, eq, inArray } 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";
export const HISTORY_PAGE_SIZE = 20;
export const HISTORY_MAX_PAGE = 1_000;
export type ClaimedDownload = {
id: string;
usageId: string;
assetId: 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<DownloadClaim>;
failBeforeDelivery(
downloadId: string,
options: { voidNewUsage: boolean },
): Promise<boolean>;
markCompleted(downloadId: string, transferredBytes: number): Promise<boolean>;
markInterrupted(downloadId: string, transferredBytes: number): Promise<boolean>;
};
type StreamAccountingRepository = Pick<
DownloadDeliveryRepository,
"failBeforeDelivery" | "markCompleted" | "markInterrupted"
>;
export function streamWithAccounting({
downloadId,
upstream,
voidNewUsageOnFailure,
repository,
}: {
downloadId: string;
upstream: ReadableStream<Uint8Array>;
voidNewUsageOnFailure: boolean;
repository: StreamAccountingRepository;
}): ReadableStream<Uint8Array> {
const reader = upstream.getReader();
let transferredBytes = 0;
let stopped = false;
let released = false;
let terminal: Promise<void> | 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<Uint8Array>({
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<typeof schema>,
): DownloadDeliveryRepository {
return {
async claimAuthorized(editorialId, downloadId) {
return database.transaction(async (transaction) => {
const [claimed] = await transaction
.update(downloadEvents)
.set({ status: "streaming", startedAt: new Date() })
.where(
and(
eq(downloadEvents.id, downloadId),
eq(downloadEvents.editorialAccountId, editorialId),
eq(downloadEvents.status, "authorized"),
),
)
.returning({
id: downloadEvents.id,
usageId: downloadEvents.usageId,
assetId: downloadEvents.immichAssetId,
intentKind: downloadEvents.intentKind,
});
if (!claimed) {
const [owned] = await transaction
.select({ id: downloadEvents.id })
.from(downloadEvents)
.where(
and(
eq(downloadEvents.id, downloadId),
eq(downloadEvents.editorialAccountId, editorialId),
),
)
.limit(1);
return owned
? ({ outcome: "not_authorized" } as const)
: ({ outcome: "not_found" } as const);
}
const [usage] = await transaction
.select({ filename: usages.filenameSnapshot })
.from(usages)
.where(
and(
eq(usages.id, claimed.usageId),
eq(usages.editorialAccountId, editorialId),
),
)
.limit(1);
if (!usage) return { outcome: "not_found" } as const;
return {
outcome: "claimed",
download: {
...claimed,
filename: usage.filename,
intentKind: claimedIntentKind(claimed.intentKind),
},
} as const;
});
},
async failBeforeDelivery(downloadId, options) {
return database.transaction(async (transaction) => {
const terminalAt = new Date();
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({
usageId: downloadEvents.usageId,
editorialId: downloadEvents.editorialAccountId,
intentKind: downloadEvents.intentKind,
requestId: downloadEvents.requestId,
});
if (!failed) return false;
if (options.voidNewUsage && failed.intentKind === "new_usage") {
const [voided] = await transaction
.update(usages)
.set({ billingStatus: "voided" })
.where(
and(
eq(usages.id, failed.usageId),
eq(usages.editorialAccountId, failed.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.insert(auditEvents).values({
eventType: "billable_usage_voided_before_delivery",
actorType: "system",
entityType: "usage",
entityId: failed.usageId,
previousValues: { billingStatus: "open" },
newValues: {
billingStatus: "voided",
downloadId,
reason: "failed_before_delivery",
},
occurredAt: terminalAt,
requestId: failed.requestId,
});
}
return true;
});
},
markCompleted(downloadId, transferredBytes) {
return markTerminal(database, downloadId, "completed", transferredBytes);
},
markInterrupted(downloadId, transferredBytes) {
return markTerminal(database, downloadId, "interrupted", transferredBytes);
},
};
}
async function markTerminal(
database: NodePgDatabase<typeof schema>,
downloadId: string,
status: "completed" | "interrupted",
transferredBytes: number,
): Promise<boolean> {
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;
status: "completed" | "interrupted" | "failed_before_delivery";
requestedAt: Date;
finishedAt: Date;
transferredBytes: number;
repeat: boolean;
billableCents: number;
};
export type UsageHistoryItem = {
usageId: string;
filename: string;
albumName: string;
purpose: string;
reference?: string;
createdAt: Date;
billingStatus: "open" | "billed" | "reopened" | "voided";
billableCents: number;
attempts: UsageHistoryAttempt[];
};
export type UsageHistoryPage = {
items: UsageHistoryItem[];
page: number;
pageSize: number;
hasNext: boolean;
};
export type DownloadHistoryRepository = {
listEditorialUsageHistory(editorialId: string, page: number): Promise<UsageHistoryPage>;
};
export function createDownloadHistoryService({
repository,
}: {
repository: DownloadHistoryRepository;
}) {
return {
async listEditorialUsageHistory(editorialId: string, rawPage: unknown) {
return repository.listEditorialUsageHistory(
normalizeUuid(editorialId),
normalizeHistoryPage(rawPage),
);
},
};
}
export function createPostgresDownloadHistoryRepository(
database: NodePgDatabase<typeof schema>,
): DownloadHistoryRepository {
return {
async listEditorialUsageHistory(editorialId, page) {
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);
if (pageRows.length === 0) {
return { items: [], page, pageSize: HISTORY_PAGE_SIZE, hasNext };
}
const usageIds = pageRows.map((usage) => usage.usageId);
const eventRows = await database
.select({
downloadId: downloadEvents.id,
usageId: downloadEvents.usageId,
status: downloadEvents.status,
requestedAt: downloadEvents.authorizedAt,
finishedAt: downloadEvents.completedAt,
transferredBytes: downloadEvents.transferredBytes,
intentKind: downloadEvents.intentKind,
})
.from(downloadEvents)
.where(
and(
eq(downloadEvents.editorialAccountId, editorialId),
inArray(downloadEvents.usageId, usageIds),
inArray(downloadEvents.status, [
"completed",
"interrupted",
"failed_before_delivery",
]),
),
)
.orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id));
const eventsByUsage = new Map<string, typeof eventRows>();
for (const event of eventRows) {
const attempts = eventsByUsage.get(event.usageId) ?? [];
attempts.push(event);
eventsByUsage.set(event.usageId, attempts);
}
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,
billableCents,
attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({
downloadId: event.downloadId,
status: terminalStatus(event.status),
requestedAt: event.requestedAt,
finishedAt: event.finishedAt ?? event.requestedAt,
transferredBytes: event.transferredBytes ?? 0,
repeat: event.intentKind === "repeat_download",
billableCents:
event.intentKind === "new_usage" && usage.billingStatus !== "voided"
? usage.priceCents
: 0,
})),
};
}),
page,
pageSize: HISTORY_PAGE_SIZE,
hasNext,
};
},
};
}
function terminalStatus(status: string): UsageHistoryAttempt["status"] {
if (
status === "completed" ||
status === "interrupted" ||
status === "failed_before_delivery"
) {
return status;
}
throw new Error("Non-terminal download in history query");
}
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 {
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 : HISTORY_MAX_PAGE;
}
return Math.min(HISTORY_MAX_PAGE, Math.max(1, page));
}
export type DownloadDialogUsage = {
id: string;
purpose: string;
createdAt: string;
};
export type EditorialDownloadOptions = {
priceCents: number;
priorUsagesByAsset: Record<string, DownloadDialogUsage[]>;
};
export async function loadEditorialDownloadOptions(
editorialId: string,
assetIds: string[],
): Promise<EditorialDownloadOptions> {
const normalizedEditorialId = normalizeUuid(editorialId);
const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))];
const [editorial] = await db
.select({ currentPriceCents: editorialAccounts.currentPriceCents })
.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");
}
if (normalizedAssets.length === 0) {
return { priceCents: priceCents!, priorUsagesByAsset: {} };
}
const rows = await db
.select({
id: usages.id,
assetId: usages.immichAssetId,
purpose: usages.purpose,
createdAt: usages.createdAt,
})
.from(usages)
.where(
and(
eq(usages.editorialAccountId, normalizedEditorialId),
inArray(usages.immichAssetId, normalizedAssets),
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
),
)
.orderBy(desc(usages.createdAt));
const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {};
for (const row of rows) {
(priorUsagesByAsset[row.assetId] ??= []).push({
id: row.id,
purpose: row.purpose,
createdAt: row.createdAt.toISOString(),
});
}
return { priceCents: priceCents!, priorUsagesByAsset };
}
const downloadHistoryService = createDownloadHistoryService({
repository: createPostgresDownloadHistoryRepository(db),
});
export const listEditorialUsageHistory = downloadHistoryService.listEditorialUsageHistory;
export const downloadDeliveryRepository = createDownloadDeliveryRepository(db);