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

+6 -2
View File
@@ -7,7 +7,7 @@ PROMETHEUS_IMAGE := prom/prometheus:latest
LOKI_IMAGE := grafana/loki:latest
ALLOY_FILE := $(ROOT)/observability/alloy/app.alloy
.PHONY: help fmt fmt-check check
.PHONY: help fmt fmt-check check verify-product-metrics
help: ## Show observability commands
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -22,8 +22,12 @@ fmt-check: ## Check Alloy formatting and dashboard JSON formatting
diff -u "$(ALLOY_FILE)" "$$tmp"
@python3 -c 'import json, pathlib, sys; bad=[]; root=pathlib.Path("$(ROOT)/observability/grafana/dashboards"); paths=sorted(root.glob("*.json")); [(bad.append(str(p)) if p.read_text() != json.dumps(json.loads(p.read_text()), indent=2) + "\n" else None) for p in paths]; print("dashboard formatting is clean" if not bad else "dashboard JSON formatting differs: " + ", ".join(bad)); sys.exit(bool(bad))'
check: fmt-check ## Validate Prometheus, Loki, Alloy, and dashboard files
check: fmt-check ## Validate Prometheus config and alert rules, Loki, Alloy, and dashboard files
$(DOCKER) run --rm --entrypoint /bin/promtool -v "$(ROOT)/observability/prometheus:/etc/prometheus:ro" "$(PROMETHEUS_IMAGE)" check config /etc/prometheus/prometheus.yml
$(DOCKER) run --rm --entrypoint /bin/promtool -v "$(ROOT)/observability/prometheus:/etc/prometheus:ro" "$(PROMETHEUS_IMAGE)" test rules /etc/prometheus/tests/lincodex_rules_test.yml
$(DOCKER) run --rm -v "$(ROOT)/observability/loki:/etc/loki:ro" "$(LOKI_IMAGE)" -config.file=/etc/loki/loki.yml -verify-config
$(DOCKER) run --rm -v "$(ROOT)/observability/alloy:/etc/alloy:ro" "$(ALLOY_IMAGE)" validate /etc/alloy/app.alloy
@python3 -c 'import json, pathlib; files=sorted(pathlib.Path("$(ROOT)/observability/grafana/dashboards").glob("*.json")); [json.loads(path.read_text()) for path in files]; assert files, "no Grafana dashboards found"; print(f"validated {len(files)} dashboard JSON file(s)")'
verify-product-metrics: ## Start isolated core and monitoring stacks, check the product metrics, dashboard, and log privacy, then remove them
@bash "$(ROOT)/observability/scripts/verify-product-metrics.sh"
+4 -3
View File
@@ -4,10 +4,11 @@
Configuration for collecting metrics and logs, with dashboards for service health.
- `prometheus/` configures metric collection and ML targets.
- `prometheus/` configures metric collection and ML targets; `prometheus/rules/` holds the alert rules and `prometheus/tests/` their `promtool` unit tests.
- `loki/` configures log storage; `alloy/` handles log collection and forwarding.
- `grafana/` contains data sources and dashboards for Go, PostgreSQL, Redis, SeaweedFS, and the host.
- `grafana/` contains data sources and dashboards for Go, PostgreSQL, Redis, SeaweedFS, the host, and the Lincodex product metrics: API latency and errors, outbox lag, consumers and scheduled jobs, mail deliveries and quota, and assessment answer saves.
- `scripts/verify-product-metrics.sh` is the end-to-end check behind `make -C observability verify-product-metrics`.
From the repository root, `make -C observability check` validates configuration using Docker. Start monitoring separately after the core services with `make -C deploy monitoring-up`; its Compose file lives in `deploy/docker/`.
From the repository root, `make -C observability check` validates configuration and runs the alert rule tests using Docker. `make -C observability verify-product-metrics` is an explicit end-to-end check, not part of `check`: it starts two separate throwaway Compose projects, core and monitoring, and checks the product metrics, the dashboard, and that a fixture address reaches neither metrics nor logs. Start monitoring separately after the core services with `make -C deploy monitoring-up`; its Compose file lives in `deploy/docker/`.
See the [deployment guide](../docs/en/DEPLOY.md).
+4 -3
View File
@@ -4,10 +4,11 @@
Настройки сбора метрик и логов, а также готовые дашборды для технического состояния сервисов.
- `prometheus/` - сбор метрик и список ML-targets.
- `prometheus/` - сбор метрик и список ML-targets; `prometheus/rules/` - правила alerts, `prometheus/tests/` - их unit-тесты для `promtool`.
- `loki/` - хранение логов; `alloy/` - их сбор и отправка.
- `grafana/` - источники данных и дашборды Go, PostgreSQL, Redis, SeaweedFS и хоста.
- `grafana/` - источники данных и дашборды Go, PostgreSQL, Redis, SeaweedFS, хоста и продуктовых метрик Lincodex: задержка и ошибки API, отставание outbox, обработчики и задания по сроку, доставки и квоты почты, сохранение ответов теста.
- `scripts/verify-product-metrics.sh` - сквозная проверка за `make -C observability verify-product-metrics`.
Из корня: `make -C observability check` проверяет конфигурации через Docker. Сам стек запускается отдельно после основных сервисов командой `make -C deploy monitoring-up`; его Compose-файл находится в `deploy/docker/`.
Из корня: `make -C observability check` проверяет конфигурации и запускает тесты правил alerts через Docker. `make -C observability verify-product-metrics` - явная сквозная проверка, не входящая в `check`: она поднимает два отдельных одноразовых Compose проекта, core и monitoring, и проверяет продуктовые метрики, dashboard и то, что fixture адрес не попадает ни в метрики, ни в логи. Сам стек запускается отдельно после основных сервисов командой `make -C deploy monitoring-up`; его Compose-файл находится в `deploy/docker/`.
Подробнее: [развертывание](../docs/ru/DEPLOY.md).
File diff suppressed because it is too large. Load diff
+3
View File
@@ -2,6 +2,9 @@ global:
scrape_interval: 30s
evaluation_interval: 30s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: prometheus
static_configs:
+129
View File
@@ -0,0 +1,129 @@
# Alert rules for the Lincodex backend product metrics. Prometheus evaluates
# them and shows their state on its /alerts page and to Grafana; no
# Alertmanager is configured, so nothing is sent to a person yet.
#
# Gauges that describe database-wide state are reported by every backend
# instance with the same value, so the rules aggregate them with max. Labels
# stay bounded: route templates, status codes, problem codes, consumer and job
# kind names, delivery kind and status, provider, and quota window.
groups:
- name: lincodex-api
rules:
- alert: LincodexBackendDown
expr: up{job="backend"} == 0
for: 2m
labels:
severity: critical
annotations:
summary: Prometheus cannot scrape the backend metrics endpoint.
description: The backend /metrics listener has not answered for 2 minutes; the API may be down as well.
- alert: LincodexApiHighServerErrorRate
# The second condition needs at least 15 requests in 5 minutes, so a
# single failure on a quiet stand does not page anyone.
expr: |
(
sum(rate(lincodex_http_requests_total{job="backend",status=~"5.."}[5m]))
/ sum(rate(lincodex_http_requests_total{job="backend"}[5m]))
> 0.05
)
and
sum(rate(lincodex_http_requests_total{job="backend"}[5m])) > 0.05
for: 10m
labels:
severity: warning
annotations:
summary: More than 5% of API requests fail with a server error.
description: Check lincodex_http_problems_total by route and code and the backend logs in Loki.
- name: lincodex-events
rules:
- alert: LincodexOutboxRelayLagging
expr: max(lincodex_outbox_relay_oldest_pending_age_seconds{job="backend"}) > 300
for: 10m
labels:
severity: warning
annotations:
summary: The earliest unpublished outbox event is older than 5 minutes.
description: The relay does not keep up or cannot publish to Kafka; compare with the published rate of lincodex_outbox_relay_events_total and read the relay warnings.
- alert: LincodexEventConsumerDeadLetter
expr: sum by (consumer) (increase(lincodex_event_consumer_records_total{job="backend",outcome="dead_lettered"}[15m])) > 0
labels:
severity: warning
annotations:
summary: Consumer {{ $labels.consumer }} dead-lettered an event.
description: The record needs an operator; its event ID is in the consumer error log.
- alert: LincodexEventConsumerStalled
expr: sum by (consumer, stage) (increase(lincodex_event_consumer_failures_total{job="backend",stage=~"poll|commit"}[5m])) > 0
for: 10m
labels:
severity: warning
annotations:
summary: Consumer {{ $labels.consumer }} keeps failing at {{ $labels.stage }}.
description: The consumer cannot read Kafka or store its offsets; records wait or will be delivered again.
- alert: LincodexScheduledJobDead
expr: sum by (kind) (increase(lincodex_scheduled_jobs_total{job="backend",outcome="dead"}[15m])) > 0
labels:
severity: warning
annotations:
summary: A scheduled job of kind {{ $labels.kind }} is dead.
description: The job used up its attempts and needs an operator.
- alert: LincodexScheduledJobsLagging
expr: max(lincodex_scheduled_jobs_oldest_due_age_seconds{job="backend"}) > 600
for: 15m
labels:
severity: warning
annotations:
summary: A due scheduled job has waited for more than 10 minutes.
description: No instance claims due jobs; the worker may be disabled, failing, or missing the handler of their kind.
- name: lincodex-mail
rules:
- alert: LincodexMailDeliveryUnknownOutcome
expr: sum(max by (kind) (lincodex_mail_deliveries{job="backend",status="unknown"})) > 0
for: 5m
labels:
severity: warning
annotations:
summary: Mail deliveries have an unknown outcome.
description: An attempt may have reached the provider without a conclusive answer; a retry needs the same idempotency key, and after the idempotency window an operator decides.
# Inert until the sending worker exists: TASK-016 must export
# lincodex_mail_sender_running (1 while its loop runs) as part of its
# definition of done. Without that series the rule matches nothing.
- alert: LincodexMailDeliveriesOverdue
expr: |
max(lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend"}) > 900
and on ()
max(lincodex_mail_sender_running{job="backend"}) == 1
for: 15m
labels:
severity: warning
annotations:
summary: A pending mail delivery has been due for more than 15 minutes.
description: The sending worker runs but does not pick up due deliveries; check its logs and the quota gauges.
- alert: LincodexMailMetricsStale
expr: time() - max(lincodex_mail_metrics_last_success_timestamp_seconds{job="backend"}) > 300
for: 5m
labels:
severity: warning
annotations:
summary: The delivery and quota gauges have not been read for more than 5 minutes.
description: The delivery metrics sampler cannot read PostgreSQL; the delivery and quota gauges show old values. Read its warnings in the backend logs.
- alert: LincodexMailQuotaUsedUp
expr: |
max by (provider, window) (lincodex_mail_quota_used_recipients{job="backend"})
>= max by (provider, window) (lincodex_mail_quota_limit_recipients{job="backend"})
or
max by (provider, window) (lincodex_mail_quota_provider_exhausted{job="backend"}) == 1
labels:
severity: info
annotations:
summary: The {{ $labels.window }} mail quota of {{ $labels.provider }} is used up.
description: New deliveries wait for the UTC window reset in status waiting_quota; nothing switches the plan or the transport automatically.
@@ -0,0 +1,243 @@
# Unit tests for rules/lincodex.yml; run with `make -C observability check`.
# Every alert has a firing case; guarded alerts also have a silent one.
rule_files:
- ../rules/lincodex.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: lincodex_outbox_relay_oldest_pending_age_seconds{job="backend",instance="a"}
values: 400x20
- series: lincodex_outbox_relay_oldest_pending_age_seconds{job="backend",instance="b"}
values: '0x20'
alert_rule_test:
- eval_time: 5m
alertname: LincodexOutboxRelayLagging
exp_alerts: []
- eval_time: 15m
alertname: LincodexOutboxRelayLagging
exp_alerts:
- exp_labels:
severity: warning
exp_annotations:
summary: The earliest unpublished outbox event is older than 5 minutes.
description: The relay does not keep up or cannot publish to Kafka; compare with the published rate of lincodex_outbox_relay_events_total and read the relay warnings.
- interval: 1m
input_series:
- series: up{job="backend",instance="backend:9090"}
values: 1 1 0 0 0 0 0
alert_rule_test:
- eval_time: 3m
alertname: LincodexBackendDown
exp_alerts: []
- eval_time: 5m
alertname: LincodexBackendDown
exp_alerts:
- exp_labels:
severity: critical
instance: backend:9090
job: backend
exp_annotations:
summary: Prometheus cannot scrape the backend metrics endpoint.
description: The backend /metrics listener has not answered for 2 minutes; the API may be down as well.
- interval: 1m
input_series:
- series: lincodex_event_consumer_records_total{job="backend",consumer="mail_delivery",outcome="dead_lettered"}
values: 0 0 0 1 1 1
- series: lincodex_event_consumer_failures_total{job="backend",consumer="mail_delivery",stage="poll"}
values: 0+1x20
- series: lincodex_event_consumer_failures_total{job="backend",consumer="mail_delivery",stage="handler"}
values: 0+1x20
alert_rule_test:
- eval_time: 2m
alertname: LincodexEventConsumerDeadLetter
exp_alerts: []
- eval_time: 5m
alertname: LincodexEventConsumerDeadLetter
exp_alerts:
- exp_labels:
severity: warning
consumer: mail_delivery
exp_annotations:
summary: Consumer mail_delivery dead-lettered an event.
description: The record needs an operator; its event ID is in the consumer error log.
- eval_time: 5m
alertname: LincodexEventConsumerStalled
exp_alerts: []
- eval_time: 16m
alertname: LincodexEventConsumerStalled
exp_alerts:
- exp_labels:
severity: warning
consumer: mail_delivery
stage: poll
exp_annotations:
summary: Consumer mail_delivery keeps failing at poll.
description: The consumer cannot read Kafka or store its offsets; records wait or will be delivered again.
- interval: 1m
input_series:
- series: lincodex_scheduled_jobs_total{job="backend",kind="invitation.response_deadline",outcome="dead"}
values: 0 0 1 1 1
- series: lincodex_scheduled_jobs_oldest_due_age_seconds{job="backend",instance="a"}
values: 700x30
alert_rule_test:
- eval_time: 1m
alertname: LincodexScheduledJobDead
exp_alerts: []
- eval_time: 4m
alertname: LincodexScheduledJobDead
exp_alerts:
- exp_labels:
severity: warning
kind: invitation.response_deadline
exp_annotations:
summary: A scheduled job of kind invitation.response_deadline is dead.
description: The job used up its attempts and needs an operator.
- eval_time: 10m
alertname: LincodexScheduledJobsLagging
exp_alerts: []
- eval_time: 20m
alertname: LincodexScheduledJobsLagging
exp_alerts:
- exp_labels:
severity: warning
exp_annotations:
summary: A due scheduled job has waited for more than 10 minutes.
description: No instance claims due jobs; the worker may be disabled, failing, or missing the handler of their kind.
- interval: 1m
input_series:
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="200"}
values: 0+10x20
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="500"}
values: 0+5x20
alert_rule_test:
- eval_time: 20m
alertname: LincodexApiHighServerErrorRate
exp_alerts:
- exp_labels:
severity: warning
exp_annotations:
summary: More than 5% of API requests fail with a server error.
description: Check lincodex_http_problems_total by route and code and the backend logs in Loki.
- interval: 1m
input_series:
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="200"}
values: '0x20'
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="500"}
values: 0+1x20
alert_rule_test:
- eval_time: 8m
alertname: LincodexApiHighServerErrorRate
exp_alerts: []
- eval_time: 15m
alertname: LincodexApiHighServerErrorRate
exp_alerts: []
- interval: 1m
input_series:
- series: lincodex_mail_deliveries{job="backend",instance="a",kind="verification",status="unknown"}
values: 1x10
- series: lincodex_mail_deliveries{job="backend",instance="b",kind="verification",status="unknown"}
values: 1x10
- series: lincodex_mail_quota_used_recipients{job="backend",instance="a",provider="resend",window="day"}
values: 100x10
- series: lincodex_mail_quota_limit_recipients{job="backend",instance="a",provider="resend",window="day"}
values: 100x10
- series: lincodex_mail_quota_provider_exhausted{job="backend",instance="a",provider="resend",window="day"}
values: '0x10'
- series: lincodex_mail_quota_used_recipients{job="backend",instance="a",provider="resend",window="month"}
values: 120x10
- series: lincodex_mail_quota_limit_recipients{job="backend",instance="a",provider="resend",window="month"}
values: 3000x10
- series: lincodex_mail_quota_provider_exhausted{job="backend",instance="a",provider="resend",window="month"}
values: '0x10'
alert_rule_test:
- eval_time: 10m
alertname: LincodexMailDeliveryUnknownOutcome
exp_alerts:
- exp_labels:
severity: warning
exp_annotations:
summary: Mail deliveries have an unknown outcome.
description: An attempt may have reached the provider without a conclusive answer; a retry needs the same idempotency key, and after the idempotency window an operator decides.
- eval_time: 10m
alertname: LincodexMailQuotaUsedUp
exp_alerts:
- exp_labels:
severity: info
provider: resend
window: day
exp_annotations:
summary: The day mail quota of resend is used up.
description: New deliveries wait for the UTC window reset in status waiting_quota; nothing switches the plan or the transport automatically.
- interval: 1m
input_series:
- series: lincodex_mail_quota_used_recipients{job="backend",instance="a",provider="resend",window="month"}
values: 120x10
- series: lincodex_mail_quota_limit_recipients{job="backend",instance="a",provider="resend",window="month"}
values: 3000x10
- series: lincodex_mail_quota_provider_exhausted{job="backend",instance="a",provider="resend",window="month"}
values: 0 0 0 0 0 1 1 1 1 1
alert_rule_test:
- eval_time: 3m
alertname: LincodexMailQuotaUsedUp
exp_alerts: []
- eval_time: 7m
alertname: LincodexMailQuotaUsedUp
exp_alerts:
- exp_labels:
severity: info
provider: resend
window: month
exp_annotations:
summary: The month mail quota of resend is used up.
description: New deliveries wait for the UTC window reset in status waiting_quota; nothing switches the plan or the transport automatically.
- interval: 1m
input_series:
- series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"}
values: 2000x40
alert_rule_test:
- eval_time: 30m
alertname: LincodexMailDeliveriesOverdue
exp_alerts: []
- interval: 1m
input_series:
- series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"}
values: 2000x40
- series: lincodex_mail_sender_running{job="backend",instance="a"}
values: 1x40
alert_rule_test:
- eval_time: 10m
alertname: LincodexMailDeliveriesOverdue
exp_alerts: []
- eval_time: 20m
alertname: LincodexMailDeliveriesOverdue
exp_alerts:
- exp_labels:
severity: warning
exp_annotations:
summary: A pending mail delivery has been due for more than 15 minutes.
description: The sending worker runs but does not pick up due deliveries; check its logs and the quota gauges.
- interval: 1m
input_series:
- series: lincodex_mail_metrics_last_success_timestamp_seconds{job="backend",instance="a"}
values: '0x20'
alert_rule_test:
- eval_time: 5m
alertname: LincodexMailMetricsStale
exp_alerts: []
- eval_time: 12m
alertname: LincodexMailMetricsStale
exp_alerts:
- exp_labels:
severity: warning
exp_annotations:
summary: The delivery and quota gauges have not been read for more than 5 minutes.
description: The delivery metrics sampler cannot read PostgreSQL; the delivery and quota gauges show old values. Read its warnings in the backend logs.
- interval: 1m
input_series:
- series: lincodex_mail_metrics_last_success_timestamp_seconds{job="backend",instance="a"}
values: 0+60x20
alert_rule_test:
- eval_time: 15m
alertname: LincodexMailMetricsStale
exp_alerts: []
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env bash
# Starts an isolated core stack and, as a separate Compose project, the
# monitoring stack; sends a successful and failing API requests and a fixture
# mail delivery through the outbox, the relay, and the delivery consumer;
# checks the product metrics in Prometheus and the product dashboard through
# Grafana; and confirms that the fixture address appears in neither the
# metrics nor the logs in Loki. Everything it creates is removed on exit.
#
# Mail: EMAIL_PROVIDER=resend with a placeholder key, so the quota gauges
# exist. Nothing sends mail in this build: the sending worker is planned
# (TASK-016), and the stored delivery stays pending.
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
core_file="$root/deploy/docker/docker-compose.yml"
monitoring_file="$root/deploy/docker/docker-compose.monitoring.yml"
env_file="$root/.env.example"
project=lincodex-metrics-check
monitoring_project=lincodex-metrics-check-monitoring
app_network="${project}_default"
storage_network="${project}_storage"
port="${METRICS_CHECK_HTTP_PORT:-18085}"
grafana_port="${METRICS_CHECK_GRAFANA_PORT:-13085}"
grafana="http://127.0.0.1:$grafana_port"
# Example-config credentials of the throwaway Grafana.
grafana_auth="admin:replace-this-grafana-password"
fixture_email="Metrics.Check.Fixture@example.com"
fixture_email_lower=$(printf '%s' "$fixture_email" | tr '[:upper:]' '[:lower:]')
evidence_dir="${METRICS_CHECK_EVIDENCE_DIR:-$(mktemp -d)}"
core_started=0
monitoring_started=0
core() {
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \
APP_PUBLIC_URL="http://localhost:$port" EMAIL_PROVIDER=resend RESEND_API_KEY=re_placeholder_not_a_key \
EMAIL_ACCOUNT=metrics-check docker compose --env-file "$env_file" -p "$project" -f "$core_file" "$@"
}
monitoring() {
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" GRAFANA_PORT="$grafana_port" \
docker compose --env-file "$env_file" -p "$monitoring_project" -f "$monitoring_file" "$@"
}
fail() {
printf 'FAIL: %s\n' "$*" >&2
exit 1
}
for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data" \
"${monitoring_project}_prometheus_data" "${monitoring_project}_loki_data" "${monitoring_project}_grafana_data"; do
if docker volume inspect "$volume" >/dev/null 2>&1; then
fail "refusing to use the existing volume $volume"
fi
done
for existing in "$app_network" "$storage_network" "${monitoring_project}_observability"; do
if docker network inspect "$existing" >/dev/null 2>&1; then
fail "refusing to use the existing network $existing"
fi
done
cleanup() {
local result=$?
trap - EXIT
if (( result != 0 )) && [[ "${METRICS_CHECK_KEEP_ON_FAILURE:-}" == 1 ]]; then
printf 'Kept projects %s and %s for inspection; remove them with docker compose down --volumes.\n' "$project" "$monitoring_project" >&2
exit "$result"
fi
if (( monitoring_started )); then
monitoring down --volumes --remove-orphans || result=1
fi
if (( core_started )); then
core down --volumes --remove-orphans --rmi local || result=1
fi
printf 'Evidence kept in %s\n' "$evidence_dir"
exit "$result"
}
trap cleanup EXIT
core config --quiet
monitoring config --quiet
core_started=1
core up --build -d --wait --wait-timeout 180
monitoring_started=1
# node-exporter is left out: it reads host metrics only, and its rslave
# root mount fails on Docker Desktop. Every service that the product metrics,
# the dashboard, and the log path need is started.
monitoring up -d prometheus-targets prometheus postgres-exporter redis-exporter loki alloy docker-socket-proxy grafana
wait_for() {
local description=$1
shift
local attempt
for attempt in $(seq 1 90); do
if "$@" >/dev/null 2>&1; then
return 0
fi
sleep 2
done
fail "timed out waiting for $description"
}
wait_for "the API" curl --fail --silent "http://127.0.0.1:$port/api/v1/healthz"
wait_for "Grafana" curl --fail --silent "$grafana/api/health"
# Requests: one success, one unknown route, one operation that requires a
# session, one unsupported method, and an operation with a path parameter.
attempt_id=0199b4f2-7c1e-7d3a-9f00-aabbccddeeff
expect_status() {
local method=$1 path=$2 want=$3 got
got=$(curl --silent --output /dev/null --write-out '%{http_code}' -X "$method" "http://127.0.0.1:$port$path")
[[ "$got" == "$want" ]] || fail "$method $path returned $got, want $want"
printf '%s %s -> %s\n' "$method" "$path" "$got"
}
expect_status GET /api/v1/healthz 200
expect_status GET /api/v1/missing 404
expect_status GET /api/v1/identity/me 401
expect_status POST /api/v1/healthz 405
expect_status GET "/api/v1/me/assessment-attempts/$attempt_id" 401
# Requests that carry the fixture address. The query goes through Nginx,
# which logs the path without the query. No API path holds an address, and
# Nginx would log one verbatim, so the path request goes straight to the
# backend from inside the core network; it stands for any client-made path.
query_request_id=$(curl --silent --output /dev/null --dump-header - \
"http://127.0.0.1:$port/api/v1/healthz?email=$fixture_email" | tr -d '\r' | sed -n 's/^[Xx]-[Rr]equest-[Ii][Dd]: //p')
[[ -n "$query_request_id" ]] || fail "the API returned no request ID"
printf 'GET /api/v1/healthz?email=<fixture> -> request %s\n' "$query_request_id"
path_request_id=metrics-check-path-$(date +%s)
core exec -T frontend wget -q -O /dev/null --header "X-Request-ID: $path_request_id" \
"http://backend:8080/api/v1/users/$fixture_email" >/dev/null 2>&1 || true
printf 'GET backend:/api/v1/users/<fixture> -> request %s\n' "$path_request_id"
# The fixture delivery: a verified account, a mail request, and the outbox
# event that announces it, written in one transaction like MailRequester
# does. The relay publishes the event and the notification_delivery consumer
# stores the delivery.
user_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
request_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
event_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
psql() {
core exec -T postgres sh -ec 'psql -v ON_ERROR_STOP=1 -At -U "$POSTGRES_USER" -d "$POSTGRES_DB"' "$@"
}
psql <<SQL
BEGIN;
INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, email_verified_at,
registration_version, last_registered_at, version, created_at, updated_at)
VALUES ('$user_id', '$fixture_email', '$fixture_email_lower',
'\$argon2id\$v=19\$m=19456,t=2,p=1\$c2FsdHNhbHRzYWx0\$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA',
'candidate', 'candidate_consents', now(), 1, now(), 1, now(), now());
INSERT INTO mail_requests (id, recipient_user_id, kind, subject, body, link_path, created_at)
VALUES ('$request_id', '$user_id', 'notification', 'Metrics check', 'Metrics check fixture body.', '/candidate/invitations', now());
INSERT INTO outbox_events (event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload)
VALUES ('$event_id', 'notification.mail_requested', 1, 'mail_request', '$request_id', 1,
jsonb_build_object('mail_request_id', '$request_id', 'kind', 'notification'));
COMMIT;
SQL
# PostgreSQL logs errors tersely, so the DETAIL of a unique violation, which
# quotes the key, never reaches the container log. The duplicate account is
# sent with bound parameters, like the backend does, so the statement text in
# the log holds only placeholders.
[[ "$(printf 'SHOW log_error_verbosity' | psql)" == terse ]] || fail "PostgreSQL does not log errors tersely"
printf '%s\n' "INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, registration_version, last_registered_at, version, created_at, updated_at) SELECT gen_random_uuid(), \$1, \$2, password_hash, scenario, onboarding_step, 1, now(), 1, now(), now() FROM users LIMIT 1 \\bind '$fixture_email' '$fixture_email_lower' \\g" |
psql >/dev/null 2>&1 && fail "the duplicate account was accepted"
postgres_logs=$(core logs --no-color postgres)
[[ "$postgres_logs" == *"duplicate key value violates unique constraint"* ]] || fail "PostgreSQL did not log the unique violation"
if grep -qiF "$fixture_email_lower" <<<"$postgres_logs"; then
fail "the PostgreSQL log quotes the fixture address"
fi
printf '%s\n' 'PostgreSQL logged the unique violation without its key value'
delivery_stored() {
[[ "$(printf "SELECT status FROM deliveries WHERE id = '%s'" "$request_id" | psql)" == pending ]]
}
wait_for "the fixture delivery" delivery_stored
printf 'Fixture delivery %s stored as pending\n' "$request_id"
stored_address=$(printf "SELECT count(*) FROM deliveries WHERE id = '%s' AND recipient_email = '%s'" "$request_id" "$fixture_email" | psql)
[[ "$stored_address" == 1 ]] || fail "the fixture delivery does not hold the fixture address"
# Prometheus through the Grafana datasource proxy.
prometheus_get() {
curl --fail --silent --show-error -u "$grafana_auth" -G "$grafana/api/datasources/proxy/uid/prometheus$1" "${@:2}"
}
query_value() {
prometheus_get /api/v1/query --data-urlencode "query=$1" |
python3 -c 'import json, sys; result = json.load(sys.stdin)["data"]["result"]; print(sum(float(item["value"][1]) for item in result) if result else "none")'
}
expect_at_least() {
local query=$1 minimum=$2 value
value=$(query_value "$query")
[[ "$value" != none ]] && python3 -c "import sys; sys.exit(0 if float('$value') >= $minimum else 1)" ||
fail "$query = $value, want at least $minimum"
printf '%s = %s\n' "$query" "$value"
}
delivery_scraped() {
[[ "$(query_value 'max(lincodex_mail_deliveries{job="backend",kind="notification",status="pending"})')" == 1.0 ]]
}
wait_for "the delivery gauge in Prometheus" delivery_scraped
{
expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/healthz",status="200"})' 1
expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/*",status="404"})' 1
expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/me/assessment-attempts/{attempt_id}",status="401"})' 1
expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="unauthenticated"})' 2
expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="not_found",route="/api/v1/*"})' 1
expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="method_not_allowed"})' 1
expect_at_least 'sum(lincodex_http_request_duration_seconds_count{job="backend",status_class="2xx"})' 1
expect_at_least 'sum(lincodex_outbox_relay_events_total{job="backend",outcome="published"})' 1
expect_at_least 'count(lincodex_outbox_relay_oldest_pending_age_seconds{job="backend"})' 1
expect_at_least 'sum(lincodex_event_consumer_records_total{job="backend",consumer="notification_delivery",outcome="applied"})' 1
expect_at_least 'max(lincodex_mail_deliveries{job="backend",kind="notification",status="pending"})' 1
expect_at_least 'count(lincodex_mail_deliveries{job="backend"})' 15
expect_at_least 'max(lincodex_mail_quota_limit_recipients{job="backend",provider="resend",window="day"})' 100
expect_at_least 'count(lincodex_mail_quota_used_recipients{job="backend"})' 2
} | tee "$evidence_dir/prometheus-values.txt"
prometheus_get /api/v1/rules >"$evidence_dir/rules.json"
grep -q LincodexOutboxRelayLagging "$evidence_dir/rules.json" || fail "Prometheus did not load the alert rules"
# The dashboard: provisioned, and every panel query is accepted by
# Prometheus.
curl --fail --silent --show-error -u "$grafana_auth" "$grafana/api/dashboards/uid/lincodex-product" >"$evidence_dir/dashboard.json"
python3 - "$evidence_dir/dashboard.json" <<'PY' >"$evidence_dir/panel-queries.txt"
import json, sys
dashboard = json.load(open(sys.argv[1]))["dashboard"]
for panel in dashboard["panels"]:
for target in panel.get("targets", []):
print(panel["title"] + "\t" + target["expr"])
PY
panels=0
while IFS=$'\t' read -r title expr; do
status=$(prometheus_get /api/v1/query --data-urlencode "query=$expr" | python3 -c 'import json, sys; data = json.load(sys.stdin); print(data["status"], len(data["data"]["result"]))')
[[ "$status" == success* ]] || fail "panel $title query failed: $status"
printf '%s\t%s\n' "$title" "$status" >>"$evidence_dir/panel-results.txt"
panels=$((panels + 1))
done <"$evidence_dir/panel-queries.txt"
printf 'Dashboard lincodex-product: %d panel queries accepted\n' "$panels"
cat "$evidence_dir/panel-results.txt"
# Privacy: the whole metric exposition of the backend, every series and
# label value in Prometheus, and the federated sample values must not hold
# the fixture address, and the logs in Loki must not either.
core exec -T frontend wget -q -O - http://backend:9090/metrics >"$evidence_dir/backend-metrics.txt"
prometheus_get /api/v1/series --data-urlencode 'match[]={job=~".+"}' >"$evidence_dir/series.json"
monitoring exec -T prometheus wget -q -O - 'http://localhost:9090/federate?match[]=%7Bjob%3D~%22.%2B%22%7D' >"$evidence_dir/federate.txt"
: >"$evidence_dir/label-values.txt"
for label in $(prometheus_get /api/v1/labels | python3 -c 'import json, sys; print("\n".join(json.load(sys.stdin)["data"]))'); do
prometheus_get "/api/v1/label/$label/values" >>"$evidence_dir/label-values.txt"
done
now=$(date +%s)
loki_get() {
curl --fail --silent --show-error -u "$grafana_auth" -G "$grafana/api/datasources/proxy/uid/loki/loki/api/v1/query_range" \
--data-urlencode "query=$1" --data-urlencode "start=$(((now - 3600) * 1000000000))" \
--data-urlencode "end=$(((now + 60) * 1000000000))" --data-urlencode limit=5000
}
logs_collected() {
local request_id
for request_id in "$query_request_id" "$path_request_id"; do
loki_get "{service=\"backend\"} |= \"$request_id\"" | grep -qF "$request_id" || return 1
done
}
# The backend logged both requests that carried the fixture address; seeing
# them proves that this run's logs reached Loki, so the absence check below
# is not vacuous.
wait_for "the backend request logs in Loki" logs_collected
loki_get '{service=~".+"}' >"$evidence_dir/loki.json"
log_lines=$(python3 -c 'import json, sys; print(sum(len(s["values"]) for s in json.load(open(sys.argv[1]))["data"]["result"]))' "$evidence_dir/loki.json")
printf 'Loki returned %s log lines of the core services\n' "$log_lines"
for file in backend-metrics.txt series.json federate.txt label-values.txt loki.json; do
if grep -qiF "$fixture_email" "$evidence_dir/$file"; then
fail "$file contains the fixture address"
fi
if grep -qF "$user_id" "$evidence_dir/$file" && [[ "$file" != loki.json ]]; then
fail "$file contains the fixture user ID"
fi
printf 'No fixture address in %s (%s bytes)\n' "$file" "$(wc -c <"$evidence_dir/$file" | tr -d ' ')"
done
if grep -qF "$attempt_id" "$evidence_dir/backend-metrics.txt" "$evidence_dir/label-values.txt"; then
fail "a path parameter reached the metric labels"
fi
printf '%s\n' 'Product metrics check passed.'