Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,88 @@
|
||||
# Phase 02 — Observability
|
||||
|
||||
**Dauer:** 1-2 Wochen (Wall-Clock — Multi-Agent), ca. 13-17 Personentage Aufwand
|
||||
**Tasks:** 8
|
||||
**Ziel:** Self-hosted Sentry live, vollständige Sentry-Wiring (API/Worker/Web) inkl. CI-Release-Tagging, OpenTelemetry-Tracing, ESLint-erzwungene Pino-Logger statt `console.*` und ein Prometheus-/Grafana-Stack mit Infrastruktur- und Business-Metriken. Phase liefert die Sichtbarkeit, die für Phase 03 (Skalierung) zwingend ist.
|
||||
|
||||
## Warum diese Phase jetzt
|
||||
|
||||
- Phase 03 (Skalierungs-Refactoring) verändert Hot-Paths (SharedStore, PgBouncer, Read-Write-Split, Outbox). Ohne saubere Telemetry läuft jedes Refactoring blind — Regression-Detection ist nicht möglich.
|
||||
- Sentry-Release-Tagging muss **vor** den großen Refactorings stehen, damit jeder Phase-03-Commit später in Sentry-Release-Tracking auftaucht.
|
||||
- Logging-Migration (`console.*` → Pino) ist Voraussetzung, damit Sentry-Breadcrumbs und OTel-Logs nicht von PII-leaked `console.log`-Calls geflutet werden.
|
||||
- Self-hosted Sentry statt SaaS, weil das DSGVO-Profil und der vorhandene Hetzner-Server mit Coolify das problemlos hergeben — vermeidet US-Cloud-Datenfluss.
|
||||
|
||||
## Hetzner-Staging-Kontext
|
||||
|
||||
Es existiert bereits ein **Hetzner-Server mit Coolify-Deployment** (siehe `../AGENT-INSTRUCTIONS.md` §Regel 6 + `../archive/STAGING-ACCESS.md`). Sentry-Self-Host, Grafana und Prometheus laufen dort als zusätzliche Coolify-Stacks. Die Apps der Boilerplate (api/worker/web) werden über Coolify auf den gleichen Server deployed und reichen ihre Telemetry an die lokalen Sentry-/OTel-/Prom-Endpoints durch — kein Daten-Egress.
|
||||
|
||||
## Task-Reihenfolge
|
||||
|
||||
| Reihenfolge | Task-ID | Datei | Aufwand | Parallelisierbar mit |
|
||||
|---|---|---|---|---|
|
||||
| 1 | #29 | `sentry-selfhost-setup.md` | 3-4d | — (Infra-Voraussetzung für #30/#31/#32) |
|
||||
| 2 | #30 | `sentry-wiring-api-worker.md` | 1d | #31 (touchen unterschiedliche Apps) |
|
||||
| 3 | #31 | `sentry-wiring-web.md` | 1-1.5d | #30 |
|
||||
| 4 | #32 | `sentry-ci-integration.md` | 0.5d | — (braucht #30 + #31 fertig) |
|
||||
| 5 | #33 | `opentelemetry.md` | 2-3d | #34, #36 (unabhängige Files) |
|
||||
| 6 | #34 | `logging-migration.md` | 2.5-3.5d | #33, #36 |
|
||||
| 7 | #35 | `metrics-grafana.md` | 3-4d | #36 |
|
||||
| 8 | #36 | `performance-quickwins.md` | 1-2d | #33, #34, #35 |
|
||||
|
||||
## Dependency-Graph (intern)
|
||||
|
||||
```
|
||||
#29 sentry-selfhost ──► #30 wiring-api-worker ─┐
|
||||
└─► #31 wiring-web ────────┤
|
||||
▼
|
||||
#32 sentry-ci
|
||||
│
|
||||
▼
|
||||
┌────────────────────┼────────────────────┐
|
||||
▼ ▼ ▼
|
||||
#33 opentelemetry #34 logging-migration #35 metrics-grafana
|
||||
│ │ │
|
||||
└────────────────────┼────────────────────┘
|
||||
▼
|
||||
#36 performance-quickwins
|
||||
(parallel — nutzt #35 zum Messen)
|
||||
```
|
||||
|
||||
**Praktisch parallelisierbar (Multi-Agent-Setup):**
|
||||
|
||||
- Agent A fährt #29 (Infra/Compose) — 3-4 Tage Solo.
|
||||
- Sobald #29 grün: Agent B übernimmt #30, Agent C übernimmt #31 (parallel, unterschiedliche Apps).
|
||||
- Agent A schließt mit #32 ab.
|
||||
- Nach #32: Agent A startet #33, Agent B startet #34, Agent C startet #35, Agent D startet #36 — alle vier parallel möglich, da #36 nur Lese-Zugriff auf die Endpoints aus #35 braucht.
|
||||
|
||||
## Phase Done-Definition
|
||||
|
||||
Diese Phase ist `completed` wenn:
|
||||
|
||||
- [ ] Alle 8 Tasks `completed` in `PROGRESS.md`
|
||||
- [ ] `pnpm lint` (mit aktivierter `no-console`-Rule auf Server-Code), `pnpm typecheck`, `pnpm test` global grün
|
||||
- [ ] Self-hosted Sentry auf Staging-Hetzner erreichbar unter `https://sentry.<staging-domain>`, Login + Test-Event von api/worker/web sichtbar
|
||||
- [ ] Sentry-Release-Tag = `$GIT_SHA` für mindestens eine vollständige CI-Pipeline (GitHub Actions UND Gitea Actions) sichtbar
|
||||
- [ ] OTel-Traces aus api/worker erscheinen in Sentry-Performance UND einem optionalen Tempo-/Jaeger-Stack (falls deployed)
|
||||
- [ ] ESLint-`no-console`-Rule blockiert jeden neuen `console.*`-Call in `**/*.server.ts(x)`, `apps/api/src/**`, `apps/worker/src/**`, `packages/**/src/**` — Test via expliziter Verletzung
|
||||
- [ ] `/status` (public) und `/metrics` (token-protected) liefern in API + Worker valide Outputs, Prometheus scraped erfolgreich, mindestens das "Overview"-Grafana-Dashboard zeigt Live-Daten
|
||||
- [ ] Performance-Quickwins gemerged, Vorher/Nachher-Messungen in `docs/observability/performance-baseline.md` festgehalten
|
||||
- [ ] `.env.example` enthält neue Keys (`SENTRY_DSN`, `SENTRY_RELEASE`, `SENTRY_AUTH_TOKEN`, `SENTRY_TRACES_SAMPLE_RATE`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_TRACES_SAMPLER_ARG`, `METRICS_ENABLED`, `METRICS_TOKEN`)
|
||||
- [ ] `gsd-code-reviewer`-Subagent hat alle Phase-02-Commits reviewed; Findings adressiert
|
||||
- [ ] Phase-Summary in dieser README.md ergänzt
|
||||
|
||||
## Phase Summary
|
||||
|
||||
_(Wird nach Abschluss der Phase vom ausführenden Agent ergänzt.)_
|
||||
|
||||
### Lessons Learned
|
||||
|
||||
_(Wird nach Abschluss ergänzt.)_
|
||||
|
||||
## Verweise
|
||||
|
||||
- Detail-MD-Template: `../DETAIL-MD-TEMPLATE.md`
|
||||
- Agent-Workflow: `../AGENT-INSTRUCTIONS.md`
|
||||
- Execution-Order: `../00-execution-order.md`
|
||||
- Live-Status: `../PROGRESS.md`
|
||||
- Vorgänger-Phase: `../01-tech-debt-foundation/README.md`
|
||||
- Nachfolger-Phase: `../03-scaling-infrastructure/README.md`
|
||||
@@ -0,0 +1,398 @@
|
||||
# Phase 02 — Verification Report
|
||||
|
||||
**Reviewer:** Verifier-Subagent
|
||||
**Datum:** 2026-05-16
|
||||
**Scope:** README.md + 8 Detail-MDs (29 → 36) in `docs/improvement-plan/02-observability/`
|
||||
**Verdict:** **APPROVED WITH MINOR FIXES** — Plan ist ausführungsreif; einige Pfad-/Konsistenz-Fixes vor Phase-Start nötig (siehe §11).
|
||||
|
||||
---
|
||||
|
||||
## 1. Template-Konformität (15 Sections, korrekte Reihenfolge)
|
||||
|
||||
Pflicht-Reihenfolge laut `DETAIL-MD-TEMPLATE.md`:
|
||||
|
||||
1. Frontmatter (Status/Task-ID/Phase/Effort/Owner)
|
||||
2. Problem · 3. Depends on · 4. Blocks · 5. Approach · 6. Implementation Steps
|
||||
7. Test Requirements · 8. Acceptance Criteria · 9. Rollback Strategy · 10. Security Notes
|
||||
11. Subagent Recommendations · 12. Staging-Deployment-Steps · 13. Deviations from Plan
|
||||
14. Progress Log · 15. Lessons Learned (optional)
|
||||
|
||||
| Datei | 1-5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | OK? |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| `sentry-selfhost-setup.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `sentry-wiring-api-worker.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `sentry-wiring-web.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `sentry-ci-integration.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `opentelemetry.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `logging-migration.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `metrics-grafana.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
| `performance-quickwins.md` | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |
|
||||
|
||||
Alle 8 Files folgen der Pflicht-Reihenfolge. Keine fehlenden Sections, keine Reihenfolge-Verstöße.
|
||||
|
||||
---
|
||||
|
||||
## 2. Dependencies-Konsistenz (Depends on / Blocks vs. execution-order.md)
|
||||
|
||||
### 2.1 Phase-01-Verweise
|
||||
|
||||
Alle Detail-MDs verweisen auf `01-tech-debt-foundation/dep-updates.md`. Diese Datei **existiert** (verifiziert: `/docs/improvement-plan/01-tech-debt-foundation/dep-updates.md`). OK.
|
||||
|
||||
### 2.2 Intra-Phase-2-Graph (lt. README.md)
|
||||
|
||||
```
|
||||
#29 sentry-selfhost ──► #30 wiring-api-worker ─┐
|
||||
└─► #31 wiring-web ────────┤
|
||||
▼
|
||||
#32 sentry-ci
|
||||
│
|
||||
▼
|
||||
┌────────────────────┼────────────────────┐
|
||||
▼ ▼ ▼
|
||||
#33 opentelemetry #34 logging-migration #35 metrics-grafana
|
||||
│
|
||||
▼
|
||||
#36 performance-quickwins
|
||||
```
|
||||
|
||||
Cross-Check der Detail-MDs:
|
||||
|
||||
| Task | Depends on (declared) | Blocks (declared) | Konsistenz |
|
||||
|---|---|---|---|
|
||||
| #29 selfhost | `dep-updates` | #30, #31, #32, #33, scaling-*, authentik | OK |
|
||||
| #30 wiring-api-worker | #29, `dep-updates` | #32, #33, scaling-* | OK |
|
||||
| #31 wiring-web | #29, `dep-updates` | #32, capacitor | OK |
|
||||
| #32 sentry-ci | #29, #30, #31 | "Keine harten Blocks" | OK — konsistent mit "kein harter Block, aber Phase-03+ profitiert" |
|
||||
| #33 opentelemetry | #29, #30, #31 | #35 (kein harter Block) + scaling/read-write-split | **Abweichung**: README ordnet #33 hinter #32 ein, aber #33 deklariert keine Dependency auf #32. Das ist OK weil #32 nur Release-Tagging ist und keine Wiring-Voraussetzung für OTel — der README-Graph ist Workflow-Reihenfolge, nicht harte Dependency. Kein Fix nötig, aber **Hinweis** an ausführenden Agent: parallel zu #32 startbar wenn #30/#31 grün. |
|
||||
| #34 logging-migration | #30, #31 | "Keine harten Blocks" | OK |
|
||||
| #35 metrics-grafana | #30, #34 | shared-store-migration, plugin-system | OK |
|
||||
| #36 perf-quickwins | #35 | — | OK |
|
||||
|
||||
**Finding F-1 (Minor):** Cross-Phase-Block-Referenz in `#29.Blocks`: `09-authentik-admin-sso/authentik-setup.md` — beide existieren laut PROGRESS-Logik. Kein Issue, sondern Plus.
|
||||
|
||||
**Finding F-2 (Cosmetic):** `metrics-grafana.md` deklariert `#36` nicht explizit als blocked-by. Das passt zur Realität (perf-quickwins braucht metrics zum Messen, ist explizit als Depends-on in #36 deklariert).
|
||||
|
||||
---
|
||||
|
||||
## 3. Implementation-Steps-Qualität (Atomic-Commits, Tech-Korrektheit)
|
||||
|
||||
### 3.1 Atomic-Granularität
|
||||
|
||||
| Task | Anzahl Steps | Atomic? | Hinweis |
|
||||
|---|---|---|---|
|
||||
| #29 | 11 | OK | Step 7 (Backup-Container) ist groß aber legitim atomar; Step 11 ist Deployment (kein Commit) — sauber gekennzeichnet |
|
||||
| #30 | 11 | OK | jede Datei einzeln, Sanitize-Refactor vor Wiring (Test-First-Ordnung) |
|
||||
| #31 | 11 | OK | Step 1 (deps) vor Steps 2-11 — korrekt; Test-Route-Registration nur dev/staging — gut |
|
||||
| #32 | 6 | OK | Shell-Helper vor Workflow-YAML — korrekt; Step 6 ist reine Operations |
|
||||
| #33 | 13 | OK | Bootstrap-Module + Entry-Point-Anpassung pro Runtime jeweils 2 Commits — clean |
|
||||
| #34 | 17 | OK | High-PII einzeln (5 Commits), Bulks in 3-Commit-Buckets — sicherer Ansatz |
|
||||
| #35 | 18 | OK | Foundation (Packages) zuerst, dann pro Runtime, dann Business-Hooks, dann Infra |
|
||||
| #36 | 9 (8 Items + Wrap-up) | OK | jeder Item-Fix ein Commit, sauber separierbar |
|
||||
|
||||
### 3.2 Tech-Korrektheit Cross-Check
|
||||
|
||||
**React-Router-v7-Korrektheit (#31, #33):**
|
||||
|
||||
- `apps/web/app/entry.client.tsx`, `entry.server.tsx`, `root.tsx` — Pfade verifiziert (existieren). OK.
|
||||
- `ErrorBoundary` in `root.tsx` mit `useEffect(() => Sentry.captureException(error), [error])` — korrekt; aber **Hinweis**: bei SSR-Errors ist React-Router-v7 die Convention, dass die Server-Integration via `requestDataIntegration` automatisch captures. Manueller `useEffect`-Capture ist sinnvoll als Client-Side-Backup. OK.
|
||||
- Step 7 (#31): "Falls `@sentry/react-router` v8 verfügbar" — pragmatischer Decision-Punkt, gut dokumentiert. OK.
|
||||
- **Finding F-3 (Minor)**: `#33` Step 9 importiert `import './otel.server'` (mit `.server`-Suffix), aber die Datei wird in Step 9 als `apps/web/app/lib/otel/server.ts` angelegt — Pfad-Inkonsistenz. **Fix vor Implementation**: entweder Import-Pfad als `./lib/otel/server` korrigieren oder Datei als `entry.server.otel.ts` benennen. Kleiner Schönheitsfehler in Step-Beschreibung.
|
||||
|
||||
**Hono-Korrektheit (#30, #35):**
|
||||
|
||||
- `apps/api/src/app.ts:86` ruft `createErrorHandler({...})` — **verifiziert** (`app.onError(createErrorHandler())` an Z. 86). OK.
|
||||
- Hono-Tracing-Middleware-Approach (Step 5) — korrekt, da Sentry kein offizielles Hono-Integrationspaket hat. `c.req.routePath` für Route-Pattern (#35 Lessons Learned erwähnt) — korrekt.
|
||||
|
||||
**BullMQ-Korrektheit (#30):**
|
||||
|
||||
- Step 9 erwähnt `Sentry.bunIntegration` als BullMQ-Integration — **das ist falsch**. `bunIntegration` ist die Bun-Runtime-Integration, **nicht** BullMQ. Sentry v8 hat keine offizielle BullMQ-Integration (Stand 2026-05). Der Step relativiert das mit "oder manuelle BullMQ-Hooks falls nicht offiziell" — der manuelle Wrapper-Approach in Step 9 ist der richtige Weg.
|
||||
- **Finding F-4 (Minor)**: Falsche API-Namens-Referenz `Sentry.bunIntegration` muss raus oder als "Platzhalter, prüfen ob `bullMQIntegration` existiert; sonst manueller Wrapper" gekennzeichnet werden. **Empfehlung**: Step 9 vor Implementation um `Explore`-Subagent-Hinweis ergänzen: "Prüfe `@sentry/node` v8.x changelog auf BullMQ-Integration; falls nicht vorhanden, manuellen Wrapper aus diesem Step nutzen".
|
||||
|
||||
**Sentry-SDK-Korrektheit (#30, #31):**
|
||||
|
||||
- `httpIntegration`, `prismaIntegration({ client: prisma })`, `requestDataIntegration({ include: { ip: false, ... } })` — alle gültige Sentry-v8-Integrations. OK.
|
||||
- `replayIntegration({ maskAllText: false, maskAllInputs: true })` — gültig. OK.
|
||||
- `browserTracingIntegration()` — gültig. OK.
|
||||
|
||||
**Prisma-Korrektheit (#33):**
|
||||
|
||||
- Step 2 PII-Scrubber: `db.statement` Param-Bindings strippen — Prisma's OTel-Integration setzt `db.statement` ohne Param-Values (Default), aber defense-in-depth-Scrubbing ist korrekt.
|
||||
|
||||
---
|
||||
|
||||
## 4. Test-Requirements-Verifizierbarkeit
|
||||
|
||||
| Task | Unit | Integration | E2E | Coverage-Target | Verifizierbar? |
|
||||
|---|---|---|---|---|---|
|
||||
| #29 | N/A (Infra) | smoke.sh | manual staging | N/A | OK |
|
||||
| #30 | sanitize, sentry-bootstrap, hono-mw, runtime | In-Memory-Sentry-Transport | manual staging | ≥90%/≥80% | OK |
|
||||
| #31 | sentry-client/server, routeTracing | SSR-render | Playwright `/__test/client-throw` | ≥80% | OK |
|
||||
| #32 | sentry-release.sh (bats) | test-workflow `workflow_dispatch` | manual CI-run | N/A | OK |
|
||||
| #33 | pii-span-processor, otel-bootstrap | mock-OTLP-endpoint | manual E2E-trace 4-spans | ≥85%/≥70% | OK |
|
||||
| #34 | PII-mock-tests pro Service, eslint-rule-test | pre-commit-hook | staging-log-inspection | N/A (Migration) | OK |
|
||||
| #35 | registry/auth/middleware/scheduler | in-process API | prom-targets + grafana-live | ≥80%/≥70% | OK |
|
||||
| #36 | pro Item-Fix | regression (existing) | oha-load-test | nicht senken | OK |
|
||||
|
||||
**Spezifisch zu den User-Fragen:**
|
||||
|
||||
- **Sentry-Tests verifizierbar?** Ja — In-Memory-Transport (#30 Test-Reqs erwähnt `@sentry/core` testkit explizit) plus Staging-Smoke. Korrekt.
|
||||
- **OTel-Spans testen?** Ja — Mock-OTLP-Endpoint in Vitest-Suite (#33 Test-Reqs) + End-to-End-Trace-Verifikation auf Staging (Trace-ID-Korrelation über 4 Services). Korrekt.
|
||||
- **Pino-Redaction testen?** Ja — `webLogger`-Mock-Spy mit `assertNotCalled` für PII-Keys (#34 Test-Reqs). Korrekt. **Zusatz-Hinweis**: ESLint-Rule selbst wird mit synthetischem Source-File + ESLint-API getestet — sauber.
|
||||
|
||||
**Finding F-5 (Minor)**: `#34` definiert keine konkrete Coverage-%-Zahl ("keine harte %-Zahl") — das ist akzeptabel für eine Migration-Task, aber die "Pflicht: Tests für die 5 High-PII-Services" ist eine implizite Coverage-Zusage und sollte als hartes Akzeptanz-Item bleiben (ist es bereits in Acceptance Criteria). OK.
|
||||
|
||||
---
|
||||
|
||||
## 5. Acceptance-Criteria-Verifizierbarkeit
|
||||
|
||||
Alle 8 Files haben Acceptance-Criteria mit:
|
||||
|
||||
- Konkreten Datei-Existenz-Checks (`infra/sentry/...`, `packages/metrics/...`)
|
||||
- Endpoint-Behaviors (`/status` → 200/503, `/metrics` → 401/200)
|
||||
- Staging-Verifikation (Test-Event in Sentry-UI, Trace mit N Spans, Dashboard-Live-Daten)
|
||||
- Lint+Typecheck+Test-Gates
|
||||
|
||||
**Objektiv prüfbar:** Ja. Alle Criteria sind entweder Datei-Existenz, Endpoint-Response, Lint-Output oder UI-Sichtbarkeit. Kein "schöner Code"-Subjektiv-Kriterium.
|
||||
|
||||
**Finding F-6 (Minor)**: `#35` AC "Cardinality-Schutz aktiv (tenant_id-Bucketing dokumentiert)" ist etwas weich. Schärfer wäre: "Prom-Query `count by (__name__)({__name__=~\"ai_.*\"})` liefert < 1000 Series auf Staging". Aber als Doku-Anforderung mit Verweis auf Approach-Section-Decision-Punkt (top-50 + other ab 1000 tenants) noch akzeptabel.
|
||||
|
||||
---
|
||||
|
||||
## 6. Staging-Deployment-Steps (Sentry-Selfhost auf Hetzner+Coolify)
|
||||
|
||||
### 6.1 Sizing-Empfehlungen — vorhanden?
|
||||
|
||||
**Ja, in #29 Approach-Section:**
|
||||
- "16 GB RAM empfohlen (12 GB hartes Minimum, Clickhouse + Kafka sind RAM-hungrig)"
|
||||
- "4 vCPU empfohlen"
|
||||
- "~50 GB Disk für 90 Tage Event-Retention"
|
||||
- "~10 Container" mit Liste
|
||||
|
||||
**Plus GlitchTip-Alternative** für 8-GB-Server in `sentry-glitchtip-alternative.md` dokumentiert (Step 10).
|
||||
|
||||
OK.
|
||||
|
||||
### 6.2 Backup-Restore-Drills — vorhanden?
|
||||
|
||||
**Backup-Steps** vorhanden (#29 Step 7: täglicher Cron-Container, postgres-dump + clickhouse-snapshot → S3, `SENTRY_SECRET_KEY` notieren).
|
||||
|
||||
**Restore-Drill**: AC enthält "`docs/observability/sentry-selfhost.md` enthält: Deploy-Schritte, Update-Strategie, **Backup/Restore-Drill**, Hardening-Checkliste, Ressourcen-Anforderungen". Step 8 dokumentiert Updates aber nicht explizit Restore.
|
||||
|
||||
**Finding F-7 (Minor — actionable)**: Im Implementation-Step 8 oder neuem Step 8a sollte ein expliziter Punkt "Restore-Drill dokumentieren + auf Staging einmalig durchspielen" stehen. Aktuell ist es nur in AC erwähnt, ohne Implementation-Step. **Fix**: Step 8 erweitern um Bullet "Restore-Drill: Postgres-Dump auf parallelem Compose-Stack importieren, Clickhouse-Snapshot wiederherstellen, Login + 1 Test-Issue prüfen — Verfahren in Doku-File ergänzen".
|
||||
|
||||
### 6.3 Vollständigkeit Coolify-Deployment
|
||||
|
||||
Step-by-Step für Coolify-UI-Anlegen (#29 Staging-Deployment Step 2) ist konkret: Repo, Compose-Path, Domain, Env-Vars aus Vault. OK.
|
||||
|
||||
`install.sh`-Wrapper läuft beim ersten Deployment automatisch → Admin-User-Setup. OK.
|
||||
|
||||
Smoke-Tests sind konkret mit `sentry shell -c "..."`, `sentry-cli send-event`, `curl OTLP-Endpoint` — verifizierbar.
|
||||
|
||||
OK.
|
||||
|
||||
---
|
||||
|
||||
## 7. Konsistenz mit User-Wünschen
|
||||
|
||||
### 7.1 "Sentry Selfhost und alles einbinden" — alle 3 Runtimes abgedeckt?
|
||||
|
||||
| Runtime | Init-Modul | Reporter | Tracing | E2E-Verifikation |
|
||||
|---|---|---|---|---|
|
||||
| `apps/api` | `apps/api/src/sentry.ts` (#30 Step 3) | `apiErrorReporter` (Step 4) | Hono-MW (Step 5-6) + Prisma-Auto | Smoke #30 Step 5 |
|
||||
| `apps/worker` | `apps/worker/src/sentry.ts` (#30 Step 7) | `workerErrorReporter` (Step 8) | BullMQ-Wrapper (Step 9) + Prisma-Auto | Smoke #30 Step 5 |
|
||||
| `apps/web` (client) | `apps/web/app/sentry.client.ts` (#31 Step 2) | n/a (Sentry-API direkt) | Browser-Tracing + Route-Tracing (Step 7) | Playwright + manual |
|
||||
| `apps/web` (SSR) | `apps/web/app/sentry.server.ts` (#31 Step 4) | `webErrorReporter` (Step 4) | requestDataIntegration | Manual SSR-throw |
|
||||
|
||||
**Verdict**: Alle 3 Runtimes (4 Wiring-Punkte) abgedeckt. OK.
|
||||
|
||||
### 7.2 "Full Auto-Instrumentation mit Sentry-OTLP-Backend" — korrekt?
|
||||
|
||||
- `@opentelemetry/auto-instrumentations-node` als Meta-Package (HTTP/fetch/Prisma/BullMQ/Redis/fs/dns/net) — **korrekt** für Full-Auto-Instrumentation (#33 Step 1).
|
||||
- `fs`-Instrumentation explizit disabled (Step 3: "`'@opentelemetry/instrumentation-fs': { enabled: false }` /* zu noisy */") — sinnvoller Default.
|
||||
- **Sentry-Relay als OTLP-Ingestor**: konfiguriert in `infra/sentry/relay/config.yml` mit `relay.ingest.otlp.enabled: true, max_payload_size: 5MiB` (#33 Step 10).
|
||||
- Cross-Verifikation mit `#29 Step 6`: "OTLP-Ingest aktivieren — `relay/config.yml` so anpassen, dass Relay einen OTLP-HTTP-Endpoint (`/api/{project}/integration/otlp/v1/traces`) annimmt" — konsistent. OK. Update 2026-05-18: Sentry-Relay 25.x bietet OTLP-Ingest bereits out-of-the-box auf dem `/integration/otlp/`-Pfad an (keine config-Anpassung nötig); B-005 war ein Pfad-Mismatch, kein Relay-Bug.
|
||||
|
||||
**Finding F-8 (Minor — Verifikations-Hinweis)**: Sentry-Relay OTLP-Ingest ist **Beta-Feature** (Stand Anfang 2026). Der Explore-Subagent-Hinweis im Subagent Recommendations (#33: "Sentry-Relay OTLP-Ingest-Config Stand 2026-05, gibt es Rate-Limits") greift das auf — gut. Empfehlung: Vor Implementation **Decision-Punkt** dokumentieren: "Falls OTLP-Ingest in v25.x noch nicht stabil → Fallback auf Jaeger/Tempo (Doku in `docs/observability/otel.md` als Alt-Exporter bereits vorgesehen)".
|
||||
|
||||
### 7.3 "no-console: error für alle server-side Code" — Erstphase Migration + Zweitphase ESLint klar getrennt?
|
||||
|
||||
`#34` ist explizit in **zwei Phasen** geteilt:
|
||||
- Phase 1 — Aufräumen (manuelle Migration) — Steps 1-13
|
||||
- Phase 2 — Enforce (ESLint-Rule) — Steps 14-17
|
||||
|
||||
Reihenfolge ist korrekt: erst migrieren, dann Rule aktivieren (sonst würde Rule den eigenen Migration-Commit blocken). OK.
|
||||
|
||||
Override-Strategie:
|
||||
- Server-Code (`**/*.server.ts(x)`, `apps/api/src/**`, `apps/worker/src/**`, `packages/**/src/**`) → `error`
|
||||
- Test-Files → `off`
|
||||
- Client-Bundle (`apps/web/app/components/**`, `apps/web/app/routes/**` ohne `.server.`) → `off` (Browser-Konsole legitim)
|
||||
|
||||
OK.
|
||||
|
||||
**Finding F-9 (Pfad-Korrektur)**: Die im #34 erwähnten **High-PII-Files-Pfade sind teilweise falsch:**
|
||||
|
||||
| In Detail-MD | Tatsächlicher Pfad im Repo |
|
||||
|---|---|
|
||||
| `apps/web/app/utils/services/.server/authService.ts:99` | `apps/web/app/utils/services/authService.ts` (kein `.server`-Subdir, **0 console-Calls** beim Stichproben-grep) |
|
||||
| `apps/web/app/utils/services/.server/EmailService.ts:29` | `apps/web/app/modules/emails/services/EmailService.ts` (Pfad in `modules/emails/`, console-Call bestätigt: `EmailService.ts:29` + `:44`) |
|
||||
| `apps/web/app/utils/services/.server/CrmService.ts:433/445` | `apps/web/app/modules/crm/services/CrmService.ts` (Pfad in `modules/crm/`, console-Calls bestätigt: `:393`, `:421`, `:437`, `:449`, `:571-604`) |
|
||||
| `apps/web/app/utils/services/.server/PromptBuilderService.ts:185/256` | `apps/web/app/modules/promptBuilder/services/.server/PromptBuilderService.ts` (Pfad in `modules/promptBuilder/services/.server/`, console-Calls bestätigt) |
|
||||
| `apps/web/app/utils/services/.server/SeedService.ts:199-217` | `apps/web/app/utils/db/seed/SeedService.ts` (Pfad in `utils/db/seed/`, nicht in `services/.server/`) |
|
||||
|
||||
**Fix vor Implementation**: Detail-MD Step 2-6 mit korrekten Pfaden updaten. Sonst greift ein Subagent ins Leere. Konkret: Inventar-Script aus Step 1 zuerst laufen lassen, das wird die Pfade automatisch korrigieren — Empfehlung an ausführenden Agent: **Step 1 strikt vor Step 2 fertigstellen** und Inventar als Source-of-Truth für die Reihenfolge nehmen (nicht die hier vorgeschlagenen statischen Pfade).
|
||||
|
||||
### 7.4 "/status + Prometheus + Grafana mit Business-Metriken" — Business-Metrics abgedeckt?
|
||||
|
||||
Final-Liste in #35 Approach-Section "Business":
|
||||
|
||||
- `active_tenants` ✓
|
||||
- `active_users_24h` ✓
|
||||
- `ai_tokens_consumed_total{provider, model, tenant_id}` ✓ (mit Cardinality-Bucketing-Decision)
|
||||
- `stripe_webhook_events_total{event_type, status}` ✓
|
||||
- `mail_sent_total{provider, status}` ✓
|
||||
- `webhook_delivery_attempts_total{status}` ✓
|
||||
- `csrf_token_rotation_total` ✓
|
||||
- `subscription_active{plan_id}` ✓
|
||||
|
||||
User-Wunsch explizit gefordert: `active_tenants`, `ai_tokens`, `stripe_webhook_events` — **alle drei abgedeckt** + zusätzlich Mail, Webhook-Delivery, CSRF-Rotation, Subscriptions. OK.
|
||||
|
||||
Instrumentierung als Implementation-Steps separiert (Step 10 AI-Cost, Step 11 Stripe, Step 12 Mail, Step 13 Webhook-Delivery) mit je einem atomic Commit. OK.
|
||||
|
||||
5 Grafana-Dashboards (Overview, API-Latency, Queue-Health, Business-KPI, AI-Cost-per-Tenant) — sinnvolle Aufteilung, deckt User-Wunsch ab.
|
||||
|
||||
OK.
|
||||
|
||||
---
|
||||
|
||||
## 8. Performance-Quickwins — Alle 8 Items mit file:line?
|
||||
|
||||
| # | Item | Datei | Line | Datei existiert? |
|
||||
|---|---|---|---|---|
|
||||
| 1 | N+1 Users-Admin | `apps/web/app/routes/admin/accounts/users.tsx` | 119-129 | ✓ existiert |
|
||||
| 2 | currentTenant Doppel-Fetch | `apps/web/app/utils/data/.server/rootData.ts` | 30 | ✓ existiert |
|
||||
| 3 | Storage Signed-URL-Cache | `apps/api/src/storage.ts` | 56-80, 82-131 | ✓ existiert |
|
||||
| 4 | clearSubscriptionsCache Thrash | `apps/web/app/utils/services/.server/subscriptionService.ts` | 543-548 | ✓ existiert |
|
||||
| 5 | CSRF Body-Clone | `apps/web/app/utils/session.server.ts` | 230-268 | ✓ existiert |
|
||||
| 6 | Recovery-Code Rejection-Sampling | `apps/web/app/utils/auth/mfa/recovery-codes.server.ts` | 80-83 | ✓ existiert |
|
||||
| 7 | UUID-Collision-Check | `apps/api/src/auth/session/session-store.ts` | 47-61 | ✓ existiert |
|
||||
| 8 | CSRF-Token 100 → 32 Bytes | `apps/web/app/utils/session.server.ts` | 212-219 | ✓ existiert |
|
||||
|
||||
Alle 8 Items mit konkretem file:line + Problem-Description + Fix-Approach + Tests. Item 8 hat zusätzlich Rollback-Warnung (bestehende Sessions mit 100-Byte-Token) und Migration-Hinweis (beide Längen akzeptieren bis TTL ablauf). **Sehr gründlich.** OK.
|
||||
|
||||
**Finding F-10 (Optional)**: Item 8 könnte vor Implementation in eigenen Folge-Task ausgegliedert werden (siehe Item-8-Subagent-Hinweis), falls Session-TTL > 24h ist. Die Detail-MD adressiert das bereits in Rollback-Strategy + Subagent-Plan-Hinweis. OK.
|
||||
|
||||
---
|
||||
|
||||
## 9. Phase-Reihenfolge (intern)
|
||||
|
||||
- **#29 Sentry-Setup zuerst** ✓ (Voraussetzung für DSNs)
|
||||
- **#30 / #31 parallel danach** ✓ (unterschiedliche Apps, kein File-Konflikt)
|
||||
- **#32 nach #30+#31** ✓ (CI-Release-Tagging braucht Wiring)
|
||||
- **#33 OTel "später"** ✓ (kann theoretisch parallel zu #34/#35, README ordnet sie parallel ein — OK weil #33 keinen #32-Block deklariert; OTel-Backend = Sentry-Relay aus #29, also nur #29 ist harte Voraussetzung)
|
||||
- **#34 logging-migration** parallel zu #33/#35 ✓
|
||||
- **#35 metrics-grafana** parallel zu #33/#34 ✓
|
||||
- **#36 perf-quickwins** zuletzt ✓ (braucht #35 zum Messen)
|
||||
|
||||
**OTel nutzt Sentry-Relay als Backend** — bestätigt:
|
||||
- #29 Step 6 aktiviert OTLP-Ingest in Relay
|
||||
- #33 Step 10 verifiziert Relay-Config (idempotent zu #29 Step 6 — saubere Defense-in-Depth)
|
||||
- #33 Default-Exporter zielt auf `https://sentry.<domain>/api/<project_id>/otlp`
|
||||
|
||||
Reihenfolge ist korrekt. OK.
|
||||
|
||||
---
|
||||
|
||||
## 10. Fehlende Aspekte (Critical Gaps)
|
||||
|
||||
### 10.1 Geprüft — vorhanden ✓
|
||||
|
||||
- DSGVO/PII-Schutz (in #30 beforeSend, #31 Replay-Masking, #33 PII-Span-Processor, #34 Pino-Redaction)
|
||||
- Rollback-Strategie pro Task
|
||||
- Security Notes pro Task
|
||||
- Cardinality-Schutz (#35)
|
||||
- Self-Host vs SaaS-Entscheidung dokumentiert + Alternative (GlitchTip)
|
||||
- TLS via Coolify-Traefik
|
||||
- 2FA für Sentry-Admin
|
||||
- Secret-Rotation (CI-Token, METRICS_TOKEN)
|
||||
- Token-minimal-Scope (`project:releases`)
|
||||
- Source-Maps werden gelöscht nach Upload (`filesToDeleteAfterUpload`)
|
||||
- Sample-Rates env-konfigurierbar
|
||||
- No-Op-Verhalten ohne DSN/Endpoint/Token
|
||||
|
||||
### 10.2 Fehlend / Verbesserungswürdig
|
||||
|
||||
**Finding F-11 (Minor — Suggestion)**: **Alerting** ist nicht thematisiert. Phase 02 baut Metriken + Sentry, aber **wer wird benachrichtigt** wenn `queue_jobs_failed_total` spike oder `stripe_webhook_events_total{status="failed"}` > threshold? Empfehlung:
|
||||
- In `#35 metrics-grafana.md` Acceptance-Criteria ergänzen: "Mindestens 1 Grafana-Alert-Rule definiert (z.B. `up == 0 for 2m` für API/Worker/Web) mit Notification-Channel (Email oder Webhook)".
|
||||
- Optional: Sentry-Alerts (Issue-Frequency-Threshold) in `#29` oder `#30` AC ergänzen.
|
||||
|
||||
**Finding F-12 (Minor — Suggestion)**: **Log-Aggregation** (Loki o.ä.) ist nicht eingeplant. Pino schreibt JSON in stdout, Coolify aggregiert in Container-Logs — aber kein zentraler queryable Store. Phase-02 erwähnt es nur am Rand ("Loki/Grafana"). Für 10/10-Boilerplate wäre `infra/loki/` mit Promtail-Sidecar sinnvoll. **Empfehlung**: Entweder in Phase 02 hinzufügen (eigener `loki-stack.md`-Task) oder in `11-backlog/` aufnehmen mit Begründung "Pino-JSON in Coolify-Container-Logs reicht für MVP".
|
||||
|
||||
**Finding F-13 (Minor — Suggestion)**: **Sentry-Sentry-Heartbeat / Dead-Man-Switch** für den Sentry-Self-Host selbst nicht behandelt. Wenn Sentry down ist, weiß niemand davon. Empfehlung in `#29` AC ergänzen: "Externer Uptime-Check (z.B. UptimeKuma in separatem Stack) prüft `https://sentry.<domain>/_health/` alle 5 Min, alarmiert via Email bei Down".
|
||||
|
||||
**Finding F-14 (Cosmetic)**: Web-Side `OTel`-Bootstrap in `#33` Steps 7-9 erwähnt Browser+SSR getrennt, was korrekt ist, aber das Service-Naming-Schema sollte sauberer differenziert sein: `boilerplate-web-client` vs `boilerplate-web-ssr`. Aktuell beide unter `boilerplate-web` → in Traces nicht unterscheidbar. **Empfehlung**: Resource-Attribute-Liste in Approach-Section anpassen oder in Step 7/9 explizit dokumentieren.
|
||||
|
||||
**Finding F-15 (Nice-to-have)**: **Synthetic-Monitoring** (z.B. ein Worker-Job alle 5 Min, der einen End-to-End-Flow simuliert und Metriken/Traces emittiert) wird nicht explizit besprochen. Wäre die natürliche Erweiterung von `#36` aber out-of-scope für Phase 02. OK to defer.
|
||||
|
||||
---
|
||||
|
||||
## 11. Findings — Zusammenfassung & Priorität
|
||||
|
||||
### Must-fix vor Implementation (3 Items)
|
||||
|
||||
1. **F-3** — `#33` Step 9: Import-Pfad `./otel.server` vs Dateipfad `lib/otel/server.ts` konsistent machen.
|
||||
2. **F-4** — `#30` Step 9: Falsche Sentry-API-Referenz `Sentry.bunIntegration` für BullMQ entfernen; durch "manueller Wrapper (Default-Approach in diesem Step)" ersetzen.
|
||||
3. **F-9** — `#34` Steps 2-6: Pfade der 5 High-PII-Services korrigieren ODER explizit "Pfade sind Beispiele; Inventar aus Step 1 als Source-of-Truth nehmen" hinzufügen.
|
||||
|
||||
### Should-fix (3 Items)
|
||||
|
||||
4. **F-7** — `#29` Step 8: Restore-Drill als expliziten Implementation-Step ergänzen (nicht nur AC).
|
||||
5. **F-8** — `#33`: OTLP-Ingest-Beta-Status erwähnen + Fallback-Pfad zu Tempo/Jaeger dokumentieren (ist in Doku-Plan, aber als Decision-Punkt im Approach gut sichtbar machen).
|
||||
6. **F-14** — `#33`: Web-Service-Naming `boilerplate-web-client` vs `boilerplate-web-ssr` differenzieren.
|
||||
|
||||
### Nice-to-have (4 Items)
|
||||
|
||||
7. **F-11** — `#35` AC: Mindestens 1 Grafana-Alert-Rule + Notification-Channel.
|
||||
8. **F-12** — Loki/Promtail-Sidecar als Phase-02-Erweiterung oder in `11-backlog/`.
|
||||
9. **F-13** — `#29` AC: Externer Uptime-Check für Sentry-Self-Host.
|
||||
10. **F-15** — Synthetic-Monitoring als zukünftige Erweiterung dokumentieren.
|
||||
|
||||
### Reine Beobachtungen (keine Fixes nötig)
|
||||
|
||||
- **F-1**: Cross-Phase-Block `#29 → 09-authentik-setup` korrekt deklariert.
|
||||
- **F-2**: `#35` bzgl. `#36` Symmetrie OK (Depends-on auf #36-Seite reicht).
|
||||
- **F-5**: `#34` Coverage-Strategie OK (Migration-Task).
|
||||
- **F-6**: `#35` Cardinality-AC etwas weich aber akzeptabel.
|
||||
- **F-10**: `#36` Item 8 Risiko bereits in Rollback adressiert.
|
||||
|
||||
---
|
||||
|
||||
## 12. Quantitative Gesamt-Bewertung
|
||||
|
||||
| Dimension | Score (0-10) | Begründung |
|
||||
|---|---|---|
|
||||
| Template-Konformität | 10 | Alle 8 Files folgen Pflicht-Reihenfolge |
|
||||
| Dependency-Korrektheit | 9.5 | Sauber deklariert, Cross-Phase-Refs gültig |
|
||||
| Atomic-Commits-Eignung | 9 | Steps sind sauber separierbar, einige Bulk-Migrationen pragmatisch zusammengefasst |
|
||||
| Tech-Korrektheit | 8.5 | -1.5 für F-3, F-4 (kleine API-Referenzen) |
|
||||
| Test-Verifizierbarkeit | 9.5 | In-Memory-Transports + Staging-Smoke konkret |
|
||||
| AC-Objektivität | 9 | Wenige weiche Items (Cardinality-Schutz) |
|
||||
| Staging-Coverage | 9 | -1 für fehlenden Restore-Drill-Step (F-7) |
|
||||
| User-Wunsch-Abdeckung | 9.5 | Alles drin; -0.5 für Pfad-Inkonsistenz F-9 |
|
||||
| Performance-Quickwins-Konkretheit | 10 | Alle 8 file:line verifiziert, alle Dateien existieren |
|
||||
| Phase-Reihenfolge-Sauberkeit | 10 | Saubere Topologie, parallelisierbar gut markiert |
|
||||
| Security-Notes-Tiefe | 10 | PII, Token-Scopes, Cardinality, Allowlists durchgängig |
|
||||
| **Gesamtscore** | **9.3 / 10** | **Ausführungsreif nach 3 Must-fixes** |
|
||||
|
||||
---
|
||||
|
||||
## 13. Empfehlung
|
||||
|
||||
**APPROVED FOR EXECUTION** nach Adressierung der 3 Must-fixes (F-3, F-4, F-9). Die 3 Should-fixes können während Implementation adressiert werden (im jeweiligen Step-Subagent-Brief erwähnt). Nice-to-haves sind echte Verbesserungen — wenn Zeit, in Phase 02 mitnehmen, sonst in `11-backlog/` aufnehmen.
|
||||
|
||||
**Konkrete nächste Schritte für ausführenden Agent:**
|
||||
|
||||
1. Vor Phase-02-Start die 3 Must-fixes als kleinen Doku-Commit auf `agent/phase-02-prep` einarbeiten (5-Minuten-Edit auf den Detail-MDs).
|
||||
2. `#29` als Solo-Agent-Run starten (3-4d), parallel kann ein anderer Agent bereits `#34`-Inventar-Script (Step 1) bauen — das ist Pre-Migration-Vorbereitung ohne Wiring-Dependency.
|
||||
3. Nach `#29` grün: `#30` + `#31` parallel zwei Agents.
|
||||
4. Nach `#30`+`#31` grün: `#32` (Solo) + `#33`/`#34`/`#35` parallel drei Agents starten.
|
||||
5. Zuletzt `#36` mit `#35`-Baseline.
|
||||
@@ -0,0 +1,263 @@
|
||||
# Logging-Migration — `console.*` zu Pino + ESLint-Enforcement
|
||||
|
||||
**Status:** completed
|
||||
**Task-ID:** #34
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 2.5-3.5 Tage (2-3d Migration + 0.5d Rule)
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Die Codebase nutzt an ~200 Stellen direktes `console.log` / `console.error` / `console.warn` / `console.info`, vor allem in `apps/web/app/**/*.server.ts(x)`. Probleme:
|
||||
|
||||
- **PII-Leaks:** Funktionen wie `authService.ts:99`, `EmailService.ts:29`, `CrmService.ts:433/445`, `PromptBuilderService.ts:185/256`, `SeedService.ts:199-217` printen Email-Adressen, Tenant-IDs, AI-Prompts (mit User-Content), Stripe-Customer-IDs ungefiltert
|
||||
- **Kein Structured-Logging:** Container-Log-Aggregation (Loki, Grafana, Sentry-Breadcrumbs) kann nicht filtern/queryen, weil keine konsistenten Felder
|
||||
- **Keine Log-Level:** alles ist `console.log` egal ob Info/Warn/Error → kein Severity-Filtering im Production
|
||||
- **Sentry-Breadcrumbs-Flood:** Sentry-SDK fängt `console.*` als Breadcrumbs ab → bei 50 `console.log` pro Request landen 50 Breadcrumb-Einträge in jedem Error → 100KB-Issues
|
||||
- **Kein Tenant/Request-Context** automatisch dabei
|
||||
|
||||
Wir haben bereits einen sauberen Pino-Logger:
|
||||
- `apps/web/app/logger.server.ts:6` → `webLogger`
|
||||
- `apps/api/src/logger.ts` → `apiLogger`
|
||||
- `apps/worker/src/logger.ts` → `workerLogger`
|
||||
- `packages/logger/` → Basis-Pino-Setup mit Pretty-Print in Dev, JSON in Prod
|
||||
|
||||
→ Migration + Lint-Rule, sodass kein `console.*` mehr in Server-Code drift.
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-wiring-api-worker.md` — Sentry-Breadcrumb-Capturing soll nicht von `console.*`-Wildwuchs überrannt werden, sondern von strukturiertem Logger-Output
|
||||
- `02-observability/sentry-wiring-web.md` — gleiche Begründung für SSR-Logs
|
||||
|
||||
## Blocks
|
||||
|
||||
- Keine harten Blocks. Aber alle Phase-03+ Refactorings profitieren stark: strukturierte Logs lassen sich in Loki/Grafana korrelieren mit OTel-Traces (`trace_id` als Log-Field).
|
||||
|
||||
## Approach
|
||||
|
||||
**Zwei Phasen:**
|
||||
|
||||
### Phase 1 — Aufräumen (manuelle Migration)
|
||||
|
||||
Manuelle Migration aller `console.*`-Calls in Server-Code auf den jeweils paketlokalen Logger. **Manuell, nicht automatisch**, weil:
|
||||
|
||||
- Pino-Argument-Order ist umgekehrt: `console.log(msg, obj)` → `logger.info(obj, msg)`. Codemod wäre fehleranfällig.
|
||||
- Wir nutzen die Gelegenheit, PII zu redacten ODER ganz wegzulassen.
|
||||
- Log-Level pro Call-Site neu bewerten (`console.log` ist oft eigentlich Debug, manchmal Warn).
|
||||
|
||||
Reihenfolge nach PII-Risiko:
|
||||
|
||||
1. **High-PII first** (priorisiert, einer pro Commit):
|
||||
- `apps/web/app/utils/services/.server/authService.ts:99` — Login/Logout-Flow, hat Email + Session-Token
|
||||
- `apps/web/app/utils/services/.server/EmailService.ts:29` — Recipient-Email + Subject
|
||||
- `apps/web/app/utils/services/.server/CrmService.ts:433/445` — Contact-Daten (Name, Email, Telefon)
|
||||
- `apps/web/app/utils/services/.server/PromptBuilderService.ts:185/256` — AI-Prompts mit User-Content
|
||||
- `apps/web/app/utils/services/.server/SeedService.ts:199-217` — könnte Seed-User-Passwords printen
|
||||
2. **Rest von `apps/web/app/**/*.server.ts(x)`** — gruppiert nach Service, ~10-15 Files pro Commit
|
||||
3. **`apps/api/src/**`** — vermutlich wenig `console.*`, aber prüfen
|
||||
4. **`apps/worker/src/**`** — gleich
|
||||
5. **`packages/**/src/**`** — paketlokaler Logger ggf. neu einführen (manche Packages haben noch keinen)
|
||||
|
||||
### Phase 2 — Enforce (ESLint-Rule)
|
||||
|
||||
Nach abgeschlossener Migration: `no-console: ['error', { allow: [] }]` für Server-Code-Pfade. Client-Bundle-Files (`apps/web/app/components/**/*.tsx`, `apps/web/app/routes/**/*.tsx` ohne `.server.`-Suffix) bleiben erlaubt (Browser-Konsole ist legitim für UX-Debug). Test-Files mit Override `allow: ['log', 'warn', 'error']` für Test-Output.
|
||||
|
||||
**Pino-Argument-Order-Beispiele** (zur Verwendung im Migration-Commit-Body):
|
||||
|
||||
```ts
|
||||
// VORHER:
|
||||
console.log('User signed in', { userId, tenantId });
|
||||
console.error('Failed to send email', error);
|
||||
|
||||
// NACHHER:
|
||||
webLogger.info({ userId, tenantId }, 'User signed in');
|
||||
webLogger.error({ err: error, userId }, 'Failed to send email');
|
||||
// ^^^ Pino-Convention: 'err' für Error-Objekte
|
||||
```
|
||||
|
||||
**Lefthook-Integration:** Pre-commit Hook ruft `pnpm lint:staged` → ESLint mit der neuen Rule blockiert den Commit bei Verstoß.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1 — Migration
|
||||
|
||||
1. **Inventar** — `scripts/observability/scan-console.ts` baut eine Liste aller `console.*`-Calls in Server-Pfaden mit File:Line + Inhalts-Snippet. Output als Markdown-Tabelle in `docs/observability/console-migration-inventory.md`.
|
||||
- Files: `scripts/observability/scan-console.ts`, `docs/observability/console-migration-inventory.md` (generiert)
|
||||
- Commit: `02-observability/logging: add console-call inventory script and baseline`
|
||||
|
||||
2. **High-PII Migration: authService** — `apps/web/app/utils/services/.server/authService.ts` — alle `console.*` auf `webLogger.*`, PII-Felder ausschließen / redacten.
|
||||
- Files: `apps/web/app/utils/services/.server/authService.ts`
|
||||
- Commit: `02-observability/logging: migrate authService.ts console calls to webLogger`
|
||||
|
||||
3. **High-PII Migration: EmailService** — analog.
|
||||
- Commit: `02-observability/logging: migrate EmailService.ts console calls to webLogger`
|
||||
|
||||
4. **High-PII Migration: CrmService** — analog.
|
||||
- Commit: `02-observability/logging: migrate CrmService.ts console calls to webLogger`
|
||||
|
||||
5. **High-PII Migration: PromptBuilderService** — analog; AI-Prompt-Body NIE volltext loggen (max. Hash + Length).
|
||||
- Commit: `02-observability/logging: migrate PromptBuilderService.ts console calls to webLogger`
|
||||
|
||||
6. **High-PII Migration: SeedService** — analog; Seed-Passwords explizit verbieten (Tests dazu, dass `webLogger.info` keine Passwords printet).
|
||||
- Commit: `02-observability/logging: migrate SeedService.ts console calls to webLogger`
|
||||
|
||||
7. **Bulk Migration: `apps/web/app/utils/services/.server/`** — Rest der `.server.ts`-Services, in 2-3 Commits gruppiert nach logischer Cluster (Stripe-related, AI-related, Workflow-related, ...). Pro Commit max 15 Files.
|
||||
- Commits: `02-observability/logging: migrate web services chunk N/M`
|
||||
|
||||
8. **Bulk Migration: `apps/web/app/utils/**/*.server.ts`** — restliche Utils.
|
||||
- Commits: `02-observability/logging: migrate web utils to webLogger`
|
||||
|
||||
9. **Bulk Migration: `apps/web/app/routes/**/*.server.ts(x)`** — Loader/Action-Side, gruppiert nach Route-Bereich.
|
||||
- Commits: `02-observability/logging: migrate web routes to webLogger chunk N/M`
|
||||
|
||||
10. **Bulk Migration: `apps/web/app/modules/**/*.server.ts(x)`** — Module-Side.
|
||||
- Commits: `02-observability/logging: migrate web modules to webLogger chunk N/M`
|
||||
|
||||
11. **API-Migration** — `apps/api/src/**` zu `apiLogger`.
|
||||
- Commits: `02-observability/logging: migrate api console calls to apiLogger`
|
||||
|
||||
12. **Worker-Migration** — `apps/worker/src/**` zu `workerLogger`.
|
||||
- Commits: `02-observability/logging: migrate worker console calls to workerLogger`
|
||||
|
||||
13. **Packages-Migration** — `packages/**/src/**` zu paketlokalem Logger:
|
||||
- Prüfen ob Package schon eigenen Logger hat (z.B. via `packages/logger`-Re-Export)
|
||||
- Falls nicht: `import { createLogger } from '@toolctrl/logger'; const log = createLogger('<package-name>');`
|
||||
- Commits: `02-observability/logging: migrate <package> to local logger` (eins pro Package)
|
||||
|
||||
### Phase 2 — Enforce
|
||||
|
||||
14. **ESLint-Rule** — Root-`eslint.config.js` (oder `.eslintrc`) erweitern:
|
||||
```js
|
||||
// Files: ['**/*.server.ts', '**/*.server.tsx', 'apps/api/src/**/*.ts', 'apps/worker/src/**/*.ts', 'packages/**/src/**/*.ts']
|
||||
rules: { 'no-console': ['error'] }
|
||||
// Override für Test-Files:
|
||||
// Files: ['**/*.test.ts', '**/*.test.tsx', '**/*.spec.ts']
|
||||
rules: { 'no-console': 'off' }
|
||||
// Override für Client-Bundle-Files (default für apps/web/app/**/*.tsx ohne .server.):
|
||||
// bleibt 'no-console': 'off'
|
||||
```
|
||||
- Files: `eslint.config.js` (oder welcher Config-File aktuell genutzt wird)
|
||||
- Commit: `02-observability/logging: enforce no-console on server code via eslint`
|
||||
|
||||
15. **Lefthook-Hook bestätigen** — bestehender `lefthook.yml`-Pre-commit-Hook ruft `pnpm lint:staged`. Prüfen ob das die neue Rule miterfasst (sollte automatisch). Test mit absichtlich injectedem `console.log` in einer `.server.ts`-Datei → Pre-commit blockt.
|
||||
- Files: ggf. `lefthook.yml` (nur falls Anpassung nötig)
|
||||
- Commit: `02-observability/logging: verify pre-commit blocks console in server code`
|
||||
|
||||
16. **CI-Job** — `.github/workflows/ci.yml` und Gitea-Equivalent: `pnpm lint` als blocking Step (sollte bereits sein, aber prüfen).
|
||||
- Files: ggf. `.github/workflows/ci.yml`, `.gitea/workflows/ci.yml`
|
||||
- Commit: `02-observability/logging: ensure lint runs in ci` (nur wenn nötig)
|
||||
|
||||
17. **Doku** — `docs/observability/logging.md`:
|
||||
- Welcher Logger wann (`webLogger` vs `apiLogger` vs paketlokal)
|
||||
- Pino-Convention (`err` für Error, `obj` als erstes Arg, `msg` als zweites)
|
||||
- Log-Level-Konventionen (`fatal` / `error` / `warn` / `info` / `debug` / `trace`)
|
||||
- Verbotene Felder (kein Plaintext-Password, keine ungehashten Tokens, kein vollständiger AI-Prompt-Body)
|
||||
- Pretty-vs-JSON-Modus, env-gesteuert
|
||||
- Files: `docs/observability/logging.md`
|
||||
- Commit: `02-observability/logging: document logger conventions`
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:**
|
||||
- Pro migrierten kritischen Service (auth, Email, Crm, PromptBuilder, Seed) ein Test, dass `webLogger`-Mock NICHT mit PII-Feldern aufgerufen wird (z.B. assertNotCalled mit `password`/`email`/`token` als String-Key in Args). Test-File neben Service.
|
||||
- ESLint-Rule-Test: `tests/lint/no-console-server.test.ts` — synthetic file mit `console.log` in `.server.ts` → ESLint-API liefert Error-Diagnostic. Synthetic file mit `console.log` in Client-File → kein Error.
|
||||
- **Integration-Test:**
|
||||
- Smoke: Pre-commit-Hook mit absichtlichem `console.log` triggern → Commit blockiert
|
||||
- **Coverage-Target:** keine harte %-Zahl; Pflicht: Tests für die 5 High-PII-Services
|
||||
- **Test-Files:** wie oben
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- alle `console.*`-Calls in Server-Code-Pfaden entfernt (`grep -r "console\." apps/api/src apps/worker/src apps/web/app/**/*.server.ts packages/*/src` liefert 0 Hits)
|
||||
- ESLint-Rule aktiv, Pre-commit blockt
|
||||
- alle Tests grün
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Inventar-Script existiert + Output committed
|
||||
- [ ] Alle ~200 `console.*`-Calls in Server-Code-Pfaden migriert
|
||||
- [ ] High-PII-Services (5 oben gelistete) haben PII-Schutz-Tests
|
||||
- [ ] ESLint-Rule `no-console: error` für Server-Pfade aktiv
|
||||
- [ ] Override für Test-Files + Client-Files vorhanden
|
||||
- [ ] Pre-commit-Hook blockt nachweislich neue `console.*` in Server-Code
|
||||
- [ ] `pnpm lint --max-warnings=0` grün auf dem gesamten Repo
|
||||
- [ ] `pnpm typecheck` grün
|
||||
- [ ] `pnpm test` grün
|
||||
- [ ] `docs/observability/logging.md` angelegt
|
||||
- [ ] Inventar-Script in `docs/observability/console-migration-inventory.md` final auf 0 Console-Calls reduziert (Re-Run nach Migration)
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **Pro-Migration-Commit revertierbar** — jeder Migration-Commit ist eigenständig. Falls eine Migration eine Funktion bricht (z.B. Log-Argument-Order verdreht und ein Test bricht): nur diesen Commit revertieren, Rest bleibt.
|
||||
- **ESLint-Rule deaktivieren** via `// eslint-disable-next-line no-console` an einer Einzelstelle (NICHT global) — als Notlösung wenn ein Hotfix dringend `console.error` braucht (und kein Logger-Init zur Verfügung steht).
|
||||
- **Lefthook-Hook umgehen** explizit verbieten (Regel 9 aus AGENT-INSTRUCTIONS) — kein `--no-verify`.
|
||||
- **Pino-Output zurück auf Pretty in Prod** falls JSON-Output kritischen Log-Konsumenten bricht — env `LOG_PRETTY=1`.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **PII-Audit ist Kern dieses Tasks** — die High-PII-Services sind explizit aufgelistet. Während Migration: aktiv prüfen, ob alte `console.log`-Aufrufe Email/Token/Password/Stripe-IDs printten und diese Felder nicht 1:1 in den neuen `webLogger`-Call übernehmen.
|
||||
- **AI-Prompt-Bodies NIEMALS volltext loggen** — User-Content kann Inhalte enthalten, die wir per DSGVO nicht persistieren dürfen. Stattdessen: `{ promptHash, promptLength, model, tenantId }` loggen.
|
||||
- **Stripe-Webhook-Bodies** sind oft im `console.log` — Body enthält Card-Last4, Customer-IDs. Nur Event-Type + Event-ID loggen.
|
||||
- **`err` als Pino-Convention für Error-Objekte** — Pino's `err`-Serializer redactet automatisch `error.config.headers.authorization` etc. (eingebaut). Wenn man Error als anderes Field-Name loggt, läuft der Serializer NICHT.
|
||||
- **Pino-Redact-Pfade** in `packages/logger/` konfigurieren als Backup: `redact: ['*.password', '*.token', '*.authorization', 'req.headers.cookie', ...]` — fängt auch dann, wenn ein Entwickler vergisst zu filtern.
|
||||
- **JSON-Logs in Prod** → Container-Log-Stream wird automatisch von Coolify zu Sentry-Breadcrumbs aggregiert. Pretty-Logs in Prod würden den Stream verschmutzen.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll Inventar zuerst bauen und dann Migration-Reihenfolge der `apps/web`-Bulk-Commits vorschlagen (welche Files in welchem Commit-Bundle)
|
||||
- **Inventar-Skript:** `general-purpose`-Subagent für Step 1
|
||||
- **High-PII Migrations:** EIN `general-purpose`-Subagent für die 5 kritischen Files (Steps 2-6), weil Sicherheits-Audit pro File konzentriert werden muss
|
||||
- **Bulk Migrations:** mehrere parallele `general-purpose`-Subagents für Steps 7-13 (je einer pro App-Bereich) — aber jeder mit klarem Brief und max 15 Files
|
||||
- **ESLint-Rule + Lefthook:** `general-purpose`-Subagent für Steps 14-16
|
||||
- **Doku:** kleiner `general-purpose`-Subagent für Step 17
|
||||
- **Verification:** `general-purpose`-Subagent für Acceptance-Criteria-Scan (`grep`-Verifikation auf 0 Hits, Lint-Audit)
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion mit besonderem Fokus auf PII-Redaction in den 5 kritischen Files
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
Eher kein Staging-Deployment nötig — das ist eine Code-Hygiene-Aufgabe. Aber:
|
||||
|
||||
1. Branch `agent/phase-02-logging` pushen → Coolify-Auto-Deploy auf Staging
|
||||
2. Container-Log-Output beobachten via Coolify-UI:
|
||||
```bash
|
||||
# SSH zum Hetzner-Server
|
||||
docker logs <coolify-web-container-id> --tail 100 -f
|
||||
# Erwartung: Strukturierte JSON-Zeilen wie:
|
||||
# {"level":30,"time":1700000000,"service":"web","msg":"User signed in","userId":"...","tenantId":"..."}
|
||||
```
|
||||
3. Ein paar User-Flows triggern (Login, Email senden, AI-Call):
|
||||
- Keine `console.*`-Output mehr
|
||||
- Keine Klartext-Passwords/-Tokens
|
||||
- AI-Prompts nur als Hash + Length
|
||||
4. Sentry-Breadcrumbs-Check: Ein Test-Error triggern, Issue öffnen, Breadcrumb-Anzahl prüfen — sollte deutlich weniger sein als vor der Migration (vorher 30-50, nachher 5-10)
|
||||
5. Wenn alles grün: PR → main
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
_(Wird vom ausführenden Agent gefüllt — typischerweise: einige Bulk-Migrations brauchen mehr Commits weil Code mehr verschachtelt ist als angenommen.)_
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 — `0b5221b4` — Step 1: scan-console.ts + docs/observability/console-migration-inventory.md baseline (29 hits / 6 files).
|
||||
- 2026-05-17 — `51c9861f` — Step 2: AuthService migrated to webLogger; AuthService.pii.test.ts added (3 tests).
|
||||
- 2026-05-17 — `d0b637ed` — Step 3: EmailService migrated; EmailService.pii.test.ts added (3 tests); AuthService PII test hardened.
|
||||
- 2026-05-17 — `b261b369` — Step 4: CrmService migrated (newsletter + ConvertKit paths); CrmService.pii.test.ts added (3 tests).
|
||||
- 2026-05-17 — `a82cac05` — Step 5: PromptBuilderService migrated; hashPrompt SHA-256 helper added; PromptBuilderService.pii.test.ts added (4 tests).
|
||||
- 2026-05-17 — `8ec57d9b` — Step 6: SeedService migrated; emailFingerprint helper; SeedService.pii.test.ts added (5 tests).
|
||||
- 2026-05-17 — `c27bb350` — Step 7 (chunk 1/3): EventsService migrated.
|
||||
- 2026-05-17 — `8c61b8de` — Step 7 (chunk 2/3): pricingService migrated.
|
||||
- 2026-05-17 — `01e77f72` — Step 13: @toolctrl/db permissions-seed migrated; @toolctrl/logger dep added.
|
||||
- 2026-05-17 — `165fed0c` — Step 14: ESLint `no-console: error` enforced for server paths; test/scripts/client overrides added.
|
||||
- 2026-05-17 — (pending commit) — Step 15-17: pre-commit blocking verified (apps/api console.log → lefthook lint-staged exit 1); docs/observability/logging.md written; final inventory refresh (0 hits / 0 files).
|
||||
|
||||
Steps 8-12 were no-ops because the post-Step 7 inventory was already empty:
|
||||
the bulk of the historical ~200 hits had been removed by earlier Phase-02
|
||||
work (the 51 console.* entries in `apps/web/app/components/**/*.tsx`,
|
||||
`apps/web/app/routes/**/*.tsx`, and various non-server helpers are in
|
||||
client-bundle files and out of the no-console-server scope per Step 14).
|
||||
A full re-scan after Step 13 returned 0 hits in server paths.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Optional — typische Stolperfallen: Pino-Argument-Order führt zu Tests die "msg"-String an falscher Position erwarten; manche Files haben `console.log` innerhalb Template-Strings; `console.dir` muss separat gemoddet werden.)_
|
||||
@@ -0,0 +1,400 @@
|
||||
# Metrics + Grafana — `/status`, `/metrics`, Dashboards
|
||||
|
||||
**Status:** completed (staging stack deployed; `/metrics` live per operator checklist A1)
|
||||
**Task-ID:** #35
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 3-4 Tage
|
||||
**Owner:** agent/02-metrics
|
||||
|
||||
## Problem
|
||||
|
||||
Aktuell gibt es keine Stelle, wo Operators auf einen Blick sehen, wie es der Boilerplate-Instance geht:
|
||||
|
||||
- Kein `/status`-Endpoint für externe Uptime-Checks (Uptime-Kuma, Statuspage)
|
||||
- Kein `/metrics`-Endpoint im Prometheus-Format → keine Infrastruktur-Metriken (Request-Latency, Queue-Depth, DB-Query-Timing)
|
||||
- Keine Business-Metriken (aktive Tenants, AI-Token-Verbrauch pro Tenant, Stripe-Webhook-Volumen, Email-Versand-Raten)
|
||||
- Keine Grafana-Dashboards → bei Performance-Issues muss man in Sentry-Performance + Container-Logs gleichzeitig graben
|
||||
|
||||
Sentry-Performance liefert per-Trace-Granularität, aber **keine aggregierten Live-Counter/Gauges**. Prometheus ist das richtige Werkzeug dafür.
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-wiring-api-worker.md` — wir verdrahten Sentry-Reporter daneben, kein Konflikt
|
||||
- `02-observability/logging-migration.md` — wir wollen, dass Metrics-Middleware nicht auf `console.*` loggt
|
||||
|
||||
## Blocks
|
||||
|
||||
- `03-scaling-infrastructure/shared-store-migration.md` — kein harter Block, aber Metrics-Vorher/Nachher-Vergleich von Cache-Hit-Rate setzt Metrics voraus
|
||||
- `06-plugin-system/*` — Plugin-Cost-Metriken sollen demselben `/metrics`-Endpoint folgen
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** `prom-client` als Library für API + Worker. Eine Hono-Middleware in der API für Auto-Instrumentation (Request-Counter, Latency-Histogram), manuelle Instrumentation in den Worker-Job-Handlern (`packages/queue/`) und in Web-SSR-Loadern (für `web_ssr_loader_duration_seconds`). Business-Metriken werden in den entsprechenden Service-Methoden gesetzt (z.B. `ai_tokens_consumed_total` im `AICostService`).
|
||||
|
||||
Zwei Endpoints pro App:
|
||||
|
||||
- **`/status`** (public, no auth) — JSON, leichtgewichtig, für Uptime-Checks. `200` wenn alle Checks ok, `503` wenn einer kritischer fehlt.
|
||||
- **`/metrics`** (token-protected via `Authorization: Bearer <token>`) — Prometheus Text-Format. Token aus `METRICS_TOKEN` env. Bei fehlender Auth: `401`.
|
||||
|
||||
Beide Endpoints **nur registriert wenn `METRICS_ENABLED=true`** — Default off in Dev, on in Staging/Prod.
|
||||
|
||||
**Grafana + Prometheus Deployment:** Coolify-Stack auf dem Hetzner-Server (gleicher Server wie Sentry). Prometheus scraped die `/metrics`-Endpoints der drei Apps. Grafana liest aus Prometheus. Dashboards als JSON-Templates versioniert in `infra/grafana/dashboards/`.
|
||||
|
||||
**Sample-Metriken** (final-Liste):
|
||||
|
||||
### Infrastruktur
|
||||
|
||||
- `http_requests_total{method, route, status}` — Counter (API + Web-SSR)
|
||||
- `http_request_duration_seconds_bucket{method, route, status}` — Histogram (API + Web-SSR)
|
||||
- `prisma_query_duration_seconds_bucket{model, action}` — Histogram (alle Apps)
|
||||
- `queue_jobs_active{queue}` — Gauge (Worker)
|
||||
- `queue_jobs_waiting{queue}` — Gauge (Worker)
|
||||
- `queue_jobs_completed_total{queue, job_name}` — Counter (Worker)
|
||||
- `queue_jobs_failed_total{queue, job_name, error_type}` — Counter (Worker)
|
||||
- `queue_job_duration_seconds_bucket{queue, job_name}` — Histogram (Worker)
|
||||
- `redis_command_duration_seconds_bucket{command}` — Histogram (alle Apps)
|
||||
- `process_*` — Default-Process-Metrics von prom-client
|
||||
|
||||
### Business
|
||||
|
||||
- `active_tenants` — Gauge (1x pro Minute aktualisiert via Scheduled-Job)
|
||||
- `active_users_24h` — Gauge (Login-Events der letzten 24h, 1x pro Minute aktualisiert)
|
||||
- `ai_tokens_consumed_total{provider, model, tenant_id}` — Counter (Cardinality-Warnung: tenant_id kann groß werden → ggf. nur top-100 tenants + "other" Bucket; Decision-Punkt im Step)
|
||||
- `stripe_webhook_events_total{event_type, status}` — Counter
|
||||
- `mail_sent_total{provider, status}` — Counter (`status` = `delivered`/`bounced`/`failed`)
|
||||
- `webhook_delivery_attempts_total{status}` — Counter (`status` = `success`/`retry`/`dlq`)
|
||||
- `csrf_token_rotation_total` — Counter
|
||||
- `subscription_active{plan_id}` — Gauge
|
||||
|
||||
**Cardinality-Constraint:** Prometheus-Label-Cardinality sollte pro Metric < 10k bleiben, sonst explodiert Prometheus-Memory. `tenant_id` als Label nur in Business-Metriken wo unvermeidlich; sonst per-Tenant-Aggregate via separater Scheduled-Aggregation in DB.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Library + Shared-Package** — `packages/metrics/` neu:
|
||||
- `prom-client` als dep
|
||||
- Exportiert `createRegistry(serviceName)`, vorgefertigte Default-Metriken (`httpRequestsTotal`, `httpRequestDurationSeconds`, `prismaQueryDurationSeconds`, `queueJobs*`, `redisCommandDurationSeconds`, etc.)
|
||||
- Token-Auth-Middleware (framework-agnostisch — gibt boolean zurück)
|
||||
- Files: `packages/metrics/package.json`, `packages/metrics/src/index.ts`, `packages/metrics/src/registry.ts`, `packages/metrics/src/defaults.ts`, `packages/metrics/src/auth.ts`, `packages/metrics/src/*.test.ts`
|
||||
- Commit: `02-observability/metrics: add packages/metrics with prom-client registry`
|
||||
|
||||
2. **API: Hono-Middleware** — `apps/api/src/middleware/metrics.ts`:
|
||||
- Counter pro Request mit Labels `method, route_pattern, status` (Route-Pattern statt URL, sonst Cardinality-Explosion)
|
||||
- Histogram für Latency, Buckets `[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]` Sekunden
|
||||
- Files: `apps/api/src/middleware/metrics.ts`, `apps/api/src/middleware/metrics.test.ts`
|
||||
- Commit: `02-observability/metrics: add metrics middleware for api`
|
||||
|
||||
3. **API: `/status` + `/metrics` Endpoints** — `apps/api/src/routes/status.ts` und `apps/api/src/routes/metrics.ts`:
|
||||
- `/status` JSON-Schema:
|
||||
```json
|
||||
{
|
||||
"status": "ok" | "degraded" | "down",
|
||||
"checks": {
|
||||
"db": "ok" | "down",
|
||||
"redis": "ok" | "down",
|
||||
"queues": "ok" | "degraded" | "down",
|
||||
"workers": "ok" | "down",
|
||||
"storage": "ok" | "down"
|
||||
},
|
||||
"version": "<git-sha>",
|
||||
"uptime_seconds": 12345,
|
||||
"region": "<env-region>"
|
||||
}
|
||||
```
|
||||
- `/metrics` ruft `registry.metrics()` → Text-Format
|
||||
- Bei `!METRICS_ENABLED` → 404 für beide
|
||||
- `/metrics` ohne Token → 401
|
||||
- Files: `apps/api/src/routes/status.ts`, `apps/api/src/routes/metrics.ts`, jeweils Tests
|
||||
- Commit: `02-observability/metrics: add status and metrics endpoints to api`
|
||||
|
||||
4. **API: Middleware + Routes registrieren** — in `apps/api/src/app.ts`.
|
||||
- Files: `apps/api/src/app.ts`
|
||||
- Commit: `02-observability/metrics: register metrics in api app`
|
||||
|
||||
5. **Worker: Manual Instrumentation in Job-Handlern** — `packages/queue/src/runtime.ts` (oder wo immer der zentrale Worker-Wrapper liegt):
|
||||
- Pro Job-Start `queue_jobs_active` inkrementieren, am Ende dekrementieren
|
||||
- `queue_job_duration_seconds` Histogram-Observation
|
||||
- `queue_jobs_completed_total` / `queue_jobs_failed_total` Counter
|
||||
- Files: `packages/queue/src/runtime.ts` (oder analog), `packages/queue/src/runtime.test.ts`
|
||||
- Commit: `02-observability/metrics: instrument queue runtime with prom counters`
|
||||
|
||||
6. **Worker: Background-Scheduler für Gauge-Refresh** — `apps/worker/src/metrics-scheduler.ts`:
|
||||
- Alle 30s: BullMQ-Queue-Metadata abfragen → `queue_jobs_active` / `queue_jobs_waiting` Gauges aktualisieren
|
||||
- Alle 60s: DB-Query → `active_tenants` / `active_users_24h` Gauges aktualisieren
|
||||
- Files: `apps/worker/src/metrics-scheduler.ts`, `apps/worker/src/metrics-scheduler.test.ts`
|
||||
- Commit: `02-observability/metrics: add worker scheduler for gauge refresh`
|
||||
|
||||
7. **Worker: `/status` + `/metrics` Endpoints** — Worker hat aktuell ggf. einen kleinen Health-Server (`apps/worker/src/health.ts`); dort erweitern um die beiden Endpoints. Wenn keiner: kleiner Hono-Server in `apps/worker/src/admin-server.ts`.
|
||||
- Files: `apps/worker/src/health.ts` oder `apps/worker/src/admin-server.ts`, Tests
|
||||
- Commit: `02-observability/metrics: add status and metrics endpoints to worker`
|
||||
|
||||
8. **Web: SSR-Loader-Wrap** — `apps/web/app/lib/metrics/ssr.ts`:
|
||||
- Helper-Funktion `withMetrics(routeId, loaderFn)` die Loader-Calls instrumentiert → `web_ssr_loader_duration_seconds_bucket{route}`
|
||||
- Verwendung in den Top-10-Routes initial (nicht in jedem Loader, sonst Boilerplate); langfristig könnte ein React-Router-Plugin das automatisch
|
||||
- Files: `apps/web/app/lib/metrics/ssr.ts`, `apps/web/app/lib/metrics/ssr.test.ts`
|
||||
- Commit: `02-observability/metrics: add web ssr loader metrics helper`
|
||||
|
||||
9. **Web: `/status` + `/metrics` Route** — `apps/web/app/routes/__metrics.tsx` (oder als Resource-Route `apps/web/app/routes/api.metrics.ts` mit Loader, der Prom-Text liefert).
|
||||
- Auth analog API
|
||||
- Files: `apps/web/app/routes/api.metrics.ts`, `apps/web/app/routes/api.status.ts`, `apps/web/app/routes.ts` (Eintrag)
|
||||
- Commit: `02-observability/metrics: add status and metrics resource routes to web`
|
||||
|
||||
10. **Business-Metriken: AI-Cost-Hook** — im AI-Service (vermutlich `apps/web/app/utils/services/.server/AICostService.ts` oder analog) bei jedem AI-Call:
|
||||
- `aiTokensConsumedTotal.labels({ provider, model, tenant_id }).inc(usage.totalTokens)`
|
||||
- Cardinality-Guard: wenn > 100 unique tenants → bucket-Strategie. Konkrete Decision: aktiv halten bis 1000 tenants, dann auf "top-50 by volume" + "other" umstellen.
|
||||
- Files: `apps/web/app/utils/services/.server/AICostService.ts` (oder Pendant), Tests
|
||||
- Commit: `02-observability/metrics: instrument ai cost service with prom counter`
|
||||
|
||||
11. **Business-Metriken: Stripe-Webhook-Hook** — im Stripe-Webhook-Handler.
|
||||
- Files: entsprechende Webhook-Datei, Test
|
||||
- Commit: `02-observability/metrics: instrument stripe webhook with prom counter`
|
||||
|
||||
12. **Business-Metriken: Mail-Provider-Hook** — im Mail-Adapter (`packages/mail/`).
|
||||
- Files: `packages/mail/src/*.ts`, Test
|
||||
- Commit: `02-observability/metrics: instrument mail provider with prom counter`
|
||||
|
||||
13. **Business-Metriken: Webhook-Delivery-Hook** — im Webhook-Delivery-Queue-Handler (`apps/api/src/webhookDeliveryQueue.ts`).
|
||||
- Files: `apps/api/src/webhookDeliveryQueue.ts`, Test
|
||||
- Commit: `02-observability/metrics: instrument webhook delivery with prom counter`
|
||||
|
||||
14. **Prometheus-Config** — `infra/prometheus/prometheus.yml`:
|
||||
- Scrape-Jobs für api, worker, web mit Bearer-Auth
|
||||
- Scrape-Interval 15s
|
||||
- Retention: 30d (default für lokales Setup ausreichend)
|
||||
- Files: `infra/prometheus/prometheus.yml`, `infra/prometheus/docker-compose.yml`
|
||||
- Commit: `02-observability/metrics: add prometheus config for scraping apps`
|
||||
|
||||
15. **Grafana-Dashboards** — `infra/grafana/dashboards/`:
|
||||
- `overview.json` — Cluster-Health (Up/Down pro Service, Request-Rate, Error-Rate, Latency p95)
|
||||
- `api-latency.json` — pro-Route Latency p50/p95/p99, Request-Rate, Status-Code-Verteilung
|
||||
- `queue-health.json` — Active/Waiting/Failed pro Queue, Job-Duration-Heatmap
|
||||
- `business-kpi.json` — Active Tenants/Users, Stripe-Events, Mail-Delivery-Rate
|
||||
- `ai-cost-per-tenant.json` — Top-20 Tenants nach Token-Verbrauch, Provider-Verteilung, Daily-Trend
|
||||
- Provisioning-Config: `infra/grafana/provisioning/dashboards.yaml` + `datasources.yaml` (Prometheus als Default-Datasource)
|
||||
- Files: `infra/grafana/dashboards/*.json`, `infra/grafana/provisioning/*.yaml`, `infra/grafana/docker-compose.yml`
|
||||
- Commit: `02-observability/metrics: add grafana dashboards and provisioning`
|
||||
|
||||
16. **Doku** — `docs/observability/metrics.md`:
|
||||
- Welche Metriken existieren + welche Frage sie beantworten
|
||||
- Wie man neue Metric hinzufügt (Cardinality-Regeln!)
|
||||
- Deploy Prometheus + Grafana auf Hetzner-Coolify
|
||||
- Dashboard-Updates-Workflow (Edit in Grafana-UI → JSON-Export → in `infra/grafana/dashboards/` committen)
|
||||
- Files: `docs/observability/metrics.md`
|
||||
- Commit: `02-observability/metrics: document metrics catalog and dashboards`
|
||||
|
||||
17. **Env-Defaults + `.env.example`**:
|
||||
- `METRICS_ENABLED` (default `false`)
|
||||
- `METRICS_TOKEN` (random 32-byte hex; in CI/Staging/Prod als Secret)
|
||||
- Files: `.env.example`, `packages/config/src/env.ts`
|
||||
- Commit: `02-observability/metrics: add metrics env vars to config schema`
|
||||
|
||||
18. **Smoke-Test** — `scripts/observability/smoke-metrics.sh`:
|
||||
- Curl `/status` → 200 + JSON-Schema-Check
|
||||
- Curl `/metrics` ohne Auth → 401
|
||||
- Curl `/metrics` mit Auth → Prom-Text mit erwarteten Metric-Names
|
||||
- Files: `scripts/observability/smoke-metrics.sh`
|
||||
- Commit: `02-observability/metrics: add smoke test script`
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:**
|
||||
- `packages/metrics/src/*.test.ts` — Registry-Setup, Token-Auth, Counter-Inkrement
|
||||
- `apps/api/src/middleware/metrics.test.ts` — Counter/Histogram bekommt korrekte Labels, Route-Pattern statt URL
|
||||
- `apps/api/src/routes/status.test.ts` — JSON-Schema validiert, `503` wenn DB down (Mock)
|
||||
- `apps/api/src/routes/metrics.test.ts` — 401 ohne Token, 200 mit Token, 404 wenn `METRICS_ENABLED=false`
|
||||
- `packages/queue/src/runtime.test.ts` — Active-Gauge inkrementiert/dekrementiert, Failed-Counter bei Throw
|
||||
- `apps/worker/src/metrics-scheduler.test.ts` — Scheduler ruft Queue-API in Intervallen, Gauges werden gesetzt
|
||||
- `apps/web/app/lib/metrics/ssr.test.ts` — `withMetrics`-Wrapper observiert Latency, fängt Errors
|
||||
- **Integration-Test:**
|
||||
- In-Process API mit injected Prom-Registry, mehrere Requests fahren, `/metrics`-Output prüfen
|
||||
- **E2E (manuell auf Staging):**
|
||||
- Prometheus-UI: `https://prometheus.<staging-domain>` → Targets-View → alle 3 Apps "UP"
|
||||
- Grafana-UI: `https://grafana.<staging-domain>` → Overview-Dashboard → Live-Daten
|
||||
- Test-Load: 100 Requests via `hey` oder `oha` → Request-Rate-Panel zeigt Spike
|
||||
- **Coverage-Target:** ≥ 80% für `packages/metrics/`, ≥ 70% für die Middleware-Files
|
||||
- **Test-Files:** wie oben
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- alle Unit + Integration grün
|
||||
- Prometheus auf Staging scraped erfolgreich alle 3 Apps
|
||||
- mindestens 1 Grafana-Dashboard (Overview) zeigt Live-Daten
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `packages/metrics/` mit Registry + Default-Metriken + Token-Auth
|
||||
- [ ] API hat `/status` + `/metrics` Endpoints, Middleware aktiv
|
||||
- [ ] Worker hat `/status` + `/metrics` Endpoints, Scheduler aktiv
|
||||
- [ ] Web hat `/status` + `/metrics` Resource-Routes, SSR-Wrapper für Top-Routes
|
||||
- [ ] Business-Metriken: AI-Cost, Stripe-Webhook, Mail, Webhook-Delivery instrumentiert
|
||||
- [ ] Cardinality-Schutz aktiv (tenant_id-Bucketing dokumentiert)
|
||||
- [ ] `infra/prometheus/` und `infra/grafana/` Compose + Config angelegt
|
||||
- [ ] 5 Grafana-Dashboards (Overview, API-Latency, Queue-Health, Business-KPI, AI-Cost-per-Tenant) committed
|
||||
- [ ] `docs/observability/metrics.md` mit Catalog + Deploy-Schritten
|
||||
- [ ] `.env.example` mit `METRICS_ENABLED`, `METRICS_TOKEN`
|
||||
- [ ] Smoke-Skript grün
|
||||
- [ ] Aktiviert nur wenn `METRICS_ENABLED=true`
|
||||
- [ ] Staging: Prometheus scraped alle 3 Apps, Grafana zeigt Live-Daten
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **`METRICS_ENABLED=false`** → beide Endpoints liefern 404, kein Overhead
|
||||
- **Middleware no-op** wenn Registry leer (`packages/metrics`-Default-Verhalten)
|
||||
- **Prometheus-Stack auf Coolify stoppen** → Scraping endet, Apps merken nichts (Endpoints sind passive Reader)
|
||||
- **Grafana-Dashboard-Revert** via `git revert` der JSON-Files + Prometheus-Reload
|
||||
- **Cardinality-Notbremse** falls Prometheus-Memory explodiert: AI-Cost-Counter ohne `tenant_id`-Label deployen, Hotfix-Commit
|
||||
- **Business-Metric-Calls einzeln revertierbar** (Steps 10-13 sind je ein Commit)
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **`/status` ist public** — KEIN Auth, weil Uptime-Check-Tools (UptimeRobot etc.) kein Token verwenden. Daher: NUR boolean-artige Health-Info, NIEMALS DB-Connection-Strings, NIEMALS Pod-Hostnames, NIEMALS Stack-Traces.
|
||||
- **`/metrics` MIT Token** — sonst kann jeder Scraper Business-Metriken (AI-Cost pro Tenant) abgreifen. Token mind. 32 Bytes Random, alle 6 Monate rotieren.
|
||||
- **Prometheus-UI nur intern oder mit Basic-Auth** — Prometheus' Built-in-UI hat keine Auth; in Coolify hinter Traefik-Basic-Auth oder Cloudflare-Access stellen.
|
||||
- **Grafana-UI mit eingebauter Auth** + 2FA für Admin-User; Anonymous-Access deaktiviert.
|
||||
- **Cardinality-Explosion ist Security-Issue** — wenn ein Endpoint einen Label-Wert vom User-Input nimmt (z.B. `user_id`), kann ein Angreifer per Bot Millionen Labels erzeugen → Prom-OOM. Daher: User-Input NIEMALS als Label-Wert. Tenant-ID als Label nur, wenn Anzahl Tenants begrenzbar.
|
||||
- **Business-Metriken sind tenant-vertraulich** — Token-Auth Pflicht, keine Cross-Tenant-Leakage via Label-Inferenz.
|
||||
- **`process.env`-Inhalte NICHT als Metric-Labels** — Default-Process-Metrics von prom-client tun das nicht, eigene Metriken auch nicht.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll konkrete Cardinality-Grenzen festzurren und Reihenfolge der Business-Metric-Instrumentierungen optimieren
|
||||
- **Implementation `packages/metrics/`:** `general-purpose`-Subagent für Step 1 (Foundation)
|
||||
- **Implementation API:** `general-purpose`-Subagent für Steps 2-4
|
||||
- **Implementation Worker:** `general-purpose`-Subagent für Steps 5-7
|
||||
- **Implementation Web:** `general-purpose`-Subagent für Steps 8-9
|
||||
- **Business-Metriken:** `general-purpose`-Subagent für Steps 10-13 (kann parallel zu API/Worker laufen)
|
||||
- **Infra (Prometheus + Grafana):** separater `general-purpose`-Subagent für Steps 14-15 (eigene Skill-Domäne)
|
||||
- **Doku + Env:** kleiner `general-purpose`-Subagent für Steps 16-17
|
||||
- **Verification:** `general-purpose`-Subagent für Staging-Smoke + Dashboard-Live-Daten-Check
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion mit Fokus auf Cardinality
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. **Prometheus + Grafana auf Coolify deployen:**
|
||||
- Neuer Service "Docker Compose" mit `infra/prometheus/docker-compose.yml`
|
||||
- Neuer Service "Docker Compose" mit `infra/grafana/docker-compose.yml`
|
||||
- Domains: `prometheus.<staging-domain>`, `grafana.<staging-domain>`
|
||||
- Grafana-Admin-Credentials in Coolify-Secrets
|
||||
2. **App-Env-Variables** für api/worker/web:
|
||||
- `METRICS_ENABLED=true`
|
||||
- `METRICS_TOKEN=<32-byte hex>` (gleich für alle 3 Apps, Bequemlichkeit; Prometheus konfiguriert nur einen)
|
||||
3. **Branch `agent/phase-02-metrics` pushen** → Coolify-Deploy
|
||||
4. **Smoke-Tests:**
|
||||
```bash
|
||||
# Status (public)
|
||||
curl https://api.<staging-domain>/status
|
||||
# Erwartung: 200, JSON wie oben
|
||||
|
||||
# Metrics (mit Token)
|
||||
curl -H "Authorization: Bearer $METRICS_TOKEN" https://api.<staging-domain>/metrics
|
||||
# Erwartung: 200, Prom-Text
|
||||
|
||||
# Metrics ohne Token
|
||||
curl -i https://api.<staging-domain>/metrics
|
||||
# Erwartung: 401
|
||||
```
|
||||
5. **Prometheus-Targets-Check:**
|
||||
- `https://prometheus.<staging-domain>/targets` → alle 3 Apps "UP"
|
||||
6. **Grafana-Dashboards:**
|
||||
- Login + Overview-Dashboard → Live-Daten sichtbar
|
||||
- Last-Test: `oha -n 1000 https://api.<staging-domain>/status` → Request-Rate-Panel zeigt Spike
|
||||
7. **Cardinality-Check:**
|
||||
- `https://prometheus.<staging-domain>/graph` → `count by (__name__)({__name__=~"ai_.*"})` → Cardinality pro AI-Metric prüfen
|
||||
- Falls > 1000 Labels: Tenant-Bucketing aktivieren
|
||||
8. Wenn alles grün: PR → main
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **Queue runtime instrumentation lives in `apps/worker/src/runtime.ts`, not
|
||||
`packages/queue/src/runtime.ts`.** `@toolctrl/queue/runtime` is the thin
|
||||
BullMQ wrapper (3 functions). The actual processor wrap with logger /
|
||||
Sentry / metrics awareness is in `apps/worker/src/runtime.ts` —
|
||||
instrumenting there reuses the existing `createLoggedProcessor` pattern
|
||||
and keeps `packages/queue` dep-free of prom-client.
|
||||
- **AI-cost cardinality cap is in-process, not config-driven.** The
|
||||
spec hinted at "top-100 tenants + other" but did not mandate where the
|
||||
bookkeeping lives. Implemented as a process-local LRU
|
||||
(`apps/web/app/lib/metrics/ai-cost.ts`) with `MAX_TENANT_BUCKETS=100`
|
||||
hard-coded. Easy to bump or wire to env if needed.
|
||||
- **Mail metric is a hook, not a direct registry call.** `packages/mail`
|
||||
is consumed by api + web + worker — coupling it to prom-client was
|
||||
rejected. The provider now takes an optional `onMetric` callback that
|
||||
the worker entry wires to `mail_sent_total`.
|
||||
- **Web SSR coverage is 9 routes, not exactly 10.** Wrapped index/app-root
|
||||
(shared loader), app-tenant, admin-root, dashboard, login, logout,
|
||||
forgot-password, new-account, invitation. Adding more is a one-line
|
||||
change once Prom data identifies hotspots.
|
||||
- **2026-05-27 status reconciliation:** `docs/improvement-plan/OPERATOR-CHECKLIST.md`
|
||||
A1 verifies `METRICS_ENABLED=true` + `METRICS_TOKEN` are live on
|
||||
web/api/worker and `/metrics` returns 200. That supersedes the older
|
||||
app-side env-flip caveat in this file and matches the #35 `completed`
|
||||
row in `PROGRESS.md`.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 06:08 — `68fd4d4c` — packages/metrics with registry + defaults + token auth (16 tests)
|
||||
- 2026-05-17 06:10 — `abeae9e7` — api metrics middleware (5 tests, route-pattern labels)
|
||||
- 2026-05-17 06:11 — `fa6f1819` — api /status + /metrics handlers (11 tests)
|
||||
- 2026-05-17 06:14 — `0bf5f66a` — wire api middleware + routes into Hono app
|
||||
- 2026-05-17 06:17 — `57f6a995` — queue runtime metrics: active gauge + completed/failed counter + duration histogram (2 tests)
|
||||
- 2026-05-17 06:19 — `84525d9b` — worker metrics-scheduler: 30s queue depth + 60s business gauges (5 tests)
|
||||
- 2026-05-17 06:26 — `9607c590` — worker admin-server (node:http) /status + /metrics with graceful shutdown (6 tests)
|
||||
- 2026-05-17 06:27 — `618c8707` — web withMetrics SSR wrapper helper (4 tests)
|
||||
- 2026-05-17 06:36 — `5d461656` — api.status + api.metrics resource routes + 8 top routes wrapped (4 route tests + 4 ssr tests)
|
||||
- 2026-05-17 06:38 — `8cff9092` — ai cost prom counter with 100-bucket tenant LRU (5 tests)
|
||||
- 2026-05-17 06:40 — `cadd6574` — stripe webhook counter with event_type + status labels (3 tests)
|
||||
- 2026-05-17 06:43 — `a1427f26` — MailjetProvider.onMetric hook + worker auto-wiring (5 tests)
|
||||
- 2026-05-17 06:45 — `ec80dec3` — webhook delivery handler counter (success/retry/dlq/rejected)
|
||||
- 2026-05-17 06:46 — `aba91e5f` — Prometheus compose + scrape config with 30d retention
|
||||
- 2026-05-17 06:48 — `4d2117b9` — 5 Grafana dashboards + file-based provisioning
|
||||
- 2026-05-17 06:50 — `52511b09` — docs/observability/metrics.md (catalog + deploy + rollback playbook)
|
||||
- 2026-05-17 06:51 — `4245c6d5` — METRICS_ENABLED / METRICS_TOKEN / WORKER_ADMIN_* / APP_REGION in env catalog + .env.example
|
||||
- 2026-05-17 06:53 — `0fcc6a17` — scripts/observability/smoke-metrics.sh
|
||||
- 2026-05-17 06:54 — `<this commit>` — progress log + PROGRESS.md update
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
- **Hono `c.req.routePath` is the right cardinality knob.** Going through
|
||||
the matched route pattern keeps `http_requests_total` bounded by the
|
||||
route table size (~50 entries) rather than by user-input URLs.
|
||||
- **`prom-client` emits labels in declaration order.** Test regexes that
|
||||
hard-code label order need to match the order in `labelNames` (not
|
||||
alphabetical, not insertion-order of `labels({...})`).
|
||||
- **Mail providers should not import from the host app.** Threading a
|
||||
callback through `MailjetProviderOptions.onMetric` is cleaner than
|
||||
reaching for a registry singleton from a leaf package.
|
||||
- **React Router v7 typegen runs lazily.** New resource routes
|
||||
(`api.status.ts`, `api.metrics.ts`) work as soon as `react-router typegen`
|
||||
has run once — committed types in `.react-router/types/` track route
|
||||
changes automatically when typecheck runs.
|
||||
|
||||
## Progress Log (continued)
|
||||
|
||||
- 2026-05-18 00:48 UTC — staging-deploy — Cloudflare A record
|
||||
`grafana.boiler.saas-ctrl.com` → 46.225.5.93 created
|
||||
(id `2267905b1ee15df4002ca02d76af1fe0`, proxied=false).
|
||||
Observability stack brought up on `/opt/observability/`: Prometheus
|
||||
v3.6.0 (`boilerplate-prometheus`) on dedicated
|
||||
`boilerplate-observability` network, Grafana 11.4.0
|
||||
(`boilerplate-grafana`) attached to both observability + coolify
|
||||
networks via on-host `docker-compose.override.yml` (Traefik labels for
|
||||
TLS via Let's Encrypt). Secrets generated via `openssl rand` on the
|
||||
host (`METRICS_TOKEN`, `GRAFANA_ADMIN_PASSWORD`,
|
||||
`GRAFANA_PROMETHEUS_TOKEN` reuses METRICS_TOKEN) stored in
|
||||
`/opt/observability/.env` (chmod 600) and
|
||||
`~/.cli-tokens/grafana-staging-env`; the same token is also bind-mounted
|
||||
into Prometheus at `/etc/prometheus/secrets/metrics_token`. While
|
||||
deploying, found and fixed a duplicate `jsonData` key in
|
||||
`infra/grafana/provisioning/datasources/prometheus.yaml` (committed file
|
||||
was invalid YAML; Grafana refused to start). Smoke green:
|
||||
`curl -fSs https://grafana.boiler.saas-ctrl.com/api/health` →
|
||||
`{"database":"ok","version":"11.4.0",...}`. Scrape targets in
|
||||
`prometheus.yml` point at the public HTTPS hostnames
|
||||
(`api.boiler.saas-ctrl.com`, etc.) and require the apps to expose
|
||||
`/metrics` with the same bearer token.
|
||||
- 2026-05-27 — docs/status reconciliation — A1 verifies
|
||||
`METRICS_ENABLED=true` + `METRICS_TOKEN` live on web/api/worker and
|
||||
`/metrics` returns 200. The older "env flips pending" note above is
|
||||
superseded; any Prometheus target outage after this date should be
|
||||
treated as a fresh runtime incident, not unfinished #35 implementation.
|
||||
@@ -0,0 +1,258 @@
|
||||
# OpenTelemetry Integration — API + Worker + Web
|
||||
|
||||
**Status:** completed
|
||||
**Task-ID:** #33
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 2-3 Tage
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Sentry-Performance (aus Tasks #30/#31) liefert gute App-Level-Traces für Errors und ausgewählte Transactions — aber:
|
||||
|
||||
- Cross-Service-Tracing (api → worker → db) ist mit Sentry-only nicht sauber, weil Sentry keine vollständigen OTel-Propagators für interne Service-Hops macht
|
||||
- Externe Tools (Tempo, Jaeger, Honeycomb) sollen optional anhängbar sein, ohne dass wir den Sentry-Vendor-Lock-In zementieren
|
||||
- Fine-grained Spans für `fs`, `dns`, `net`, `redis` sind in Sentry's Auto-Instrumentation für Node nicht enthalten — OTel hat die per Default
|
||||
- Ohne OTel-Standard kein konsistentes `service.name`/`deployment.environment`-Tagging über alle Services
|
||||
|
||||
Wir wollen OTel als **neutrales Telemetrie-Layer**, das primär in das self-hosted Sentry (via Relay-OTLP-Ingest) exportiert, aber bei Bedarf auch zu einem Tempo/Jaeger umgeleitet werden kann.
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-selfhost-setup.md` — Sentry-Relay muss OTLP-Ingest aktiviert haben (Step 6 dort)
|
||||
- `02-observability/sentry-wiring-api-worker.md` — Sentry-SDK ist initialisiert; OTel-SDK koexistiert (Sentry v8 nutzt intern bereits OTel-Spans, wir docken nur den Exporter an)
|
||||
- `02-observability/sentry-wiring-web.md` — analog für Web-Side
|
||||
|
||||
## Blocks
|
||||
|
||||
- `02-observability/metrics-grafana.md` — kein harter Block, aber OTel-Metrics-API könnte parallel zu prom-client genutzt werden — wir entscheiden bewusst dagegen (Prom-Client direkter, weniger Overhead). Falls später Wechsel zu OTel-Metrics: dieser Task ist Voraussetzung.
|
||||
- `03-scaling-infrastructure/read-write-split.md` — beim Routen zwischen primary/replica wollen wir DB-Spans mit `db.replica`-Tag sehen
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** `@opentelemetry/sdk-node` mit `@opentelemetry/auto-instrumentations-node` in `apps/api` und `apps/worker`. Web-Browser-Side: `@opentelemetry/sdk-trace-web` mit `fetch` + `xhr` Instrumentations. Custom Span-Processor für PII-Scrubbing **vor** dem Exporter. OTLP-HTTP-Exporter, der per Default an Sentry-Relay-OTLP-Endpoint geht. Initialisierung nur wenn `OTEL_EXPORTER_OTLP_ENDPOINT` env gesetzt ist — sonst No-Op.
|
||||
|
||||
**Begründung:**
|
||||
|
||||
- `auto-instrumentations-node` ist ein Meta-Package, das HTTP, fetch, Prisma, BullMQ, Redis, fs, dns, net out-of-the-box abdeckt → minimaler Bootstrap-Code
|
||||
- OTel ist Industrie-Standard, Vendor-neutral — Sentry, Tempo, Honeycomb, Datadog können alle den gleichen Stream konsumieren
|
||||
- Sentry-SDK v8 baut intern auf OTel auf → keine Konflikte zwischen Sentry-Tracer und OTel-Tracer, sie teilen sich denselben Tracer-Provider
|
||||
- **Web-Side** hält sich auf `fetch` + `xhr` beschränkt (kein `document-load`, kein `user-interaction` — die sind in Browser-OTel teuer und Sentry-Replay deckt diese UX-Bedürfnisse bereits ab)
|
||||
- **Sampling:** `parentBasedSampler` + `traceIdRatioBasedSampler(ratio)` — sodass Distributed-Trace-Konsistenz erhalten bleibt (wenn Eltern-Span sampled wird, wird das Kind auch gesampled)
|
||||
|
||||
**Resource-Attributes** (Standard-OTel-Semantik):
|
||||
- `service.name`: `boilerplate-api` | `boilerplate-worker` | `boilerplate-web`
|
||||
- `service.version`: `process.env.SENTRY_RELEASE` (= `$GIT_SHA`)
|
||||
- `service.instance.id`: hostname + PID
|
||||
- `deployment.environment`: `process.env.SENTRY_ENVIRONMENT`
|
||||
- `service.namespace`: `toolctrl`
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Dependencies** — `@opentelemetry/sdk-node`, `@opentelemetry/auto-instrumentations-node`, `@opentelemetry/exporter-trace-otlp-http`, `@opentelemetry/resources`, `@opentelemetry/semantic-conventions`, `@opentelemetry/api`, `@opentelemetry/core`, `@opentelemetry/sdk-trace-base` in `apps/api/package.json` und `apps/worker/package.json`. Für Web: `@opentelemetry/sdk-trace-web`, `@opentelemetry/instrumentation-fetch`, `@opentelemetry/instrumentation-xml-http-request`, `@opentelemetry/context-zone`.
|
||||
- Files: `apps/api/package.json`, `apps/worker/package.json`, `apps/web/package.json`, `pnpm-lock.yaml`
|
||||
- Commit: `02-observability/otel: add opentelemetry dependencies for api/worker/web`
|
||||
|
||||
2. **PII-Scrubber-Span-Processor (shared)** — neues Package `packages/observability/` mit `pii-span-processor.ts`:
|
||||
- Implementiert `SpanProcessor`-Interface
|
||||
- In `onEnd(span)`: spans-Attribute durchsehen und PII redacten:
|
||||
- `http.target` / `http.url`: Query-String strippen via `?` → `?[scrubbed]`
|
||||
- `http.request.header.*`: Allowlist (`content-type`, `user-agent`, `accept-language`, `x-request-id`); alles andere droppen, vor allem `authorization`, `cookie`, `set-cookie`, `x-api-key`
|
||||
- `db.statement` (Prisma): Param-Bindings durch `?` ersetzen via einfaches Regex `'([^']*)' → '?'` (Prisma's `db.statement` enthält bereits parametrisierte Queries, aber sicher ist sicher)
|
||||
- `messaging.message_payload_size_bytes` behalten, aber `messaging.message_payload` als gesamtes Field droppen
|
||||
- Wraps einen anderen `SpanProcessor` (Decorator-Pattern) und delegiert an diesen
|
||||
- Files: `packages/observability/package.json`, `packages/observability/src/pii-span-processor.ts`, `packages/observability/src/pii-span-processor.test.ts`, `packages/observability/src/index.ts`
|
||||
- Commit: `02-observability/otel: add packages/observability with pii span processor`
|
||||
|
||||
3. **OTel-Bootstrap (API)** — `apps/api/src/otel.ts`:
|
||||
- Init nur wenn `process.env.OTEL_EXPORTER_OTLP_ENDPOINT` gesetzt
|
||||
- `NodeSDK({ resource, traceExporter: new OTLPTraceExporter({ url, headers }), spanProcessors: [new PIISpanProcessor(new BatchSpanProcessor(otlpExporter))], instrumentations: [getNodeAutoInstrumentations({ '@opentelemetry/instrumentation-fs': { enabled: false } /* zu noisy */ })], sampler: parentBasedSampler(traceIdRatioBasedSampler(Number(process.env.OTEL_TRACES_SAMPLER_ARG ?? 0.1))) })`
|
||||
- `sdk.start()` — MUSS vor allen anderen Imports laufen, damit Instrumentations hooken können. Daher als allererster Import in `apps/api/src/server.ts` (vor `app.ts`).
|
||||
- Files: `apps/api/src/otel.ts`, `apps/api/src/otel.test.ts`
|
||||
- Commit: `02-observability/otel: add api otel bootstrap`
|
||||
|
||||
4. **API-Entry-Point anpassen** — `apps/api/src/server.ts` (oder `index.ts`, je nach existierender Datei) MUSS `import './otel'` als ALLERERSTES haben, vor allen anderen Imports.
|
||||
- Files: `apps/api/src/server.ts`
|
||||
- Commit: `02-observability/otel: bootstrap otel before all imports in api`
|
||||
|
||||
5. **OTel-Bootstrap (Worker)** — analog `apps/worker/src/otel.ts`. Sampler-Default für Worker etwas höher (`0.2` prod), weil Worker-Jobs weniger frequent und mehr Wert pro Trace.
|
||||
- Files: `apps/worker/src/otel.ts`, `apps/worker/src/otel.test.ts`
|
||||
- Commit: `02-observability/otel: add worker otel bootstrap`
|
||||
|
||||
6. **Worker-Entry-Point anpassen** — `apps/worker/src/index.ts` mit `import './otel'` als ALLERERSTES.
|
||||
- Files: `apps/worker/src/index.ts`
|
||||
- Commit: `02-observability/otel: bootstrap otel before all imports in worker`
|
||||
|
||||
7. **OTel-Bootstrap (Web Browser)** — `apps/web/app/lib/otel/web.ts`:
|
||||
- `WebTracerProvider` mit `ZoneContextManager`, `OTLPTraceExporter` (Endpoint via `VITE_OTEL_EXPORTER_OTLP_ENDPOINT`)
|
||||
- Instrumentations: `FetchInstrumentation({ propagateTraceHeaderCorsUrls: [/api\.<our-domain>/] })`, `XMLHttpRequestInstrumentation`
|
||||
- PII-Span-Processor wiederverwenden aus `packages/observability/`
|
||||
- Init nur wenn Env-Endpoint gesetzt
|
||||
- Files: `apps/web/app/lib/otel/web.ts`, `apps/web/app/lib/otel/web.test.ts`
|
||||
- Commit: `02-observability/otel: add web browser otel bootstrap`
|
||||
|
||||
8. **Web-Entry-Point anpassen** — `apps/web/app/entry.client.tsx` ruft Init nach Sentry-Init aber vor `hydrateRoot`.
|
||||
- Files: `apps/web/app/entry.client.tsx`
|
||||
- Commit: `02-observability/otel: wire otel into web client entry`
|
||||
|
||||
9. **Web-SSR-OTel** — `apps/web/app/entry.server.tsx` mit `import './otel.server'` (analog API-Pattern). Wiederverwendet `apps/api`-ähnliche Bootstrap-Datei aber für Web-SSR.
|
||||
- Files: `apps/web/app/lib/otel/server.ts`, `apps/web/app/entry.server.tsx`
|
||||
- Commit: `02-observability/otel: add web ssr otel bootstrap`
|
||||
|
||||
10. **Relay-Config für OTLP** — Verifikation, dass `infra/sentry/relay/config.yml` (aus `sentry-selfhost-setup.md` Step 6) den OTLP-HTTP-Endpoint exposed. Falls noch nicht: ergänzen mit:
|
||||
```yaml
|
||||
relay:
|
||||
ingest:
|
||||
otlp:
|
||||
enabled: true
|
||||
max_payload_size: 5MiB
|
||||
```
|
||||
- Files: `infra/sentry/relay/config.yml` (Update)
|
||||
- Commit: `02-observability/otel: enable otlp ingestion in sentry relay config`
|
||||
|
||||
11. **Env-Defaults + `.env.example`**:
|
||||
- `OTEL_EXPORTER_OTLP_ENDPOINT` (server-side, z.B. `https://sentry.<domain>/api/<project_id>/otlp`)
|
||||
- `OTEL_EXPORTER_OTLP_HEADERS` (z.B. `x-sentry-auth=Sentry sentry_key=<key>`)
|
||||
- `OTEL_TRACES_SAMPLER_ARG` (default `0.1` prod, `1.0` dev)
|
||||
- `OTEL_SERVICE_NAME` (überschreibt Default, optional)
|
||||
- `VITE_OTEL_EXPORTER_OTLP_ENDPOINT` (Browser-Side; wird in Vite-Bundle eingebacken)
|
||||
- Files: `.env.example`, `packages/config/src/env.ts`
|
||||
- Commit: `02-observability/otel: add otel env vars to config schema`
|
||||
|
||||
12. **Doku** — `docs/observability/otel.md`:
|
||||
- Overview: was wird gesammelt, was nicht
|
||||
- Relay-Setup-Snippet (für eigenes Sentry-Self-Host)
|
||||
- Alternative Exporter (Tempo, Jaeger, Honeycomb) — Config-Snippets
|
||||
- Sampling-Strategie + wie man bei Debugging temporär auf `1.0` hochzieht
|
||||
- PII-Span-Processor-Doku: welche Attribute werden redacted, wie ergänzt man neue
|
||||
- Troubleshooting: "keine Spans sichtbar" Checkliste
|
||||
- Files: `docs/observability/otel.md`
|
||||
- Commit: `02-observability/otel: document otel setup and alternatives`
|
||||
|
||||
13. **Smoke-Test** — `scripts/observability/smoke-otel.ts`:
|
||||
- Triggert manuell einen API-Request, einen Worker-Job, einen Web-Loader-Call
|
||||
- Wartet 10s
|
||||
- Queryt Sentry-Performance-API ob Spans mit den erwarteten `trace_id`s da sind
|
||||
- Files: `scripts/observability/smoke-otel.ts`
|
||||
- Commit: `02-observability/otel: add smoke test script`
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:**
|
||||
- `packages/observability/src/pii-span-processor.test.ts` — Scrubber redactet alle Denylist-Attribute, Allowlist-Header bleiben durch, Prisma-Param-Bindings werden zu `?`
|
||||
- `apps/api/src/otel.test.ts` — No-Op wenn Endpoint fehlt; korrekter Sampler bei verschiedenen `OTEL_TRACES_SAMPLER_ARG`-Werten
|
||||
- `apps/worker/src/otel.test.ts` — analog
|
||||
- `apps/web/app/lib/otel/web.test.ts` — Fetch-Instrumentation propagiert Trace-Header an Same-Origin/Allowed-Origin
|
||||
- **Integration-Test:**
|
||||
- Mock-OTLP-Endpoint in einer Vitest-Suite, API-Request → Span lands at endpoint mit erwartetem `service.name`, redacted Headers
|
||||
- **E2E (manuell auf Staging):**
|
||||
- 1 End-to-End-Flow `User klickt im Web → SSR-Loader → API-Call → Worker-Job` → in Sentry-Performance ein zusammenhängender Trace mit 4 Spans, gleiche `trace_id`
|
||||
- PII-Check: Authorization-Header im Span ist `[Redacted]` oder gar nicht vorhanden
|
||||
- Sample-Rate-Check: bei `OTEL_TRACES_SAMPLER_ARG=0.1` und 100 Requests sollten ~10 Traces landen (±20% Toleranz)
|
||||
- **Coverage-Target:** ≥ 85% für `packages/observability/`, ≥ 70% für jeden Bootstrap-File
|
||||
- **Test-Files:** wie in Implementation Steps gelistet
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- Unit + Integration grün
|
||||
- End-to-End-Trace mit 4 verknüpften Spans im Staging-Sentry sichtbar
|
||||
- PII-Audit erfolgreich (keine sensiblen Header in einem stichprobenartig geöffneten Trace)
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `packages/observability/` mit PII-Span-Processor angelegt + getestet
|
||||
- [ ] OTel-Bootstrap in api, worker, web (Browser + SSR)
|
||||
- [ ] Bootstrap-Imports sind ALLERERSTE Imports in den jeweiligen Entry-Points
|
||||
- [ ] Auto-Instrumentations für HTTP, fetch, Prisma, BullMQ, Redis aktiv (fs/dns/net je nach Noise-Level)
|
||||
- [ ] PII-Scrubber wird VOR Exporter ausgeführt (per Span-Processor-Chain-Order verifiziert)
|
||||
- [ ] OTLP-Exporter sendet an Sentry-Relay-OTLP-Endpoint
|
||||
- [ ] Sampling konfigurierbar via `OTEL_TRACES_SAMPLER_ARG`, default 0.1 prod / 1.0 dev
|
||||
- [ ] Aktiviert nur wenn `OTEL_EXPORTER_OTLP_ENDPOINT` gesetzt — sonst sauberer No-Op
|
||||
- [ ] `docs/observability/otel.md` mit Sentry-Relay-Setup + Alternative-Exporter
|
||||
- [ ] `.env.example` erweitert
|
||||
- [ ] Staging: End-to-End-Trace mit 4 verknüpften Spans sichtbar
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **`OTEL_EXPORTER_OTLP_ENDPOINT` unset** → kompletter OTel-Stack ist No-Op, App läuft weiter
|
||||
- **`OTEL_TRACES_SAMPLER_ARG=0`** → keine Spans gesampled, OTel-SDK initialisiert aber sendet nichts
|
||||
- **Auto-Instrumentations selektiv abklemmen** via `{ '@opentelemetry/instrumentation-<name>': { enabled: false } }` in Bootstrap — falls eine Library Performance-Issues macht
|
||||
- **Commits einzeln revertierbar** — kritische Rollback-Points: Steps 4, 6, 8, 9 (Entry-Point-Bootstrap)
|
||||
- **Relay-OTLP-Endpoint abschalten** in `infra/sentry/relay/config.yml` falls Sentry-Performance überlastet wird
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **PII-Scrubber-Reihenfolge ist kritisch** — Span-Processors laufen in Reihenfolge; PII-Scrubber MUSS vor Exporter sein, sonst landet PII bei Sentry/Tempo/etc. Test in `pii-span-processor.test.ts` verifiziert die Reihenfolge explizit.
|
||||
- **Headers-Allowlist statt -Denylist** — neue Header (z.B. neue Auth-Schemata) sind by default raus, nicht drin. Sicherer Default.
|
||||
- **Prisma-Param-Bindings** sind bei Prisma als `?` parameterisiert — `db.statement` zeigt also nie Klartext-Values. Trotzdem doppelt scrubben (defense-in-depth).
|
||||
- **Trace-Header-Propagation** zu cross-origin: `propagateTraceHeaderCorsUrls` MUSS Allowlist sein, sonst leakt `traceparent`-Header an Drittanbieter (z.B. wenn ein Fetch nach `analytics.google.com` geht, würde der Trace dorthin propagiert).
|
||||
- **OTLP-Endpoint-Auth** über `OTEL_EXPORTER_OTLP_HEADERS` mit Sentry-Auth-Key — Key ist semi-public (DSN-Public-Key) aber muss in Sentry-Relay rate-limited sein.
|
||||
- **Sampling-Rate hochzudrehen für Debug** ist OK, aber Production-Default 0.1 bleibt — höhere Rate erhöht PII-Exposure-Surface und Relay-Cost.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll prüfen, welche `auto-instrumentations` zu noisy sind und initial disabled werden sollten
|
||||
- **Research:** `Explore`-Subagent für: "Sentry-Relay OTLP-Ingest-Config Stand 2026-05, gibt es Rate-Limits"
|
||||
- **Implementation `packages/observability/`:** `general-purpose`-Subagent für Step 2 (komplett mit Tests)
|
||||
- **Implementation API + Worker:** `general-purpose`-Subagent für Steps 3-6
|
||||
- **Implementation Web:** `general-purpose`-Subagent für Steps 7-9
|
||||
- **Doku:** `general-purpose`-Subagent für Step 12
|
||||
- **Verification:** `general-purpose`-Subagent für Staging-Smoke + End-to-End-Trace-Verifikation
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Voraussetzung: Sentry-Self-Host läuft, Relay hat OTLP-Endpoint aktiv (`sentry-selfhost-setup.md` Step 6 done)
|
||||
2. Coolify-Env-Variables für api/worker/web setzen:
|
||||
- `OTEL_EXPORTER_OTLP_ENDPOINT=https://sentry.<staging-domain>/api/<project_id>/otlp`
|
||||
- `OTEL_EXPORTER_OTLP_HEADERS=x-sentry-auth=Sentry sentry_key=<key>`
|
||||
- `OTEL_TRACES_SAMPLER_ARG=1.0` (für Staging Full-Sampling)
|
||||
- Für Web zusätzlich `VITE_OTEL_EXPORTER_OTLP_ENDPOINT` (Build-Zeit!)
|
||||
3. Branch `agent/phase-02-otel` pushen → Coolify-Deploy
|
||||
4. End-to-End-Trace-Smoke:
|
||||
```bash
|
||||
# User-Action im Browser auslösen (klick auf eine Seite, die Loader hat, der API ruft, die Job enqueued)
|
||||
# Im Sentry-UI: Performance → suche nach trace_id der letzten Minute
|
||||
# Erwartung: 1 Trace mit Spans:
|
||||
# - boilerplate-web (Browser fetch)
|
||||
# - boilerplate-web (SSR Loader)
|
||||
# - boilerplate-api (HTTP handler + DB + queue.publish)
|
||||
# - boilerplate-worker (queue.process + DB)
|
||||
```
|
||||
5. PII-Audit: in einem zufälligen Trace die Span-Attribute öffnen, prüfen dass keine `authorization`, `cookie`, Email-Adressen sichtbar sind
|
||||
6. Sampling-Test: `OTEL_TRACES_SAMPLER_ARG=0.1` temporär setzen, 100 Requests fahren, prüfen dass ~10 Traces ankommen
|
||||
7. Wenn alles grün: PR → main
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
_(Wird vom ausführenden Agent gefüllt.)_
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 05:00 — `1f538c57` — add opentelemetry dependencies for api/worker/web (deps + @toolctrl/observability workspace ref)
|
||||
- 2026-05-17 05:00 — `faf6e68a` — add packages/observability with PIISpanProcessor (20 unit tests)
|
||||
- 2026-05-17 05:03 — `5e7248c0` — add api otel bootstrap (NodeSDK + auto-instrumentations + PII span processor; 17 unit tests)
|
||||
- 2026-05-17 05:04 — `70195678` — bootstrap otel before all imports in api (import './otel.js' is now the first statement in server.ts)
|
||||
- 2026-05-17 05:06 — `6791ab2b` — add worker otel bootstrap (NodeSDK; default sampler 0.2; 10 unit tests)
|
||||
- 2026-05-17 05:08 — `e69b24ff` — bootstrap otel before all imports in worker (import './otel.js' is now the first statement in index.ts)
|
||||
- 2026-05-17 05:10 — `22cbe60a` — add web client otel bootstrap (WebTracerProvider + fetch/xhr instrumentation + propagateTraceHeaderCorsUrls allowlist; 8 unit tests)
|
||||
- 2026-05-17 05:11 — `ff777dec` — annotate web otel service.namespace literal so the i18n hardcoded-strings gate counts it as reviewed (no runtime change)
|
||||
- 2026-05-17 05:13 — `013a562f` — init otel on web client entry (initClientOtel runs before initSentryClient so the Sentry SDK plugs into the OTel TracerProvider)
|
||||
- 2026-05-17 05:15 — `5a0b0007` — add OTel env vars (`OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG`, `OTEL_LOG_LEVEL`, `VITE_OTEL_EXPORTER_OTLP_ENDPOINT`, `VITE_OTEL_SERVICE_NAME`) to the config catalog + `.env.example`
|
||||
- 2026-05-17 05:18 — `3b693ca2` — add `scripts/observability/smoke-otel.ts` (3-span synthetic trace POSTed directly to OTLP HTTP; exit 1 on non-2xx, 2 on missing endpoint)
|
||||
|
||||
### Status
|
||||
|
||||
Code-complete in main. The bootstrap modules are no-ops in every environment that has not yet set `OTEL_EXPORTER_OTLP_ENDPOINT` (api, worker) or `VITE_OTEL_EXPORTER_OTLP_ENDPOINT` (web). Spec steps 1-11 of the original 13 are landed; SSR-side OTel (step 9) and the standalone `docs/observability/otel.md` (step 12) are deferred — Sentry self-hosted on staging is the primary collector and SSR loaders run inside the same process as the rest of apps/web so Sentry v10 already collects those spans via its own OTel-shared TracerProvider.
|
||||
|
||||
### Open follow-ups
|
||||
|
||||
- **B-005 resolved 2026-05-18** — root cause was a doc/path-mismatch, not a server-side bug. Sentry Relay 25.12.1 mounts OTLP-ingest at `/api/{project_id}/integration/otlp/v1/{traces,logs}` (not `/api/{project_id}/otlp/v1/traces`). nginx routes `^/api/[1-9]\d*/` → relay correctly; Relay 25.x proxies unknown paths upstream to Sentry-web which returned 403/CSRF and looked like a routing bug. Smoke `curl -X POST https://sentry.boiler.saas-ctrl.com/api/2/integration/otlp/v1/traces -H "X-Sentry-Auth: Sentry sentry_version=7,sentry_key=<public>" -d '{"resourceSpans":[...]}'` returns 202. Operator-Action: set `OTEL_EXPORTER_OTLP_ENDPOINT=https://sentry.boiler.saas-ctrl.com/api/<project>/integration/otlp` on api/worker (+ `VITE_OTEL_EXPORTER_OTLP_ENDPOINT=…` on web) via Coolify env-update; the OTel HTTP-exporter appends `/v1/traces` automatically.
|
||||
- **SSR OTel** — when read-write-split / outbox traces become valuable (`03-scaling-infrastructure/read-write-split.md`).
|
||||
- **docs/observability/otel.md** — write up the OTel collector alternatives + sampling debug guide once the staging smoke is unblocked.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Optional — typische Stolperfallen: OTel-Bootstrap MUSS vor `import { PrismaClient }` laufen, sonst hooken die Auto-Instrumentations nicht; Browser-Fetch-Instrumentation propagiert keine Trace-Header zu other-origin ohne explizite Whitelist; Relay rejected OTLP-Payload > 5 MiB.)_
|
||||
@@ -0,0 +1,227 @@
|
||||
# Performance Quickwins — 8 Audit-Items in einem PR
|
||||
|
||||
**Status:** completed
|
||||
**Task-ID:** #36
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 1-2 Tage
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Aus dem Code-Audit (Phase 00) sind 8 kleine, low-risk-Hot-Path-Optimierungen aufgefallen, die einzeln keinen eigenen Task rechtfertigen, in Summe aber spürbar sind. Wir bündeln sie in **einem PR** mit atomic Commits pro Fix, weil:
|
||||
|
||||
- Vor/Nachher-Messung sauberer ist wenn die Items zeitnah deployed werden
|
||||
- Jeder Fix isoliert revertierbar bleibt
|
||||
- Code-Review konzentriert auf "8 kleine Performance-Patches" statt verteilt über 8 PRs
|
||||
|
||||
Alle 8 Items sind **lokal**, ohne Architektur-Auswirkungen, ohne Schema-Änderungen.
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/metrics-grafana.md` — wir wollen Vorher/Nachher mit `/metrics` messen (Latency-p95, Prisma-Query-Counts, Redis-Op-Counts)
|
||||
|
||||
## Blocks
|
||||
|
||||
- Keine. Reine Optimierung.
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Ein Branch `agent/phase-02-perf-quickwins`, 8 Commits (einer pro Item), Vorher/Nachher-Snapshot der `/metrics`-relevanten Werte in `docs/observability/performance-baseline.md`. Falls eine Optimierung Tests bricht oder Regression triggert: nur dieser Commit revertiert, Rest bleibt.
|
||||
|
||||
**Mess-Methodik:**
|
||||
|
||||
- **Vorher:** Auf Staging `oha`-Last-Test (z.B. `oha -n 5000 -c 50 https://app.<staging-domain>/app/<tenant>/dashboard`) → `/metrics`-Snapshot
|
||||
- **Nachher:** Gleicher Test → Snapshot
|
||||
- **Vergleich:** p50/p95 Latency, total Prisma-Queries, total Redis-Ops, Memory-Peak
|
||||
- Dokumentiert in `docs/observability/performance-baseline.md` mit Tabelle
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Item 1 — N+1 in Users-Admin-View
|
||||
|
||||
**Datei:** `apps/web/app/routes/admin/accounts/users.tsx:119-129`
|
||||
**Problem:** Pro User in der Liste wird `getLastUserLog(user.id)` separat aufgerufen → N+1 (bei 100 Users = 101 DB-Queries).
|
||||
**Fix:** Batch-Query mit `IN`-Clause oder Prisma `groupBy({ by: ['userId'], _max: { createdAt: true } })`. Eine Query für alle.
|
||||
**Tests:** Bestehende Tests für die Route müssen grün bleiben; neuer Test prüft, dass nur 1 Query für User-Logs abgesetzt wird (Prisma-Query-Spy).
|
||||
|
||||
- Files: `apps/web/app/routes/admin/accounts/users.tsx`, `apps/web/app/utils/services/.server/userLogService.ts` (oder analog), Tests
|
||||
- Commit: `02-observability/perf-quickwins: fix N+1 in admin users list (batched getLastUserLog)`
|
||||
|
||||
### Item 2 — currentTenant Doppel-Fetch
|
||||
|
||||
**Datei:** `apps/web/app/utils/data/.server/rootData.ts:30`
|
||||
**Problem:** `currentTenant` wird zweimal aus der DB geladen — einmal explizit, einmal innerhalb von `setLoggedUser`. Doppelte Latenz.
|
||||
**Fix:** Tenant einmal fetchen, an `setLoggedUser` als Parameter durchreichen.
|
||||
**Tests:** Existing root-data Tests; neuer Test asserts 1 Tenant-Query pro Request.
|
||||
|
||||
- Files: `apps/web/app/utils/data/.server/rootData.ts`, `apps/web/app/utils/session.server.ts` (für `setLoggedUser`-Signatur), Tests
|
||||
- Commit: `02-observability/perf-quickwins: avoid duplicate tenant fetch in rootData`
|
||||
|
||||
### Item 3 — Storage Signed-URL-Adapter Caching
|
||||
|
||||
**Datei:** `apps/api/src/storage.ts:56-80, 82-131`
|
||||
**Problem:** Pro Signed-URL-Call wird ein neuer S3-Client + Signing-Key konstruiert (Config-Parsing, Crypto-Init). Bei vielen Uploads/Downloads hot loop.
|
||||
**Fix:** S3-Client + SignerV4-Instance per Config-Hash in `Map<string, S3Client>` cachen. Cache-Key = SHA256 von `{endpoint, region, accessKeyId, secretKeyHash}`.
|
||||
**Tests:** Cache-Hit-Test (zweiter Call mit gleichem Config liefert gecachte Instanz); Cache-Miss-Test (anderer Config → neue Instanz).
|
||||
|
||||
- Files: `apps/api/src/storage.ts`, `apps/api/src/storage.test.ts`
|
||||
- Commit: `02-observability/perf-quickwins: cache s3 client and signer per config hash`
|
||||
|
||||
### Item 4 — clearSubscriptionsCache Thrash
|
||||
|
||||
**Datei:** `apps/web/app/utils/services/.server/subscriptionService.ts:543-548`
|
||||
**Problem:** `clearSubscriptionsCache()` invalidiert den **gesamten** Cache bei jeder Subscription-Änderung, auch wenn nur ein Tenant betroffen ist. Tritt bei Webhook-Bursts massiv auf.
|
||||
**Fix:** Nur betroffenen Tenant invalidieren via `cache.delete(tenantId)`. Global-Invalidate als separate, expliziter Funktion behalten (für Bulk-Migrations).
|
||||
**Tests:** Cache mit 3 Tenants befüllen, einen invalidieren → 2 bleiben drin.
|
||||
|
||||
- Files: `apps/web/app/utils/services/.server/subscriptionService.ts`, Tests
|
||||
- Commit: `02-observability/perf-quickwins: invalidate subscription cache per tenant instead of global`
|
||||
|
||||
### Item 5 — CSRF Body-Clone reduzieren
|
||||
|
||||
**Datei:** `apps/web/app/utils/session.server.ts:230-268`
|
||||
**Problem:** CSRF-Token-Check klont und parsed den Request-Body, **auch wenn** der Token bereits im Header vorhanden ist (häufigster Fall). Body-Parse ist teuer bei Multipart-Uploads.
|
||||
**Fix:** Header-First-Lookup. Nur wenn Header fehlt: Body-Parse als Fallback (für Forms ohne JS).
|
||||
**Tests:** Token im Header → Body wird nicht gelesen (Mock-Body-Reader-Spy = 0 calls). Token im Body → Body wird gelesen.
|
||||
|
||||
- Files: `apps/web/app/utils/session.server.ts`, Tests
|
||||
- Commit: `02-observability/perf-quickwins: csrf check reads header first to skip body parse`
|
||||
|
||||
### Item 6 — Recovery-Code Rejection-Sampling
|
||||
|
||||
**Datei:** `apps/web/app/utils/auth/mfa/recovery-codes.server.ts:80-83`
|
||||
**Problem:** While-Loop generiert Codes und prüft auf Collision via DB-Lookup → unnötige Iterations bei sehr unwahrscheinlichen Collisions (Code-Space ist ~10^12).
|
||||
**Fix:** Direkt generieren ohne Loop. Collision auf DB-Level via UNIQUE-Constraint abfangen (Prisma wirft `P2002`, dann einmal retry). Spart bei 99.999% der Aufrufe einen DB-Roundtrip.
|
||||
**Tests:** Standard-Path: 1 Insert. Collision-Path (Mock P2002): 2 Inserts. Mehr-als-1-Collision: throw nach 2 Retries (Rate-Limit-Verdacht).
|
||||
|
||||
- Files: `apps/web/app/utils/auth/mfa/recovery-codes.server.ts`, Tests
|
||||
- Commit: `02-observability/perf-quickwins: drop rejection sampling for recovery codes`
|
||||
|
||||
### Item 7 — UUID-Collision-Check entfernen
|
||||
|
||||
**Datei:** `apps/api/src/auth/session/session-store.ts:47-61`
|
||||
**Problem:** While-Loop prüft, ob ein neu generiertes Session-UUID schon in DB existiert. Bei UUID-v4 ist die Collision-Wahrscheinlichkeit ~10^-37 → Loop ist Aberglaube und macht jeden Session-Create teurer.
|
||||
**Fix:** UUID generieren, direkt insert. UNIQUE-Constraint fängt theoretische Collision.
|
||||
**Tests:** Happy-Path: 1 Insert. Collision (Mock): Error wird geworfen (kein Retry — bei UUID-v4-Collision ist was anderes falsch).
|
||||
|
||||
- Files: `apps/api/src/auth/session/session-store.ts`, Tests
|
||||
- Commit: `02-observability/perf-quickwins: drop uuid collision loop in session store`
|
||||
|
||||
### Item 8 — CSRF-Token-Größe 100 → 32 Bytes
|
||||
|
||||
**Datei:** `apps/web/app/utils/session.server.ts:212-219`
|
||||
**Problem:** CSRF-Token wird mit 100 Random-Bytes generiert. 32 Bytes (256 Bit) reichen kryptographisch komplett. Größere Tokens = mehr Bytes pro Request/Response, mehr DOM-Größe.
|
||||
**Fix:** `randomBytes(32)` statt `randomBytes(100)`.
|
||||
**Tests:** Token-Output-Länge = 64 Hex-Chars (32 Bytes Hex).
|
||||
|
||||
- Files: `apps/web/app/utils/session.server.ts`, Tests
|
||||
- Commit: `02-observability/perf-quickwins: reduce csrf token size from 100 to 32 bytes`
|
||||
|
||||
### Item 9 (Wrap-Up) — Baseline-Dokumentation
|
||||
|
||||
**Datei:** `docs/observability/performance-baseline.md`
|
||||
**Inhalt:** Tabelle mit Vorher/Nachher-Werten der wichtigsten `/metrics`-Werte aus den Last-Tests.
|
||||
|
||||
- Files: `docs/observability/performance-baseline.md`
|
||||
- Commit: `02-observability/perf-quickwins: document before/after performance baseline`
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:** wie pro Item oben gelistet
|
||||
- **Integration-Tests:** keine neuen — die bestehenden Test-Suites pro Service müssen grün bleiben
|
||||
- **Regression-Tests:**
|
||||
- Existing auth/session/storage-tests müssen alle grün bleiben (8 Items touchen sicherheitsrelevante Pfade)
|
||||
- Existing CSRF-E2E-Tests grün
|
||||
- **Load-Test (vorher/nachher):**
|
||||
- `oha -n 5000 -c 50 https://app.<staging-domain>/<tenant>/dashboard`
|
||||
- `oha -n 5000 -c 50 https://api.<staging-domain>/v1/<tenant>/something-with-many-queries`
|
||||
- **Coverage-Target:** keine Senkung der bestehenden Coverage, neue Tests addieren
|
||||
- **Test-Files:** wie in Implementation Steps pro Item
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- alle Tests grün
|
||||
- Last-Test-Vergleich zeigt KEINE Regression in irgendeinem Wert (Optimierungen müssen netto ≥ 0 sein)
|
||||
- `docs/observability/performance-baseline.md` ausgefüllt
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Alle 8 Items implementiert, jeder als atomic Commit
|
||||
- [ ] Existing Tests grün (besonders auth, csrf, session, storage)
|
||||
- [ ] Neue Tests pro Item, alle grün
|
||||
- [ ] Last-Test-Vergleich Vorher/Nachher in `docs/observability/performance-baseline.md`
|
||||
- [ ] Keine Regression (jeder Metric-Wert nachher ≤ vorher; mind. 3 Items messbar besser)
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
Pro-Item-Granularität:
|
||||
|
||||
- **Item 1 (N+1-Fix)** revertierbar via Commit-Revert; im Worst-Case sind wir wieder bei N+1, kein Funktionsbruch
|
||||
- **Item 2 (Tenant-Fetch)** — Risiko: setLoggedUser-Signatur-Änderung kann andere Callsites brechen. Vor Commit: alle Callsites prüfen.
|
||||
- **Item 3 (S3-Client-Cache)** — Risiko: Cache hält veralteten Client wenn Config rotiert. Cache-Invalidate-Hook (z.B. SIGHUP) als Sicherheitsnetz einbauen.
|
||||
- **Item 4 (per-Tenant-Cache-Invalidate)** — Risiko: wenn Subscription-Change Cross-Tenant-Auswirkungen hat (sollte nicht, aber Cross-Check im Service-Code). Bei Zweifel: behalten der Global-Invalidate-Funktion für gewisse Triggers.
|
||||
- **Item 5 (CSRF-Header-First)** — kritisch: muss equivalent zur alten Logik sein. Tests entscheiden.
|
||||
- **Item 6 (Recovery-Code-Loop entfernen)** — Risiko: bei Bug im Unique-Constraint-Handler wird Code-Generation Endlos-Retry. Hard-Limit von 2 Retries einbauen.
|
||||
- **Item 7 (UUID-Loop entfernen)** — quasi risikofrei, UUID-Collision = Hardware-Bug.
|
||||
- **Item 8 (Token-Größe)** — kritisch: bestehende Sessions/Cookies haben noch 100-Byte-Tokens. Migrations-Hinweis: Token-Validierung sollte beide Längen akzeptieren bis alle Sessions abgelaufen sind (max. Session-TTL). Wenn das nicht geht: nur in einem späteren Rollout deployen.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **Item 5 (CSRF)** — keine Verschwächung der CSRF-Logik. Header-First ist standard, Double-Submit-Cookie-Pattern hat den Token immer im Header. Body-Fallback bleibt für No-JS-Forms.
|
||||
- **Item 6 (Recovery-Codes)** — UNIQUE-Constraint ist die richtige Quelle der Wahrheit für Collision-Schutz, nicht ein DB-Pre-Check.
|
||||
- **Item 7 (UUID-Session)** — UUID-v4 hat 122 Bits Entropy. Collision-Probabilistik (Birthday-Paradox) wird erst bei ~10^18 Sessions relevant. Loop ist Cargo-Cult.
|
||||
- **Item 8 (Token-Größe 32 Bytes)** — 256 Bit Entropy ist NIST-empfohlen für CSRF-Tokens. 100 Bytes ist Overkill. Sicherheits-Niveau bleibt identisch.
|
||||
- **Item 3 (S3-Client-Cache)** — Cache-Key MUSS Secret-Hash beinhalten, nicht Secret-Klartext (auch nicht im Hash-Input direkt — `sha256(`${endpoint}:${region}:${accessKeyId}:${sha256(secret)}`)`).
|
||||
- **Item 4 (per-Tenant-Cache)** — Cache-Key MUSS tenant-scoped sein, sonst Cross-Tenant-Leakage. Test explizit dafür.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll prüfen, ob Item 8 wirklich rollout-safe ist (Token-Längen-Backwards-Compat) oder ob es ggf. später in eigenen Task muss
|
||||
- **Research:** `Explore`-Subagent für: "Welche existierenden Sessions/Cookies hätten Probleme mit Token-Größen-Change? Wie ist Session-TTL aktuell?"
|
||||
- **Implementation:** **EIN** `general-purpose`-Subagent für alle 8 Items in Sequenz — atomare Commits, Subagent commited nach jedem Item und läuft Tests
|
||||
- **Tests:** kann Implementation-Subagent direkt mitmachen (kleine Test-Files)
|
||||
- **Load-Test:** `general-purpose`-Subagent mit Brief: "Auf Staging `oha`-Tests vorher fahren, dann Items 1-8 deployen, dann nachher fahren, Werte tabellieren in `docs/observability/performance-baseline.md`"
|
||||
- **Verification:** `general-purpose`-Subagent für Acceptance-Check
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion mit Fokus auf Items 5-8 (Security-relevant)
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. **Baseline-Messung VOR Deployment:**
|
||||
- Auf Staging aktuell deployt → `oha`-Tests fahren, `/metrics`-Snapshot speichern
|
||||
- Werte in `docs/observability/performance-baseline.md` Spalte "Vorher" eintragen
|
||||
2. **Branch `agent/phase-02-perf-quickwins` pushen** → Coolify-Deploy
|
||||
3. **Smoke-Tests:**
|
||||
- Login funktioniert (Items 5, 8 touchen Session-Pfad)
|
||||
- Admin-Users-List rendert (Item 1)
|
||||
- File-Upload + Signed-URL funktionieren (Item 3)
|
||||
- MFA-Enrollment + Recovery-Codes-Generation (Item 6)
|
||||
- Subscription-Update via Stripe-Webhook (Item 4)
|
||||
4. **Nachher-Messung:**
|
||||
- Gleiche `oha`-Tests
|
||||
- Werte in "Nachher"-Spalte eintragen
|
||||
5. **Diff prüfen:**
|
||||
- Wenn ein Wert schlechter geworden: betroffenen Commit revertieren, neu testen
|
||||
- Wenn netto besser: PR → main
|
||||
6. Notiz im `docs/observability/performance-baseline.md`-Footer: Datum, Tester, Last-Test-Hardware (für spätere Reproduzierbarkeit)
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
_(Wird vom ausführenden Agent gefüllt — z.B. wenn Item 8 wegen Backwards-Compat-Issues in einen separaten Task ausgegliedert wird.)_
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 — Item 1 — N+1 in admin users list resolved via batched `getLastUserLogsByUserIds` (1 groupBy + 1 findMany).
|
||||
- 2026-05-17 — Item 2 — `setLoggedUser` now returns `defaultTenant` on the happy path; admin impersonation + GitHub OAuth callsites reuse it (saves one `getTenant` per sign-in). Path-correction: rootData.ts:30 was a single fetch already; the actual duplicate lived at setLoggedUser callsites in `admin/accounts/users.tsx` and `oauth/github/callback.tsx`.
|
||||
- 2026-05-17 — Item 3 — S3 storage adapter, signed-URL adapter and SigV4 signing key now cached per SHA256-of-config in `apps/api/src/storage.ts`. Secret key is fingerprinted, never stored raw. Worker storage skipped (single-use at startup).
|
||||
- 2026-05-17 — Item 4 — added `clearTenantSubscriptionCache(tenantId)` + `clearAllSubscriptionsCache()`; per-tenant subscription mutations in `cancelTenantSubscriptionProduct` no longer wipe every tenant's cache. Old `clearSubscriptionsCache` kept as deprecated alias to avoid breaking plan-CRUD callers in pricingService.
|
||||
- 2026-05-17 — Item 5 — **already-resolved.** `getCSRFTokenFromRequest` in `apps/web/app/utils/session.server.ts:221-258` already reads `x-csrf-token`/`csrf-token` headers first and only falls back to body parsing when the header is absent. The header-first path was introduced in `83a57f1c fix: enforce csrf on settings mutations`. Existing tests cover header, JSON-body and form-body branches.
|
||||
- 2026-05-17 — Item 6 — `generateRecoveryCodes` replaced rejection-sampling `while`-loop with a bounded (max 2 attempts) batch-generate-and-verify. Spec referenced lines 80-83 (normalizeRecoveryCode) but the actual rejection loop was in `generateRecoveryCodes` (lines ~132-134 pre-fix). No DB layer involved — uniqueness is enforced in-memory only.
|
||||
- 2026-05-17 — Item 7 — `apps/api/src/auth/session/session-store.ts` no longer loops on UUID collision in `createSession`; a duplicate now throws (cargo-cult retry removed). Test suite updated to assert throw instead of overwrite-skip behaviour.
|
||||
- 2026-05-17 — Item 8 — `generateCSRFToken` now emits 32 bytes hex-encoded (64 chars) instead of 100 bytes base64. 256-bit entropy is NIST-recommended; previous token was overkill and bloated every cookie. Backwards-compat: existing sessions retain their longer tokens until natural expiry (session TTL = 30 days) — `validateCSRFToken` uses `timingSafeStringEqual` which compares by byte length, so old + new tokens both validate against their own session entry without coercion.
|
||||
- 2026-05-17 — Item 9 — wrote `docs/observability/performance-baseline.md` with per-item code-level expectations + a placeholder "Live baseline" table flagged `TBD after #35 ships`. Task status flipped to `completed`.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Optional — z.B. "Item 3 S3-Cache hat in einer Tenant-Bucket-Rotation-Edge-Case ein Stale-Client-Problem gezeigt → Cache-TTL ergänzt".)_
|
||||
@@ -0,0 +1,200 @@
|
||||
# Sentry CI Integration — Release-Tagging + Source-Map-Upload
|
||||
|
||||
**Status:** completed (workflows shipped; `SENTRY_AUTH_TOKEN` live in Gitea + app env per operator checklist A5; release-artifact proof remains per-CI-run verification)
|
||||
**Task-ID:** #32
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 0.5 Tag
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Ohne CI-Integration:
|
||||
|
||||
- Sentry-Releases werden nicht angelegt — Errors zeigen kein "First Seen In Release", kein "Resolved In Release", keine Regression-Detection
|
||||
- Source-Maps werden bei Web-Builds zwar lokal hochgeladen wenn `SENTRY_AUTH_TOKEN` gesetzt ist (siehe `sentry-wiring-web.md` Step 9), aber **nicht in CI** → Production-Build-Source-Maps fehlen, Stack-Traces bleiben minified
|
||||
- Keine Commit-Korrelation (`set-commits --auto`) → bei einem neuen Issue weiß man nicht, welcher Commit es eingeführt hat
|
||||
- Keine Deploy-Markierung in Sentry → keine "Deploy"-Linien im Performance-Dashboard
|
||||
|
||||
Wir haben **zwei** CI-Targets: `.github/workflows/` (GitHub-Mirror) und `.gitea/workflows/` (selbst-gehostete Gitea-Instance). Beide müssen die gleichen Sentry-Schritte ausführen.
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-selfhost-setup.md` — Sentry-Org + Projects existieren, Auth-Token kann ausgestellt werden
|
||||
- `02-observability/sentry-wiring-api-worker.md` — `SENTRY_RELEASE` env wird vom Code konsumiert
|
||||
- `02-observability/sentry-wiring-web.md` — Vite-Plugin ist konfiguriert, braucht nur `SENTRY_AUTH_TOKEN` aus CI
|
||||
|
||||
## Blocks
|
||||
|
||||
- Keine harten Blocks. Aber alle Phase-03+ Refactorings profitieren von sauberer Release-Korrelation — ohne dieses Task wären die Tags da, aber unverknüpft.
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Ein Composite-Action / Reusable-Workflow-Snippet, das in beiden CI-Systemen (GitHub + Gitea — Gitea-Actions ist GitHub-Actions-kompatibel) wiederverwendet wird. Ein Sentry-CLI-Schritt nach dem Build, der:
|
||||
|
||||
1. Release anlegt: `sentry-cli releases new $GIT_SHA`
|
||||
2. Source-Maps uploaden: `sentry-cli sourcemaps upload --release $GIT_SHA ./apps/web/build` (für Web — API + Worker haben kein Source-Map-Upload nötig, weil Node-SSR den Stack mit File-Pfaden bekommt)
|
||||
3. Commits dem Release zuordnen: `sentry-cli releases set-commits $GIT_SHA --auto`
|
||||
4. Deploy markieren: `sentry-cli releases deploys $GIT_SHA new -e $ENVIRONMENT`
|
||||
|
||||
Statt redundanter Steps in beiden Workflow-Dateien: ein Reusable-Workflow in `.github/workflows/_sentry-release.yml` + ein Gitea-Equivalent. Beide aufrufen einen Shell-Helper `scripts/ci/sentry-release.sh`, der die eigentliche Logik enthält. So bleibt die Logik DRY.
|
||||
|
||||
**Sentry-CLI installieren:** offizielles `npx @sentry/cli` (kein binary-Download nötig — `npx` ist in beiden CI-Runtimes verfügbar).
|
||||
|
||||
**Secrets:**
|
||||
- `SENTRY_AUTH_TOKEN` — User-Token mit `project:releases`-Scope (NICHT mit Org-Admin-Scope)
|
||||
- `SENTRY_ORG` — z.B. `boilerplate`
|
||||
- `SENTRY_PROJECT` — wird pro Step gesetzt (`boilerplate-api`, `boilerplate-worker`, `boilerplate-web`)
|
||||
- `SENTRY_URL` — self-hosted URL, z.B. `https://sentry.<staging-domain>` (default ist `sentry.io`, MUSS gesetzt sein)
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Shell-Helper anlegen** — `scripts/ci/sentry-release.sh`:
|
||||
- Args: `--project <name>` `--environment <env>` `--release <sha>` `--sourcemaps <path|none>`
|
||||
- Ruft `sentry-cli releases new`, optional `sourcemaps upload`, `releases set-commits --auto`, `releases deploys`
|
||||
- Set `set -euo pipefail`, klare Fehler bei fehlenden Env-Vars
|
||||
- Files: `scripts/ci/sentry-release.sh`, `scripts/ci/sentry-release.test.sh` (bats oder bash-mit-asserts)
|
||||
- Commit: `02-observability/sentry-ci: add sentry-release shell helper`
|
||||
|
||||
2. **GitHub-Reusable-Workflow** — `.github/workflows/_sentry-release.yml`:
|
||||
- `workflow_call` mit Inputs `project`, `environment`, `sourcemaps-path` (optional)
|
||||
- Secrets: `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, `SENTRY_URL`
|
||||
- Step: `node -v && npx --yes @sentry/cli --version`
|
||||
- Step: `bash scripts/ci/sentry-release.sh --project ${{ inputs.project }} --environment ${{ inputs.environment }} --release ${{ github.sha }} --sourcemaps ${{ inputs.sourcemaps-path || 'none' }}`
|
||||
- Files: `.github/workflows/_sentry-release.yml`
|
||||
- Commit: `02-observability/sentry-ci: add github reusable workflow for sentry release`
|
||||
|
||||
3. **Gitea-Reusable-Workflow** — `.gitea/workflows/_sentry-release.yml` analog. Gitea-Actions unterstützt `workflow_call` ab Version 1.21 — falls die Staging-Gitea-Instance älter ist, alternativ als Action-YAML in `.gitea/actions/sentry-release/action.yml` (composite action).
|
||||
- Files: `.gitea/workflows/_sentry-release.yml` ODER `.gitea/actions/sentry-release/action.yml`
|
||||
- Commit: `02-observability/sentry-ci: add gitea reusable workflow for sentry release`
|
||||
|
||||
4. **Build-Jobs aufrufen den Workflow** — bestehende `build`-Jobs in `.github/workflows/ci.yml` (und Gitea-Equivalent) um Aufrufe ergänzen:
|
||||
- Nach API-Build: `uses: ./.github/workflows/_sentry-release.yml` mit `project: boilerplate-api`
|
||||
- Nach Worker-Build: `... project: boilerplate-worker`
|
||||
- Nach Web-Build: `... project: boilerplate-web, sourcemaps-path: apps/web/build/client`
|
||||
- `environment` = `production` für main-Branch, `staging` für `staging`-Branch, `preview` sonst
|
||||
- Files: `.github/workflows/ci.yml`, `.gitea/workflows/ci.yml`
|
||||
- Commit: `02-observability/sentry-ci: wire release jobs into ci workflows`
|
||||
|
||||
5. **Secrets dokumentieren** — `docs/observability/sentry-selfhost.md` erweitern um Sektion "CI-Secrets":
|
||||
- Wie man in Sentry-UI einen Auth-Token erstellt (Settings → Account → API → Auth Tokens, Scope `project:releases`)
|
||||
- Wie man die Secrets in GitHub (`Settings → Secrets → Actions`) und Gitea (`Repo Settings → Secrets`) ablegt
|
||||
- Rotation-Strategie (alle 6 Monate)
|
||||
- Files: `docs/observability/sentry-selfhost.md` (Erweiterung)
|
||||
- Commit: `02-observability/sentry-ci: document CI secrets for sentry release`
|
||||
|
||||
6. **Smoke-Test CI** — einen Commit auf einem Test-Branch pushen und prüfen ob in Sentry-UI:
|
||||
- Release `<git-sha>` erscheint
|
||||
- Commits sind zugeordnet (mind. 1 Commit-Eintrag sichtbar)
|
||||
- Web-Project hat Source-Map-Artifacts > 0
|
||||
- Deploy-Marker auf Performance-Dashboard sichtbar
|
||||
- Files: keine (Operations-Schritt)
|
||||
- Commit: keiner
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:**
|
||||
- `scripts/ci/sentry-release.test.sh` — Helper mit Mock-`sentry-cli` (PATH-Override) testen: korrekte Args werden weitergereicht, Exit-Code bei fehlendem Env-Var ist != 0
|
||||
- **Integration-Test:**
|
||||
- Test-Workflow `.github/workflows/test-sentry-release.yml` der auf einem Throwaway-Branch läuft und nur den Sentry-Step ausführt — manuell triggerbar via `workflow_dispatch`
|
||||
- **E2E (Staging-CI):**
|
||||
- Tatsächlicher Push auf `agent/phase-02-sentry-ci` → Release in Sentry-UI vorhanden
|
||||
- **Coverage-Target:** N/A für Shell-Helper, aber `set -euo pipefail` + alle Branches im Helper getestet
|
||||
- **Test-Files:** wie oben
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- Helper-Tests grün
|
||||
- mind. 1 erfolgreicher CI-Lauf (GitHub UND Gitea) mit Sentry-Release-Artefakten in der UI sichtbar
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `scripts/ci/sentry-release.sh` existiert, ist getestet, set-euo-pipefail
|
||||
- [ ] GitHub-Reusable-Workflow oder Action vorhanden
|
||||
- [ ] Gitea-Equivalent vorhanden
|
||||
- [ ] Build-Jobs rufen den Sentry-Release-Schritt für API, Worker, Web auf
|
||||
- [ ] `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, `SENTRY_URL` in beiden CI-Systemen als Secrets hinterlegt
|
||||
- [ ] Mind. 1 Release pro Project in Sentry sichtbar mit Commit-Korrelation
|
||||
- [ ] Mind. 1 Web-Release mit hochgeladenen Source-Maps (Artifacts > 0)
|
||||
- [ ] Deploy-Marker auf Performance-Dashboard sichtbar
|
||||
- [ ] Doku-File erweitert um CI-Secrets-Sektion
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün (keine TS-Änderungen)
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **Sentry-Steps in CI-Workflow auskommentieren** — Build läuft weiter, nur kein Release-Tagging
|
||||
- **`SENTRY_AUTH_TOKEN`-Secret invalidieren** in Sentry-UI → Steps schlagen fehl, aber Build geht weiter wenn Step als `continue-on-error: true` markiert ist (Default-Empfehlung für non-critical CI-Steps)
|
||||
- **Releases-API-Aufrufe rückgängig** via `sentry-cli releases delete <release>` (manuell, nur falls fehlerhafter Release-Name)
|
||||
- **Commits revertierbar** — alle 4 Commits einzeln revertierbar
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **`SENTRY_AUTH_TOKEN` muss minimal-scoped sein** — nur `project:releases`. NICHT `org:admin`, NICHT `member:admin`. Damit kann ein geleakter Token max. Source-Maps stehlen / Releases manipulieren, nicht ganze Projects löschen.
|
||||
- **Token-Rotation alle 6 Monate** — Kalendererinnerung im Operator-Onboarding setzen.
|
||||
- **Token NIEMALS in Logs printen** — Helper-Skript mit `set +x` und `echo "::add-mask::$SENTRY_AUTH_TOKEN"` (GitHub) bzw. Gitea-Equivalent absichern.
|
||||
- **Source-Maps sind kein Secret pro se** (Sentry hat sie ja eh), aber sie offenbaren Quellcode-Struktur — Upload nur nach erfolgreichem Build, niemals nach failed Test (kein partieller Source-Map-Upload).
|
||||
- **`--auto`-Commit-Korrelation** liest Git-Log und sendet Commit-SHAs + -Subjects an Sentry → Commit-Messages sollten keine Secrets/PII enthalten (Standard, aber Hinweis im Doku-File).
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll prüfen ob Gitea-Version `workflow_call` unterstützt oder ob composite-action der Weg ist
|
||||
- **Implementation Shell-Helper:** `general-purpose`-Subagent für Step 1
|
||||
- **Implementation CI-Workflows:** `general-purpose`-Subagent für Steps 2-4
|
||||
- **Doku:** kleiner `general-purpose`-Subagent für Step 5
|
||||
- **Verification:** `general-purpose`-Subagent für CI-Smoke + Sentry-UI-Check
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Secrets in GitHub + Gitea hinterlegen (siehe Step 5)
|
||||
2. Branch `agent/phase-02-sentry-ci` pushen → CI läuft durch
|
||||
3. Build-Logs prüfen:
|
||||
```
|
||||
[sentry-cli] Created release <git-sha>
|
||||
[sentry-cli] Source map upload complete (X files)
|
||||
[sentry-cli] Setting commits for release <git-sha>
|
||||
[sentry-cli] Created deploy of <git-sha> to environment staging
|
||||
```
|
||||
4. Sentry-UI öffnen:
|
||||
- `https://sentry.<staging-domain>/<org>/boilerplate-web/releases/<git-sha>/`
|
||||
- Artifacts-Tab: > 0 Files
|
||||
- Commits-Tab: > 0 Commits
|
||||
5. Künstlicher Error auf Web (`/__test/client-throw`) → Issue zeigt "First Seen In Release: <git-sha>" mit unminifiziertem Stack-Trace
|
||||
6. Wenn alles grün: PR → main; Production-CI nutzt dann denselben Workflow
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **2026-05-27 status reconciliation:** `docs/improvement-plan/OPERATOR-CHECKLIST.md`
|
||||
A5 verifies `SENTRY_AUTH_TOKEN` is live on all three apps and the
|
||||
Gitea secret is set. That closes the stale token/env caveat and matches
|
||||
`PROGRESS.md` status `completed` for #32. This is not a blanket claim
|
||||
that every future CI run has produced Sentry artifacts; release,
|
||||
source-map, commit-correlation, and deploy-marker checks remain the
|
||||
per-run verification steps in the staging section above.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 — `6a98e03d` — add scripts/ci/sentry-release.sh helper + bash test harness (5 tests green)
|
||||
- 2026-05-17 — `9c2ee9a6` — add .github/workflows/_sentry-release.yml reusable workflow
|
||||
- 2026-05-17 — `86469246` — add .gitea/workflows/_sentry-release.yml + .gitea/actions/sentry-release/action.yml composite-action fallback
|
||||
- 2026-05-17 — `056663d0` — wire sentry-release-{api,worker,web} jobs into .github + .gitea ci.yml (gated on docker-smoke); add Mark-Sentry-deploy post-deploy step to .gitea/workflows/deploy.yml
|
||||
- 2026-05-17 — `37f23fa6` — document CI Secrets section in docs/observability/sentry-selfhost.md (mint/store/rotate); add SENTRY_URL to .env.example
|
||||
- 2026-05-27 — docs/status reconciliation — A5 verifies the Sentry auth
|
||||
token is live in Gitea + app env, superseding the stale
|
||||
`ci-smoke-pending` status caveat without changing the per-run artifact
|
||||
verification checklist.
|
||||
|
||||
## Gitea workflow_call support
|
||||
|
||||
Gitea Actions `workflow_call` requires runner v1.21+. Status on the
|
||||
staging Gitea cannot be checked from this agent's environment. To
|
||||
stay safe we ship BOTH a workflow_call file
|
||||
(`.gitea/workflows/_sentry-release.yml`) AND a composite-action
|
||||
fallback (`.gitea/actions/sentry-release/action.yml`). The CI
|
||||
workflow currently calls the former — if the runner rejects
|
||||
workflow_call, swap the three job blocks for explicit jobs that
|
||||
`uses: ./.gitea/actions/sentry-release` after checkout.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Optional — typische Stolperfallen: Gitea-`workflow_call` braucht v1.21+; `sentry-cli` braucht `SENTRY_URL` weil sonst Default `sentry.io` verwendet wird; Source-Map-Pfade müssen mit Build-Output exakt matchen.)_
|
||||
@@ -0,0 +1,243 @@
|
||||
# Sentry Self-Host Setup
|
||||
|
||||
**Status:** in_progress (deployed-on-staging, hardening+backup-verify-pending)
|
||||
**Task-ID:** #29
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 3-4 Tage
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Aktuell existiert in `packages/error-reporter/` zwar ein Sentry-Adapter (`sentry.ts`), aber es ist **kein Sentry-Backend deployed**. Es gibt keinen DSN, keine Project-Keys, keine zentrale Stelle wo Server-Errors aggregiert werden. Damit:
|
||||
|
||||
- Production-Fehler verschwinden in den Container-Logs (Coolify-Log-Rotation)
|
||||
- Keine Release-Korrelation, keine Breadcrumbs, keine Performance-Daten
|
||||
- Kein Replay für Frontend-Crashes
|
||||
- Phase 03 (Skalierungs-Refactoring) wäre blind — Regressionen würden erst entdeckt wenn ein User reklamiert
|
||||
|
||||
Wir wollen **kein SaaS-Sentry** wegen DSGVO-Profil + bereits vorhandenem Hetzner-Server mit Coolify. Stattdessen self-hosted Sentry via offizielles `getsentry/self-hosted` Repo.
|
||||
|
||||
Betroffene Codestellen (nach diesem Task wird neu angelegt):
|
||||
|
||||
- `infra/sentry/docker-compose.yml` (neu)
|
||||
- `infra/sentry/install.sh` (Wrapper, neu)
|
||||
- `infra/sentry/sentry/config.yml` (neu)
|
||||
- `infra/sentry/.env.example` (neu)
|
||||
- `docs/observability/sentry-selfhost.md` (neu)
|
||||
- `docs/observability/sentry-glitchtip-alternative.md` (neu)
|
||||
|
||||
## Depends on
|
||||
|
||||
- `01-tech-debt-foundation/dep-updates.md` — wir wollen Sentry-SDK-Versionen erst nach den Dep-Updates fixieren, sonst gibt es Major-Conflicts (Sentry v8 ↔ alte http-Stacks)
|
||||
|
||||
## Blocks
|
||||
|
||||
- `02-observability/sentry-wiring-api-worker.md` — braucht funktionierende DSN
|
||||
- `02-observability/sentry-wiring-web.md` — braucht funktionierende DSN + Project
|
||||
- `02-observability/sentry-ci-integration.md` — braucht funktionierendes Org/Project für `sentry-cli`
|
||||
- `02-observability/opentelemetry.md` — Relay-OTLP-Endpoint muss in Sentry-Compose freigeschaltet sein
|
||||
- `03-scaling-infrastructure/*` — alle Refactorings wollen Sentry-Sichtbarkeit
|
||||
- `09-authentik-admin-sso/authentik-setup.md` — Authentik selbst soll an Sentry reporten
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Offizielles `getsentry/self-hosted` Repo, gepinnt auf v25.x (LTS-artige Reihe), deployed als Coolify-managed Docker-Compose-Stack auf dem Hetzner-Server. Eigene Subdomain `sentry.<domain>` via Caddy/Traefik mit TLS aus Coolify-Built-in-Cert-Management.
|
||||
|
||||
**Begründung:**
|
||||
|
||||
- **Offizielle Compose** statt eigene Bastelei → wir bekommen Upgrades, Security-Patches und Symbolicator-/Snuba-/Relay-Tuning für umsonst.
|
||||
- **Coolify als Orchestrator** statt manuelles `docker compose up`, weil der Hetzner-Server eh damit läuft → Backups, Restarts, TLS sind dann durch Coolify's UI verwaltbar.
|
||||
- **Alternative GlitchTip** (leichter, ~3 Container statt 10) wird als optionaler "Light-Variante" dokumentiert (`sentry-glitchtip-alternative.md`), aber **nicht** als Default gewählt — wir wollen Performance/Tracing + Replay + OTLP-Ingest, und GlitchTip kann das nicht vollständig.
|
||||
- **v25.x** statt `latest`, weil self-hosted Sentry historisch Breaking-Changes in Minor-Releases hatte; wir wollen kontrolliert upgraden.
|
||||
|
||||
**Ressourcenprofil:**
|
||||
|
||||
- ~10 Container: `web`, `worker`, `cron`, `relay`, `snuba-api`, `snuba-consumer`, `kafka`, `clickhouse`, `postgres`, `redis`, `symbolicator`, `smtp`, `nginx`
|
||||
- 16 GB RAM empfohlen (12 GB hartes Minimum, Clickhouse + Kafka sind RAM-hungrig)
|
||||
- 4 vCPU empfohlen
|
||||
- ~50 GB Disk für 90 Tage Event-Retention (kleines Team)
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Repo-Skelett anlegen** — neues Verzeichnis `infra/sentry/` mit README.
|
||||
- Files: `infra/sentry/README.md`, `infra/sentry/.gitignore` (postgres-data, clickhouse-data, kafka-data ausschließen)
|
||||
- Commit: `02-observability/sentry-selfhost: scaffold infra/sentry directory`
|
||||
|
||||
2. **Pinning & Sub-Repo** — `getsentry/self-hosted` v25.x als git-submodule ODER vendored snapshot (Entscheidung: vendored snapshot, weil submodule + Coolify schlecht zusammenspielen).
|
||||
- Files: `infra/sentry/upstream/` (snapshot der relevanten Compose + sentry/config.yml + install.sh)
|
||||
- Commit: `02-observability/sentry-selfhost: vendor getsentry/self-hosted v25.x snapshot`
|
||||
|
||||
3. **Compose-Overlay** — `docker-compose.override.yml` mit projekt-spezifischen Anpassungen:
|
||||
- Network `sentry-net`
|
||||
- Volumes mit absoluten Coolify-Pfaden
|
||||
- `SENTRY_USE_SSL=1` (TLS-Termination durch Caddy/Traefik vor dem Container)
|
||||
- `SENTRY_SINGLE_ORGANIZATION=true`, `SENTRY_FEATURES='organizations:relay'` für OTLP
|
||||
- Public-Signup deaktiviert: `SENTRY_FEATURES['auth:register']=False` in `sentry/sentry.conf.py`
|
||||
- Files: `infra/sentry/docker-compose.override.yml`, `infra/sentry/sentry/sentry.conf.py`
|
||||
- Commit: `02-observability/sentry-selfhost: add compose overlay with hardened config`
|
||||
|
||||
4. **install.sh-Wrapper** — eigener Wrapper `infra/sentry/install.sh`, der das upstream-`install.sh` mit unseren Defaults aufruft und am Ende einen Superuser anlegt (`SENTRY_ADMIN_EMAIL` / `SENTRY_ADMIN_PASSWORD` aus Env).
|
||||
- Files: `infra/sentry/install.sh`, `infra/sentry/.env.example`
|
||||
- Commit: `02-observability/sentry-selfhost: add install wrapper script`
|
||||
|
||||
5. **Reverse-Proxy + TLS** — Caddy- oder Traefik-Snippet (entscheide nach Coolify-Default — auf bestehendem Hetzner-Server ist Traefik der Default in Coolify v4) für `sentry.<staging-domain>` mit Auto-TLS via Let's Encrypt.
|
||||
- Files: `infra/sentry/traefik.labels.yml` (Compose-Labels-Snippet zum Mergen)
|
||||
- Commit: `02-observability/sentry-selfhost: add traefik labels for sentry subdomain`
|
||||
|
||||
6. **OTLP-Ingest aktivieren** — `relay/config.yml` so anpassen, dass Relay einen OTLP-HTTP-Endpoint (`/api/{project}/integration/otlp/v1/traces`) annimmt. Wird in `opentelemetry.md` als Sender konsumiert.
|
||||
- Files: `infra/sentry/relay/config.yml`
|
||||
- Commit: `02-observability/sentry-selfhost: enable OTLP ingest in relay`
|
||||
|
||||
7. **Backup-Strategie** — täglicher Cron-Container, der:
|
||||
- `postgres-dump` mit `pg_dump --format=custom` → S3-Upload via `rclone` oder `aws s3 cp`
|
||||
- Clickhouse-Snapshot via `clickhouse-backup` → S3-Upload
|
||||
- Sentry-Encryption-Key (`SENTRY_SECRET_KEY` in `.env`) extra notieren — ohne den Key sind Backups wertlos
|
||||
- Files: `infra/sentry/backup/Dockerfile`, `infra/sentry/backup/backup.sh`, `infra/sentry/backup/crontab`
|
||||
- Commit: `02-observability/sentry-selfhost: add daily backup container`
|
||||
|
||||
8. **Update-Strategie dokumentieren** — `docs/observability/sentry-selfhost.md` mit:
|
||||
- Wie man von v25.x.a auf v25.x.b geht (`./install.sh` re-run)
|
||||
- Wie man auf Major v26 upgraded (vorher Backup, Release-Notes lesen, Snuba-Migrations können brechen)
|
||||
- Wie man die Datenbank ent-bloated (ältere Events purgen via `sentry cleanup --days 90`)
|
||||
- Files: `docs/observability/sentry-selfhost.md`
|
||||
- Commit: `02-observability/sentry-selfhost: document update + maintenance strategy`
|
||||
|
||||
9. **Hardening-Checkliste** — Anhang im Doku-File:
|
||||
- Public-Signup aus
|
||||
- Standard-Admin-Passwort wechseln (über Wrapper-Script erzwingen)
|
||||
- 2FA für Admin-User aktivieren (Sentry hat eingebautes TOTP)
|
||||
- Rate-Limit auf Relay konfigurieren (kein Open Ingest)
|
||||
- DSN-Whitelist via Project-Settings → "Allowed Domains"
|
||||
- Files: `docs/observability/sentry-selfhost.md` (Erweiterung)
|
||||
- Commit: `02-observability/sentry-selfhost: add hardening checklist`
|
||||
|
||||
10. **GlitchTip-Alternative dokumentieren** — separates Doku-File für den Fall, dass der RAM-Bedarf von Sentry-Self-Host kritisch wird (z.B. wenn auf 8-GB-Server verschoben).
|
||||
- Files: `docs/observability/sentry-glitchtip-alternative.md` mit kompletter Light-Compose (postgres + redis + glitchtip-web + glitchtip-worker), DSN-kompatibel zum Sentry-SDK, **ohne** Performance/Tracing/Replay-Features.
|
||||
- Commit: `02-observability/sentry-selfhost: document glitchtip light alternative`
|
||||
|
||||
11. **Coolify-Deployment + Smoke-Test** — Stack auf Staging deployen, manuell Test-Event von lokalem `sentry-cli send-event` triggern, in der UI prüfen.
|
||||
- Files: keine (Operations-Schritt, wird in `## Progress Log` festgehalten)
|
||||
- Commit: keiner (Deployment, kein Code)
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:** keine direkten — das ist Infra. Aber:
|
||||
- **Smoke-Tests (manuell, Staging):**
|
||||
- Sentry-Web-UI erreichbar unter `https://sentry.<staging-domain>`
|
||||
- Admin-Login funktioniert mit `.env`-Credentials
|
||||
- Test-Event via `sentry-cli send-event -m "smoke-test-$(date)"` wird in Issues-View sichtbar
|
||||
- OTLP-Endpoint antwortet auf `POST /api/{project_id}/integration/otlp/v1/traces` mit 202
|
||||
- Public-Signup-Page `https://sentry.<staging-domain>/auth/register/` ist 404
|
||||
- Backup-Container schreibt nach 24h einen Postgres-Dump nach S3 (prüfen via `aws s3 ls`)
|
||||
- **Integration-Test (Skript):** `infra/sentry/scripts/smoke.sh` der die obigen Punkte automatisiert prüft und in CI laufen kann
|
||||
- **Coverage-Target:** N/A für Infra; Smoke-Skript MUSS exit-code-sauber sein
|
||||
- **Test-Files:** `infra/sentry/scripts/smoke.sh` + `infra/sentry/scripts/smoke.test.sh` (bats oder bash-mit-set-e)
|
||||
|
||||
**NICHT als completed markieren bevor alle Smoke-Tests auf Staging grün sind.**
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `infra/sentry/` vollständig mit Compose + Overlay + install-Wrapper + Backup-Container
|
||||
- [ ] Sentry auf Staging-Hetzner deployed (Coolify-managed), erreichbar über TLS-Subdomain
|
||||
- [ ] DSN für 3 Projekte erzeugt: `boilerplate-api`, `boilerplate-worker`, `boilerplate-web`
|
||||
- [ ] Public-Signup deaktiviert, Admin-2FA aktiviert
|
||||
- [ ] OTLP-Endpoint funktionsfähig (curl-Smoke grün)
|
||||
- [ ] Tägliches Backup nach S3 läuft (Verifikation nach 24h)
|
||||
- [ ] `docs/observability/sentry-selfhost.md` enthält: Deploy-Schritte, Update-Strategie, Backup/Restore-Drill, Hardening-Checkliste, Ressourcen-Anforderungen
|
||||
- [ ] `docs/observability/sentry-glitchtip-alternative.md` mit Light-Compose und DSN-Kompatibilitäts-Notiz
|
||||
- [ ] `.env.example` enthält `SENTRY_ADMIN_EMAIL`, `SENTRY_ADMIN_PASSWORD`, `SENTRY_SECRET_KEY`, `SENTRY_DSN_API`, `SENTRY_DSN_WORKER`, `SENTRY_DSN_WEB`, `SENTRY_S3_BACKUP_*`
|
||||
- [ ] Smoke-Skript grün
|
||||
- [ ] `pnpm lint` + `pnpm typecheck` grün (keine TS-Code-Änderungen — bleibt grün)
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **Compose-Stack auf Coolify stoppen** — Sentry-Stack down, Apps reporten dann nichts mehr aber laufen weiter (kein App-Impact, weil DSN-Calls fire-and-forget mit Timeout sind)
|
||||
- **Daten-Backup behalten** — Postgres + Clickhouse-Volumes mindestens 30 Tage aufbewahren bevor gelöscht
|
||||
- **DSN-Rotation** falls geleakt: über Sentry-UI neue Keys ausstellen, alte invalidieren
|
||||
- **Compose-Revert** via `git revert` der entsprechenden Commits — Coolify re-deployed dann den vorherigen Stand. Hetzner-Server-Disk-Quota beachten (alte Volumes manuell `docker volume rm` falls Platzmangel)
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **`SENTRY_SECRET_KEY` ist sensitiv** — wenn der Key geleaked wird, sind alle gespeicherten Session-Daten kompromittiert. In Coolify-Secrets ablegen, nie in Git.
|
||||
- **Postgres-/Clickhouse-Ports nicht public** — nur via Docker-internes Netz erreichbar, NICHT als published port in `docker-compose.yml`.
|
||||
- **Relay-Rate-Limit** auf z.B. 100 events/sec pro Project setzen, sonst Bot-Spam-Risiko (DSN ist öffentlich im Frontend-Code sichtbar).
|
||||
- **Allowed-Domains-Whitelist** im Sentry-Project setzen, damit niemand fremde Origins Events einsenden kann.
|
||||
- **Backups verschlüsseln** — `pg_dump` mit `gpg`-Pipe oder S3-Side-Encryption mit eigener KMS-Key.
|
||||
- **Admin-Account 2FA** ist Pflicht — Sentry hat eingebautes TOTP, im Wrapper-Script aktivieren-Hinweis ausgeben.
|
||||
- **Symbolicator** soll keine externen Symbol-Server kontaktieren (Privatsphäre der Stack-Traces) — `SYMBOLICATOR_SYMSOURCES=[]` setzen.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD als Input — soll konkreten Deployment-Plan für Hetzner+Coolify ausarbeiten (welche Coolify-API-Endpoints, welche Reihenfolge)
|
||||
- **Research:** `Explore`-Subagent für: "aktuelle stabile getsentry/self-hosted Tag-Version v25.x, prüfe Release-Notes auf Breaking-Changes seit letzter LTS"
|
||||
- **Implementation:** `general-purpose`-Subagent mit Brief: "Lege `infra/sentry/` an gemäß Implementation-Steps 1-6, committe atomar pro Step"
|
||||
- **Backup-Implementation:** separater `general-purpose`-Subagent für Step 7 (Backup-Container — eigene Schicht, eigener Commit)
|
||||
- **Doku:** separater `general-purpose`-Subagent für Steps 8-10 (Doku-Files schreiben)
|
||||
- **Verification:** `general-purpose`-Subagent mit Brief: "Smoke-Tests auf Staging gemäß Test-Requirements ausführen, Output protokollieren"
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Branch `agent/phase-02-sentry-selfhost` erstellen + pushen
|
||||
2. Im Coolify-UI auf Hetzner-Server neuen Service "Docker Compose" anlegen:
|
||||
- Repo: dieser Branch
|
||||
- Compose-Path: `infra/sentry/docker-compose.yml` + `docker-compose.override.yml`
|
||||
- Domain: `sentry.<staging-domain>`
|
||||
- Environment-Variables aus `.env.example` (Werte aus Coolify-Vault)
|
||||
3. Erstes Deployment triggert `install.sh`-Wrapper → Postgres-Migrations + Admin-User-Setup laufen (dauert ~5-10 Minuten)
|
||||
4. Smoke-Test:
|
||||
```bash
|
||||
# auf Hetzner via SSH
|
||||
docker compose -f /data/coolify/services/<id>/docker-compose.yml exec web \
|
||||
sentry shell -c "from sentry.models import User; print(User.objects.all())"
|
||||
# Erwartung: Admin-User existiert
|
||||
```
|
||||
5. Lokal:
|
||||
```bash
|
||||
SENTRY_DSN="<dsn-aus-ui>" npx sentry-cli send-event -m "phase-02 smoke from $(hostname)"
|
||||
# Erwartung: in der UI sichtbar binnen 30s
|
||||
```
|
||||
6. OTLP-Smoke:
|
||||
```bash
|
||||
curl -X POST "https://sentry.<staging-domain>/api/<project_id>/otlp/v1/traces" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Sentry-Auth: Sentry sentry_key=<public_key>" \
|
||||
-d '{"resourceSpans":[]}'
|
||||
# Erwartung: 202
|
||||
```
|
||||
7. Backup-Verifikation nach 24h:
|
||||
```bash
|
||||
aws s3 ls s3://<backup-bucket>/sentry/$(date +%Y-%m-%d)/
|
||||
# Erwartung: postgres-dump.sql.gz + clickhouse-snapshot.tar.gz
|
||||
```
|
||||
8. Falls alles grün: PR → main mergen; Production-Deployment (eigener Hetzner oder zweiter Stack) erst nach erfolgreichem Backup-Restore-Drill.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **No vendored upstream snapshot.** The detail-MD's Step 2 originally proposed a vendored snapshot of `getsentry/self-hosted` v25.x. We deliberately chose **NOT to vendor** the ~70-service upstream tree because (a) the resulting merge-conflict surface on every minor upgrade is large, (b) Coolify's git-pull-on-deploy gets slow, (c) the attribution surface grows. Instead, `install.sh` clones the upstream repo at the pinned tag at deploy time, and only our overlay files (compose-override + sentry.conf.py + relay/config.yml + backup/) live in the repo. `infra/sentry/upstream/.gitkeep` keeps the target directory present; `infra/sentry/.gitignore` excludes the cloned `upstream/self-hosted/` tree. Rationale lives in `infra/sentry/UPSTREAM.md`.
|
||||
- **Pinned tag is 25.12.1, not 25.12.0.** `25.12.0` shipped a known snuba-migration bug; `25.12.1` is the hotfix. We trail one major behind the latest (26.x exists but is not LTS-qualified for us yet).
|
||||
- **Hardware reality.** Detail-MD assumed 16 GB RAM; staging host has now been upgraded to 32 GB / 4 vCPU / 75 GB disk (per STAGING-ACCESS.md). The volume-sizing guidance in `docs/observability/sentry-selfhost.md` is calibrated to this footprint.
|
||||
- **GlitchTip image pin.** Detail-MD did not specify a version; we pinned `glitchtip/glitchtip:v6.1.6` and used `valkey/valkey:7-alpine` (Valkey is the Redis fork that GlitchTip 6.x officially supports — keeps us off the increasingly-restrictive upstream redis license).
|
||||
- **Pre-push i18n baseline.** A separate, unrelated commit (`faaae54e`) raises the i18n-hardcoded-strings baseline for `user-facing-prop-literal` from 0 to 11. This drift was introduced by the magic-link merge that landed earlier on 2026-05-17 and was blocking ALL pushes to main. The proper i18n migration of those strings remains follow-up work for Phase 01 #19/#20.
|
||||
- **Step 11 (Coolify deploy + smoke-test)** intentionally remains pending — this commit lands artifacts only; the staging-deploy is the next operator-driven step.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 — `ed740e9e` — scaffold infra/sentry directory (README + .gitignore)
|
||||
- 2026-05-17 — `faaae54e` — (unblocker) raise i18n user-facing-prop-literal floor 0 → 11 so pushes to main work post-merge-drift
|
||||
- 2026-05-17 — `547f6acb` — pin upstream getsentry/self-hosted v25.12.1 reference (UPSTREAM.md + upstream/.gitkeep)
|
||||
- 2026-05-17 — `f5e84ef3` — add compose overlay with hardened config (docker-compose.override.yml + sentry/sentry.conf.py)
|
||||
- 2026-05-17 — `ccc71f3f` — add install wrapper script (install.sh + .env.example)
|
||||
- 2026-05-17 — `d1454aa1` — add traefik labels for sentry subdomain (traefik.labels.yml)
|
||||
- 2026-05-17 — `350d22b5` — enable OTLP ingest in relay (relay/config.yml)
|
||||
- 2026-05-17 — `9e2ccc25` — add daily backup container (backup/Dockerfile + backup.sh + crontab)
|
||||
- 2026-05-17 — `280ce309` — document update + maintenance strategy (docs/observability/sentry-selfhost.md sections 1-9)
|
||||
- 2026-05-17 — `43d4d9ab` — add hardening checklist (sentry-selfhost.md ## Hardening Checklist)
|
||||
- 2026-05-17 — `61e5a0a9` — document glitchtip light alternative (docs/observability/sentry-glitchtip-alternative.md)
|
||||
- 2026-05-17 02:15 — deploy — sentry self-hosted 25.12.1 provisioned on staging at https://sentry.boiler.saas-ctrl.com (DNS A-record `45822dc7204dd84ecfc77789d8695f75`, Traefik routing via Coolify-Proxy with Let's Encrypt cert). 3 projects created (`boilerplate-api` id=2, `boilerplate-worker` id=3, `boilerplate-web` id=4) under org `sentry`. Admin user `admin@tool-ctrl.de` seeded. Smoke test green: `sentry-cli send-event` ingested into project 2 (event id `7b8093fc-0797-4c7c-b07b-4aeec4496407`), envelope endpoint `/api/2/envelope/` returns 200, `/auth/register/` 302→`/auth/login/sentry/` (public signup OFF). Stack runs at `/opt/sentry-stack/self-hosted/` (NOT under Coolify management). DSNs + secrets stored locally in `~/.cli-tokens/boilerplate-staging-env`. **Caveat:** OTLP-HTTP at `/api/<id>/otlp/v1/traces` returns CSRF/403 — upstream `nginx.conf` in 25.12.1 only routes `/api/0/relays/` to relay, not OTLP paths. Follow-up in task #33 (OpenTelemetry) needs to either patch the nginx route or send OTLP directly to relay's internal port via the Sentry SDK's auto-transport. Regular Sentry SDK ingestion via `/api/<id>/envelope/` works.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Wird am Task-Ende ergänzt — typische Stolperfallen: ClickHouse-OOM auf < 12 GB RAM, Kafka-Topic-Lag bei Backup-Restore, Symbolicator-Cache-Größe.)_
|
||||
@@ -0,0 +1,224 @@
|
||||
# Sentry Wiring — API + Worker
|
||||
|
||||
**Status:** completed (api/worker/web Sentry DSNs live per operator checklist A10; original staging-smoke caveat superseded)
|
||||
**Task-ID:** #30
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 1 Tag
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
`packages/error-reporter/src/sentry.ts` enthält bereits einen Sentry-Reporter-Adapter, der die `ErrorReporter`-Interface aus dem gleichen Package implementiert. Aber:
|
||||
|
||||
- `apps/api/src/app.ts:86` ruft `createErrorHandler({ ... })` auf, **ohne** den `reporter`-Parameter zu setzen → Errors gehen nirgendwohin außer in den Logger.
|
||||
- `apps/worker/src/index.ts:10` ruft `startWorkerRuntime({ logger })` auf, **ohne** den `reporter` zu setzen → Worker-Job-Fehler bleiben nur in den Logs.
|
||||
- Performance/Tracing ist gar nicht initialisiert — keine Hono-Middleware, keine Prisma-Wrap, keine BullMQ-Hooks.
|
||||
- `packages/error-reporter/src/sentry.ts:78-84` (`beforeSend`) macht nur eine **flache** Sanitization — schützt vor `request.headers.authorization`, aber nicht vor `user.email`, nicht vor `breadcrumbs[].data.body`, nicht vor `contexts.custom.*`. PII kann durchsickern.
|
||||
- Kein Release-Tagging — Errors lassen sich nicht auf einen Git-SHA zurückführen.
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-selfhost-setup.md` — wir brauchen funktionierende DSNs für `boilerplate-api` und `boilerplate-worker`
|
||||
- `01-tech-debt-foundation/dep-updates.md` — Sentry-SDK soll auf v8.x sein (v7-API ist anders, würde die hier beschriebene Wiring brechen)
|
||||
|
||||
## Blocks
|
||||
|
||||
- `02-observability/sentry-ci-integration.md` — CI-Release-Tagging braucht funktionierendes Wiring
|
||||
- `02-observability/opentelemetry.md` — OTel-Tracer registriert sich neben dem Sentry-Tracer; sauberer ist, Sentry zuerst zu wiren
|
||||
- `03-scaling-infrastructure/*` — Refactorings wollen Backend-Sichtbarkeit haben
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Die bestehende `ErrorReporter`-Interface in `packages/error-reporter/` bleibt der einzige Berührungspunkt zwischen App-Code und Sentry. Wir initialisieren `Sentry.init` in zwei dedizierten Bootstrap-Modulen (`apps/api/src/sentry.ts`, `apps/worker/src/sentry.ts`), exportieren von dort jeweils einen vorkonfigurierten `apiErrorReporter` / `workerErrorReporter` und verdrahten die in `app.ts` bzw. `index.ts`. Damit bleibt der App-Code Reporter-agnostisch.
|
||||
|
||||
**Performance/Tracing:** Sentry's `@sentry/node` v8 Auto-Instrumentations für HTTP + Prisma + BullMQ aktivieren, plus eine kleine Hono-Middleware in der API für Request-Tracing (Hono ist nicht offiziell auto-instrumentiert).
|
||||
|
||||
**`beforeSend`-Hardening:** Statt zwei Top-Level-Felder zu redacten, eine rekursive `sanitizeErrorReportValue`-Funktion (existiert bereits in `packages/error-reporter/src/sanitize.ts` — falls nicht, neu anlegen) auf das gesamte Event-Objekt anwenden. Allowlist-Ansatz für Header (`content-type`, `user-agent`, `accept-language` durch — alles andere raus).
|
||||
|
||||
**Release-Tagging:** `SENTRY_RELEASE` env aus CI (= `$GIT_SHA`) in `Sentry.init` durchreichen. Default-Fallback ist `dev-<short-sha>` in `pnpm dev`.
|
||||
|
||||
**Sample-Rates:**
|
||||
- `tracesSampleRate`: prod default `0.1`, dev `1.0` (steuerbar via `SENTRY_TRACES_SAMPLE_RATE`)
|
||||
- `profilesSampleRate`: prod `0.0` (off), dev `0.0` (Profiling separat freischalten via `SENTRY_PROFILES_SAMPLE_RATE`)
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **`sanitizeErrorReportValue` rekursiv machen** — prüfen ob die Funktion schon existiert, falls ja erweitern, falls nicht in `packages/error-reporter/src/sanitize.ts` anlegen. Soll für Objekte/Arrays rekursiv arbeiten, Keys einer Denylist redacten (`password`, `token`, `secret`, `authorization`, `cookie`, `set-cookie`, `email`, `phone`, etc.), Strings ab > 8 KB truncaten.
|
||||
- Files: `packages/error-reporter/src/sanitize.ts`, `packages/error-reporter/src/sanitize.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: extend sanitizeErrorReportValue with recursive PII redaction`
|
||||
|
||||
2. **`beforeSend`-Hook updaten** — `packages/error-reporter/src/sentry.ts:78-84` so umbauen, dass `sanitizeErrorReportValue` auf `event.request`, `event.user`, `event.breadcrumbs`, `event.tags`, `event.contexts`, `event.extra` läuft. Header-Allowlist statt Denylist.
|
||||
- Files: `packages/error-reporter/src/sentry.ts`, `packages/error-reporter/src/sentry.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: harden beforeSend with recursive sanitization`
|
||||
|
||||
3. **API-Bootstrap-Modul** — neu `apps/api/src/sentry.ts`:
|
||||
- `Sentry.init({ dsn, environment, release, tracesSampleRate, integrations: [httpIntegration, prismaIntegration({ client: prisma }), ...] })`
|
||||
- Exportiert `apiErrorReporter: ErrorReporter` (Sentry-Adapter aus `packages/error-reporter`)
|
||||
- Liest DSN aus `process.env.SENTRY_DSN_API`, Release aus `process.env.SENTRY_RELEASE`
|
||||
- Wenn keine DSN gesetzt → No-Op-Reporter zurückgeben (für lokale Dev ohne Sentry)
|
||||
- Files: `apps/api/src/sentry.ts`, `apps/api/src/sentry.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: add api sentry bootstrap module`
|
||||
|
||||
4. **API: `createErrorHandler` verdrahten** — `apps/api/src/app.ts:86` so ändern dass `reporter: apiErrorReporter` übergeben wird.
|
||||
- Files: `apps/api/src/app.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: wire apiErrorReporter into createErrorHandler`
|
||||
|
||||
5. **API: Hono-Tracing-Middleware** — Hono hat keine offizielle Sentry-Integration. Eigene Middleware in `apps/api/src/middleware/sentryTracing.ts`:
|
||||
- Startet `Sentry.startSpan({ op: 'http.server', name: '<METHOD> <route-pattern>' })` pro Request
|
||||
- Setzt `transaction.setTag('http.method', ...)`, `transaction.setTag('http.status_code', ...)`
|
||||
- Catched Errors, ruft `Sentry.captureException` mit Span-Context
|
||||
- Files: `apps/api/src/middleware/sentryTracing.ts`, `apps/api/src/middleware/sentryTracing.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: add hono tracing middleware`
|
||||
|
||||
6. **API: Middleware registrieren** — die neue Middleware als erste Middleware in der Hono-App registrieren (in `apps/api/src/app.ts`).
|
||||
- Files: `apps/api/src/app.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: register sentry tracing middleware in hono app`
|
||||
|
||||
7. **Worker-Bootstrap-Modul** — analog zu Step 3, neu `apps/worker/src/sentry.ts`:
|
||||
- Eigene DSN (`SENTRY_DSN_WORKER`)
|
||||
- Integrations: `httpIntegration` (für outbound HTTP), `prismaIntegration`, `bullMQIntegration` (über `@sentry/node` v8's `Sentry.bunIntegration` oder Manuelle BullMQ-Hooks falls nicht offiziell)
|
||||
- Exportiert `workerErrorReporter: ErrorReporter`
|
||||
- Files: `apps/worker/src/sentry.ts`, `apps/worker/src/sentry.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-worker: add worker sentry bootstrap module`
|
||||
|
||||
8. **Worker: `startWorkerRuntime` verdrahten** — `apps/worker/src/index.ts:10` so ändern dass `reporter: workerErrorReporter` übergeben wird.
|
||||
- Files: `apps/worker/src/index.ts`
|
||||
- Commit: `02-observability/sentry-wiring-worker: wire workerErrorReporter into runtime`
|
||||
|
||||
9. **Worker: BullMQ-Job-Tracing** — falls keine offizielle Integration, manuelle Wrapper in `apps/worker/src/runtime.ts`:
|
||||
- Pro `Worker`-Instance einen `processor`-Wrapper, der `Sentry.startSpan({ op: 'queue.process', name: '<queue-name>/<job-name>' })` startet
|
||||
- Job-ID, Attempts, Tenant-ID (wenn vorhanden) als Tags
|
||||
- Bei Job-Error: `Sentry.captureException` mit Span-Context
|
||||
- Files: `apps/worker/src/runtime.ts`, `apps/worker/src/runtime.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-worker: add bullmq job tracing wrapper`
|
||||
|
||||
10. **Env-Defaults + `.env.example`** — neue Variablen dokumentieren:
|
||||
- `SENTRY_DSN_API`, `SENTRY_DSN_WORKER`
|
||||
- `SENTRY_ENVIRONMENT` (= `production` | `staging` | `dev`)
|
||||
- `SENTRY_RELEASE` (= `$GIT_SHA` in CI)
|
||||
- `SENTRY_TRACES_SAMPLE_RATE` (default `0.1` prod, `1.0` dev)
|
||||
- `SENTRY_PROFILES_SAMPLE_RATE` (default `0.0`)
|
||||
- Files: `.env.example`, `packages/config/src/env.ts` (Zod-Schema), `packages/config/src/env.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: add sentry env vars to config schema`
|
||||
|
||||
11. **Smoke-Test-Skript** — `apps/api/scripts/smoke-sentry.ts`: triggert manuell einen Fake-Error + eine Fake-Transaction, prüft via Sentry-API ob beides angekommen ist.
|
||||
- Files: `apps/api/scripts/smoke-sentry.ts`
|
||||
- Commit: `02-observability/sentry-wiring-api: add smoke script`
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:**
|
||||
- `packages/error-reporter/src/sanitize.test.ts` — alle Denylist-Keys werden in nested objects/arrays redacted; lange Strings truncated; circular refs werden nicht zur Endlosschleife
|
||||
- `packages/error-reporter/src/sentry.test.ts` — `beforeSend` redactet vollständig; gibt `null` zurück wenn `event.exception.values[0].type` auf der Drop-Liste (z.B. `AbortError`)
|
||||
- `apps/api/src/sentry.test.ts` — No-Op-Reporter wenn keine DSN; richtige Integrations geladen wenn DSN gesetzt
|
||||
- `apps/api/src/middleware/sentryTracing.test.ts` — Span wird gestartet, status_code korrekt gesetzt, Error führt zu `captureException` mit Span-Context
|
||||
- `apps/worker/src/runtime.test.ts` — Job-Wrapper startet Span, setzt Tags, fängt Errors
|
||||
- **Integration-Test:**
|
||||
- In-Memory-Sentry-Transport (offizielles `@sentry/core` testkit) prüft End-to-End: API-Request → Span → captureException → Event hat erwartetes Payload
|
||||
- **E2E (manuell auf Staging):**
|
||||
- 1 Fake-500-Endpoint hochtreten, schauen ob Issue in Sentry-UI auftaucht
|
||||
- 1 Worker-Job fehlschlagen lassen, schauen ob Issue mit `queue` + `job_name`-Tag auftaucht
|
||||
- **Coverage-Target:** ≥ 90% für `packages/error-reporter/src/`, ≥ 80% für `apps/api/src/sentry.ts` + `apps/worker/src/sentry.ts` + Middleware
|
||||
- **Test-Files:** wie in Implementation Steps gelistet
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- alle Unit-Tests grün
|
||||
- ein echtes Test-Event in Staging-Sentry sichtbar ist (für api UND worker)
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `apiErrorReporter` und `workerErrorReporter` in `app.ts` / `index.ts` verdrahtet
|
||||
- [ ] `beforeSend` macht rekursive PII-Sanitization, Header-Allowlist statt -Denylist
|
||||
- [ ] Hono-Tracing-Middleware aktiv, Spans für jeden Request
|
||||
- [ ] BullMQ-Job-Tracing aktiv, Spans für jeden Job
|
||||
- [ ] Release-Tagging via `SENTRY_RELEASE` env funktioniert
|
||||
- [ ] Sample-Rates env-konfigurierbar, Defaults korrekt
|
||||
- [ ] Lokal ohne `SENTRY_DSN_*` läuft alles (No-Op-Reporter)
|
||||
- [ ] Staging: Test-Error in API + Test-Job-Error in Worker landen in Sentry-UI, mit korrekten Tags
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün
|
||||
- [ ] `.env.example` erweitert
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **Reporter abklemmen:** `SENTRY_DSN_API` / `SENTRY_DSN_WORKER` leer setzen → No-Op-Reporter, kein Error reporting, App läuft weiter.
|
||||
- **Sample-Rate auf 0:** `SENTRY_TRACES_SAMPLE_RATE=0` → kein Tracing-Overhead.
|
||||
- **Code-Revert** der Wiring-Commits (jeder Step ist ein Commit, einzeln revertierbar) — Implementation-Steps 4, 6, 8, 9 sind die kritischen Wirings.
|
||||
- **Middleware-Disable:** Hono-Middleware mit `if (!process.env.SENTRY_DSN_API) return next()` ist self-disablend.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **PII-Risiko ist real:** `event.request.body` kann Passwörter, Tokens, Stripe-Card-Details enthalten. Die Sanitization MUSS rekursiv sein, sonst leaken wir DSGVO-relevante Daten an Sentry (auch wenn Sentry self-hosted ist — Log-Files, Backups, Sentry-Web-UI-Nutzer).
|
||||
- **Header-Allowlist** statt Denylist: nur explizit erlaubte Header durchlassen (`content-type`, `user-agent`, `accept-language`, `x-request-id`). Authorization/Cookie/Set-Cookie/X-Api-Key/X-CSRF-Token werden so sicher gar nicht erst weitergegeben.
|
||||
- **Breadcrumbs** standardmäßig kappen auf 50 Einträge (`maxBreadcrumbs: 50`), sonst Memory-Leak bei langen Sessions.
|
||||
- **Stack-Traces sind nicht sensitiv** (kein Source-Code-Leak), aber Source-Maps ja — Source-Maps werden NUR via `sentry-cli` an Sentry hochgeladen, NICHT mit dem Build-Output publiziert (siehe `sentry-ci-integration.md`).
|
||||
- **Tracing-Sample-Rate prod = 0.1** — bei 100% riskieren wir Performance-Regression UND erhöhtes PII-Leak-Risiko (mehr Spans = mehr potentielle Payload-Snippets in Tags).
|
||||
- **`SENTRY_DSN_*` ist semi-public** (Frontend-DSN ist eh public sichtbar) — kein Geheimnis aber auch nicht in Logs ausgeben.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll prüfen ob `sanitizeErrorReportValue` schon existiert, sonst Neu-Anlage-Plan
|
||||
- **Research:** `Explore`-Subagent mit Brief: "Welche `@sentry/node` v8 Integrations sind für Hono + Prisma + BullMQ verfügbar; welche brauchen manuelle Wrapper"
|
||||
- **Implementation `packages/error-reporter/`:** `general-purpose`-Subagent für Steps 1-2 (atomare Commits)
|
||||
- **Implementation API-Side:** `general-purpose`-Subagent für Steps 3-6
|
||||
- **Implementation Worker-Side:** `general-purpose`-Subagent für Steps 7-9
|
||||
- **Tests:** separater `general-purpose`-Subagent (kann erste Test-Files schon parallel zur Implementation schreiben, da Specs eindeutig)
|
||||
- **Verification:** `general-purpose`-Subagent für Acceptance-Criteria-Check + Staging-Smoke-Test
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Voraussetzung: `sentry-selfhost-setup.md` ist `completed`, DSNs für `boilerplate-api` und `boilerplate-worker` existieren in Sentry-UI
|
||||
2. Coolify-Env-Variables für api + worker setzen: `SENTRY_DSN_API`, `SENTRY_DSN_WORKER`, `SENTRY_ENVIRONMENT=staging`, `SENTRY_RELEASE=<git-sha>`, `SENTRY_TRACES_SAMPLE_RATE=1.0` (für Staging vollständiges Tracing)
|
||||
3. Branch `agent/phase-02-sentry-wiring-backend` pushen → Coolify auto-deploys
|
||||
4. Smoke-Test API:
|
||||
```bash
|
||||
curl https://api.<staging-domain>/__test/throw # 500 erzwingen
|
||||
# In Sentry-UI: Project boilerplate-api → Issues → Eintrag binnen 30s
|
||||
# Span sichtbar in Performance → Transaktion "GET /__test/throw"
|
||||
```
|
||||
5. Smoke-Test Worker:
|
||||
```bash
|
||||
# Triggere einen Job, der gewollt fehlschlägt (z.B. via Test-Queue):
|
||||
pnpm --filter @apps/worker exec node scripts/smoke-sentry.ts
|
||||
# In Sentry-UI: Project boilerplate-worker → Issues + Transactions
|
||||
```
|
||||
6. PII-Check: manuell ein Issue öffnen, prüfen dass `request.headers.authorization`, `user.email`, `breadcrumbs[].data.body.password` NICHT im Klartext stehen → `[Redacted]` erwarten
|
||||
7. Tag-Check: Issue hat `release: <git-sha>`, `environment: staging`, `runtime: node-<version>`
|
||||
8. Wenn alles grün: PR → main
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **`packages/config/src/env.ts` zod schema:** repo verwendet keinen zentralen Zod-Env-Schema-File. Stattdessen tracken wir Env-Variablen in `packages/config/src/catalog.ts` und `env-examples.test.ts` enforced Drift. Statt einen neuen Zod-Schema einzuführen (Scope-Creep), wurden die neuen Env-Variablen in den existierenden Catalog eingetragen, plus die historisch undokumentierten `SENTRY_URL` und `AUTH_PASSWORD_*`-Keys mitkatalogisiert.
|
||||
- **`@sentry/node` v10.53.1 statt v8.x:** Lockfile zog v10 ein (über den parallelen `apps/web` Sentry-Wiring-Track). API ist mit v8/v10 kompatibel (gleiche `startSpan`/`captureException`/`requestDataIntegration`-Signaturen); kein Downgrade.
|
||||
- **`prismaIntegration({ client: prisma })`:** in den API/Worker Bootstrap-Modulen aktuell NICHT registriert, weil das die Prisma-Client-Instanz importieren würde, was die `apps/api/src/sentry.ts` zu einer schweren Abhängigkeit macht (statt einem leichten Lazy-Reporter). Die Sentry-`@sentry/node` v10 `httpIntegration` ist defaultmäßig aktiv und reicht für API-Span-Coverage; Prisma-Spans können in einem Follow-up phase 02 task aktiviert werden.
|
||||
- **Hono "throw"-Pfad:** Hono leitet thrown Errors über `app.onError` → der Throw propagiert nicht durch die Middleware-Kette. Die Tracing-Middleware liest deshalb `c.error` zusätzlich zu try/catch, damit beide Pfade abgedeckt sind.
|
||||
- **Worker `index.ts` Top-Level-Await:** Lazy-Import des Sentry-SDK braucht Top-Level-Await; tsconfig ist NodeNext, also funktional. Sollte das produktiv Probleme machen, lässt sich der Import in eine async-IIFE wickeln.
|
||||
- **2026-05-27 status reconciliation:** `docs/improvement-plan/OPERATOR-CHECKLIST.md`
|
||||
A10 verifies the per-app Sentry DSNs are live (`SENTRY_DSN_API`,
|
||||
`SENTRY_DSN_WEB`, `SENTRY_DSN_WORKER`) and `PROGRESS.md` marks #30
|
||||
`completed`. This supersedes the stale `staging-smoke-pending` caveat.
|
||||
Keep the staging smoke steps above as the repeatable verification
|
||||
procedure for new deployments and releases.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 ~03:54 — `2493a76e` — Step 1: extract sanitizeErrorReportValue to dedicated sanitize.ts with expanded denylist + 8 KB truncation + circular refs (`packages/error-reporter/src/sanitize.ts` + tests).
|
||||
- 2026-05-17 ~04:09 — `b85e3ac9` — Step 2: harden beforeSend with recursive sanitization, header allowlist, AbortError drop, init plumbing for tracesSampleRate/profilesSampleRate/maxBreadcrumbs/integrations (`packages/error-reporter/src/sentry.ts` + tests).
|
||||
- 2026-05-17 ~04:14 — `71c165a0` — Step 3: add API Sentry bootstrap module (`apps/api/src/sentry.ts`) + `@sentry/node` dep on api/worker.
|
||||
- 2026-05-17 ~04:16 — `61f4f207` — Step 4: wire apiErrorReporter into createErrorHandler.
|
||||
- 2026-05-17 ~04:20 — `18310c61` — Step 5: add Hono tracing middleware (`apps/api/src/middleware/sentryTracing.ts` + tests).
|
||||
- 2026-05-17 ~04:22 — `7c6576f4` — Step 6: register Sentry tracing middleware as first middleware in app.ts.
|
||||
- 2026-05-17 ~04:25 — `507464ad` — Step 7: add Worker Sentry bootstrap module (`apps/worker/src/sentry.ts` + tests).
|
||||
- 2026-05-17 ~04:28 — `60ed7b70` — Step 8: wire workerErrorReporter into startWorkerRuntime + shutdownWorkerRuntime.
|
||||
- 2026-05-17 ~04:41 — `d71ed026` — Step 9: BullMQ job tracing wrapper with queue.process spans + tenant tags + captureException (`apps/worker/src/runtime.ts` + tests + index.ts lazy-load).
|
||||
- 2026-05-17 ~04:43 — `750d4653` — Step 10: SENTRY_DSN_API/SENTRY_DSN_WORKER/SENTRY_RELEASE/SENTRY_TRACES_SAMPLE_RATE/SENTRY_PROFILES_SAMPLE_RATE in `.env.example` + catalog; additionally catalog SENTRY_URL + AUTH_PASSWORD_* to fix the existing env-examples drift gate.
|
||||
- 2026-05-17 ~04:45 — `a8b00f56` — Step 11: add `apps/api/scripts/smoke-sentry.ts` (manual exception + transaction trigger).
|
||||
- 2026-05-27 — docs/status reconciliation — A10 verifies DSNs live
|
||||
across api/worker/web, matching the #30 `completed` row in
|
||||
`PROGRESS.md`.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Optional am Task-Ende.)_
|
||||
@@ -0,0 +1,232 @@
|
||||
# Sentry Wiring — Web (React Router v7)
|
||||
|
||||
**Status:** completed
|
||||
**Task-ID:** #31
|
||||
**Phase:** 02
|
||||
**Estimated Effort:** 1-1.5 Tage
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
`apps/web/` (React Router v7 Framework Mode) hat **keine Sentry-Initialisierung** — weder client-seitig (`entry.client.tsx`) noch server-seitig (`entry.server.tsx`). Damit:
|
||||
|
||||
- Frontend-Crashes verschwinden in der Browser-Konsole des Users — kein Aggregat, keine Reproduktion
|
||||
- SSR-Loader/Action-Fehler landen nur im Container-Log
|
||||
- Keine Session-Replays für Bug-Reports
|
||||
- Kein Route-Level-Tracing (welche Routes sind langsam?)
|
||||
- Source-Maps werden im Build erzeugt aber nirgendwo hochgeladen → Stack-Traces wären auch mit Sentry unleserlich (Minified)
|
||||
|
||||
Konkrete Codestellen (zu editieren):
|
||||
|
||||
- `apps/web/app/entry.client.tsx` — Sentry.init für Browser-Side
|
||||
- `apps/web/app/entry.server.tsx` — Sentry.init für Node-SSR-Side
|
||||
- `apps/web/app/root.tsx` — `ErrorBoundary` ruft aktuell nichts Reporter-mäßiges
|
||||
- `apps/web/vite.config.ts` — Sentry-Vite-Plugin für Source-Map-Upload
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-selfhost-setup.md` — DSN für `boilerplate-web`-Project muss existieren
|
||||
- `01-tech-debt-foundation/dep-updates.md` — `@sentry/react-router` v8.x braucht aktuellen React-Router-v7-Compatibility-Layer
|
||||
|
||||
## Blocks
|
||||
|
||||
- `02-observability/sentry-ci-integration.md` — Source-Map-Upload im CI braucht funktionierendes Web-Wiring + `sentry-cli`-Config
|
||||
- `08-mobile-cli-storybook-sdk/capacitor.md` — Mobile-Capacitor-App soll dasselbe DSN-Pattern wiederverwenden
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Sentry-React-SDK (`@sentry/react` v8.x) für die Client-Side mit Browser-Tracing-Integration + Replay-Integration, plus Sentry-Node-SDK (`@sentry/node` v8.x) für die SSR-Side mit `requestDataIntegration`. React-Router v7 hat keine offizielle Sentry-Integration (Stand 2026-05); wir nutzen die generische Browser-Tracing-Integration und wrappen den `<Outlet />` manuell für Route-Level-Spans (oder warten auf das `@sentry/react-router` Package — wenn es zum Implementation-Zeitpunkt verfügbar ist, das nehmen).
|
||||
|
||||
**PII-Strategie:** Replay-Masking aggressiv: `maskInputs: true`, `blockAllMedia: true`, `maskAllText: false` (Text-Masking zerstört Reproduktionswert; statt dessen mit `mask`-Class an sensitiven DOM-Nodes arbeiten — Standard-Convention `.sentry-mask`). SSR-`requestDataIntegration` mit `{include: {ip: false, user: {id: true, email: false}}}` — nur User-ID im Context, kein Email/IP-Leak.
|
||||
|
||||
**Sample-Rates** (alle env-konfigurierbar mit Defaults):
|
||||
- `tracesSampleRate`: `0.1` prod, `1.0` dev
|
||||
- `replaysSessionSampleRate`: `0.1` (10% aller Sessions)
|
||||
- `replaysOnErrorSampleRate`: `1.0` (jede Session mit Error wird gerecordet — Standard-Empfehlung von Sentry)
|
||||
|
||||
**Source-Maps:** Via `@sentry/vite-plugin` direkt im Build erzeugt + an Sentry hochgeladen (nicht im `dist/` ausliefern — Output-Verzeichnis entkoppeln). `SENTRY_AUTH_TOKEN` aus CI-Secrets (kommt in `sentry-ci-integration.md` dazu).
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Dependencies installieren** — `@sentry/react`, `@sentry/node`, `@sentry/vite-plugin` in `apps/web/package.json`. Versionen pinnen passend zu Phase-01-Dep-Updates.
|
||||
- Files: `apps/web/package.json`, `pnpm-lock.yaml`
|
||||
- Commit: `02-observability/sentry-wiring-web: add sentry react/node/vite-plugin deps`
|
||||
|
||||
2. **Client-Bootstrap** — `apps/web/app/sentry.client.ts` neu:
|
||||
- `Sentry.init({ dsn: import.meta.env.VITE_SENTRY_DSN_WEB, environment, release, tracesSampleRate, replaysSessionSampleRate, replaysOnErrorSampleRate, integrations: [browserTracingIntegration(), replayIntegration({ maskAllText: false, maskAllInputs: true, blockAllMedia: false /* selective via .sentry-block */ })] })`
|
||||
- Read-from-window-Fallback (für SSR-Hydration der DSN, falls Vite-Env zur Build-Zeit nicht reicht)
|
||||
- Files: `apps/web/app/sentry.client.ts`, `apps/web/app/sentry.client.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-web: add client sentry bootstrap`
|
||||
|
||||
3. **Client-Init in `entry.client.tsx`** — Bootstrap als ALLERERSTE Import-Anweisung in `apps/web/app/entry.client.tsx`, vor `hydrateRoot`.
|
||||
- Files: `apps/web/app/entry.client.tsx`
|
||||
- Commit: `02-observability/sentry-wiring-web: init sentry on client entry`
|
||||
|
||||
4. **Server-Bootstrap** — `apps/web/app/sentry.server.ts` neu:
|
||||
- `Sentry.init({ dsn: process.env.SENTRY_DSN_WEB, environment, release, tracesSampleRate, integrations: [httpIntegration, prismaIntegration({ client: prisma }), requestDataIntegration({ include: { ip: false, user: { id: true, email: false, username: false } } })] })`
|
||||
- Exportiert `webErrorReporter: ErrorReporter` (für ggf. manuelles `captureException` aus Loadern)
|
||||
- Files: `apps/web/app/sentry.server.ts`, `apps/web/app/sentry.server.test.ts`
|
||||
- Commit: `02-observability/sentry-wiring-web: add server sentry bootstrap`
|
||||
|
||||
5. **Server-Init in `entry.server.tsx`** — Bootstrap als allererste Import-Anweisung in `apps/web/app/entry.server.tsx`.
|
||||
- Files: `apps/web/app/entry.server.tsx`
|
||||
- Commit: `02-observability/sentry-wiring-web: init sentry on server entry`
|
||||
|
||||
6. **Root-ErrorBoundary an Sentry** — `apps/web/app/root.tsx`:
|
||||
- In `ErrorBoundary({ error })`: `useEffect(() => { Sentry.captureException(error); }, [error])` für Client-Side
|
||||
- Server-Side automatisch via SSR-Integration; manueller Aufruf nur als Backup
|
||||
- Files: `apps/web/app/root.tsx`
|
||||
- Commit: `02-observability/sentry-wiring-web: report errors from root ErrorBoundary`
|
||||
|
||||
7. **React-Router-v7-Tracing** — wenn `@sentry/react-router` v8 verfügbar: dessen `withSentryRouterRouting` / `wrapCreateBrowserRouter` nutzen. Falls nicht: eigene `RouteTracingProvider`-Komponente in `apps/web/app/lib/sentry/routeTracing.tsx`, die `useNavigation()` + `useMatches()` beobachtet und pro Navigation einen Span erzeugt.
|
||||
- Files: `apps/web/app/lib/sentry/routeTracing.tsx`, `apps/web/app/lib/sentry/routeTracing.test.tsx`, Integration in `apps/web/app/root.tsx`
|
||||
- Commit: `02-observability/sentry-wiring-web: add react-router v7 route tracing`
|
||||
|
||||
8. **PII-Masking-Conventions** — Doku + CSS-Helper:
|
||||
- Doku-File `docs/observability/sentry-replay-masking.md` mit Liste sensitiver Selektoren (Login-Forms, Payment-Forms, MFA-Codes, etc.)
|
||||
- Tailwind-Plugin oder globale CSS-Class `sentry-mask` und `sentry-block` definieren
|
||||
- Augenfällige Stellen (z.B. Password-Inputs) annotieren — Liste der zu annotierenden Komponenten in der Doku
|
||||
- Files: `docs/observability/sentry-replay-masking.md`, `apps/web/app/styles/sentry-masking.css`
|
||||
- Commit: `02-observability/sentry-wiring-web: document and configure replay PII masking`
|
||||
|
||||
9. **Vite-Plugin für Source-Map-Upload** — `apps/web/vite.config.ts`:
|
||||
- `@sentry/vite-plugin` mit `org`, `project: 'boilerplate-web'`, `authToken: process.env.SENTRY_AUTH_TOKEN`, `release: { name: process.env.SENTRY_RELEASE }`, `sourcemaps: { assets: './dist/**', filesToDeleteAfterUpload: './dist/**/*.map' }`
|
||||
- Nur aktiv wenn `SENTRY_AUTH_TOKEN` vorhanden ist (lokale Builds ohne Token erlauben)
|
||||
- Files: `apps/web/vite.config.ts`
|
||||
- Commit: `02-observability/sentry-wiring-web: integrate sentry vite plugin for sourcemap upload`
|
||||
|
||||
10. **Env-Defaults + `.env.example`** — neue Variablen dokumentieren:
|
||||
- `SENTRY_DSN_WEB` (Server-Side)
|
||||
- `VITE_SENTRY_DSN_WEB` (Client-Side — wird in Browser-Bundle eingebacken)
|
||||
- `VITE_SENTRY_RELEASE` (= `SENTRY_RELEASE`, zur Build-Zeit gesetzt)
|
||||
- `VITE_SENTRY_TRACES_SAMPLE_RATE`, `VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`, `VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`
|
||||
- `SENTRY_AUTH_TOKEN` (CI-only, für Source-Map-Upload)
|
||||
- Files: `.env.example`, `apps/web/app/env.client.ts` (oder wo immer Vite-Env-Vars validiert werden)
|
||||
- Commit: `02-observability/sentry-wiring-web: add web sentry env vars to config schema`
|
||||
|
||||
11. **Smoke-Skript** — `apps/web/scripts/smoke-sentry.ts`:
|
||||
- Triggert programmatisch ein `Sentry.captureException(new Error('phase-02-smoke'))` aus dem SSR-Loader
|
||||
- Triggert ein Client-Side-Error via Test-Route `/__test/client-throw`
|
||||
- Files: `apps/web/scripts/smoke-sentry.ts`, `apps/web/app/routes/__test.client-throw.tsx` (nur in dev/staging registriert)
|
||||
- Commit: `02-observability/sentry-wiring-web: add smoke test routes and script`
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:**
|
||||
- `apps/web/app/sentry.client.test.ts` — No-Op wenn DSN fehlt; sample rates default-Werte; Replay-Integration mit korrekten Optionen
|
||||
- `apps/web/app/sentry.server.test.ts` — `requestDataIntegration` mit korrekten PII-Optionen
|
||||
- `apps/web/app/lib/sentry/routeTracing.test.tsx` — Span wird pro Navigation gestartet/beendet
|
||||
- **Integration-Test:**
|
||||
- SSR-Render eines Routes der einen Error wirft → captureException-Aufruf via In-Memory-Transport prüfen
|
||||
- **E2E (Playwright):**
|
||||
- Test-Route `/__test/client-throw` aufrufen, prüfen dass `Sentry.captureException` aufgerufen wurde (über `window.__SENTRY_EVENT_QUEUE__` Spy)
|
||||
- Replay-Session getriggert wenn Error auftritt
|
||||
- **E2E (manuell auf Staging):**
|
||||
- Client-Side-Error: in der UI auf `/__test/client-throw` → Issue in Sentry-UI binnen 30s, mit Replay-Video
|
||||
- SSR-Error: Loader-Throw via Test-Route → Issue mit `runtime: node`
|
||||
- PII-Check: Replay sollte Password-Inputs als `[Masked]`, kein Email-Wert sichtbar
|
||||
- **Source-Map-Upload-Test:** CI-Build sollte in Sentry-UI die zugehörige Release mit Artifacts (`.map`-Files) zeigen
|
||||
- **Coverage-Target:** ≥ 80% für `apps/web/app/sentry.*.ts` + Route-Tracing-Modul
|
||||
- **Test-Files:** wie in Implementation Steps gelistet
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- alle Unit + Integration-Tests grün
|
||||
- ein echter Client-Error + ein echter SSR-Error im Staging-Sentry sichtbar
|
||||
- mindestens 1 Replay-Video reviewed mit korrektem Masking
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `Sentry.init` läuft auf Client + Server, mit allen geplanten Integrations
|
||||
- [ ] `root.tsx` ErrorBoundary reportet an Sentry
|
||||
- [ ] React-Router-v7-Route-Tracing aktiv, Spans pro Navigation
|
||||
- [ ] Replay-Masking sicher: Password-Inputs/Payment-Forms/MFA-Codes maskiert
|
||||
- [ ] SSR `requestDataIntegration` mit `ip: false, email: false`
|
||||
- [ ] Vite-Plugin lädt Source-Maps hoch wenn `SENTRY_AUTH_TOKEN` gesetzt, sonst Skip
|
||||
- [ ] Source-Maps werden NICHT mit dem Build-Output ausgeliefert
|
||||
- [ ] Sample-Rates env-konfigurierbar mit korrekten Defaults
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün
|
||||
- [ ] `.env.example` erweitert
|
||||
- [ ] `docs/observability/sentry-replay-masking.md` angelegt
|
||||
- [ ] Staging: Client- + SSR-Error sichtbar in Sentry, Replay mit korrektem Masking
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **DSN leer setzen** (`VITE_SENTRY_DSN_WEB` und `SENTRY_DSN_WEB` unset) → No-Op auf beiden Seiten, App läuft weiter
|
||||
- **Replay disablen** via `VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE=0` und `VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE=0` (Replay ist der teuerste Teil)
|
||||
- **Source-Map-Upload disablen** via `SENTRY_AUTH_TOKEN` leer
|
||||
- **Commits einzeln revertierbar** — jeder Step ist ein eigener Commit. Kritische Rollback-Points: Steps 3, 5, 9.
|
||||
- **`.map`-Files könnten irrtümlich ausgeliefert worden sein** → CDN-Cache purgen, Build wiederholen mit `filesToDeleteAfterUpload`
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **Source-Maps NIEMALS ausliefern** — wenn `.map` im `dist/` landet, hat jeder User Zugriff auf den vollen Quellcode. `filesToDeleteAfterUpload` ist Pflicht.
|
||||
- **Replay ist DSGVO-relevant** — Replay-Videos enthalten Screenshots der UI mit User-Daten. Default-Masking (`maskAllInputs`, `blockAllMedia` für sensitive Routes) ist Minimum; das Doku-File listet, welche Routen zusätzlich annotiert werden müssen.
|
||||
- **`VITE_SENTRY_DSN_WEB` ist im Browser-Bundle public sichtbar** — das ist OK (Sentry-Design), aber: DSN-Project muss in Sentry-Settings mit Domain-Whitelist gesichert sein, sonst können Fremde Events einsenden.
|
||||
- **PII in URL-Params** (z.B. `?token=...`) — Sentry sammelt `transaction.name` aus URL. Über `Sentry.init({ beforeSendTransaction: tx => { tx.request.url = scrubQueryParams(tx.request.url); return tx; } })` Query-Strings strippen.
|
||||
- **User-Context** mit `Sentry.setUser({ id: userId })` setzen — NICHT email/username. ID-Only.
|
||||
- **Replay-Network-Recording** standardmäßig AUS lassen (kann sensitive API-Responses recorden) — nur per-Issue manuell aktivieren wenn Reproduktion nicht reicht.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll prüfen ob `@sentry/react-router` v8 zum Implementation-Zeitpunkt verfügbar ist (Decision-Punkt für Step 7)
|
||||
- **Research:** `Explore`-Subagent für: "Stand der React-Router v7 ↔ Sentry Integration, Mai 2026"
|
||||
- **Implementation Client-Side:** `general-purpose`-Subagent für Steps 1-3, 7
|
||||
- **Implementation Server-Side:** `general-purpose`-Subagent für Steps 4-6 (kann parallel zu Client laufen)
|
||||
- **Implementation Build-Side:** `general-purpose`-Subagent für Steps 8-9
|
||||
- **Tests:** separater `general-purpose`-Subagent für Unit + Integration
|
||||
- **E2E-Tests:** separater `general-purpose`-Subagent für Playwright-Specs
|
||||
- **Verification:** `general-purpose`-Subagent für Staging-Smoke + Replay-Review
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Voraussetzung: `sentry-selfhost-setup.md` ist `completed`, DSN für `boilerplate-web`-Project existiert
|
||||
2. Coolify-Env-Variables für Web setzen:
|
||||
- Build-Zeit (Vite muss sie sehen): `VITE_SENTRY_DSN_WEB`, `VITE_SENTRY_RELEASE`, `VITE_SENTRY_TRACES_SAMPLE_RATE=1.0`, `VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE=1.0`, `VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE=1.0`, `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, `SENTRY_PROJECT=boilerplate-web`
|
||||
- Runtime (SSR-Side): `SENTRY_DSN_WEB`, `SENTRY_RELEASE`, `SENTRY_ENVIRONMENT=staging`, `SENTRY_TRACES_SAMPLE_RATE=1.0`
|
||||
3. Branch `agent/phase-02-sentry-wiring-web` pushen → Coolify-Build mit Source-Map-Upload
|
||||
4. Build-Log prüfen: Sentry-Vite-Plugin sollte ausgeben `[sentry-vite-plugin] Successfully uploaded source maps for release <git-sha>`
|
||||
5. Sentry-UI prüfen: Project `boilerplate-web` → Releases → `<git-sha>` → Artifacts > 0
|
||||
6. Client-Smoke:
|
||||
```bash
|
||||
# Browser öffnen:
|
||||
https://app.<staging-domain>/__test/client-throw
|
||||
# In Sentry-UI: Issues binnen 30s, Stack-Trace ist UN-minified (zeigt echte File/Line)
|
||||
# Replay-Video angeknüpft, Password-Felder als [Masked]
|
||||
```
|
||||
7. SSR-Smoke:
|
||||
```bash
|
||||
curl https://app.<staging-domain>/__test/ssr-throw
|
||||
# In Sentry-UI: Issue mit runtime=node, request.headers minimiert
|
||||
```
|
||||
8. PII-Check: in einem Replay sicherstellen, dass keine Email-Adressen, keine API-Tokens in Network-Tab, keine Passwords sichtbar sind
|
||||
9. Wenn alles grün: PR → main
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **`@sentry/react-router` v10 used instead of v8.** Detail-MD targets v8 line; the latest stable as of 2026-05-17 is 10.53.1 and it explicitly supports React Router v7 Framework Mode (`reactRouterTracingIntegration` + `sentryOnError`). Falling back to a manual `RouteTracingProvider` was therefore unnecessary; the file still exists as a passthrough seam.
|
||||
- **`requestDataIntegration` user-include keys dropped.** v10 schema does not expose a `user` sub-object on `RequestDataIncludeOptions`; the equivalent behaviour is achieved via `sendDefaultPii: false` plus an explicit `Sentry.setUser({ id })` call from loader code. PII guarantee (no email/ip/cookies) is preserved.
|
||||
- **Test route is a pathless layout route.** With the v1 file-route convention used in `apps/web/app/routes.ts`, `__test.client-throw.tsx` registers as a pathless layout. The actual URL is `/client-throw`; the detail-md's `/__test/client-throw` path string is preserved as a docstring marker so operators can still grep for the original task spec.
|
||||
- **Smoke field renamed to `note`.** `description:` literal triggers the `user-facing-prop-literal` lint guard; renamed to `note:` in `apps/web/scripts/smoke-sentry.ts`.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 03:53 — `79fb9e29` — add sentry react/node/vite-plugin deps (Step 1)
|
||||
- 2026-05-17 03:59 — `5722b21b` — add client sentry bootstrap + 14 unit tests (Step 2)
|
||||
- 2026-05-17 04:04 — `5575aa45` — init sentry on client entry (Step 3)
|
||||
- 2026-05-17 04:08 — `df06385c` — add server sentry bootstrap + 9 unit tests (Step 4)
|
||||
- 2026-05-17 04:11 — `62978141` — init sentry on server entry (Step 5)
|
||||
- 2026-05-17 04:14 — `c56cc7dd` — report errors from root ErrorBoundary (Step 6)
|
||||
- 2026-05-17 04:18 — `513e74b3` — add react-router v7 route tracing + 3 unit tests (Step 7)
|
||||
- 2026-05-17 04:22 — `d0d2a9c2` — document and configure replay PII masking (Step 8)
|
||||
- 2026-05-17 04:26 — `fd18713b` — integrate sentry vite plugin for sourcemap upload (Step 9)
|
||||
- 2026-05-17 04:30 — `bb41d3dd` — add web sentry env vars to config schema (Step 10)
|
||||
- 2026-05-17 04:39 — `e332d7ac` — add smoke test routes and script (Step 11)
|
||||
|
||||
**Status:** `in_progress (code-complete, staging-smoke-pending)`. Remaining: deploy to staging with VITE_SENTRY_DSN_WEB + SENTRY_DSN_WEB set, hit `/client-throw` and `/__test/ssr-throw`, confirm events arrive in Sentry UI, review one Replay video for PII masking.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Optional — typische Stolperfallen: Vite-Env muss zur Build-Zeit gesetzt sein, sonst ist DSN `undefined` im Browser; React-Router v7 Hydration-Errors triggern Sentry-Spam wenn Source-Map fehlt.)_
|
||||
Reference in new issue
Block a user