feat(portal-shell): wire spa-side opentelemetry tracing
CI / commits (pull_request) Successful in 1m9s
CI / scan (pull_request) Successful in 1m21s
CI / check (pull_request) Successful in 1m35s
CI / a11y (pull_request) Successful in 1m25s
CI / perf (pull_request) Successful in 2m38s

Phase 2 of ADR-0012 — closes the loop SPA → BFF → DB. With this
PR a single user action (page load, click, form submit) produces
one trace whose root span is owned by the SPA and whose child
spans cover the BFF request, Postgres queries, and (eventually)
Redis / downstream-API hops.

Runtime libs added (production deps):

- @opentelemetry/sdk-trace-web              browser tracer + provider
- @opentelemetry/exporter-trace-otlp-http   OTLP/HTTP+JSON exporter
- @opentelemetry/instrumentation            auto-instrumentation runtime
- @opentelemetry/instrumentation-fetch      fetch + W3C traceparent propagation
- @opentelemetry/instrumentation-document-load  initial-paint timings
- @opentelemetry/instrumentation-user-interaction  click / keypress / submit

Code:

- apps/portal-shell/src/observability/tracing.ts — WebTracerProvider
  bootstrap. Documents the load-order constraint inline (must be
  the very first import of main.ts, same pattern as the BFF). No
  context-zone package because the workspace is zoneless (per
  ADR-0004); the default StackContextManager covers the
  auto-instrumentation cases.
- main.ts now imports the tracing module as line 1.

CORS plumbing for end-to-end propagation:

- BFF (apps/portal-bff/src/main.ts) calls enableCors with a
  minimal dev allowlist (http://localhost:4200) and explicit
  permission for the W3C traceparent and tracestate headers. The
  full security-grade CORS belongs to phase-2 security ADR; this
  is the strict minimum for the SPA→BFF link to keep the trace
  context across origins.
- OTel Collector (infra/local/otel-collector.yaml) gains a cors
  block on its OTLP/HTTP receiver so the browser's OTLP POST
  clears its own pre-flight.

ADR-0012 §Confirmation: a new "Wired in the SPA foundation PR
(phase 2)" block enumerates what landed here; the carry-over
"Wired as features land" list is updated to drop the SPA-side
SDK item that used to live there and to add a CORS-grade
follow-up note.

Verified locally:
- pnpm exec nx run-many -t lint test build → 8 projects green.
- pnpm audit clean.
- After ./infra/local/dev.sh up observability and nx serve
  portal-shell, opening http://localhost:4200 produces a
  document_load trace in Jaeger with the SPA service.name; a
  manual fetch from DevTools to /api/health on the BFF produces
  a child span on the same trace.
This commit is contained in:
Julien Gautier
2026-05-09 23:18:42 +02:00
parent c3c15585ff
commit 13a12e6591
7 changed files with 255 additions and 36 deletions
+6
View File
@@ -1,3 +1,9 @@
// MUST be the very first import — see apps/portal-shell/src/observability/tracing.ts
// for the reasoning. The auto-instrumentations patch `fetch`,
// `XMLHttpRequest`, and `addEventListener` at module-load time;
// anything imported above this line escapes that patching.
import './observability/tracing';
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
@@ -0,0 +1,81 @@
/**
* OpenTelemetry SDK bootstrap for the SPA (per ADR-0012, phase 2).
*
* Symmetrical to apps/portal-bff/src/observability/tracing.ts — must
* be the very first import in `main.ts` so the auto-instrumentations
* patch `fetch` / `XMLHttpRequest` / `addEventListener` before any
* application code runs.
*
* What this enables out of the box
* ────────────────────────────────
* - `document_load` span on first paint, capturing every Performance
* Timing API metric (DNS, TLS, request, response, DOM events).
* - `fetch` spans for every outgoing request, with the W3C
* `traceparent` header propagated so the BFF picks up the same
* trace id and produces a child span. The result in Jaeger is one
* end-to-end trace SPA → BFF → DB.
* - `user_interaction` spans for click / keypress events on
* instrumented elements.
*
* Notes on the zoneless setup
* ───────────────────────────
* Angular here is zoneless (per ADR-0004), so we deliberately do NOT
* pull in `@opentelemetry/context-zone`. The default
* `StackContextManager` baked into `@opentelemetry/sdk-trace-web` is
* sufficient: the auto-instrumentations capture context at patch
* time and propagate it across the boundaries they own (fetch
* lifecycle, event handlers). Custom spans across `await` will need
* explicit `context.with(...)` plumbing — fine, encountered as code
* lands.
*
* Endpoint configuration
* ──────────────────────
* The OTLP/HTTP endpoint is hard-coded for v1 because env vars do
* not flow into the browser bundle natively (Angular's
* `environment.ts` mechanism is the standard alternative; we'll
* adopt it when prod build needs it). The default targets the
* Collector that ships in `infra/local/dev.compose.yml`. CORS is
* enabled on that Collector receiver — see `otel-collector.yaml`.
*/
import { WebTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-web';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load';
import { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction';
const SERVICE_NAME = 'portal-shell';
const SERVICE_VERSION = 'dev';
const OTLP_ENDPOINT = 'http://localhost:4318/v1/traces';
const provider = new WebTracerProvider({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: SERVICE_NAME,
[ATTR_SERVICE_VERSION]: SERVICE_VERSION,
}),
spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({ url: OTLP_ENDPOINT }))],
});
provider.register();
registerInstrumentations({
instrumentations: [
// Times the initial page load — fires once.
new DocumentLoadInstrumentation(),
// Wraps every `fetch` call. Propagates `traceparent` to the
// listed origins; the BFF dev server is the one we care about
// today. Add prod origins once they exist.
new FetchInstrumentation({
propagateTraceHeaderCorsUrls: [
/^http:\/\/localhost:3000\/.*/, // BFF dev server
],
}),
// Auto-spans on click / keypress / submit (and a small allow-list
// beyond that). Quiet in dev, useful in staging perf
// investigations.
new UserInteractionInstrumentation(),
],
});