feat: stream originals with download accounting
This commit is contained in:
1 parent
c400167b8f
commit
8871e4794a
28 files changed
+4081
-8
No files matched your search
@@ -2,7 +2,7 @@ import "server-only";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -95,6 +95,7 @@ export function createRepeatDownloadRepository(
|
||||
and(
|
||||
eq(usages.id, input.usageId),
|
||||
eq(usages.editorialAccountId, input.editorialId),
|
||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
||||
),
|
||||
)
|
||||
.for("update")
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createDownloadHistoryService,
|
||||
HISTORY_MAX_PAGE,
|
||||
streamWithAccounting,
|
||||
} from "./stream";
|
||||
|
||||
const downloadId = "11111111-1111-4111-8111-111111111111";
|
||||
|
||||
function accounting() {
|
||||
return {
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
}
|
||||
|
||||
async function readAll(stream: ReadableStream<Uint8Array>) {
|
||||
const reader = stream.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) return chunks;
|
||||
chunks.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
test("marks a new usage failed and voidable when upstream fails before its first byte", async () => {
|
||||
const repository = accounting();
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
controller.error(new Error("upstream unavailable"));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("upstream unavailable");
|
||||
|
||||
expect(repository.failBeforeDelivery).toHaveBeenCalledOnce();
|
||||
expect(repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
expect(repository.markInterrupted).not.toHaveBeenCalled();
|
||||
expect(repository.markCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("marks a repeat attempt failed without voiding its original usage", async () => {
|
||||
const repository = accounting();
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.error(new Error("upstream unavailable"));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: false,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("upstream unavailable");
|
||||
|
||||
expect(repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("marks a stream interrupted with the exact delivered byte count", async () => {
|
||||
const repository = accounting();
|
||||
let pull = 0;
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (pull++ === 0) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3, 4]));
|
||||
return;
|
||||
}
|
||||
controller.error(new Error("connection reset"));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("connection reset");
|
||||
|
||||
expect(repository.markInterrupted).toHaveBeenCalledOnce();
|
||||
expect(repository.markInterrupted).toHaveBeenCalledWith(downloadId, 4);
|
||||
expect(repository.failBeforeDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("marks a successful close completed with all delivered bytes", async () => {
|
||||
const repository = accounting();
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2]));
|
||||
controller.enqueue(new Uint8Array([3, 4, 5]));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).resolves.toHaveLength(2);
|
||||
|
||||
expect(repository.markCompleted).toHaveBeenCalledOnce();
|
||||
expect(repository.markCompleted).toHaveBeenCalledWith(downloadId, 5);
|
||||
expect(repository.markInterrupted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("cancels upstream and contains a rejecting upstream cancellation", async () => {
|
||||
const repository = accounting();
|
||||
const cancelError = new Error("cancel failed");
|
||||
const upstreamCancel = vi.fn().mockRejectedValue(cancelError);
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
},
|
||||
cancel: upstreamCancel,
|
||||
});
|
||||
const stream = streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
});
|
||||
const reader = stream.getReader();
|
||||
await reader.read();
|
||||
|
||||
await expect(reader.cancel("browser disconnected")).resolves.toBeUndefined();
|
||||
|
||||
expect(upstreamCancel).toHaveBeenCalledWith("browser disconnected");
|
||||
expect(repository.markInterrupted).toHaveBeenCalledWith(downloadId, 3);
|
||||
expect(repository.markCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("settles terminal accounting exactly once when error and cancel race", async () => {
|
||||
const repository = accounting();
|
||||
let rejectRead: ((error: Error) => void) | undefined;
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
pull() {
|
||||
return new Promise<void>((_resolve, reject) => {
|
||||
rejectRead = reject;
|
||||
});
|
||||
},
|
||||
cancel: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const stream = streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
});
|
||||
const reader = stream.getReader();
|
||||
const pendingRead = reader.read();
|
||||
await Promise.resolve();
|
||||
const cancellation = reader.cancel("closed");
|
||||
rejectRead?.(new Error("late upstream error"));
|
||||
|
||||
await Promise.allSettled([pendingRead, cancellation]);
|
||||
|
||||
expect(
|
||||
repository.failBeforeDelivery.mock.calls.length +
|
||||
repository.markInterrupted.mock.calls.length +
|
||||
repository.markCompleted.mock.calls.length,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test("normalizes and bounds history pagination before the scoped repository query", async () => {
|
||||
const repository = {
|
||||
listEditorialUsageHistory: vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
page: HISTORY_MAX_PAGE,
|
||||
pageSize: 20,
|
||||
hasNext: false,
|
||||
}),
|
||||
};
|
||||
const history = createDownloadHistoryService({ repository });
|
||||
|
||||
await history.listEditorialUsageHistory(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
"999999999999999999999999",
|
||||
);
|
||||
|
||||
expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
HISTORY_MAX_PAGE,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects an invalid editorial scope before querying usage history", async () => {
|
||||
const repository = { listEditorialUsageHistory: vi.fn() };
|
||||
const history = createDownloadHistoryService({ repository });
|
||||
|
||||
await expect(history.listEditorialUsageHistory("other-editorial", 1)).rejects.toMatchObject({
|
||||
code: "INVALID_INPUT",
|
||||
});
|
||||
expect(repository.listEditorialUsageHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -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);
|
||||
Reference in new issue
Block a user