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
+2131 -155

No files matched your search

+1
View File
@@ -9,3 +9,4 @@ node_modules/
dist/ dist/
coverage/ coverage/
*.tsbuildinfo *.tsbuildinfo
.DS_Store
@@ -122,3 +122,56 @@
### Remaining concern ### Remaining concern
- Real PostgreSQL assertions remain blocked solely by the absent local Docker/container runtime. The expanded suite is not skipped and should be run unchanged on a Docker-enabled CI/release host. - Real PostgreSQL assertions remain blocked solely by the absent local Docker/container runtime. The expanded suite is not skipped and should be run unchanged on a Docker-enabled CI/release host.
## Fix Round 2
### Eligibility alignment
- Removed the Repeat service's unlocked `findIntent` fast path. Every initial request and same-key retry now enters the repository transaction, takes the editorial/usage locks, checks the original-delivery invariant, and only then returns or creates an intent. The insertion-race fallback repeats that same locked transaction instead of loading a winner outside the invariant.
- Persisted intents now carry the real `download_events.status`. `resolveIntent` checks fingerprint/kind conflict semantics first and exposes only a still-`authorized` event; terminal or streaming events are rejected with generic not-found semantics instead of producing a stale 201/file URL.
- Centralized the database delivery predicate in `deliveredOriginalEventCondition`: same editorial and usage, `intent_kind = new_usage`, `status in (completed, interrupted)`, and `transferred_bytes > 0`. Repeat creation/claim, prior-usage reads, and catalog dialog choices use this same predicate alongside non-voided billing status.
- Catalog choices use one correlated `EXISTS` query, not N+1 reads. Inputs are bounded to the 60-photo catalog page and results to 300 choices. Abandoned, authorized-only, zero-byte, failed, voided, and foreign-editorial usages are not serialized to the dialog; delivered open/billed/reopened usages remain eligible.
### Global attempt stream
- Split usage pagination from attempt pagination. Usage snapshots remain bounded to 20+1 rows, while attempts are queried directly from `download_events` by authenticated `editorial_account_id`, independent of the selected usage page.
- Attempt traversal includes all five statuses (`authorized`, `streaming`, `completed`, `interrupted`, `failed_before_delivery`). Because membership and ordering depend only on immutable `authorized_at + id`, later terminal transitions cannot insert an old row behind an issued cursor.
- The attempt query joins `usages` once with a matching editorial scope and returns at most 25+1 rows. Every serialized attempt includes filename, album, purpose, reference, immutable usage price, effective billable cents, bytes, kind, timestamps, and current outcome. No hidden N+1 or unbounded attempt array remains.
- The UI renders a separate German `Downloadversuche` ledger, including in-progress statuses and both effective attempt cost and immutable usage-price context. Attempt navigation preserves the usage page but is no longer constrained by its membership.
- The cursor compares the raw indexed `(authorized_at, id)` tuple and serializes exact PostgreSQL microseconds plus UUID. Concurrent later events stay on a refreshed newest page; traversal of the pre-existing older stream has no duplicates or omissions.
### Migration
- Added `drizzle/0004_download_history_indexes.sql`, generated `drizzle/meta/0004_snapshot.json`, and updated the journal.
- Added `download_events_editorial_authorized_id_idx` on `(editorial_account_id, authorized_at DESC, id DESC)`.
- Added `usages_editorial_created_id_idx` on `(editorial_account_id, created_at DESC, id DESC)`.
- The deterministic migration contract asserts both exact indexes and that neither usage nor download history is deleted. `drizzle-kit check` passes and the final generate is a no-op.
### Fix-round TDD evidence
- Repeat retry RED: an equivalent same-key request resolved successfully after repository eligibility was revoked. GREEN routes the retry through the locked repository; the focused Repeat suite passed 10/10.
- Persisted-state RED: a `failed_before_delivery` event was returned as an intent. GREEN selects the true event status and rejects every non-authorized persisted event; combined usage/repeat services passed 2 files / 30 tests with typecheck.
- Attempt-stream RED: the new separate all-status UI model failed because the component still dereferenced nested `usage.attempts`. GREEN renders the global bounded ledger; focused history tests passed 2 files / 12 tests.
- Price-context RED: attempt rows did not expose their immutable usage price. GREEN renders labeled usage-price context for every attempt.
- Migration RED: the 0004 contract failed with ENOENT. GREEN passed after schema generation, snapshot/journal update, Drizzle validation, and a no-op generation.
- Combined focused verification passed 9 files / 61 tests before final full verification.
### PostgreSQL coverage and blocker
- Expanded the unskipped PostgreSQL suite with: same-key repeat rejection after a usage void; delivered-choice filtering across open/billed/reopened, abandoned and zero-byte rows; foreign-editorial isolation; global traversal from an empty usage page; status-transition and concurrent-new-event cursor stability; and `EXPLAIN` assertions for both new history indexes.
- Command: `pnpm test tests/db/download-delivery.test.ts tests/db/usage-accounting.test.ts tests/db/accounting-migration.test.ts`.
- Result: all three suites failed before collection with `Could not find a working container runtime strategy`; exactly 0 PostgreSQL tests executed. No test is skipped.
### Final verification
- `pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts tests/db/download-history-index-migration-sql.test.ts` — 28 files / 169 tests passed.
- `pnpm typecheck` — passed.
- `pnpm lint` — passed.
- `pnpm exec drizzle-kit check` — passed.
- `pnpm exec drizzle-kit generate --name task_9_fix_round_2_final_noop` — no schema changes, nothing to migrate.
- `git diff --check` — passed.
- Webpack production build with documented `.env.example` values — passed compilation, TypeScript, page-data collection, 14/14 static pages, and build tracing.
### Remaining concern
- The only unresolved verification gap is environmental: the real PostgreSQL migration, race, traversal, and query-plan assertions require a Docker-capable host. Run the unchanged three-suite command above in CI before release.
@@ -0,0 +1,2 @@
CREATE INDEX "download_events_editorial_authorized_id_idx" ON "download_events" USING btree ("editorial_account_id","authorized_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -29,6 +29,13 @@
"when": 1786358492749, "when": 1786358492749,
"tag": "0003_stream_delivery", "tag": "0003_stream_delivery",
"breakpoints": true "breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1786363479515,
"tag": "0004_download_history_indexes",
"breakpoints": true
} }
] ]
} }
+35
View File
@@ -870,6 +870,16 @@ a {
border-top: 1px solid var(--ink); 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 { .usage-attempts li {
display: grid; display: grid;
grid-template-columns: minmax(9rem, 1.2fr) minmax(11rem, 1.5fr) minmax(8rem, 1fr) 0.7fr 0.7fr; 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; 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 { .usage-attempt-empty {
margin: 0; margin: 0;
padding: 1rem 0; padding: 1rem 0;
+57 -6
View File
@@ -22,35 +22,81 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
billingStatus: "open", billingStatus: "open",
priceCents: 1_500, priceCents: 1_500,
billableCents: 1_500, billableCents: 1_500,
},
],
attempts: [ 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", downloadId: "download-3",
usageId: "usage-1",
status: "failed_before_delivery", status: "failed_before_delivery",
requestedAt: new Date("2026-08-10T12:00:00.000Z"), requestedAt: new Date("2026-08-10T12:00:00.000Z"),
finishedAt: new Date("2026-08-10T12:00:01.000Z"), finishedAt: new Date("2026-08-10T12:00:01.000Z"),
transferredBytes: 0, transferredBytes: 0,
repeat: true, repeat: true,
billableCents: 0, billableCents: 0,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
}, },
{ {
downloadId: "download-2", downloadId: "download-2",
usageId: "usage-1",
status: "interrupted", status: "interrupted",
requestedAt: new Date("2026-08-10T11:00:00.000Z"), requestedAt: new Date("2026-08-10T11:00:00.000Z"),
finishedAt: new Date("2026-08-10T11:00:02.000Z"), finishedAt: new Date("2026-08-10T11:00:02.000Z"),
transferredBytes: 40, transferredBytes: 40,
repeat: true, repeat: true,
billableCents: 0, billableCents: 0,
filename: "tor-des-monats.jpg",
albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
}, },
{ {
downloadId: "download-1", downloadId: "download-1",
usageId: "usage-1",
status: "completed", status: "completed",
requestedAt: new Date("2026-08-09T10:00:00.000Z"), requestedAt: new Date("2026-08-09T10:00:00.000Z"),
finishedAt: new Date("2026-08-09T10:00:03.000Z"), finishedAt: new Date("2026-08-09T10:00:03.000Z"),
transferredBytes: 100, transferredBytes: 100,
repeat: false, repeat: false,
billableCents: 1_500, billableCents: 1_500,
}, filename: "tor-des-monats.jpg",
], albumName: "Heimspiel gegen Nord",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 1_500,
}, },
], ],
page: 1, 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("Abgeschlossen")).not.toBeNull();
expect(screen.getByText("Unterbrochen")).not.toBeNull(); expect(screen.getByText("Unterbrochen")).not.toBeNull();
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull(); expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull();
expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(2); expect(screen.getByText("Autorisiert")).not.toBeNull();
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2); 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( expect(screen.getByRole("link", { name: /nächste nutzungsseite/i }).getAttribute("href")).toBe(
"/redaktion/nutzungen?page=2", "/redaktion/nutzungen?page=2",
); );
@@ -89,6 +139,7 @@ test("renders a directional empty state", () => {
<UsageHistoryContent <UsageHistoryContent
history={{ history={{
items: [], items: [],
attempts: [],
page: 1, page: 1,
pageSize: 20, pageSize: 20,
hasNext: false, hasNext: false,
@@ -115,9 +166,9 @@ test("shows the usage-level price and billing status before any attempt is termi
billingStatus: "open", billingStatus: "open",
priceCents: 1_500, priceCents: 1_500,
billableCents: 1_500, billableCents: 1_500,
attempts: [],
}, },
], ],
attempts: [],
page: 1, page: 1,
pageSize: 20, pageSize: 20,
hasNext: false, hasNext: false,
@@ -145,9 +196,9 @@ test("keeps the immutable usage price visible when billing was voided", () => {
billingStatus: "voided", billingStatus: "voided",
priceCents: 1_500, priceCents: 1_500,
billableCents: 0, billableCents: 0,
attempts: [],
}, },
], ],
attempts: [],
page: 1, page: 1,
pageSize: 20, pageSize: 20,
hasNext: false, hasNext: false,
@@ -63,17 +63,6 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
</div> </div>
) : null} ) : null}
</dl> </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> </article>
</li> </li>
))} ))}
@@ -81,21 +70,47 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
)} )}
<HistoryPagination history={history} /> <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} /> <AttemptPagination history={history} />
</section> </section>
); );
} }
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) { function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
const displayedAt = attempt.finishedAt ?? attempt.requestedAt;
return ( return (
<li> <li>
<time dateTime={attempt.finishedAt.toISOString()}> <time dateTime={displayedAt.toISOString()}>
{formatBerlinDateTime(attempt.finishedAt)} {formatBerlinDateTime(displayedAt)}
</time> </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> <strong>{statusLabel(attempt.status)}</strong>
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span> <span>
<span>{byteFormatter.format(attempt.transferredBytes)}</span> {attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} ·{" "}
{byteFormatter.format(attempt.transferredBytes)}
</span>
<span className="usage-attempt-price">
<b>{priceFormatter.format(attempt.billableCents / 100)}</b> <b>{priceFormatter.format(attempt.billableCents / 100)}</b>
<small>Nutzungspreis {priceFormatter.format(attempt.priceCents / 100)}</small>
</span>
</li> </li>
); );
} }
@@ -142,6 +157,8 @@ function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>)
function statusLabel(status: UsageHistoryAttempt["status"]): string { function statusLabel(status: UsageHistoryAttempt["status"]): string {
const labels: Record<UsageHistoryAttempt["status"], string> = { const labels: Record<UsageHistoryAttempt["status"], string> = {
authorized: "Autorisiert",
streaming: "Wird ausgeliefert",
completed: "Abgeschlossen", completed: "Abgeschlossen",
interrupted: "Unterbrochen", interrupted: "Unterbrochen",
failed_before_delivery: "Vor Auslieferung fehlgeschlagen", failed_before_delivery: "Vor Auslieferung fehlgeschlagen",
+11
View File
@@ -3,6 +3,7 @@ import {
bigint, bigint,
boolean, boolean,
check, check,
index,
integer, integer,
pgEnum, pgEnum,
pgTable, pgTable,
@@ -49,6 +50,11 @@ export const usages = pgTable(
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
}, },
(table) => [ (table) => [
index("usages_editorial_created_id_idx").on(
table.editorialAccountId,
table.createdAt.desc(),
table.id.desc(),
),
check( check(
"usages_canonical_immich_asset_id_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}$'`, 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), legacyIntent: boolean("legacy_intent").notNull().default(false),
}, },
(table) => [ (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( uniqueIndex("download_events_editorial_idempotency_key_unique").on(
table.editorialAccountId, table.editorialAccountId,
table.idempotencyKey, table.idempotencyKey,
+19 -10
View File
@@ -1,6 +1,6 @@
import "server-only"; 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 type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { downloadEvents } from "@/db/schema"; import { downloadEvents } from "@/db/schema";
@@ -15,6 +15,23 @@ export function isFreeRepeatEligible(
return billingStatus !== "voided" && deliveredOriginal; 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( export async function hasDeliveredOriginal(
database: NodePgDatabase<typeof schema>, database: NodePgDatabase<typeof schema>,
editorialId: string, editorialId: string,
@@ -23,15 +40,7 @@ export async function hasDeliveredOriginal(
const [delivery] = await database const [delivery] = await database
.select({ id: downloadEvents.id }) .select({ id: downloadEvents.id })
.from(downloadEvents) .from(downloadEvents)
.where( .where(deliveredOriginalEventCondition(editorialId, usageId))
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); .limit(1);
return Boolean(delivery); return Boolean(delivery);
} }
+18 -5
View File
@@ -17,16 +17,15 @@ function createService() {
const intents = new Map<string, PersistedRepeatIntent>(); const intents = new Map<string, PersistedRepeatIntent>();
const events: RepeatIntentInput[] = []; const events: RepeatIntentInput[] = [];
let active = true; let active = true;
let eligible = true;
let usageOwner = editorialId; let usageOwner = editorialId;
let snapshotPrice = 1_500; let snapshotPrice = 1_500;
const repository: RepeatDownloadRepository = { const repository: RepeatDownloadRepository = {
async findIntent(requestEditorialId, key) {
return intents.get(`${requestEditorialId}:${key}`) ?? null;
},
async createRepeatIntent(input) { async createRepeatIntent(input) {
if (!active) throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); if (!active) throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
if (usageOwner !== input.editorialId) throw new UsageAccountingError("USAGE_NOT_FOUND"); 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 key = `${input.editorialId}:${input.idempotencyKey}`;
const existing = intents.get(key); const existing = intents.get(key);
if (existing) return existing; if (existing) return existing;
@@ -54,6 +53,9 @@ function createService() {
setActive(value: boolean) { setActive(value: boolean) {
active = value; active = value;
}, },
setEligible(value: boolean) {
eligible = value;
},
setUsageOwner(value: string) { setUsageOwner(value: string) {
usageOwner = value; usageOwner = value;
}, },
@@ -127,6 +129,17 @@ test("returns the same free intent once for an equivalent retry", async () => {
expect(events).toHaveLength(1); 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 () => { test("treats mixed-case UUID input as the same repeat intent", async () => {
const { service, events } = createService(); const { service, events } = createService();
const uppercaseInput = { const uppercaseInput = {
@@ -159,10 +172,10 @@ test.each([
[undefined, "not-a-uuid"], [undefined, "not-a-uuid"],
] as const)("rejects malformed repeat input before repository side effects", async (note, key) => { ] as const)("rejects malformed repeat input before repository side effects", async (note, key) => {
const { service, repository } = createService(); const { service, repository } = createService();
const findIntent = vi.spyOn(repository, "findIntent"); const createRepeatIntent = vi.spyOn(repository, "createRepeatIntent");
await expect( await expect(
service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }), service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }),
).rejects.toMatchObject({ code: "INVALID_INPUT" }); ).rejects.toMatchObject({ code: "INVALID_INPUT" });
expect(findIntent).not.toHaveBeenCalled(); expect(createRepeatIntent).not.toHaveBeenCalled();
}); });
+18 -22
View File
@@ -36,7 +36,6 @@ export type RepeatIntentInput = {
}; };
export type RepeatDownloadRepository = { export type RepeatDownloadRepository = {
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
createRepeatIntent(input: RepeatIntentInput): Promise<PersistedRepeatIntent>; createRepeatIntent(input: RepeatIntentInput): Promise<PersistedRepeatIntent>;
}; };
@@ -50,8 +49,6 @@ export function createDownloadService({ repository }: { repository: RepeatDownlo
usageId: input.usageId, usageId: input.usageId,
note: input.note ?? null, 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({ const persisted = await repository.createRepeatIntent({
...input, ...input,
requestFingerprint: fingerprint, requestFingerprint: fingerprint,
@@ -65,13 +62,24 @@ export function createRepeatDownloadRepository(
database: NodePgDatabase<typeof schema>, database: NodePgDatabase<typeof schema>,
): RepeatDownloadRepository { ): RepeatDownloadRepository {
return { return {
findIntent(editorialId, idempotencyKey) {
return findPersistedIntent(database, editorialId, idempotencyKey);
},
async createRepeatIntent(input) { async createRepeatIntent(input) {
for (let attempt = 0; attempt < 2; attempt += 1) {
try { try {
return await database.transaction(async (transaction) => { 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); await lockEditorialAccounting(transaction, input.editorialId);
const existing = await findPersistedIntent( const existing = await findPersistedIntent(
transaction, transaction,
@@ -148,24 +156,12 @@ export function createRepeatDownloadRepository(
assetId: usage.assetId, assetId: usage.assetId,
priceCents: 0, priceCents: 0,
billable: false, billable: false,
status: "authorized" as const, status: "authorized",
authorizedAt, authorizedAt,
requestFingerprint: input.requestFingerprint, requestFingerprint: input.requestFingerprint,
kind: "repeat_download" as const, kind: "repeat_download",
}; };
}); });
} catch (error) {
if (!(error instanceof RepeatIdempotencyRaceError)) throw error;
const existing = await findPersistedIntent(
database,
input.editorialId,
input.idempotencyKey,
);
if (existing) return asRepeatIntent(existing);
throw error;
}
},
};
} }
function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput { function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput {
+1
View File
@@ -194,6 +194,7 @@ test("normalizes and bounds history pagination before the scoped repository quer
const repository = { const repository = {
listEditorialUsageHistory: vi.fn().mockResolvedValue({ listEditorialUsageHistory: vi.fn().mockResolvedValue({
items: [], items: [],
attempts: [],
page: HISTORY_MAX_PAGE, page: HISTORY_MAX_PAGE,
pageSize: 20, pageSize: 20,
hasNext: false, hasNext: false,
+63 -52
View File
@@ -1,6 +1,6 @@
import "server-only"; 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 type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client"; 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 type * as schema from "@/db/schema";
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types"; 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_PAGE_SIZE = 20;
export const HISTORY_MAX_PAGE = 1_000; export const HISTORY_MAX_PAGE = 1_000;
export const HISTORY_ATTEMPT_PAGE_SIZE = 25; export const HISTORY_ATTEMPT_PAGE_SIZE = 25;
export const DOWNLOAD_OPTIONS_MAX_ASSETS = 60;
export const DOWNLOAD_OPTIONS_MAX_USAGES = 300;
export type ClaimedDownload = { export type ClaimedDownload = {
id: string; id: string;
@@ -351,12 +357,18 @@ function assertByteCount(value: number) {
export type UsageHistoryAttempt = { export type UsageHistoryAttempt = {
downloadId: string; downloadId: string;
status: "completed" | "interrupted" | "failed_before_delivery"; usageId: string;
status: typeof downloadEvents.$inferSelect.status;
requestedAt: Date; requestedAt: Date;
finishedAt: Date; finishedAt?: Date;
transferredBytes: number; transferredBytes: number;
repeat: boolean; repeat: boolean;
billableCents: number; billableCents: number;
filename: string;
albumName: string;
purpose: string;
reference?: string;
priceCents: number;
}; };
export type UsageHistoryItem = { export type UsageHistoryItem = {
@@ -369,11 +381,11 @@ export type UsageHistoryItem = {
billingStatus: "open" | "billed" | "reopened" | "voided"; billingStatus: "open" | "billed" | "reopened" | "voided";
priceCents: number; priceCents: number;
billableCents: number; billableCents: number;
attempts: UsageHistoryAttempt[];
}; };
export type UsageHistoryPage = { export type UsageHistoryPage = {
items: UsageHistoryItem[]; items: UsageHistoryItem[];
attempts: UsageHistoryAttempt[];
page: number; page: number;
pageSize: number; pageSize: number;
hasNext: boolean; hasNext: boolean;
@@ -443,20 +455,9 @@ export function createPostgresDownloadHistoryRepository(
.offset(offset); .offset(offset);
const hasNext = usageRows.length > HISTORY_PAGE_SIZE; const hasNext = usageRows.length > HISTORY_PAGE_SIZE;
const pageRows = usageRows.slice(0, 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 authorizedAtMicros = sql<string>`floor(extract(epoch from ${downloadEvents.authorizedAt}) * 1000000)::bigint`;
const beforeCursor = attemptCursor 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; : undefined;
const eventRowsWithNext = await database const eventRowsWithNext = await database
.select({ .select({
@@ -468,17 +469,24 @@ export function createPostgresDownloadHistoryRepository(
transferredBytes: downloadEvents.transferredBytes, transferredBytes: downloadEvents.transferredBytes,
intentKind: downloadEvents.intentKind, intentKind: downloadEvents.intentKind,
authorizedAtMicros, authorizedAtMicros,
filename: usages.filenameSnapshot,
albumName: usages.albumNameSnapshot,
purpose: usages.purpose,
reference: usages.internalReference,
priceCents: usages.priceCents,
billingStatus: usages.billingStatus,
}) })
.from(downloadEvents) .from(downloadEvents)
.innerJoin(
usages,
and(
eq(usages.id, downloadEvents.usageId),
eq(usages.editorialAccountId, editorialId),
),
)
.where( .where(
and( and(
eq(downloadEvents.editorialAccountId, editorialId), eq(downloadEvents.editorialAccountId, editorialId),
inArray(downloadEvents.usageId, usageIds),
inArray(downloadEvents.status, [
"completed",
"interrupted",
"failed_before_delivery",
]),
beforeCursor, beforeCursor,
), ),
) )
@@ -495,13 +503,6 @@ export function createPostgresDownloadHistoryRepository(
}) })
: undefined; : 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 { return {
items: pageRows.map((usage) => { items: pageRows.map((usage) => {
const billableCents = usage.billingStatus === "voided" ? 0 : usage.priceCents; const billableCents = usage.billingStatus === "voided" ? 0 : usage.priceCents;
@@ -515,20 +516,26 @@ export function createPostgresDownloadHistoryRepository(
billingStatus: usage.billingStatus, billingStatus: usage.billingStatus,
priceCents: usage.priceCents, priceCents: usage.priceCents,
billableCents, billableCents,
attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({ };
}),
attempts: eventRows.map((event) => ({
downloadId: event.downloadId, downloadId: event.downloadId,
status: terminalStatus(event.status), usageId: event.usageId,
status: event.status,
requestedAt: event.requestedAt, requestedAt: event.requestedAt,
finishedAt: event.finishedAt ?? event.requestedAt, ...(event.finishedAt === null ? {} : { finishedAt: event.finishedAt }),
transferredBytes: event.transferredBytes ?? 0, transferredBytes: event.transferredBytes ?? 0,
repeat: event.intentKind === "repeat_download", repeat: event.intentKind === "repeat_download",
billableCents: billableCents:
event.intentKind === "new_usage" && usage.billingStatus !== "voided" event.intentKind === "new_usage" && event.billingStatus !== "voided"
? usage.priceCents ? event.priceCents
: 0, : 0,
filename: event.filename,
albumName: event.albumName,
purpose: event.purpose,
...(event.reference === null ? {} : { reference: event.reference }),
priceCents: event.priceCents,
})), })),
};
}),
page, page,
pageSize: HISTORY_PAGE_SIZE, pageSize: HISTORY_PAGE_SIZE,
hasNext, 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"] { function claimedIntentKind(value: string): ClaimedDownload["intentKind"] {
if (value === "new_usage" || value === "repeat_download" || value === "legacy") { if (value === "new_usage" || value === "repeat_download" || value === "legacy") {
return value; return value;
@@ -601,13 +597,19 @@ export type EditorialDownloadOptions = {
priorUsagesByAsset: Record<string, DownloadDialogUsage[]>; priorUsagesByAsset: Record<string, DownloadDialogUsage[]>;
}; };
export async function loadEditorialDownloadOptions( export function createEditorialDownloadOptionsLoader(
database: NodePgDatabase<typeof schema>,
) {
return async function loadOptions(
editorialId: string, editorialId: string,
assetIds: string[], assetIds: string[],
): Promise<EditorialDownloadOptions> { ): Promise<EditorialDownloadOptions> {
const normalizedEditorialId = normalizeUuid(editorialId); const normalizedEditorialId = normalizeUuid(editorialId);
const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))]; const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))];
const [editorial] = await db if (normalizedAssets.length > DOWNLOAD_OPTIONS_MAX_ASSETS) {
throw new UsageAccountingError("INVALID_INPUT");
}
const [editorial] = await database
.select({ currentPriceCents: editorialAccounts.currentPriceCents }) .select({ currentPriceCents: editorialAccounts.currentPriceCents })
.from(editorialAccounts) .from(editorialAccounts)
.where( .where(
@@ -625,7 +627,11 @@ export async function loadEditorialDownloadOptions(
return { priceCents: priceCents!, priorUsagesByAsset: {} }; return { priceCents: priceCents!, priorUsagesByAsset: {} };
} }
const rows = await db const deliveredOriginal = database
.select({ id: downloadEvents.id })
.from(downloadEvents)
.where(deliveredOriginalEventCondition(normalizedEditorialId, usages.id));
const rows = await database
.select({ .select({
id: usages.id, id: usages.id,
assetId: usages.immichAssetId, assetId: usages.immichAssetId,
@@ -638,9 +644,11 @@ export async function loadEditorialDownloadOptions(
eq(usages.editorialAccountId, normalizedEditorialId), eq(usages.editorialAccountId, normalizedEditorialId),
inArray(usages.immichAssetId, normalizedAssets), inArray(usages.immichAssetId, normalizedAssets),
inArray(usages.billingStatus, ["open", "billed", "reopened"]), inArray(usages.billingStatus, ["open", "billed", "reopened"]),
exists(deliveredOriginal),
), ),
) )
.orderBy(desc(usages.createdAt)); .orderBy(desc(usages.createdAt), desc(usages.id))
.limit(DOWNLOAD_OPTIONS_MAX_USAGES);
const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {}; const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {};
for (const row of rows) { for (const row of rows) {
(priorUsagesByAsset[row.assetId] ??= []).push({ (priorUsagesByAsset[row.assetId] ??= []).push({
@@ -650,8 +658,11 @@ export async function loadEditorialDownloadOptions(
}); });
} }
return { priceCents: priceCents!, priorUsagesByAsset }; return { priceCents: priceCents!, priorUsagesByAsset };
};
} }
export const loadEditorialDownloadOptions = createEditorialDownloadOptionsLoader(db);
const downloadHistoryService = createDownloadHistoryService({ const downloadHistoryService = createDownloadHistoryService({
repository: createPostgresDownloadHistoryRepository(db), repository: createPostgresDownloadHistoryRepository(db),
}); });
+16
View File
@@ -80,6 +80,12 @@ function createRepository() {
setStatus(value: string) { setStatus(value: string) {
status = value; 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 }); ).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([ test.each([
["zero", 0], ["zero", 0],
["missing", null], ["missing", null],
+16 -4
View File
@@ -2,7 +2,7 @@ import "server-only";
import { randomUUID } from "node:crypto"; 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 type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client"; import { db } from "@/db/client";
@@ -16,6 +16,7 @@ import {
import type * as schema from "@/db/schema"; import type * as schema from "@/db/schema";
import { immichClient } from "@/modules/immich/client"; import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary } from "@/modules/immich/types"; import type { ImmichAlbumSummary } from "@/modules/immich/types";
import { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility";
import { import {
type CreateNewUsageInput, type CreateNewUsageInput,
@@ -28,7 +29,8 @@ import {
UsageAccountingError, UsageAccountingError,
} from "./types"; } from "./types";
export type PersistedDownloadIntent = DownloadIntent & { export type PersistedDownloadIntent = Omit<DownloadIntent, "status"> & {
status: typeof downloadEvents.$inferSelect.status;
requestFingerprint: string; requestFingerprint: string;
kind: "new_usage" | "repeat_download"; kind: "new_usage" | "repeat_download";
}; };
@@ -243,6 +245,10 @@ export function createUsageServiceRepository(
}, },
async listPriorUsages(editorialId, assetId) { async listPriorUsages(editorialId, assetId) {
const deliveredOriginal = database
.select({ id: downloadEvents.id })
.from(downloadEvents)
.where(deliveredOriginalEventCondition(editorialId, usages.id));
const rows = await database const rows = await database
.select({ .select({
id: usages.id, id: usages.id,
@@ -262,6 +268,7 @@ export function createUsageServiceRepository(
eq(usages.editorialAccountId, editorialId), eq(usages.editorialAccountId, editorialId),
eq(usages.immichAssetId, assetId), eq(usages.immichAssetId, assetId),
inArray(usages.billingStatus, ["open", "billed", "reopened"]), inArray(usages.billingStatus, ["open", "billed", "reopened"]),
exists(deliveredOriginal),
), ),
) )
.orderBy(desc(usages.createdAt)); .orderBy(desc(usages.createdAt));
@@ -331,8 +338,11 @@ export function resolveIntent(
if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) { if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
} }
if (persisted.status !== "authorized") {
throw new UsageAccountingError("USAGE_NOT_FOUND");
}
const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted; const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted;
return intent; return { ...intent, status: "authorized" };
} }
class IdempotencyRaceError extends Error {} class IdempotencyRaceError extends Error {}
@@ -382,6 +392,7 @@ const intentSelection = {
usageId: downloadEvents.usageId, usageId: downloadEvents.usageId,
assetId: downloadEvents.immichAssetId, assetId: downloadEvents.immichAssetId,
authorizedAt: downloadEvents.authorizedAt, authorizedAt: downloadEvents.authorizedAt,
eventStatus: downloadEvents.status,
intentKind: downloadEvents.intentKind, intentKind: downloadEvents.intentKind,
requestFingerprint: downloadEvents.requestFingerprint, requestFingerprint: downloadEvents.requestFingerprint,
usagePriceCents: usages.priceCents, usagePriceCents: usages.priceCents,
@@ -392,6 +403,7 @@ function persistedIntent(row: {
usageId: string; usageId: string;
assetId: string; assetId: string;
authorizedAt: Date; authorizedAt: Date;
eventStatus: PersistedDownloadIntent["status"];
intentKind: string; intentKind: string;
requestFingerprint: string; requestFingerprint: string;
usagePriceCents: number; usagePriceCents: number;
@@ -408,7 +420,7 @@ function persistedIntent(row: {
assetId: row.assetId, assetId: row.assetId,
priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0, priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0,
billable: row.intentKind === "new_usage", billable: row.intentKind === "new_usage",
status: "authorized", status: row.eventStatus,
authorizedAt: row.authorizedAt, authorizedAt: row.authorizedAt,
requestFingerprint: row.requestFingerprint, requestFingerprint: row.requestFingerprint,
kind: row.intentKind, kind: row.intentKind,
+166 -17
View File
@@ -5,6 +5,7 @@ import { afterAll, expect, test } from "vitest";
import { import {
createDownloadDeliveryRepository, createDownloadDeliveryRepository,
createDownloadHistoryService, createDownloadHistoryService,
createEditorialDownloadOptionsLoader,
createPostgresDownloadHistoryRepository, createPostgresDownloadHistoryRepository,
HISTORY_ATTEMPT_PAGE_SIZE, HISTORY_ATTEMPT_PAGE_SIZE,
} from "@/modules/downloads/stream"; } from "@/modules/downloads/stream";
@@ -137,11 +138,13 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async
const repeats = createDownloadService({ const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database), repository: createRepeatDownloadRepository(testDb.database),
}); });
const repeatIntent = await repeats.createRepeatDownload({ const repeatKey = randomUUID();
const repeatInput = {
editorialId: seed.editorialId, editorialId: seed.editorialId,
usageId: seed.usageId, usageId: seed.usageId,
idempotencyKey: randomUUID(), idempotencyKey: repeatKey,
}); };
const repeatIntent = await repeats.createRepeatDownload(repeatInput);
const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true }); const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true });
const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id); const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id);
@@ -153,6 +156,101 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async
[repeatIntent.id], [repeatIntent.id],
); );
expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" }); expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" });
await expect(repeats.createRepeatDownload(repeatInput)).rejects.toMatchObject({
code: "USAGE_NOT_FOUND",
});
});
test("dialog choices include only owned usages with delivered original bytes", async () => {
const own = await testDb.seedEditorialWithUsage();
const foreign = await testDb.seedEditorialWithUsage();
const billedAssetId = randomUUID();
const reopenedAssetId = randomUUID();
const zeroByteAssetId = randomUUID();
const deliveredOpen = await insertUsage(own.editorialId, own.assetId, "open", "Open geliefert");
const deliveredBilled = await insertUsage(
own.editorialId,
billedAssetId,
"billed",
"Abgerechnet geliefert",
);
const deliveredReopened = await insertUsage(
own.editorialId,
reopenedAssetId,
"reopened",
"Wieder geöffnet geliefert",
);
const zeroByte = await insertUsage(
own.editorialId,
zeroByteAssetId,
"open",
"Null Byte",
);
const eventSeeds = [
{ ...own, usageId: deliveredOpen, id: randomUUID(), bytes: 7, status: "completed" },
{
...own,
usageId: deliveredBilled,
assetId: billedAssetId,
id: randomUUID(),
bytes: 9,
status: "completed",
},
{
...own,
usageId: deliveredReopened,
assetId: reopenedAssetId,
id: randomUUID(),
bytes: 3,
status: "interrupted",
},
{
...own,
usageId: zeroByte,
assetId: zeroByteAssetId,
id: randomUUID(),
bytes: 0,
status: "completed",
},
{ ...foreign, id: randomUUID(), bytes: 11, status: "completed" },
] as const;
for (const event of eventSeeds) {
await testDb.insertDownload({
editorialId: event.editorialId,
usageId: event.usageId,
assetId: event.assetId,
id: event.id,
idempotencyKey: randomUUID(),
});
await testDb.pool.query(
"update download_events set status = $2, started_at = now(), completed_at = now(), transferred_bytes = $3 where id = $1",
[event.id, event.status, event.bytes],
);
}
const loadOptions = createEditorialDownloadOptionsLoader(testDb.database);
const options = await loadOptions(own.editorialId, [
own.assetId,
billedAssetId,
reopenedAssetId,
zeroByteAssetId,
]);
expect(options.priorUsagesByAsset[own.assetId]?.map((usage) => usage.purpose)).toEqual([
"Open geliefert",
]);
expect(options.priorUsagesByAsset[billedAssetId]?.map((usage) => usage.purpose)).toEqual([
"Abgerechnet geliefert",
]);
expect(options.priorUsagesByAsset[reopenedAssetId]?.map((usage) => usage.purpose)).toEqual([
"Wieder geöffnet geliefert",
]);
expect(options.priorUsagesByAsset[zeroByteAssetId]).toBeUndefined();
expect(
Object.values(options.priorUsagesByAsset)
.flat()
.some((usage) => usage.id === foreign.usageId),
).toBe(false);
}); });
test("a failed repeat attempt never mutates the original usage", async () => { test("a failed repeat attempt never mutates the original usage", async () => {
@@ -200,7 +298,7 @@ test("terminal completion and interruption race to exactly one database transiti
expect(["completed", "interrupted"]).toContain(event.rows[0].status); expect(["completed", "interrupted"]).toContain(event.rows[0].status);
}); });
test("history is editorial-scoped, terminal-only, and paginated by usage", async () => { test("history keeps the global all-status attempt stream editorial-scoped", async () => {
const own = await testDb.seedEditorialWithUsage(); const own = await testDb.seedEditorialWithUsage();
const foreign = await testDb.seedEditorialWithUsage(); const foreign = await testDb.seedEditorialWithUsage();
const ownCompleted = randomUUID(); const ownCompleted = randomUUID();
@@ -234,14 +332,14 @@ test("history is editorial-scoped, terminal-only, and paginated by usage", async
expect(page.items).toHaveLength(1); expect(page.items).toHaveLength(1);
expect(page.items[0].usageId).toBe(own.usageId); expect(page.items[0].usageId).toBe(own.usageId);
expect(new Set(page.items[0].attempts.map((attempt) => attempt.downloadId))).toEqual( expect(new Set(page.attempts.map((attempt) => attempt.downloadId))).toEqual(
new Set([ownInterrupted, ownCompleted]), new Set([ownAuthorized, ownInterrupted, ownCompleted]),
); );
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === ownAuthorized)).toBe(false); expect(page.attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false);
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false); expect(page.attempts.every((attempt) => attempt.filename === "bild.jpg")).toBe(true);
}); });
test("history bounds terminal attempts and exposes every attempt through pagination", async () => { test("global attempt traversal is independent of usage pages and stable across status changes", async () => {
const own = await testDb.seedEditorialWithUsage(); const own = await testDb.seedEditorialWithUsage();
const attemptIds: string[] = []; const attemptIds: string[] = [];
for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) { for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) {
@@ -254,26 +352,77 @@ test("history bounds terminal attempts and exposes every attempt through paginat
intentKind: index === 0 ? "new_usage" : "repeat_download", intentKind: index === 0 ? "new_usage" : "repeat_download",
}); });
} }
await testDb.pool.query(
"update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where usage_id = $1",
[own.usageId],
);
const history = createDownloadHistoryService({ const history = createDownloadHistoryService({
repository: createPostgresDownloadHistoryRepository(testDb.database), repository: createPostgresDownloadHistoryRepository(testDb.database),
}); });
const first = await history.listEditorialUsageHistory(own.editorialId, 1, 1); const first = await history.listEditorialUsageHistory(own.editorialId, 2);
expect(first.nextAttemptCursor).toBeDefined(); expect(first.nextAttemptCursor).toBeDefined();
expect(first.items).toHaveLength(0);
await testDb.pool.query(
"update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where id = $1",
[first.attempts[0].downloadId],
);
const laterEventId = randomUUID();
await testDb.insertDownload({
...own,
id: laterEventId,
idempotencyKey: randomUUID(),
intentKind: "repeat_download",
});
const second = await history.listEditorialUsageHistory( const second = await history.listEditorialUsageHistory(
own.editorialId, own.editorialId,
1, 2,
first.nextAttemptCursor, first.nextAttemptCursor,
); );
const firstIds = first.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId)); const firstIds = first.attempts.map((attempt) => attempt.downloadId);
const secondIds = second.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId)); const secondIds = second.attempts.map((attempt) => attempt.downloadId);
expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE); expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE);
expect(secondIds).toHaveLength(1); expect(secondIds).toHaveLength(1);
expect(second.nextAttemptCursor).toBeUndefined(); expect(second.nextAttemptCursor).toBeUndefined();
expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds)); expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds));
expect([...firstIds, ...secondIds]).not.toContain(laterEventId);
}); });
test("history ordering queries can use the editorial keyset indexes", async () => {
const own = await testDb.seedEditorialWithUsage();
const client = await testDb.pool.connect();
try {
await client.query("begin");
await client.query("set local enable_seqscan = off");
const events = await client.query(
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc, id desc limit 26",
[own.editorialId],
);
const usageRows = await client.query(
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc, id desc limit 21",
[own.editorialId],
);
const eventPlan = events.rows.map((row) => row["QUERY PLAN"]).join("\n");
const usagePlan = usageRows.rows.map((row) => row["QUERY PLAN"]).join("\n");
expect(eventPlan).toContain("download_events_editorial_authorized_id_idx");
expect(usagePlan).toContain("usages_editorial_created_id_idx");
} finally {
await client.query("rollback");
client.release();
}
});
async function insertUsage(
editorialId: string,
assetId: string,
billingStatus: "open" | "billed" | "reopened",
purpose: string,
): Promise<string> {
const usageId = randomUUID();
await testDb.pool.query(
`insert into usages (
id, editorial_account_id, immich_asset_id, filename_snapshot,
immich_album_id_snapshot, album_name_snapshot, purpose, price_cents, billing_status
) values ($1, $2, $3, 'dialog.jpg', 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'Dialog', $4, 1500, $5)`,
[usageId, editorialId, assetId, purpose, billingStatus],
);
return usageId;
}
@@ -0,0 +1,19 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test } from "vitest";
test("0004 adds both editorial history keyset indexes without rewriting history", async () => {
const migration = await readFile(
path.join(process.cwd(), "drizzle/0004_download_history_indexes.sql"),
"utf8",
);
expect(migration).toContain(
'CREATE INDEX "download_events_editorial_authorized_id_idx" ON "download_events" USING btree ("editorial_account_id","authorized_at" DESC NULLS LAST,"id" DESC NULLS LAST)',
);
expect(migration).toContain(
'CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST)',
);
expect(migration).not.toMatch(/delete\s+from\s+"?(usages|download_events)"?/i);
});
+18 -24
View File
@@ -432,6 +432,7 @@ test("a repeat remains free after a price change and creates no additional usage
const editorialId = await seedEditorial(); const editorialId = await seedEditorial();
const { usageService, downloadService } = createServices(); const { usageService, downloadService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId)); const first = await usageService.createNewUsage(newInput(editorialId));
await markDelivered(first.id);
await database await database
.update(editorialAccounts) .update(editorialAccounts)
.set({ currentPriceCents: 2_100 }) .set({ currentPriceCents: 2_100 })
@@ -456,6 +457,7 @@ test("same-key repeat concurrency creates one free event", async () => {
const editorialId = await seedEditorial(); const editorialId = await seedEditorial();
const { usageService, downloadService } = createServices(); const { usageService, downloadService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId)); const first = await usageService.createNewUsage(newInput(editorialId));
await markDelivered(first.id);
const repeatInput = { const repeatInput = {
editorialId, editorialId,
usageId: first.usageId, usageId: first.usageId,
@@ -476,7 +478,7 @@ test("same-key repeat concurrency creates one free event", async () => {
expect(eventCount.value).toBe(1); expect(eventCount.value).toBe(1);
}); });
test("returns a repeat winner committed while waiting before later suspension is checked", async () => { test("rechecks suspension after an idempotent repeat winner commits", async () => {
const editorialId = await seedEditorial(); const editorialId = await seedEditorial();
const { usageService } = createServices(); const { usageService } = createServices();
const first = await usageService.createNewUsage(newInput(editorialId)); const first = await usageService.createNewUsage(newInput(editorialId));
@@ -486,20 +488,8 @@ test("returns a repeat winner committed while waiting before later suspension is
note: "Web-Ausgabe", note: "Web-Ausgabe",
idempotencyKey: randomUUID(), idempotencyKey: randomUUID(),
}; };
const realRepository = createRepeatDownloadRepository(database);
let releaseFastMiss!: () => void;
const fastMiss = new Promise<void>((resolve) => {
releaseFastMiss = resolve;
});
const downloadService = createDownloadService({ const downloadService = createDownloadService({
repository: { repository: createRepeatDownloadRepository(database),
...realRepository,
async findIntent(requestEditorialId, key) {
const intent = await realRepository.findIntent(requestEditorialId, key);
releaseFastMiss();
return intent;
},
},
}); });
const eventId = randomUUID(); const eventId = randomUUID();
const authorizedAt = new Date("2026-08-09T11:00:00.000Z"); const authorizedAt = new Date("2026-08-09T11:00:00.000Z");
@@ -509,7 +499,6 @@ test("returns a repeat winner committed while waiting before later suspension is
try { try {
const pending = downloadService.createRepeatDownload(input); const pending = downloadService.createRepeatDownload(input);
await fastMiss;
await locker.query( await locker.query(
`insert into download_events ( `insert into download_events (
id, editorial_account_id, usage_id, immich_asset_id, authorized_at, id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
@@ -538,15 +527,7 @@ test("returns a repeat winner committed while waiting before later suspension is
]); ]);
await locker.query("commit"); await locker.query("commit");
await expect(pending).resolves.toEqual({ await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" });
id: eventId,
usageId: first.usageId,
assetId,
priceCents: 0,
billable: false,
status: "authorized",
authorizedAt,
});
} finally { } finally {
await locker.query("rollback"); await locker.query("rollback");
locker.release(); locker.release();
@@ -585,3 +566,16 @@ test("repeat ownership is scoped to the active editorial", async () => {
}), }),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
}); });
async function markDelivered(downloadId: string): Promise<void> {
const deliveredAt = new Date();
await database
.update(downloadEvents)
.set({
status: "completed",
startedAt: deliveredAt,
completedAt: deliveredAt,
transferredBytes: 1,
})
.where(eq(downloadEvents.id, downloadId));
}