fix: harden delivery accounting and history

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:44:04 +02:00
1 parent 8871e4794a
commit 510fde7afa
13 files changed
+728 -88

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
import { expect, test } from "vitest";
import { isFreeRepeatEligible } from "./eligibility";
test.each([
["open", true, true],
["billed", true, true],
["reopened", true, true],
["voided", true, false],
["open", false, false],
["billed", false, false],
] as const)(
"repeat eligibility for billing status %s and deliveredOriginal=%s is %s",
(billingStatus, deliveredOriginal, expected) => {
expect(isFreeRepeatEligible(billingStatus, deliveredOriginal)).toBe(expected);
},
);
+37
View File
@@ -0,0 +1,37 @@
import "server-only";
import { and, eq, gt, inArray } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { downloadEvents } from "@/db/schema";
import type * as schema from "@/db/schema";
type UsageBillingStatus = "open" | "billed" | "reopened" | "voided";
export function isFreeRepeatEligible(
billingStatus: UsageBillingStatus,
deliveredOriginal: boolean,
): boolean {
return billingStatus !== "voided" && deliveredOriginal;
}
export async function hasDeliveredOriginal(
database: NodePgDatabase<typeof schema>,
editorialId: string,
usageId: string,
): Promise<boolean> {
const [delivery] = await database
.select({ id: downloadEvents.id })
.from(downloadEvents)
.where(
and(
eq(downloadEvents.editorialAccountId, editorialId),
eq(downloadEvents.usageId, usageId),
eq(downloadEvents.intentKind, "new_usage"),
inArray(downloadEvents.status, ["completed", "interrupted"]),
gt(downloadEvents.transferredBytes, 0),
),
)
.limit(1);
return Boolean(delivery);
}
+18
View File
@@ -0,0 +1,18 @@
import { afterEach, expect, test, vi } from "vitest";
const originalTimeZone = process.env.TZ;
afterEach(() => {
process.env.TZ = originalTimeZone;
vi.resetModules();
});
test("formats dialog and history dates explicitly in Europe/Berlin", async () => {
process.env.TZ = "America/Los_Angeles";
vi.resetModules();
const { formatBerlinDate, formatBerlinDateTime } = await import("./format");
const afterBerlinMidnight = new Date("2026-08-09T22:30:00.000Z");
expect(formatBerlinDate(afterBerlinMidnight)).toBe("10.08.2026");
expect(formatBerlinDateTime(afterBerlinMidnight)).toBe("10.08.2026, 00:30");
});
+18
View File
@@ -0,0 +1,18 @@
const berlinDateFormatter = new Intl.DateTimeFormat("de-DE", {
dateStyle: "medium",
timeZone: "Europe/Berlin",
});
const berlinDateTimeFormatter = new Intl.DateTimeFormat("de-DE", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "Europe/Berlin",
});
export function formatBerlinDate(value: Date): string {
return berlinDateFormatter.format(value);
}
export function formatBerlinDateTime(value: Date): string {
return berlinDateTimeFormatter.format(value);
}
+24 -4
View File
@@ -2,7 +2,7 @@ import "server-only";
import { randomUUID } from "node:crypto";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
@@ -23,6 +23,8 @@ import {
type PersistedDownloadIntent,
} from "@/modules/usages/service";
import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility";
export type PersistedRepeatIntent = PersistedDownloadIntent & { kind: "repeat_download" };
export type RepeatIntentInput = {
@@ -76,7 +78,13 @@ export function createRepeatDownloadRepository(
input.editorialId,
input.idempotencyKey,
);
if (existing) return asRepeatIntent(existing);
if (
existing &&
(existing.kind !== "repeat_download" ||
existing.requestFingerprint !== input.requestFingerprint)
) {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
const [editorial] = await transaction
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
@@ -89,18 +97,30 @@ export function createRepeatDownloadRepository(
}
const [usage] = await transaction
.select({ id: usages.id, assetId: usages.immichAssetId })
.select({
id: usages.id,
assetId: usages.immichAssetId,
billingStatus: usages.billingStatus,
})
.from(usages)
.where(
and(
eq(usages.id, input.usageId),
eq(usages.editorialAccountId, input.editorialId),
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
),
)
.for("update")
.limit(1);
if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND");
const deliveredOriginal = await hasDeliveredOriginal(
transaction,
input.editorialId,
usage.id,
);
if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) {
throw new UsageAccountingError("USAGE_NOT_FOUND");
}
if (existing) return asRepeatIntent(existing);
const authorizedAt = new Date();
const [event] = await transaction
+6
View File
@@ -197,6 +197,7 @@ test("normalizes and bounds history pagination before the scoped repository quer
page: HISTORY_MAX_PAGE,
pageSize: 20,
hasNext: false,
attemptPageSize: 25,
}),
};
const history = createDownloadHistoryService({ repository });
@@ -204,11 +205,16 @@ test("normalizes and bounds history pagination before the scoped repository quer
await history.listEditorialUsageHistory(
"11111111-1111-4111-8111-111111111111",
"999999999999999999999999",
"1786314600000000.22222222-2222-4222-8222-222222222222",
);
expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith(
"11111111-1111-4111-8111-111111111111",
HISTORY_MAX_PAGE,
{
authorizedAtMicros: "1786314600000000",
downloadId: "22222222-2222-4222-8222-222222222222",
},
);
});
+209 -59
View File
@@ -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 = {