fix: harden delivery accounting and history
This commit is contained in:
1 parent
8871e4794a
commit
510fde7afa
13 files changed
+728
-88
No files matched your search
+209
-59
@@ -1,6 +1,6 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, desc, eq, inArray } from "drizzle-orm";
|
||||
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -8,8 +8,11 @@ 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";
|
||||
|
||||
export const HISTORY_PAGE_SIZE = 20;
|
||||
export const HISTORY_MAX_PAGE = 1_000;
|
||||
export const HISTORY_ATTEMPT_PAGE_SIZE = 25;
|
||||
|
||||
export type ClaimedDownload = {
|
||||
id: string;
|
||||
@@ -127,57 +130,80 @@ export function createDownloadDeliveryRepository(
|
||||
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,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.id, candidate.usageId),
|
||||
eq(usages.editorialAccountId, editorialId),
|
||||
),
|
||||
)
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!usage) 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, downloadId),
|
||||
eq(downloadEvents.id, candidate.id),
|
||||
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;
|
||||
.returning({ id: downloadEvents.id });
|
||||
if (!claimed) return { outcome: "not_authorized" } as const;
|
||||
|
||||
return {
|
||||
outcome: "claimed",
|
||||
download: {
|
||||
...claimed,
|
||||
id: candidate.id,
|
||||
usageId: candidate.usageId,
|
||||
assetId: candidate.assetId,
|
||||
filename: usage.filename,
|
||||
intentKind: claimedIntentKind(claimed.intentKind),
|
||||
intentKind,
|
||||
},
|
||||
} as const;
|
||||
});
|
||||
@@ -186,6 +212,33 @@ export function createDownloadDeliveryRepository(
|
||||
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({
|
||||
@@ -196,22 +249,17 @@ export function createDownloadDeliveryRepository(
|
||||
.where(
|
||||
and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")),
|
||||
)
|
||||
.returning({
|
||||
usageId: downloadEvents.usageId,
|
||||
editorialId: downloadEvents.editorialAccountId,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
requestId: downloadEvents.requestId,
|
||||
});
|
||||
.returning({ id: downloadEvents.id });
|
||||
if (!failed) return false;
|
||||
|
||||
if (options.voidNewUsage && failed.intentKind === "new_usage") {
|
||||
if (options.voidNewUsage && candidate.intentKind === "new_usage") {
|
||||
const [voided] = await transaction
|
||||
.update(usages)
|
||||
.set({ billingStatus: "voided" })
|
||||
.where(
|
||||
and(
|
||||
eq(usages.id, failed.usageId),
|
||||
eq(usages.editorialAccountId, failed.editorialId),
|
||||
eq(usages.id, candidate.usageId),
|
||||
eq(usages.editorialAccountId, candidate.editorialId),
|
||||
inArray(usages.billingStatus, ["open", "reopened"]),
|
||||
),
|
||||
)
|
||||
@@ -219,19 +267,34 @@ export function createDownloadDeliveryRepository(
|
||||
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: failed.usageId,
|
||||
previousValues: { billingStatus: "open" },
|
||||
entityId: candidate.usageId,
|
||||
previousValues: { billingStatus: usage.billingStatus },
|
||||
newValues: {
|
||||
billingStatus: "voided",
|
||||
downloadId,
|
||||
reason: "failed_before_delivery",
|
||||
},
|
||||
occurredAt: terminalAt,
|
||||
requestId: failed.requestId,
|
||||
requestId: candidate.requestId,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
@@ -248,6 +311,23 @@ export function createDownloadDeliveryRepository(
|
||||
};
|
||||
}
|
||||
|
||||
async function invalidateAuthorizedRepeat(
|
||||
transaction: NodePgDatabase<typeof schema>,
|
||||
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<typeof schema>,
|
||||
downloadId: string,
|
||||
@@ -287,6 +367,7 @@ export type UsageHistoryItem = {
|
||||
reference?: string;
|
||||
createdAt: Date;
|
||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||
priceCents: number;
|
||||
billableCents: number;
|
||||
attempts: UsageHistoryAttempt[];
|
||||
};
|
||||
@@ -296,10 +377,22 @@ export type UsageHistoryPage = {
|
||||
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): Promise<UsageHistoryPage>;
|
||||
listEditorialUsageHistory(
|
||||
editorialId: string,
|
||||
page: number,
|
||||
attemptCursor: HistoryAttemptCursor | undefined,
|
||||
): Promise<UsageHistoryPage>;
|
||||
};
|
||||
|
||||
export function createDownloadHistoryService({
|
||||
@@ -308,11 +401,20 @@ export function createDownloadHistoryService({
|
||||
repository: DownloadHistoryRepository;
|
||||
}) {
|
||||
return {
|
||||
async listEditorialUsageHistory(editorialId: string, rawPage: unknown) {
|
||||
return repository.listEditorialUsageHistory(
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -321,7 +423,7 @@ export function createPostgresDownloadHistoryRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): DownloadHistoryRepository {
|
||||
return {
|
||||
async listEditorialUsageHistory(editorialId, page) {
|
||||
async listEditorialUsageHistory(editorialId, page, attemptCursor) {
|
||||
const offset = (page - 1) * HISTORY_PAGE_SIZE;
|
||||
const usageRows = await database
|
||||
.select({
|
||||
@@ -342,11 +444,21 @@ export function createPostgresDownloadHistoryRepository(
|
||||
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 };
|
||||
return {
|
||||
items: [],
|
||||
page,
|
||||
pageSize: HISTORY_PAGE_SIZE,
|
||||
hasNext,
|
||||
attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE,
|
||||
};
|
||||
}
|
||||
|
||||
const usageIds = pageRows.map((usage) => usage.usageId);
|
||||
const eventRows = await database
|
||||
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)`
|
||||
: undefined;
|
||||
const eventRowsWithNext = await database
|
||||
.select({
|
||||
downloadId: downloadEvents.id,
|
||||
usageId: downloadEvents.usageId,
|
||||
@@ -355,6 +467,7 @@ export function createPostgresDownloadHistoryRepository(
|
||||
finishedAt: downloadEvents.completedAt,
|
||||
transferredBytes: downloadEvents.transferredBytes,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
authorizedAtMicros,
|
||||
})
|
||||
.from(downloadEvents)
|
||||
.where(
|
||||
@@ -366,9 +479,21 @@ export function createPostgresDownloadHistoryRepository(
|
||||
"interrupted",
|
||||
"failed_before_delivery",
|
||||
]),
|
||||
beforeCursor,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id));
|
||||
.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;
|
||||
|
||||
const eventsByUsage = new Map<string, typeof eventRows>();
|
||||
for (const event of eventRows) {
|
||||
@@ -388,6 +513,7 @@ export function createPostgresDownloadHistoryRepository(
|
||||
...(usage.reference === null ? {} : { reference: usage.reference }),
|
||||
createdAt: usage.createdAt,
|
||||
billingStatus: usage.billingStatus,
|
||||
priceCents: usage.priceCents,
|
||||
billableCents,
|
||||
attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({
|
||||
downloadId: event.downloadId,
|
||||
@@ -406,6 +532,8 @@ export function createPostgresDownloadHistoryRepository(
|
||||
page,
|
||||
pageSize: HISTORY_PAGE_SIZE,
|
||||
hasNext,
|
||||
attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE,
|
||||
...(nextAttemptCursor ? { nextAttemptCursor } : {}),
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -430,14 +558,36 @@ function claimedIntentKind(value: string): ClaimedDownload["intentKind"] {
|
||||
}
|
||||
|
||||
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 : HISTORY_MAX_PAGE;
|
||||
page = Number.isSafeInteger(parsed) ? parsed : maximum;
|
||||
}
|
||||
return Math.min(HISTORY_MAX_PAGE, Math.max(1, page));
|
||||
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 = {
|
||||
|
||||
Reference in new issue
Block a user