
# Connect error tracking and metrics

You connect the instance to error tracking ([Bugsink](https://www.bugsink.com/), Sentry protocol and SDK), to an optional audience measurement ([Cloudflare Web Analytics](https://www.cloudflare.com/web-analytics/)) and to a Prometheus, knowing what each one sees and what it must never see. The first two components are **disabled** until you give them a key, and in development and test.

## What always runs

The **health probes** `/q/health/live` and `/q/health/ready` are public and silent on any connection detail; their use is in [Monitor the instance](surveillance.md). Readiness rests on a single check, the Flyway history, which first says the database is unreachable; a pending or failed migration also makes the instance not ready (defence in depth against a history modified under a running instance). Once the history is read up to date, the verdict is kept: each call only does a `SELECT 1`, and goes `DOWN` without any driver message if the database stops answering (the detail goes to the server log, once per outage), re-read at most every 5 s. Quarkus's datasource check is **switched off**: on failure, it would copy the driver message, hence the database host, into the public answer.

The **operating metrics**, in Prometheus format, are served on a separate port that the production stack does not publish ([Metrics](#métriques)).

## The non-negotiable point: the staff espace token

The espace URL carries the access token, **a unique identifier of a person, often a minor**. The wall display's URL carries its own, which opens the day's named schedule to whoever holds it. Three safeguards, for both:

- the Cloudflare beacon **is not loaded at all** on `/animateur/*` or `/mural/*`;
- error reports are scrubbed **on both sides**, for pages (`/animateur/…`, `/mural/…`) and API calls (`/api/espace-animateur/…`, `/api/mural/…`). In the browser, `maskTokensEverywhere` walks the **whole** report (`beforeSend`, `beforeBreadcrumb`) rather than a list of fields: masking only `request.url` and `data.url` let through an internal page change (`data.from` / `data.to`) and an HTTP failure whose message contains the URL. On the server, `maskTokensInReport` does the same, and also masks any e-mail address (a relay's refusal often quotes the recipient's);
- a refused send logs **its category** (address refused, relay unreachable…), never the exception's trace and so never the address the relay quotes in it; a failure that is not a relay's refusal (a bug) keeps its class and trace, without the exception's message;
- `Referrer-Policy: same-origin` closes the outgoing-link channel.

This is what makes true the sentence the privacy policy addresses to staff. **Every new sending path must preserve this property.**

## What a solve that dies used to tell nobody

A solve is launched with a `202`: the solve runs apart and its failure arrives later **in the job**, never crossing `GlobalExceptionMapper`. It is the only failure the organiser sees on their screen and nobody else sees. `SolverJobService.reportFailure` reports it where the exception is still in hand, with its stack, for the screen, the API and MCP; the event carries the job type, its identifier, the edition and the scope. If the tracker is absent or down, the log line remains. A **cancelled** job is not a failure and is not reported.

## Metrics

Sentry says what broke; metrics say how it runs. Micrometer, Prometheus registry, always on.

### Where, and why not elsewhere

The endpoint is **`/q/metrics` on the management interface**, port **9000**, a second HTTP server distinct from the application port. It has **no authentication** (a scraper opens no session): its only protection is to be reachable only from the internal network. `docker-compose.prod.yml` publishes only `127.0.0.1:8080`, the reverse proxy knows only that port, the image does not declare 9000 in `EXPOSE` (a `docker run -P` would publish it), and on the application port `/q/metrics` answers `404`. A Prometheus added to the stack reads `http://app:9000/q/metrics`; outside a container (`quarkus:dev`), `localhost:9000`. The `/q/health/*` probes and the API documentation (`/q/openapi`, `/q/swagger-ui`) **stay on the application port**, where the compose `healthcheck`, the deployment scripts and the external probes look for them.

### What is measured

| Metric | Type | Labels | What it says |
| --- | --- | --- | --- |
| `planning_solver_duration_seconds` | timer | `type` (`full`, `incremental`), `outcome` (`completed`, `failed`, `refused`, `cancelled`, `interrupted`) | duration of a solve, from start to final state; `refused` = business refusal (nothing to schedule), not a failure |
| `planning_solver_failures_total` | counter | `type` | solves dead on an unexpected error, exactly those `reportFailure` sends to Sentry |
| `planning_solver_queue_size` | gauge | — | jobs in the queue (in memory: empty after a restart) |
| `planning_solver_active` | gauge (0/1) | — | a job holds the solver |
| `planning_mail_sent_total`, `planning_mail_failures_total` | counters | `template` (`code-acces`, `planning-publie`, `rappel-veille`…) | mails handed to the SMTP server, or refused, notifications included |
| `planning_backup_duration_seconds` | timer | `outcome` (`success`, `failure`) | duration of each `pg_dump` |
| `planning_backup_last_success_timestamp_seconds` | gauge | — | date of the last successful backup (epoch seconds) |
| `planning_backup_size_bytes` | gauge | — | size of that last dump |
| `http_server_requests_seconds` | timer | `uri` (route template), `method`, `status`, `outcome` | API latency |

Added to these is what the extension and Timefold publish by default: JVM, Vert.x, connection pool (`agroal_*`) and the solver counters (`timefold_solver_*`). Three behaviours to know when writing an alert:

- **on restart, counters start again from zero** (Prometheus rule: `increase()` and `rate()` account for it); the last successful backup date is re-read from the database, the size from the dump still present;
- **without `BACKUP_DIR`, the two backup gauges do not exist**, nor on an instance that never succeeded a backup: an absent date rather than a zero that would say "1970";
- **`MAIL_MOCK=true` still counts**: in acceptance testing, "the mail would have gone" is what you want to see.

### Bounded cardinality: the token, again

No label carries an edition, a staff member, a token, an address or an identifier: every label is a closed set. For `uri`, the requirement is the same as for error reports: **the espace token and the ICS subscription token travel in the path**, and a label that copied it would send it to monitoring. Three `application.properties` settings:

- a REST route is labelled by its **template** (`/espace-animateur/{jeton}`, `/abonnements/{token}/planning.ics`, without the `/api` prefix), never by the path called;
- a 4xx/5xx answer with no recognised route (refused connection, rate limiter, a bot trying `/wp-admin`) is labelled `UNKNOWN` (`suppress4xx-errors`), a 404 `NOT_FOUND`;
- everything the Angular frontend serves, espace link `/animateur/<token>` and fingerprinted files included, is folded into a single value, `/{frontend}` (`match-patterns`).

The number of `uri` values is bounded by the number of routes (about two hundred): the extension's default ceiling, 100, would silently drop every route past the hundredth, hence `max-uri-tags` at 500. **Every new metric must preserve this property.**

## Two configuration traps

**Audience measurement is off until you give it a token.** The `%prod` profile used to provide a fallback (the publisher's account): any instance deployed without thinking sent its audience to that account, while declaring a transfer outside the EU in its own legal notices. The default has been empty since; setting `CLOUDFLARE_WEB_ANALYTICS_TOKEN` is the only way to switch the measurement on.

**The Sentry SDK's collection is set explicitly** (`dataCollection`), and the SDK is loaded only if a DSN is configured. Leaving the option empty since version 11 would attach the user, cookies, headers and HTTP bodies to errors; the configuration takes version 10's restrictive base: no user, no cookie, no body, headers and URL parameters filtered.

## Variables

| Variable | Default | Use |
| --- | --- | --- |
| `SENTRY_DSN` | empty | Bugsink DSN, or any Sentry-compatible endpoint. Empty = disabled on both sides |
| `SENTRY_ENVIRONMENT` | `local` | Label attached to every error |
| `CLOUDFLARE_WEB_ANALYTICS_TOKEN` | empty | Token of the Cloudflare account that receives the audience. Empty = disabled |

The frontend is built **once** and served as is: it cannot receive these keys at build time without duplicating the bundle per environment, so the backend exposes them through `/api/config`, read before `bootstrapApplication()`. A DSN and a beacon token are public identifiers by construction: exposing them creates no leak. The Debug page (*Checks* tab) raises a test exception on each side to check a freshly configured DSN.

## GDPR

Bugsink is consumed as a **hosted offer**: it is a **processor**, which the privacy policy must say. The publisher announces EU hosting, so there is no transfer outside the EU to declare, unlike Cloudflare. The policy says it **only if the tool runs**: `/api/mentions-legales` returns `mesureAudience` and `suiviErreurs`, computed on the **effective value** of these two keys, and the page shows only the matching paragraphs. Setting a variable switches the tool on and adds its declaration; emptying it removes both, so a deployment that sends nothing to Cloudflare announces no transfer outside the EU. A third component calls for a third flag, not one more hard-coded paragraph.
