fix: harden download history and attempt ledger

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 16:45:40 +02:00
1 parent 510fde7afa
commit ba673ad732
19 files changed
+2287 -311

No files matched your search

+35
View File
@@ -870,6 +870,16 @@ a {
border-top: 1px solid var(--ink);
}
.usage-attempt-history {
margin-top: 3rem;
}
.usage-attempt-history h2 {
margin: 0 0 1rem;
font-size: clamp(1.3rem, 3vw, 2rem);
letter-spacing: -0.03em;
}
.usage-attempts li {
display: grid;
grid-template-columns: minmax(9rem, 1.2fr) minmax(11rem, 1.5fr) minmax(8rem, 1fr) 0.7fr 0.7fr;
@@ -889,6 +899,31 @@ a {
text-align: right;
}
.usage-attempt-context {
display: grid;
gap: 0.2rem;
}
.usage-attempt-context strong {
overflow-wrap: anywhere;
color: var(--ink);
}
.usage-attempt-context small {
line-height: 1.35;
}
.usage-attempt-price {
display: grid;
gap: 0.2rem;
text-align: right;
}
.usage-attempt-price small {
color: var(--metadata);
white-space: nowrap;
}
.usage-attempt-empty {
margin: 0;
padding: 1rem 0;
+84 -33
View File
@@ -22,35 +22,81 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
billingStatus: "open",
priceCents: 1_500,
billableCents: 1_500,
attempts: [
{
downloadId: "download-3",
status: "failed_before_delivery",
requestedAt: new Date("2026-08-10T12:00:00.000Z"),
finishedAt: new Date("2026-08-10T12:00:01.000Z"),
transferredBytes: 0,
repeat: true,
billableCents: 0,
},
{
downloadId: "download-2",
status: "interrupted",
requestedAt: new Date("2026-08-10T11:00:00.000Z"),
finishedAt: new Date("2026-08-10T11:00:02.000Z"),
transferredBytes: 40,
repeat: true,
billableCents: 0,
},
{
downloadId: "download-1",
status: "completed",
requestedAt: new Date("2026-08-09T10:00:00.000Z"),
finishedAt: new Date("2026-08-09T10:00:03.000Z"),
transferredBytes: 100,
repeat: false,
billableCents: 1_500,
},
],
},
],
attempts: [
{
downloadId: "download-5",
usageId: "usage-1",
status: "authorized",
requestedAt: new Date("2026-08-10T13:00:00.000Z"),
transferredBytes: 0,
repeat: true,
billableCents: 0,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
},
{
downloadId: "download-4",
usageId: "usage-1",
status: "streaming",
requestedAt: new Date("2026-08-10T12:30:00.000Z"),
transferredBytes: 0,
repeat: true,
billableCents: 0,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
},
{
downloadId: "download-3",
usageId: "usage-1",
status: "failed_before_delivery",
requestedAt: new Date("2026-08-10T12:00:00.000Z"),
finishedAt: new Date("2026-08-10T12:00:01.000Z"),
transferredBytes: 0,
repeat: true,
billableCents: 0,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
},
{
downloadId: "download-2",
usageId: "usage-1",
status: "interrupted",
requestedAt: new Date("2026-08-10T11:00:00.000Z"),
finishedAt: new Date("2026-08-10T11:00:02.000Z"),
transferredBytes: 40,
repeat: true,
billableCents: 0,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
},
{
downloadId: "download-1",
usageId: "usage-1",
status: "completed",
requestedAt: new Date("2026-08-09T10:00:00.000Z"),
finishedAt: new Date("2026-08-09T10:00:03.000Z"),
transferredBytes: 100,
repeat: false,
billableCents: 1_500,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
},
],
page: 1,
@@ -69,8 +115,12 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
expect(screen.getByText("Abgeschlossen")).not.toBeNull();
expect(screen.getByText("Unterbrochen")).not.toBeNull();
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull();
expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(2);
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2);
expect(screen.getByText("Autorisiert")).not.toBeNull();
expect(screen.getByText("Wird ausgeliefert")).not.toBeNull();
expect(screen.getByRole("heading", { name: "Downloadversuche" })).not.toBeNull();
expect(screen.getAllByText(/Nutzungspreis\s+15,00\s*€/)).toHaveLength(5);
expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(7);
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(4);
expect(screen.getByRole("link", { name: /nächste nutzungsseite/i }).getAttribute("href")).toBe(
"/redaktion/nutzungen?page=2",
);
@@ -89,6 +139,7 @@ test("renders a directional empty state", () => {
<UsageHistoryContent
history={{
items: [],
attempts: [],
page: 1,
pageSize: 20,
hasNext: false,
@@ -115,9 +166,9 @@ test("shows the usage-level price and billing status before any attempt is termi
billingStatus: "open",
priceCents: 1_500,
billableCents: 1_500,
attempts: [],
},
],
attempts: [],
page: 1,
pageSize: 20,
hasNext: false,
@@ -145,9 +196,9 @@ test("keeps the immutable usage price visible when billing was voided", () => {
billingStatus: "voided",
priceCents: 1_500,
billableCents: 0,
attempts: [],
},
],
attempts: [],
page: 1,
pageSize: 20,
hasNext: false,
@@ -63,17 +63,6 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
</div>
) : null}
</dl>
{usage.attempts.length === 0 ? (
<p className="usage-attempt-empty">
Keine Auslieferungsversuche auf dieser Auslieferungsseite.
</p>
) : (
<ol className="usage-attempts" aria-label={`Auslieferungen für ${usage.filename}`}>
{usage.attempts.map((attempt) => (
<AttemptRow attempt={attempt} key={attempt.downloadId} />
))}
</ol>
)}
</article>
</li>
))}
@@ -81,21 +70,47 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
)}
<HistoryPagination history={history} />
<section className="usage-attempt-history" aria-labelledby="usage-attempt-title">
<h2 id="usage-attempt-title">Downloadversuche</h2>
{history.attempts.length === 0 ? (
<p className="usage-attempt-empty">Noch keine Downloadversuche erfasst.</p>
) : (
<ol className="usage-attempts" aria-label="Downloadversuche Ihrer Redaktion">
{history.attempts.map((attempt) => (
<AttemptRow attempt={attempt} key={attempt.downloadId} />
))}
</ol>
)}
</section>
<AttemptPagination history={history} />
</section>
);
}
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
const displayedAt = attempt.finishedAt ?? attempt.requestedAt;
return (
<li>
<time dateTime={attempt.finishedAt.toISOString()}>
{formatBerlinDateTime(attempt.finishedAt)}
<time dateTime={displayedAt.toISOString()}>
{formatBerlinDateTime(displayedAt)}
</time>
<span className="usage-attempt-context">
<strong>{attempt.filename}</strong>
<small>
{attempt.albumName} · {attempt.purpose}
{attempt.reference ? ` · ${attempt.reference}` : ""}
</small>
</span>
<strong>{statusLabel(attempt.status)}</strong>
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span>
<span>{byteFormatter.format(attempt.transferredBytes)}</span>
<b>{priceFormatter.format(attempt.billableCents / 100)}</b>
<span>
{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} ·{" "}
{byteFormatter.format(attempt.transferredBytes)}
</span>
<span className="usage-attempt-price">
<b>{priceFormatter.format(attempt.billableCents / 100)}</b>
<small>Nutzungspreis {priceFormatter.format(attempt.priceCents / 100)}</small>
</span>
</li>
);
}
@@ -142,6 +157,8 @@ function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>)
function statusLabel(status: UsageHistoryAttempt["status"]): string {
const labels: Record<UsageHistoryAttempt["status"], string> = {
authorized: "Autorisiert",
streaming: "Wird ausgeliefert",
completed: "Abgeschlossen",
interrupted: "Unterbrochen",
failed_before_delivery: "Vor Auslieferung fehlgeschlagen",
+11
View File
@@ -3,6 +3,7 @@ import {
bigint,
boolean,
check,
index,
integer,
pgEnum,
pgTable,
@@ -49,6 +50,11 @@ export const usages = pgTable(
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("usages_editorial_created_id_idx").on(
table.editorialAccountId,
table.createdAt.desc(),
table.id.desc(),
),
check(
"usages_canonical_immich_asset_id_check",
sql`${table.immichAssetId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
@@ -84,6 +90,11 @@ export const downloadEvents = pgTable(
legacyIntent: boolean("legacy_intent").notNull().default(false),
},
(table) => [
index("download_events_editorial_authorized_id_idx").on(
table.editorialAccountId,
table.authorizedAt.desc(),
table.id.desc(),
),
uniqueIndex("download_events_editorial_idempotency_key_unique").on(
table.editorialAccountId,
table.idempotencyKey,
+19 -10
View File
@@ -1,6 +1,6 @@
import "server-only";
import { and, eq, gt, inArray } from "drizzle-orm";
import { and, eq, gt, inArray, sql, type SQL, type SQLWrapper } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { downloadEvents } from "@/db/schema";
@@ -15,6 +15,23 @@ export function isFreeRepeatEligible(
return billingStatus !== "voided" && deliveredOriginal;
}
export function deliveredOriginalEventCondition(
editorialId: string,
usageId: string | SQLWrapper,
): SQL {
const scopedUsage =
typeof usageId === "string"
? eq(downloadEvents.usageId, usageId)
: sql`${downloadEvents.usageId} = ${usageId}`;
return and(
eq(downloadEvents.editorialAccountId, editorialId),
scopedUsage,
eq(downloadEvents.intentKind, "new_usage"),
inArray(downloadEvents.status, ["completed", "interrupted"]),
gt(downloadEvents.transferredBytes, 0),
)!;
}
export async function hasDeliveredOriginal(
database: NodePgDatabase<typeof schema>,
editorialId: string,
@@ -23,15 +40,7 @@ export async function hasDeliveredOriginal(
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),
),
)
.where(deliveredOriginalEventCondition(editorialId, usageId))
.limit(1);
return Boolean(delivery);
}
+18 -5
View File
@@ -17,16 +17,15 @@ function createService() {
const intents = new Map<string, PersistedRepeatIntent>();
const events: RepeatIntentInput[] = [];
let active = true;
let eligible = true;
let usageOwner = editorialId;
let snapshotPrice = 1_500;
const repository: RepeatDownloadRepository = {
async findIntent(requestEditorialId, key) {
return intents.get(`${requestEditorialId}:${key}`) ?? null;
},
async createRepeatIntent(input) {
if (!active) throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
if (usageOwner !== input.editorialId) throw new UsageAccountingError("USAGE_NOT_FOUND");
if (!eligible) throw new UsageAccountingError("USAGE_NOT_FOUND");
const key = `${input.editorialId}:${input.idempotencyKey}`;
const existing = intents.get(key);
if (existing) return existing;
@@ -54,6 +53,9 @@ function createService() {
setActive(value: boolean) {
active = value;
},
setEligible(value: boolean) {
eligible = value;
},
setUsageOwner(value: string) {
usageOwner = value;
},
@@ -127,6 +129,17 @@ test("returns the same free intent once for an equivalent retry", async () => {
expect(events).toHaveLength(1);
});
test("revalidates eligibility under the repository lock for the same idempotency key", async () => {
const { service, setEligible } = createService();
const input = { editorialId, usageId, note: "noch einmal", idempotencyKey };
await service.createRepeatDownload(input);
setEligible(false);
await expect(service.createRepeatDownload(input)).rejects.toMatchObject({
code: "USAGE_NOT_FOUND",
});
});
test("treats mixed-case UUID input as the same repeat intent", async () => {
const { service, events } = createService();
const uppercaseInput = {
@@ -159,10 +172,10 @@ test.each([
[undefined, "not-a-uuid"],
] as const)("rejects malformed repeat input before repository side effects", async (note, key) => {
const { service, repository } = createService();
const findIntent = vi.spyOn(repository, "findIntent");
const createRepeatIntent = vi.spyOn(repository, "createRepeatIntent");
await expect(
service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }),
).rejects.toMatchObject({ code: "INVALID_INPUT" });
expect(findIntent).not.toHaveBeenCalled();
expect(createRepeatIntent).not.toHaveBeenCalled();
});
+96 -100
View File
@@ -36,7 +36,6 @@ export type RepeatIntentInput = {
};
export type RepeatDownloadRepository = {
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
createRepeatIntent(input: RepeatIntentInput): Promise<PersistedRepeatIntent>;
};
@@ -50,8 +49,6 @@ export function createDownloadService({ repository }: { repository: RepeatDownlo
usageId: input.usageId,
note: input.note ?? null,
});
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
if (existing) return resolveIntent(existing, fingerprint, "repeat_download");
const persisted = await repository.createRepeatIntent({
...input,
requestFingerprint: fingerprint,
@@ -65,109 +62,108 @@ export function createRepeatDownloadRepository(
database: NodePgDatabase<typeof schema>,
): RepeatDownloadRepository {
return {
findIntent(editorialId, idempotencyKey) {
return findPersistedIntent(database, editorialId, idempotencyKey);
},
async createRepeatIntent(input) {
try {
return await database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId);
const existing = await findPersistedIntent(
transaction,
input.editorialId,
input.idempotencyKey,
);
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 })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
.for("update")
.limit(1);
if (!editorial || editorial.status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
const [usage] = await transaction
.select({
id: usages.id,
assetId: usages.immichAssetId,
billingStatus: usages.billingStatus,
})
.from(usages)
.where(
and(
eq(usages.id, input.usageId),
eq(usages.editorialAccountId, input.editorialId),
),
)
.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
.insert(downloadEvents)
.values({
editorialAccountId: input.editorialId,
usageId: usage.id,
immichAssetId: usage.assetId,
authorizedAt,
status: "authorized",
repeatDownloadNote: input.note,
requestId: randomUUID(),
idempotencyKey: input.idempotencyKey,
intentKind: "repeat_download",
requestFingerprint: input.requestFingerprint,
})
.onConflictDoNothing({
target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey],
})
.returning({ id: downloadEvents.id });
if (!event) throw new RepeatIdempotencyRaceError();
return {
id: event.id,
usageId: usage.id,
assetId: usage.assetId,
priceCents: 0,
billable: false,
status: "authorized" as const,
authorizedAt,
requestFingerprint: input.requestFingerprint,
kind: "repeat_download" as const,
};
});
} catch (error) {
if (!(error instanceof RepeatIdempotencyRaceError)) throw error;
const existing = await findPersistedIntent(
database,
input.editorialId,
input.idempotencyKey,
);
if (existing) return asRepeatIntent(existing);
throw error;
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
return await createRepeatIntentTransaction(database, input);
} catch (error) {
if (!(error instanceof RepeatIdempotencyRaceError) || attempt === 1) throw error;
}
}
throw new RepeatIdempotencyRaceError();
},
};
}
async function createRepeatIntentTransaction(
database: NodePgDatabase<typeof schema>,
input: RepeatIntentInput,
): Promise<PersistedRepeatIntent> {
return database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId);
const existing = await findPersistedIntent(
transaction,
input.editorialId,
input.idempotencyKey,
);
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 })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
.for("update")
.limit(1);
if (!editorial || editorial.status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
const [usage] = await transaction
.select({
id: usages.id,
assetId: usages.immichAssetId,
billingStatus: usages.billingStatus,
})
.from(usages)
.where(
and(
eq(usages.id, input.usageId),
eq(usages.editorialAccountId, input.editorialId),
),
)
.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
.insert(downloadEvents)
.values({
editorialAccountId: input.editorialId,
usageId: usage.id,
immichAssetId: usage.assetId,
authorizedAt,
status: "authorized",
repeatDownloadNote: input.note,
requestId: randomUUID(),
idempotencyKey: input.idempotencyKey,
intentKind: "repeat_download",
requestFingerprint: input.requestFingerprint,
})
.onConflictDoNothing({
target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey],
})
.returning({ id: downloadEvents.id });
if (!event) throw new RepeatIdempotencyRaceError();
return {
id: event.id,
usageId: usage.id,
assetId: usage.assetId,
priceCents: 0,
billable: false,
status: "authorized",
authorizedAt,
requestFingerprint: input.requestFingerprint,
kind: "repeat_download",
};
});
}
function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput {
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
const note = normalizeOptionalText(input.note, 200);
+1
View File
@@ -194,6 +194,7 @@ test("normalizes and bounds history pagination before the scoped repository quer
const repository = {
listEditorialUsageHistory: vi.fn().mockResolvedValue({
items: [],
attempts: [],
page: HISTORY_MAX_PAGE,
pageSize: 20,
hasNext: false,
+112 -101
View File
@@ -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),
});
+16
View File
@@ -80,6 +80,12 @@ function createRepository() {
setStatus(value: string) {
status = value;
},
setIntentStatus(value: string) {
const key = `${editorialId}:${idempotencyKey}`;
const intent = intents.get(key);
if (!intent) throw new Error("intent missing");
intents.set(key, { ...intent, status: value } as unknown as PersistedDownloadIntent);
},
};
}
@@ -174,6 +180,16 @@ test("keeps the original snapshot after a price change while a new key uses the
).resolves.toMatchObject({ priceCents: 2_100 });
});
test("does not expose a terminal persisted event as an authorized intent", async () => {
const { service, setIntentStatus } = createService();
await service.createNewUsage(newUsageInput);
setIntentStatus("failed_before_delivery");
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
code: "USAGE_NOT_FOUND",
});
});
test.each([
["zero", 0],
["missing", null],
+16 -4
View File
@@ -2,7 +2,7 @@ import "server-only";
import { randomUUID } from "node:crypto";
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { and, desc, eq, exists, inArray, isNull, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
@@ -16,6 +16,7 @@ import {
import type * as schema from "@/db/schema";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
import { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility";
import {
type CreateNewUsageInput,
@@ -28,7 +29,8 @@ import {
UsageAccountingError,
} from "./types";
export type PersistedDownloadIntent = DownloadIntent & {
export type PersistedDownloadIntent = Omit<DownloadIntent, "status"> & {
status: typeof downloadEvents.$inferSelect.status;
requestFingerprint: string;
kind: "new_usage" | "repeat_download";
};
@@ -243,6 +245,10 @@ export function createUsageServiceRepository(
},
async listPriorUsages(editorialId, assetId) {
const deliveredOriginal = database
.select({ id: downloadEvents.id })
.from(downloadEvents)
.where(deliveredOriginalEventCondition(editorialId, usages.id));
const rows = await database
.select({
id: usages.id,
@@ -262,6 +268,7 @@ export function createUsageServiceRepository(
eq(usages.editorialAccountId, editorialId),
eq(usages.immichAssetId, assetId),
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
exists(deliveredOriginal),
),
)
.orderBy(desc(usages.createdAt));
@@ -331,8 +338,11 @@ export function resolveIntent(
if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
if (persisted.status !== "authorized") {
throw new UsageAccountingError("USAGE_NOT_FOUND");
}
const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted;
return intent;
return { ...intent, status: "authorized" };
}
class IdempotencyRaceError extends Error {}
@@ -382,6 +392,7 @@ const intentSelection = {
usageId: downloadEvents.usageId,
assetId: downloadEvents.immichAssetId,
authorizedAt: downloadEvents.authorizedAt,
eventStatus: downloadEvents.status,
intentKind: downloadEvents.intentKind,
requestFingerprint: downloadEvents.requestFingerprint,
usagePriceCents: usages.priceCents,
@@ -392,6 +403,7 @@ function persistedIntent(row: {
usageId: string;
assetId: string;
authorizedAt: Date;
eventStatus: PersistedDownloadIntent["status"];
intentKind: string;
requestFingerprint: string;
usagePriceCents: number;
@@ -408,7 +420,7 @@ function persistedIntent(row: {
assetId: row.assetId,
priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0,
billable: row.intentKind === "new_usage",
status: "authorized",
status: row.eventStatus,
authorizedAt: row.authorizedAt,
requestFingerprint: row.requestFingerprint,
kind: row.intentKind,