13 KiB
13 KiB
Task 9 — Authorized Original Streaming and Delivery Outcomes
Delivered
- Added authenticated
POST /api/download-intentsandGET /api/downloads/:downloadId/fileroutes. Both derive the editorial scope exclusively fromrequireActiveEditorial; request payloads cannot supply editorial IDs or prices. - Added a strict discriminated intent payload for
new_usageversusrepeat_download. Unknown/mixed fields, including client-controllededitorialIdandpriceCents, are rejected before accounting side effects. Responses expose only the download ID, same-origin file URL, server price, and billable flag. - Added an atomic PostgreSQL claim for one owned
authorizedevent. The conditionalauthorized -> streamingupdate commits before Immich is called, so concurrent GETs allow at most one upstream request. A same-editorial reused event returns a stable conflict; invalid, missing, and foreign-editorial IDs retain generic not-found behavior. - Added unbuffered original streaming with exact byte accounting, upstream cancellation, contained cancellation rejections, safe upstream-reader cleanup, and exactly-once terminal settlement under local and database races.
- Added safe download response headers:
private, no-store, syntactically validated media type and length,nosniff, and an attachment disposition with a control/path-separator-free ASCII fallback plus RFC 5987 UTF-8filename*. No Immich URL, API key, or upstream-internal header is forwarded. - Added the accessible German usage dialog to each catalog photo. Existing owned usages show
0,00 EUR; a new usage shows the current server-read editorial price and requires a purpose. Only the dialog is a Client Component. Native dialog/radio/keyboard behavior, explicit focus, pending-state Escape handling, and visible focus styles are retained. - The dialog creates one UUID only when a submission starts. It keeps that key through a failed retry, suppresses double-click requests, and resets the key only when the material selection/purpose changes or the action completes/closes.
- Added the editorial usage-history page and navigation. Its bounded, principal-scoped read model paginates immutable usage snapshots and includes every completed, interrupted, and failed-before-delivery attempt with filename, album, purpose, reference, date/time, bytes, attempt kind, outcome, and billable cents. It has German empty, pagination, and unavailable states.
- Voided usages are excluded from free-repeat authorization and prior-usage choices. Interrupted/completed original usages remain eligible for a new zero-cost repeat intent.
Delivery state machine
- Intent services create one immutable
authorizedevent. - The file route conditionally claims
authorized -> streaming, scoped by bothdownloadIdand the authenticatededitorialId. - A clean upstream close performs
streaming -> completedwith the exact enqueued byte count. - An upstream error or client cancellation after at least one byte performs
streaming -> interrupted; the usage remains unchanged and can receive a new repeat intent. - An upstream error or cancellation before the first byte performs
streaming -> failed_before_deliverywith zero bytes. - For a
new_usagefailure before delivery, the same transaction changes the usage fromopen|reopened -> voidedand appendsbillable_usage_voided_before_deliveryto the audit log. The failed event and usage remain immutable/explainable; nothing is deleted. - For a repeat failure, the original usage is never mutated. The event alone records the failed attempt.
- Every terminal repository update is conditional on
status = streaming; competing completion/interruption/failure attempts therefore have at most one winner.
Migration
- Added
drizzle/0003_stream_delivery.sqlwith the durableusage_billing_status = 'voided'value. - Generated
drizzle/meta/0003_snapshot.jsonand updateddrizzle/meta/_journal.json. pnpm exec drizzle-kit checkreportsEverything's fine.pnpm exec drizzle-kit generate --name stream_delivery_final_noopreportsNo schema changes, nothing to migrate.- The deterministic migration contract verifies that 0003 adds the supported state and never deletes usage history.
TDD evidence
Initial streaming, routes, dialog, and migration RED
- Command:
pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts src/app/api/download-intents/route.test.ts src/components/download/usage-dialog.test.tsx tests/db/download-delivery-migration-sql.test.ts - Result: 5 failed suites. The stream, both routes, dialog, and 0003 migration were absent; failures were module-resolution/ENOENT failures, as expected.
Catalog and history RED
- Command:
pnpm test src/modules/albums/catalog-content.test.tsx src/app/redaktion/nutzungen/page.test.tsx - Result: 2 failed files. The catalog had no original-download action and the history page did not exist.
Claimed-body cleanup RED/GREEN
- RED command:
pnpm test src/app/api/downloads/'[downloadId]'/file/route.test.ts -t 'upstream body cannot' - RED result: the route returned 503 for a locked upstream body but failed to terminally account for its already-claimed event.
- GREEN result after the scoped fix: 1 passed / 10 skipped. The route now cancels the upstream body best-effort and records the no-byte terminal outcome.
Header-boundary hardening RED/GREEN
- RED command:
pnpm test src/app/api/downloads/'[downloadId]'/file/route.test.ts -t 'untrustworthy media|malformed Unicode' - RED result: 2 failed / 11 skipped. CR/LF in an upstream media type reached
Headersand produced 503; a lone Unicode surrogate causedencodeURIComponentto throw. - GREEN result: 2 passed / 11 skipped. Media-type optional whitespace is now restricted to HTTP space/tab, malformed values fall back to
application/octet-stream, and malformed surrogate code units are replaced before RFC 5987 encoding.
Focused GREEN
- Command:
pnpm typecheck && pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts src/app/api/download-intents/route.test.ts src/components/download/usage-dialog.test.tsx src/modules/albums/catalog-content.test.tsx src/app/redaktion/nutzungen/page.test.tsx tests/db/download-delivery-migration-sql.test.ts - Result: typecheck passed; 7 files / 33 tests passed before the final route-handler build refactor.
- After isolating handler/test exports from Next route/page modules, the focused route/history set passed 3 files / 19 tests and lint passed.
Real PostgreSQL tests
- Added
tests/db/download-delivery.test.ts, unskipped, against PostgreSQL 17 via Testcontainers. - It covers the concurrent authorized claim, new-use pre-byte void plus audit and repeat denial, repeat failure preservation, exactly-one competing terminal transition, and editorial-scoped terminal history.
- Command:
pnpm test tests/db/download-delivery.test.ts - Result: the suite failed before collecting/executing tests with
Could not find a working container runtime strategy; 0 tests ran. This is an external Docker-runtime limitation, not a skipped application test.
Final verification
pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts— 25 files / 157 tests passed.pnpm typecheck— passed.pnpm lint— passed.pnpm exec drizzle-kit check— passed.pnpm exec drizzle-kit generate --name stream_delivery_final_noop— no schema changes.git diff --check— passed.pnpm exec next build --webpackwith the repository test environment — passed compilation, TypeScript, page-data collection, 14-page static generation, and build tracing. The intent route, file route, and usage-history page are dynamic server routes.
Concern
- The five new PostgreSQL transition assertions could not execute locally because no container runtime is available. On a Docker-enabled host, run
pnpm test tests/db/download-delivery.test.tsbefore release. The suite is unskipped and included in the normal full test command.
Fix Round 1
Review findings resolved
- Repeat intent creation, stream claim, and pre-first-byte void now lock the same usage row as their transaction mutex. A repeat is eligible only while the usage is non-voided and a
new_usageevent has already reachedcompleted|interruptedwith more than zero delivered bytes. This eligibility is rechecked for idempotent existing intents and again immediately before the conditionalauthorized -> streamingclaim. - Voiding a new usage preserves every audit/history row and terminally changes all still-
authorizedrepeats for that usage tofailed_before_delivery. A repeat discovered without valid delivery evidence is likewise retained and terminally invalidated instead of deleted. The usage-first lock order plus the conditional event update keeps concurrent claims and voids serializable and prevents a repeat from remaining claimable after a committed void. - History attempt work and payload are globally bounded to 25 terminal events for the current 20-usage page. Exact PostgreSQL microsecond timestamp plus UUID keyset cursors provide stable continuation without a maximum attempt-page ceiling, hidden N+1 queries, or unbounded arrays. The cursor remains opaque in the URL, while editorial scope still comes exclusively from the authenticated principal.
- Each usage ledger entry now renders the immutable
price_centssnapshot and its billing status even when no attempt has reached a terminal state. EffectivebillableCentsremains separate, so a voided usage retains its historical price while being markedStorniertand nonbillable. - The before-delivery void audit reads
previousValues.billingStatusfrom the usage row locked in the same transaction. It therefore recordsreopenedtruthfully instead of hard-codingopen. - Dialog dates and history date/times share explicit
Europe/Berlinformatters, making SSR and browser output independent of the host time zone.
State-machine additions
createRepeatDownloadlocks editorial accounting and then the usage row, verifies an actually delivered original event, and only then returns or creates the authorized repeat.claimAuthorizedreads the scoped event, locks its usage row, revalidates non-voided/delivered-original eligibility, and finally performs the conditional claim. A competing claim still loses at the event transition.failBeforeDeliveryreads the streaming event, locks its usage row before the terminal transition, voids an eligible new usage, invalidates every outstanding authorized repeat, and writes the audit with the locked prior billing status in one transaction.- Completed, interrupted, and failed events remain terminal and immutable. No usage or delivery history is deleted.
Fix-round TDD evidence
- Repeat eligibility RED:
pnpm test src/modules/downloads/eligibility.test.tsfailed because the eligibility module did not exist. GREEN after adding the invariant and repository locking: 4 focused files / 36 tests passed, followed bypnpm typecheck. - History bounding RED: the service did not normalize a separate attempt continuation and the UI exposed only usage pagination (2 focused failures). The first bounded-page implementation passed 2 files / 10 tests plus typecheck. It was then tightened to a no-ceiling keyset cursor; the cursor contract/UI tests failed against the offset implementation and passed after the keyset change (2 files / 12 tests).
- Usage-level price/status RED: the open/no-terminal-attempt test could not find
Abrechnungsstatusor the server price (1 failure). The immutable-price regression additionally showed0,00 EURafter void instead of the snapshot. Both pass with separatepriceCentsandbillableCentsfields. - Time-zone RED:
pnpm test src/modules/downloads/format.test.tsfailed because the explicit Berlin formatter did not exist. GREEN verifies a Berlin-midnight boundary while the process time zone isAmerica/Los_Angeles. - Audit and PostgreSQL sequence/race coverage is unskipped in
tests/db/download-delivery.test.ts: reopened prior-status truth, repeat rejection before delivered bytes, completed/interrupted eligibility, pre-authorized repeat invalidation on later void, concurrent claim ownership, and keyset access to every bounded attempt. The environment still fails before collection withCould not find a working container runtime strategy; exactly 0 PostgreSQL tests execute locally.
Migration and final verification
- No schema migration was required in Fix Round 1; the existing durable
voidedstate supports the invariant without deleting history. pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts— 27 files / 166 tests passed.pnpm typecheck— passed.pnpm lint— passed.pnpm exec drizzle-kit check— passed.pnpm exec drizzle-kit generate --name task_9_fix_round_1_final_noop— no schema changes, nothing to migrate.git diff --check— passed.pnpm exec next build --webpackwith the documented.env.examplevalues — passed compilation, TypeScript, page-data collection, 14/14 static pages, and build tracing.
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.