125 lines
13 KiB
Markdown
125 lines
13 KiB
Markdown
# Task 9 — Authorized Original Streaming and Delivery Outcomes
|
|
|
|
## Delivered
|
|
|
|
- Added authenticated `POST /api/download-intents` and `GET /api/downloads/:downloadId/file` routes. Both derive the editorial scope exclusively from `requireActiveEditorial`; request payloads cannot supply editorial IDs or prices.
|
|
- Added a strict discriminated intent payload for `new_usage` versus `repeat_download`. Unknown/mixed fields, including client-controlled `editorialId` and `priceCents`, 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 `authorized` event. The conditional `authorized -> streaming` update 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-8 `filename*`. 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
|
|
|
|
1. Intent services create one immutable `authorized` event.
|
|
2. The file route conditionally claims `authorized -> streaming`, scoped by both `downloadId` and the authenticated `editorialId`.
|
|
3. A clean upstream close performs `streaming -> completed` with the exact enqueued byte count.
|
|
4. 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.
|
|
5. An upstream error or cancellation before the first byte performs `streaming -> failed_before_delivery` with zero bytes.
|
|
6. For a `new_usage` failure before delivery, the same transaction changes the usage from `open|reopened -> voided` and appends `billable_usage_voided_before_delivery` to the audit log. The failed event and usage remain immutable/explainable; nothing is deleted.
|
|
7. For a repeat failure, the original usage is never mutated. The event alone records the failed attempt.
|
|
8. 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.sql` with the durable `usage_billing_status = 'voided'` value.
|
|
- Generated `drizzle/meta/0003_snapshot.json` and updated `drizzle/meta/_journal.json`.
|
|
- `pnpm exec drizzle-kit check` reports `Everything's fine`.
|
|
- `pnpm exec drizzle-kit generate --name stream_delivery_final_noop` reports `No 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 `Headers` and produced 503; a lone Unicode surrogate caused `encodeURIComponent` to 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 --webpack` with 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.ts` before 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_usage` event has already reached `completed|interrupted` with more than zero delivered bytes. This eligibility is rechecked for idempotent existing intents and again immediately before the conditional `authorized -> streaming` claim.
|
|
- Voiding a new usage preserves every audit/history row and terminally changes all still-`authorized` repeats for that usage to `failed_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_cents` snapshot and its billing status even when no attempt has reached a terminal state. Effective `billableCents` remains separate, so a voided usage retains its historical price while being marked `Storniert` and nonbillable.
|
|
- The before-delivery void audit reads `previousValues.billingStatus` from the usage row locked in the same transaction. It therefore records `reopened` truthfully instead of hard-coding `open`.
|
|
- Dialog dates and history date/times share explicit `Europe/Berlin` formatters, making SSR and browser output independent of the host time zone.
|
|
|
|
### State-machine additions
|
|
|
|
1. `createRepeatDownload` locks editorial accounting and then the usage row, verifies an actually delivered original event, and only then returns or creates the authorized repeat.
|
|
2. `claimAuthorized` reads 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.
|
|
3. `failBeforeDelivery` reads 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.
|
|
4. 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.ts` failed because the eligibility module did not exist. GREEN after adding the invariant and repository locking: 4 focused files / 36 tests passed, followed by `pnpm 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 `Abrechnungsstatus` or the server price (1 failure). The immutable-price regression additionally showed `0,00 EUR` after void instead of the snapshot. Both pass with separate `priceCents` and `billableCents` fields.
|
|
- Time-zone RED: `pnpm test src/modules/downloads/format.test.ts` failed because the explicit Berlin formatter did not exist. GREEN verifies a Berlin-midnight boundary while the process time zone is `America/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 with `Could 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 `voided` state 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 --webpack` with the documented `.env.example` values — 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.
|