fix: harden download history and attempt ledger
This commit is contained in:
1 parent
510fde7afa
commit
ba673ad732
19 files changed
+2287
-311
No files matched your search
+112
-101
@@ -1,6 +1,6 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, exists, inArray, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -8,11 +8,17 @@ import { auditEvents, downloadEvents, editorialAccounts, usages } from "@/db/sch
|
||||
import type * as schema from "@/db/schema";
|
||||
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility";
|
||||
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;
|
||||
@@ -351,12 +357,18 @@ function assertByteCount(value: number) {
|
||||
|
||||
export type UsageHistoryAttempt = {
|
||||
downloadId: string;
|
||||
status: "completed" | "interrupted" | "failed_before_delivery";
|
||||
usageId: string;
|
||||
status: typeof downloadEvents.$inferSelect.status;
|
||||
requestedAt: Date;
|
||||
finishedAt: Date;
|
||||
finishedAt?: Date;
|
||||
transferredBytes: number;
|
||||
repeat: boolean;
|
||||
billableCents: number;
|
||||
filename: string;
|
||||
albumName: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
priceCents: number;
|
||||
};
|
||||
|
||||
export type UsageHistoryItem = {
|
||||
@@ -369,11 +381,11 @@ export type UsageHistoryItem = {
|
||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||
priceCents: number;
|
||||
billableCents: number;
|
||||
attempts: UsageHistoryAttempt[];
|
||||
};
|
||||
|
||||
export type UsageHistoryPage = {
|
||||
items: UsageHistoryItem[];
|
||||
attempts: UsageHistoryAttempt[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNext: boolean;
|
||||
@@ -443,20 +455,9 @@ export function createPostgresDownloadHistoryRepository(
|
||||
.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,
|
||||
attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE,
|
||||
};
|
||||
}
|
||||
|
||||
const usageIds = pageRows.map((usage) => usage.usageId);
|
||||
const authorizedAtMicros = sql<string>`floor(extract(epoch from ${downloadEvents.authorizedAt}) * 1000000)::bigint`;
|
||||
const beforeCursor = attemptCursor
|
||||
? sql`(${authorizedAtMicros}, ${downloadEvents.id}) < (${attemptCursor.authorizedAtMicros}::bigint, ${attemptCursor.downloadId}::uuid)`
|
||||
? sql`(${downloadEvents.authorizedAt}, ${downloadEvents.id}) < (timestamptz 'epoch' + ${attemptCursor.authorizedAtMicros}::bigint * interval '1 microsecond', ${attemptCursor.downloadId}::uuid)`
|
||||
: undefined;
|
||||
const eventRowsWithNext = await database
|
||||
.select({
|
||||
@@ -468,17 +469,24 @@ export function createPostgresDownloadHistoryRepository(
|
||||
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),
|
||||
inArray(downloadEvents.usageId, usageIds),
|
||||
inArray(downloadEvents.status, [
|
||||
"completed",
|
||||
"interrupted",
|
||||
"failed_before_delivery",
|
||||
]),
|
||||
beforeCursor,
|
||||
),
|
||||
)
|
||||
@@ -495,13 +503,6 @@ export function createPostgresDownloadHistoryRepository(
|
||||
})
|
||||
: undefined;
|
||||
|
||||
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;
|
||||
@@ -515,20 +516,26 @@ export function createPostgresDownloadHistoryRepository(
|
||||
billingStatus: usage.billingStatus,
|
||||
priceCents: usage.priceCents,
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
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,
|
||||
@@ -539,17 +546,6 @@ export function createPostgresDownloadHistoryRepository(
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -601,57 +597,72 @@ export type EditorialDownloadOptions = {
|
||||
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: {} };
|
||||
}
|
||||
export function createEditorialDownloadOptionsLoader(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
) {
|
||||
return async function loadOptions(
|
||||
editorialId: string,
|
||||
assetIds: string[],
|
||||
): Promise<EditorialDownloadOptions> {
|
||||
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 })
|
||||
.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 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,
|
||||
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<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 };
|
||||
};
|
||||
}
|
||||
|
||||
export const loadEditorialDownloadOptions = createEditorialDownloadOptionsLoader(db);
|
||||
|
||||
const downloadHistoryService = createDownloadHistoryService({
|
||||
repository: createPostgresDownloadHistoryRepository(db),
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user