feat(observability): add product metrics for API, outbox and delivery

This commit is contained in:
shira committed 2026-10-06 19:48:15 +03:00
1 parent 560724e2aa
commit 94488e2b57
51 files changed
+3655 -68

No files matched your search

+10 -2
View File
@@ -248,6 +248,7 @@ A notification request is a row in `mail_requests` until the consumer `notificat
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Deliveries created while `EMAIL_PROVIDER=disabled` stay pinned to `disabled` until the sending worker (TASK-016) moves them with `Rebind`, which is allowed only before the first attempt.
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats.
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Until the sending worker exists (TASK-016), every stored delivery stays `pending` and its due age only grows. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1; that gauge belongs to the sending worker of TASK-016, which must export it while its loop runs, so the alert stays silent while no sender exists, with `EMAIL_PROVIDER=disabled`, and without traffic.
- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision.
- Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request.
@@ -259,6 +260,7 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo
- Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month.
- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet.
- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`.
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up.
- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused.
- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017).
@@ -299,11 +301,17 @@ Start the core project first. Monitoring joins its Docker network. Monitoring st
Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports.
The `Lincodex product` dashboard in the Lincodex folder shows API request rate, error ratio, p50 and p95 latency of successful requests by route template, problem responses by code, outbox backlog and lag, relay, consumer, and scheduled job outcomes, mail deliveries by kind and status, the oldest due pending delivery, quota usage, and assessment answer saves. The answer save panel stays empty until the answer command is implemented. Prometheus loads the alert rules from `observability/prometheus/rules/`; their state is in the Prometheus rules API `/api/v1/rules`, which Grafana reaches through the Prometheus data source (Prometheus itself publishes no host port). No Alertmanager or notification channel is configured, so no alert reaches a person.
`make -C observability verify-product-metrics` checks this end to end on throwaway stacks: it starts an isolated core project `lincodex-metrics-check` on port 18085 and, separately, the monitoring project `lincodex-metrics-check-monitoring` with Grafana on 127.0.0.1:13085 (`METRICS_CHECK_HTTP_PORT` and `METRICS_CHECK_GRAFANA_PORT` change them), sends successful and failing API requests and a fixture mail delivery through the outbox, checks the values in Prometheus and every panel query of the product dashboard through Grafana, sends the fixture address in a query through Nginx and in a path straight to the backend, provokes a unique violation on the fixture address in PostgreSQL and checks that its log line omits the key, searches the metric exposition, all series and label values, the federated samples, and the Loki logs for the fixture address (after Loki shows both backend request lines of the run), and removes both projects with their volumes. It uses `EMAIL_PROVIDER=resend` with a placeholder key so the quota gauges exist; nothing sends mail in this build. It is an explicit end-to-end check, not part of `make -C observability check`: it starts two separate Compose projects and builds the core images. It starts every monitoring service except node-exporter, which reads only host metrics and whose root mount fails on Docker Desktop. It refuses to run when volumes or networks of these projects already exist, removes the images it built, and with `METRICS_CHECK_KEEP_ON_FAILURE=1` keeps both projects after a failure for inspection.
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Kafka logs and metrics are not collected yet; read the logs with `make -C deploy logs`. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
What reaches Loki from the core services: the backend request log (`http request`, `http request error`, `http request failed`) names a request only by its request ID, method, route template (the same as the metric label, such as `/api/v1/me/invitations/{invitation_id}`), status and status class, problem code, latency, response size, and the number of query parameters; it never logs the raw path, a query key or value, a header, the client address, or the user agent. Nginx in the frontend container logs the method, the path without the query string, status, timings, and request ID; a path that a client fills with an address would therefore appear in its log, which no API route invites. PostgreSQL runs with `log_error_verbosity=terse`, so an error line leaves out the DETAIL that quotes a duplicate or missing key, such as an address; the backend binds parameters, so the logged statement holds only placeholders. Handler logs follow the rules of their components, for example deliveries by `delivery_id` only.
Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent.
Alloy uses docker-socket-proxy for container discovery. The proxy enables only the needed Docker API sections for containers, events, ping, and version; POST is disabled. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user/<uid>/docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
Alloy uses docker-socket-proxy for container discovery and log collection. The proxy enables only the needed Docker API sections for containers, events, networks, ping, and version; POST is disabled. Alloy's Docker discovery reads the networks of each container for its labels; without the networks section discovery fails with 403 and no log reaches Loki. The proxy sits alone with Alloy on the internal `docker-api` network, so no other monitoring or core container can call it. What the containers section still allows to Alloy: `GET /containers/{id}/json` returns the configuration of every container on the host, including `Config.Env` with the passwords and keys of the core services, and the same path prefix also allows `GET` of `/containers/{id}/logs`, `/containers/{id}/archive` (files from a container), and `/containers/{id}/export` (a container's whole file system). A compromised Alloy can therefore read the secrets of the stack; the network keeps every other container from doing the same. The `read_only` flag of the socket mount only protects the socket file and does not restrict any API call. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user/<uid>/docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
PostgreSQL creates a separate exporter role only while initializing an empty volume and when POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD are set. Set both before the first make -C deploy up. Changing them after the volume exists does not rerun the init script.
@@ -566,7 +574,7 @@ go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, Redis exporter on port 9121, SeaweedFS on port 9327, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
The five checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux system. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
The six checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, Linux system, and Lincodex product (`lincodex-product.json`, described in [Separate monitoring Compose project](#separate-monitoring-compose-project)). Prometheus loads `prometheus/rules/*.yml`; `make -C observability check` validates them with `promtool check config` and runs their unit tests in `prometheus/tests/` with `promtool test rules`. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior.