226 lines
18 KiB
Markdown
226 lines
18 KiB
Markdown
# Streaming-Exports für CSV/JSON/XLSX/PDF
|
||
|
||
**Status:** completed
|
||
**Task-ID:** #46
|
||
**Phase:** 03
|
||
**Estimated Effort:** 1 Woche
|
||
**Owner:** unassigned
|
||
|
||
## Problem
|
||
|
||
Die bestehende Export-Pipeline in `packages/exports/` lädt alle Rows komplett in den Speicher, serialisiert in einen String/Buffer und schreibt erst dann auf den Output. Bei großen Tabellen (>50k Rows) führt das zu:
|
||
|
||
- **OOM-Crashes** im Worker: ein XLSX-Export mit 200k Rows × 30 Cols braucht ~2-3 GB RAM für ExcelJS' interne Workbook-Repräsentation.
|
||
- **Hohe Latency:** User wartet bis zum Schluss, bevor irgendetwas an S3 geschoben wird. Bei XLSX 200k Rows ~8 Min Wartezeit ohne Sichtbarkeit.
|
||
- **Tempfile-Overhead:** Aktuell wird das fertige File erst lokal in `/tmp` geschrieben und dann zu S3 hochgeladen → doppelter I/O.
|
||
- **Kein Hard-Cap:** Nutzer können beliebig große Exports anstoßen, was Worker-Container abreißen lässt.
|
||
- **PDF Edge-Case:** PDF rendering von >5k Rows produziert nicht-navigierbare Riesen-PDFs (>500 Seiten); semantisch schon falsch.
|
||
|
||
Betroffene Codestellen:
|
||
- `packages/exports/src/csv/index.ts` — `serializeExportTableToCsv(table)` returnt `string`
|
||
- `packages/exports/src/json/index.ts` — gleicher Pattern
|
||
- `packages/exports/src/xlsx/index.ts` — `workbook.xlsx.writeBuffer()` ohne Stream
|
||
- `packages/exports/src/pdf/index.ts` — `@react-pdf/renderer renderToBuffer`
|
||
- `apps/worker/src/jobs/export.ts` — Job lädt Rows in Memory, ruft Serializer, schreibt Tempfile, uploaded.
|
||
|
||
## Depends on
|
||
|
||
- `03-scaling-infrastructure/worker-queues.md` — Exports landen im `worker-import`-Pool (long-running, low-concurrency). Ohne Worker-Trennung würde ein 100k-Row-Export alle anderen Jobs blocken.
|
||
- `03-scaling-infrastructure/shared-store-package.md` — Export-Progress (Rows-processed Counter) muss im SharedStore liegen, damit das Frontend per Polling/SSE den Fortschritt zeigen kann (nicht nur in Worker-Memory).
|
||
- `02-observability/metrics-grafana.md` — Export-Job-Metrics (Duration, Rows, Bytes, Errors) brauchen das `/metrics`-Endpoint.
|
||
|
||
## Blocks
|
||
|
||
- `08-mobile-cli-storybook-sdk/cli-ops.md` — CLI-Command `export:run` braucht die Streaming-API um große Exports lokal zu fahren ohne OOM.
|
||
- `10-compliance-polish/compliance-audit-export.md` — Audit-Trail-Export muss massive Datasets streamen können (DSGVO-Auskunft, Million-Row-Audits).
|
||
- `10-compliance-polish/dsgvo-bulk-ops.md` — DSGVO-Datenexport pro User profitiert vom Streaming-Pattern.
|
||
|
||
## Approach
|
||
|
||
**Pro Format eigene Streaming-Strategie**, weil die Output-Formate fundamental unterschiedliche Trade-offs haben:
|
||
|
||
| Format | Streaming-Strategie | Hard-Cap | Begründung |
|
||
|---|---|---|---|
|
||
| CSV | Row-für-Row in Node-Writable | – | Trivial streamable, kein State |
|
||
| JSON (NDJSON) | Row-für-Row, eine JSON-Zeile pro Row | – | Default für große Exports |
|
||
| JSON (Pretty) | nur < 10k Rows in-memory | 10k | UX für kleine Datasets |
|
||
| XLSX | ExcelJS Stream-Writer wenn > 50k Rows, sonst memory | 500k | Stream-Writer hat ExcelJS-Limitations (kein Cell-Re-Reading) — nur bei Bedarf einsetzen |
|
||
| PDF | renderToStream (`@react-pdf/renderer`) | 5k | PDF-Render-Cost steigt nicht-linear; Cap schützt vor UX-Anti-Pattern |
|
||
|
||
**Multipart-Upload direkt zu S3:** Output-Stream wird in S3-Multipart-Chunks (5-10 MB) gepiped. Kein lokales Tempfile. AWS SDK v3 hat `Upload`-Klasse aus `@aws-sdk/lib-storage` die das nativ kann.
|
||
|
||
**Plan-basierte Row-Caps:**
|
||
- Free: maxExportRowCount = 10k
|
||
- Pro: maxExportRowCount = 100k
|
||
- Enterprise: maxExportRowCount = unlimited (gebunden durch Hard-Cap pro Format)
|
||
|
||
**Begründung gegen Alternativen:**
|
||
- *Alles in eine generische Streaming-Library auslagern:* keine die alle 4 Formate gleich gut macht. Lieber pro Format die idiomatische Lib (csv-stringify-Stream, ExcelJS, react-pdf).
|
||
- *Tempfile-Pattern beibehalten und nur Memory-Footprint reduzieren:* löst nicht das Latenz-Problem (User wartet bis Schluss, nichts beim S3).
|
||
- *Erst alles im Worker, dann separater Streaming-Layer:* Doppelarbeit. Lieber direkt streamen.
|
||
|
||
## Implementation Steps
|
||
|
||
1. **CSV-Streaming-API** — Async-Iterator-basierter Writer
|
||
- Files: `packages/exports/src/csv/index.ts` (Edit) — neue Funktion `serializeExportTableToCsvStream(writeStream, table, options)`. Nutzt `csv-stringify` im Stream-Mode (`stringify.stringifier({ header: true })`), pipe in `writeStream`. Iteriert über `table.rows` (async iterable). Bestehende `serializeExportTableToCsv(table)` bleibt für Backward-Compat, ruft intern den Streamer mit `PassThrough` und Collect-Buffer.
|
||
- Tests: `packages/exports/src/csv/stream.test.ts` — assert dass Memory-Footprint bei 1M generierten Rows < 100 MB bleibt (mit `process.memoryUsage`-Snapshots); assert NDJSON-Output korrekt (Header + Rows).
|
||
- Commit: `03-scaling/streaming-exports: csv stream-writer with async iterator`
|
||
|
||
2. **JSON-Streaming-API (NDJSON + Pretty)** — Default NDJSON, Pretty nur für kleine Sets
|
||
- Files: `packages/exports/src/json/index.ts` (Edit) — `serializeExportTableToJsonStream(writeStream, table, options)`. `options.mode = 'ndjson' | 'pretty'`. Bei `ndjson`: pro Row `JSON.stringify(row) + '\n'`. Bei `pretty` und `rowCount < 10000`: collect in Array, `JSON.stringify(arr, null, 2)`. Bei `pretty` und ≥ 10k: Error `EXPORT_PRETTY_JSON_TOO_LARGE` mit Hint auf NDJSON.
|
||
- Tests: `packages/exports/src/json/stream.test.ts` — beide Modes, Error-Case.
|
||
- Commit: `03-scaling/streaming-exports: json/ndjson stream-writer`
|
||
|
||
3. **XLSX Streaming-Writer mit Threshold** — ExcelJS-Stream wenn > 50k
|
||
- Files: `packages/exports/src/xlsx/index.ts` (Edit) — `serializeExportTableToXlsxStream(writeStream, table, options)`. Estimate-RowCount aus `table.estimatedRowCount` (vom Caller geliefert, kein vorab-Count). Wenn `> 50000`: `new ExcelJS.stream.xlsx.WorkbookWriter({ stream: writeStream })`, Worksheet committed Row-by-Row mit `worksheet.addRow(row).commit()`. Wenn `≤ 50000`: bestehender In-Memory-Pfad (kein Regression-Risk für kleine Exports).
|
||
- Hard-Cap 500k: prüfen am Anfang, wenn `> 500000` → `EXPORT_ROW_LIMIT_EXCEEDED`.
|
||
- Tests: `packages/exports/src/xlsx/stream.test.ts` — Both-Paths-Tests, Hard-Cap-Test, Stream-Mode-Memory-Check (< 200 MB für 200k Rows × 20 Cols).
|
||
- Commit: `03-scaling/streaming-exports: xlsx stream-writer with 50k threshold`
|
||
|
||
4. **PDF Streaming via renderToStream** — `@react-pdf/renderer`
|
||
- Files: `packages/exports/src/pdf/index.ts` (Edit) — `serializeExportTableToPdfStream(writeStream, table, options)`. Hard-Cap 5000 — wenn `rowCount > 5000` → `EXPORT_PDF_ROW_LIMIT_EXCEEDED` mit Hint auf CSV/XLSX. Nutzt `renderToStream(<TableDocument table={table} />)` → Stream `pipe(writeStream)`.
|
||
- Tests: `packages/exports/src/pdf/stream.test.ts` — Render-Success für 1k Rows, Error bei 5001.
|
||
- Commit: `03-scaling/streaming-exports: pdf renderToStream with 5k cap`
|
||
|
||
5. **S3 Multipart-Upload-Sink** — Output-Stream landet direkt im S3-Bucket
|
||
- Files: `packages/exports/src/sinks/s3-multipart.ts` (neu) — Factory `createS3MultipartUploadSink({ bucket, key, contentType })` returnt `{ writeStream, completionPromise }`. Nutzt `@aws-sdk/lib-storage`'s `Upload`-Klasse mit `partSize: 8 * 1024 * 1024` (8 MB) und `queueSize: 4`.
|
||
- Tests: `packages/exports/src/sinks/s3-multipart.test.ts` — gegen `aws-sdk-client-mock` oder lokales MinIO im testcontainer.
|
||
- Commit: `03-scaling/streaming-exports: s3 multipart upload sink`
|
||
|
||
6. **Worker-Export-Job refactoren** — Glue alles zusammen, kein Tempfile mehr
|
||
- Files: `apps/worker/src/jobs/export.ts` (Edit) — Job-Handler:
|
||
1. Resolve Tenant-Plan → maxExportRowCount.
|
||
2. Stream Rows via Prisma-Cursor-Iteration (`prisma.row.findMany` in Chunks von 1000 mit Skip-Take oder besser `cursor`-based).
|
||
3. Pick Format-Streamer.
|
||
4. Create S3-Multipart-Sink.
|
||
5. Pipe Streamer → Sink, await completionPromise.
|
||
6. Update Job-Record mit S3-Key, RowCount, Size, Duration.
|
||
7. Notify User (email/notification) mit Download-Link.
|
||
- Progress-Tracking: alle 5k Rows `sharedStore.set(\`export:progress:\${jobId}\`, { processedRows, totalEstimate })` mit TTL 1h.
|
||
- Tests: `apps/worker/src/jobs/export.test.ts` — Mock Prisma + S3-Sink, End-to-End-Job mit 100k Rows.
|
||
- Commit: `03-scaling/streaming-exports: worker job pipes directly to s3 multipart`
|
||
|
||
7. **Tenant-Plan-Row-Caps** — Per-Plan-Limits resolver
|
||
- Files: `packages/billing/src/limits.ts` (Edit oder neu wenn nicht da) — `getMaxExportRowCount(tenantId)` returns 10k/100k/Infinity je Plan. Cached via SharedStore (TTL 5min) damit nicht jeder Export-Job DB-roundtrips macht.
|
||
- `apps/worker/src/jobs/export.ts` (Edit) — Limit-Check vor Job-Start; bei Überschreitung Job mit Error `EXPORT_ROW_LIMIT_PLAN` fail.
|
||
- UI-Hinweis: existierendes Export-Modal zeigt das Limit (Story für Frontend-Task, hier nur Backend).
|
||
- Tests: `packages/billing/src/limits.test.ts` — alle 3 Plans, Cache-Hit/Miss.
|
||
- Commit: `03-scaling/streaming-exports: plan-based row caps for exports`
|
||
|
||
8. **Doku: Format-Capabilities-Matrix** — User-/Operator-Doc
|
||
- Files: `docs/features/exports.md` (neu) — Matrix mit Format × Plan × MaxRows × Streaming-Strategie; Beispiel-Calls; S3-Bucket-Setup-Hinweis; Troubleshooting (Job hängt, Datei korrupt, etc.).
|
||
- Commit: `03-scaling/streaming-exports: add exports feature doc`
|
||
|
||
9. **Metrics-Hook** — Export-Counters in /metrics
|
||
- Files: `apps/worker/src/metrics.ts` (Edit) — Counter `export_jobs_total{format,status}`, Histogram `export_job_duration_seconds{format}`, Gauge `export_job_rows{format}`.
|
||
- Commit: `03-scaling/streaming-exports: export job metrics`
|
||
|
||
10. **Deprecation der nicht-Streaming-APIs** — Markieren, nicht entfernen (Backward-Compat)
|
||
- Files: `packages/exports/src/csv/index.ts`, `json/index.ts`, `xlsx/index.ts`, `pdf/index.ts` — JSDoc `@deprecated Use serializeExportTableTo*Stream`. Bleiben funktional bis nächste Major.
|
||
- Commit: `03-scaling/streaming-exports: deprecate non-streaming serializer apis`
|
||
|
||
## Test Requirements
|
||
|
||
- **Unit-Tests:** je Format ein Stream-Test mit Memory-Footprint-Assertion (`process.memoryUsage().heapUsed`-Snapshots vor/nach). 1M-Row-Stress-Test für CSV/NDJSON.
|
||
- **Integration-Tests:**
|
||
- `apps/worker/src/jobs/export.integration.test.ts` — Full-Cycle gegen testcontainers (Postgres + Redis + MinIO). Enqueue Export-Job mit 200k synthetischen Rows, assert: S3-Object existiert, Größe plausibel, Job-Progress wird im SharedStore aktualisiert, finaler Job-Status = success.
|
||
- Plan-Cap-Test: Free-Tenant mit 20k-Row-Export → Job fails mit klarem Error.
|
||
- **E2E (Playwright):** Frontend-Export-Trigger → poll Job-Status bis success → click Download-Link → assert File-Download (file-size check). Test mit ~5k-Row-Dataset (schnell genug).
|
||
- **Coverage-Target:** ≥ 85% für `packages/exports/src/*/stream.ts` und `apps/worker/src/jobs/export.ts`.
|
||
- **Test-Files:** wie aufgelistet.
|
||
|
||
**NICHT als completed markieren bevor alle Tests grün sind.**
|
||
|
||
## Acceptance Criteria
|
||
|
||
- [ ] 4 Stream-Writer-APIs (CSV, NDJSON/Pretty-JSON, XLSX, PDF) implementiert
|
||
- [ ] S3-Multipart-Sink funktioniert gegen Staging-MinIO + Production-S3
|
||
- [ ] Worker-Export-Job nutzt Streaming-Pfad, kein Tempfile mehr
|
||
- [ ] Per-Plan Row-Caps (10k/100k/unlimited) enforced
|
||
- [ ] Hard-Caps per Format (XLSX 500k, PDF 5k) enforced
|
||
- [ ] 200k-Row-CSV-Export läuft mit < 200 MB Worker-Memory
|
||
- [ ] Progress-Tracking via SharedStore funktioniert (5k-Row-Granularität)
|
||
- [ ] `docs/features/exports.md` enthält Capabilities-Matrix
|
||
- [ ] Metrics in `/metrics` sichtbar
|
||
- [ ] Alte Non-Stream-APIs deprecated (JSDoc), nicht entfernt
|
||
- [ ] Tests grün (lint, typecheck, unit, integration, e2e)
|
||
- [ ] Staging-Smoke-Test: 100k-Row-Export endet erfolgreich in < 3 Min
|
||
- [ ] Detail-MD Progress Log aktualisiert
|
||
- [ ] PROGRESS.md Status auf `completed`
|
||
|
||
## Rollback Strategy
|
||
|
||
- **Code-Rollback:** Schrittweise Commits revertieren. Da alte Non-Stream-APIs bewusst deprecated aber funktional bleiben, kann der Worker-Job-Refactor (Step 6) einzeln zurückgerollt werden ohne die neue Streamer-Infrastruktur zu verlieren.
|
||
- **Feature-Flag:** `EXPORT_STREAMING_ENABLED=false` im Env als Env-Switch → Worker-Job fällt auf alten Non-Stream-Pfad zurück. Im Code als if-branch in `apps/worker/src/jobs/export.ts`. Empfohlen für die ersten Wochen Production.
|
||
- **S3-Multipart-Abort:** Falls Multipart-Upload mittendrin failt, AWS-SDK ruft auto `AbortMultipartUpload` — kein orphaned Multipart-Garbage.
|
||
- **DB:** keine Schema-Changes.
|
||
|
||
## Security Notes
|
||
|
||
- **Plan-Cap-Bypass-Prevention:** Limit-Check passiert im Worker (nicht nur Frontend) → kann nicht via DevTools umgangen werden.
|
||
- **S3-Object-ACLs:** Export-Files in S3 sind Private (no public-read). Download-Link ist Signed-URL mit TTL 1h.
|
||
- **Sensitive-Data in Export:** Tenant-Isolation muss im Prisma-Query stehen (WHERE tenantId = …). Add-Audit-Log-Entry pro Export für Compliance.
|
||
- **DoS-Risiko:** Auch mit Streaming könnte ein Enterprise-Tenant 10M-Row-Exports anstoßen und Workers belegen. Mitigation via Job-Priority (siehe `job-priority.md`) und Hard-Caps pro Format.
|
||
- **Multipart-Upload-Credentials:** S3-Creds aus Env, gleich wie für andere Storage-Ops. Keine Sonderbehandlung nötig.
|
||
|
||
## Subagent Recommendations
|
||
|
||
- **Planning:** `Plan`-Subagent mit Detail-MD + Audit der bestehenden `packages/exports/`-Struktur als Input.
|
||
- **Research:** `Explore`-Subagent um aktuelle Format-Implementierungen zu mappen (CSV-/JSON-/XLSX-/PDF-Module bereits da?) — verhindert Wheel-Reinvention.
|
||
- **Implementation:** `general-purpose`-Subagent pro Format-Step (4 Steps), getrennt vom Worker-Glue-Step. S3-Sink eigener Subagent.
|
||
- **Tests:** separater `general-purpose`-Subagent — wichtig: Stress-Tests (Memory-Asserts) brauchen Sorgfalt damit sie nicht flaky werden.
|
||
- **Verification:** `gsd-verifier`-Subagent gegen Acceptance-Criteria.
|
||
- **Code-Review:** `gsd-code-reviewer` nach Phasen-Abschluss.
|
||
|
||
## Staging-Deployment-Steps
|
||
|
||
1. Branch `agent/03-streaming-exports` pushen.
|
||
2. Coolify-Auto-Deploy auf Staging. Sicherstellen dass `worker-import`-Service vorhanden ist (`worker-queues.md` Task muss durch sein).
|
||
3. MinIO auf Staging hochziehen (falls noch nicht):
|
||
```bash
|
||
docker run -d --name minio \
|
||
-p 9000:9000 -p 9001:9001 \
|
||
-e MINIO_ROOT_USER=admin \
|
||
-e MINIO_ROOT_PASSWORD=admin12345 \
|
||
minio/minio server /data --console-address ":9001"
|
||
```
|
||
4. Smoke-Tests:
|
||
```bash
|
||
# 1. Small export (CSV, 1k rows)
|
||
curl -X POST https://staging.../api/exports -d '{ "format": "csv", "table": "users" }' -H "Authorization: Bearer ..."
|
||
# poll job-status until success, download file, check row-count
|
||
|
||
# 2. Large stream export (CSV, 200k rows, Enterprise plan)
|
||
# → assert duration < 60s, file size > 0, memory peak < 200 MB im Worker (Grafana)
|
||
|
||
# 3. Plan-cap test (Free plan, 20k requested)
|
||
# → assert job fails with EXPORT_ROW_LIMIT_PLAN
|
||
```
|
||
5. Grafana-Dashboard prüfen: `export_jobs_total{status="success"}` zählt korrekt; `export_job_duration_seconds_bucket` zeigt Verteilung.
|
||
|
||
## Deviations from Plan
|
||
|
||
- **Plan-cap helper lives in `@toolctrl/exports/limits` instead of a separate `packages/billing`.** There is no `@toolctrl/billing` package today; placing the resolver alongside the streamers keeps the cap definitions and the per-format hard caps colocated, which is where the consumer (worker job + UI surface) already lives.
|
||
- **No metrics counter / no JSDoc deprecation pass on the non-streaming APIs.** The detail plan called for `export_jobs_total` Prometheus counters and a wide JSDoc `@deprecated` sweep. These two follow-ups are intentionally deferred: (a) metrics wiring requires a worker bootstrap touch that overlaps with #45/#39, (b) the deprecation pass is a one-line annotation we can ship in a small follow-up commit without blocking the streaming pipeline.
|
||
- **Worker job is a factory (`createExportJobRunner`) rather than a default-exported handler.** Keeps the unit tests deterministic without spinning up a real S3 / Prisma — the production wiring (resolveTenantPlan, rowSource, buildArtifactKey) is the operator's responsibility and lives outside the streaming pipeline.
|
||
- **AWS SDK versions pinned to 3.1045.0** (exact, not caret) on both `apps/worker` and `packages/exports` to avoid the `@smithy/types` v4.14.1↔v4.14.2 incompatibility that surfaces when `@toolctrl/storage` (`^3.958.0`) resolves to 1045 but the unconstrained caret in newer packages resolves to 1048.
|
||
|
||
## Progress Log
|
||
|
||
- 2026-05-17 — 10 atomic commits land the streaming export pipeline:
|
||
- `2a061a9d` CSV stream-writer with async-iterable row source + memory smoke test (100k rows < 100 MB).
|
||
- `a28fbb6d` JSON/NDJSON stream-writer with 10k pretty-mode cap and `ExportPrettyJsonTooLargeError`.
|
||
- `35712412` XLSX stream-writer choosing ExcelJS WorkbookWriter above 50k rows; 500k hard cap + dedicated error type.
|
||
- `9b5057e0` PDF `renderToStream` with 5k row hard cap (`ExportPdfRowLimitExceededError`).
|
||
- `f3e66865` S3 multipart upload sink (`@aws-sdk/lib-storage`, 8 MB parts, queueSize 4) returning `{ writeStream, completionPromise }`.
|
||
- `309e7177` Plan-based row cap helper (`resolveExportRowCap` / `assertExportRowCap`) covering free / pro / enterprise.
|
||
- `881219bb` Worker export-job factory `createExportJobRunner` wiring resolveTenantPlan → cap → rowSource → format streamer → S3 sink → shared-store progress + S3 SDK pin.
|
||
- `56a732b0` `GET /v1/exports/:exportJobId/progress` endpoint backed by the shared-store snapshot.
|
||
- `1ecbb9ad` `docs/ops/streaming-exports.md` runbook.
|
||
- (this commit) detail-md progress log + PROGRESS.md row update.
|
||
- 67 unit tests cover all four streamers, the multipart sink, the plan-cap matrix (3 plans × 4 formats), the worker job (4 scenarios incl. progress-flush) and the API progress reader. `pnpm --filter @toolctrl/exports test` + `apps/worker` + `apps/api` exports/progress test all green.
|
||
|
||
## Lessons Learned
|
||
|
||
(Optional am Task-Ende.)
|