Перенести реализацию мессенджера из lab6 в skeleton lab7.

Контракт, публичные тесты и README задания оставлены от lab7.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-26 19:23:53 +03:00
co-authored by Cursor
parent 20afc2c790
commit 54b4b9e509
61 changed files with 5879 additions and 0 deletions
+156
View File
@@ -0,0 +1,156 @@
{
"uid": "messenger-lab6",
"title": "Messenger observability",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {"from": "now-1h", "to": "now"},
"description": "RPS and errors use messenger_http_requests_total. Durations are histogram_quantile over buckets, in seconds. Queue age is seconds. API error ratio excludes health.",
"panels": [
{
"id": 1,
"type": "timeseries",
"title": "API RPS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
"fieldConfig": {"defaults": {"unit": "reqps", "custom": {"drawStyle": "line"}}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum by (method, route) (rate(messenger_http_requests_total[1m]))",
"legendFormat": "{{method}} {{route}}"
}
]
},
{
"id": 2,
"type": "timeseries",
"title": "API error ratio (5xx / business)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 1e-9)",
"legendFormat": "5xx ratio"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "API duration p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 4,
"type": "timeseries",
"title": "Jobs by outcome",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Worker duration p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 16},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Time to ready p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 16},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Queue depth and oldest job age",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 24},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth)", "legendFormat": "depth (jobs)"},
{"refId": "B", "expr": "max(messenger_queue_oldest_age_seconds)", "legendFormat": "oldest age (seconds)"}
]
},
{
"id": 8,
"type": "timeseries",
"title": "DB pool used and waiting",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 24},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name, service_instance_id) (messenger_db_pool_used)", "legendFormat": "used {{service_name}} {{service_instance_id}}"},
{"refId": "B", "expr": "max by (service_name, service_instance_id) (messenger_db_pool_waiting)", "legendFormat": "waiting {{service_name}} {{service_instance_id}}"}
]
},
{
"id": 9,
"type": "timeseries",
"title": "Worker busy / capacity",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 32},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_worker_busy)", "legendFormat": "busy"},
{"refId": "B", "expr": "max(messenger_worker_capacity)", "legendFormat": "capacity"}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Process CPU and RSS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 32},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name, service_instance_id) (process_cpu_percent)", "legendFormat": "cpu % {{service_name}} {{service_instance_id}}"},
{"refId": "B", "expr": "max by (service_name, service_instance_id) (process_memory_rss_bytes)", "legendFormat": "rss {{service_name}} {{service_instance_id}}"}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Firing alerts",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 40},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "ALERTS{alertstate=\"firing\"}", "legendFormat": "{{alertname}}"}
]
}
]
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,38 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- datasourceUid: tempo
matcherRegex: '"trace_id":"([0-9a-f]+)"'
name: trace_id
url: "$${__value.raw}"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
@@ -0,0 +1,9 @@
# High API error rate
Signal: `messenger_http_requests_total`. Numerator is `status_class="5xx"`. Denominator is every instrumented business request. `/health/*`, `/docs` and `/openapi.json` are not in this ratio, so a bad password (401) is not an incident.
1. Open the Messenger dashboard and compare the 5xx ratio with p95 duration.
2. In Tempo, open a server span with `http.response.status_code >= 500`. The span attribute `http.route` is the template, not a user id.
3. In Loki, query `{service_name="messenger-api"}` and match `trace_id` from that span. The log line has `event`, `severity`, `trace_id` and `span_id`.
4. If the span stops inside the database client or the pool-used gauge is at `DB_POOL_MAX` with waiters, the cause is Postgres, not the HTTP handler itself.
5. After the dependency recovers, the 5m ratio falls and `HighApiErrorRate` leaves `firing`.
+8
View File
@@ -0,0 +1,8 @@
# Queue lag
Signal: `messenger_queue_oldest_age_seconds` is `now() - min(created_at)` for rows still `queued`. `messenger_queue_depth` counts `queued` and `processing`. Age is not the same number as worker duration.
1. If age grows and `messenger_worker_busy` is 0, the worker process is stopped or not consuming. Messages stay in RabbitMQ and in `attachment_jobs`.
2. If busy equals capacity and age still grows, the worker is saturated. Look at `messenger_job_duration_seconds` and the consumer span.
3. A consumer span's parent is the producer span, whose parent is the API server span that accepted the upload (`traceparent` stored on the job row).
4. Start the worker again. Depth and age return toward zero, then `QueueLagHigh` resolves. Do not delete the RabbitMQ volume.
+13
View File
@@ -0,0 +1,13 @@
# SLO burn
Two SLOs, each with a 1% error budget over 30 days.
- API availability: business requests that are not 5xx. Fast burn pages when both the 5 minute and 1 hour windows exceed 14.4% errors (14.4x budget). Slow burn warns when both 30 minutes and 6 hours exceed 6% (6x budget).
- Time to ready: jobs whose ready time is at most 30 seconds, read from the `le="30"` histogram bucket, not from an average. The same 14.4x and 6x windows apply.
A short spike can trip only the fast pair. A long degradation keeps the slow pair firing after the spike is gone. Both windows must agree, so one noisy minute does not page by itself.
1. Read which alert is firing and which SLO label it has.
2. For `api-availability`, follow `high-error-rate.md`. Separate 4xx from 5xx before calling it an incident.
3. For `time-to-ready`, follow `queue-lag.md`, then open the worker trace and see whether time is in `s3.get`, `image.render`, `s3.put` or `db.complete`.
4. Record the first firing timestamp and the first resolved timestamp. That pair is time-to-detect and time-to-recover for the experiment.
+35
View File
@@ -0,0 +1,35 @@
global
log stdout format raw local0 info
maxconn 200
defaults
log global
mode http
option httplog
timeout connect 2s
timeout client 120s
timeout server 120s
timeout http-request 15s
timeout check 2s
timeout queue 2s
retries 1
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
accepted_payload_size 8192
frontend fe_http
bind *:8080
default_backend be_api
backend be_api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr host api
http-check expect status 200
default-server inter 1s fall 2 rise 1
server-template srv 8 api:8080 check resolvers docker init-addr none resolve-prefer ipv4
+30
View File
@@ -0,0 +1,30 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
+89
View File
@@ -0,0 +1,89 @@
# Collector 0.128.0. It forwards signals and is not a database.
# memory_limiter refuses data before the process grows without bound.
# Exporter queues are capped; a dead backend drops telemetry after retry, the API keeps serving.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 5s
send_batch_size: 256
send_batch_max_size: 512
exporters:
otlphttp/tempo:
traces_endpoint: http://tempo:4318/v1/traces
tls:
insecure: true
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 1000
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
prometheusremotewrite:
endpoint: http://prometheus:9090/api/v1/write
tls:
insecure: true
resource_to_telemetry_conversion:
enabled: true
remote_write_queue:
enabled: true
queue_size: 1000
num_consumers: 2
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
otlphttp/loki:
logs_endpoint: http://loki:3100/otlp/v1/logs
tls:
insecure: true
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 1000
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
logs:
level: info
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
+112
View File
@@ -0,0 +1,112 @@
groups:
- name: messenger
rules:
- alert: HighApiErrorRate
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
/
clamp_min(sum(rate(messenger_http_requests_total[5m])), 1e-9)
) > 0.05
for: 1m
labels:
severity: warning
slo: api-availability
annotations:
summary: API 5xx ratio is above 5% over 5 minutes
description: Numerator is status_class=5xx. Denominator is instrumented business requests. Health, docs and openapi are excluded.
runbook: infra/grafana/runbooks/high-error-rate.md
- alert: QueueLagHigh
expr: max(messenger_queue_oldest_age_seconds) > 30
for: 30s
labels:
severity: warning
slo: time-to-ready
annotations:
summary: Oldest queued job is older than 30 seconds
description: Age is now minus created_at of jobs still in status queued. Depth is a separate gauge.
runbook: infra/grafana/runbooks/queue-lag.md
- alert: ApiAvailabilityFastBurn
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
/ clamp_min(sum(rate(messenger_http_requests_total[5m])), 1e-9)
) > 0.144
and
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[1h]))
/ clamp_min(sum(rate(messenger_http_requests_total[1h])), 1e-9)
) > 0.144
for: 2m
labels:
severity: critical
slo: api-availability
window: fast
annotations:
summary: API error budget burn rate is above 14.4x on both 5m and 1h
runbook: infra/grafana/runbooks/slo-burn.md
- alert: ApiAvailabilitySlowBurn
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[30m]))
/ clamp_min(sum(rate(messenger_http_requests_total[30m])), 1e-9)
) > 0.06
and
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[6h]))
/ clamp_min(sum(rate(messenger_http_requests_total[6h])), 1e-9)
) > 0.06
for: 15m
labels:
severity: warning
slo: api-availability
window: slow
annotations:
summary: API error budget burn rate is above 6x on both 30m and 6h
runbook: infra/grafana/runbooks/slo-burn.md
- alert: TimeToReadyFastBurn
expr: |
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[5m]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[5m])), 1e-9)
)
) > 0.144
and
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[1h]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[1h])), 1e-9)
)
) > 0.144
for: 2m
labels:
severity: critical
slo: time-to-ready
window: fast
annotations:
summary: Share of jobs slower than 30s is burning the ready-time budget (5m and 1h)
runbook: infra/grafana/runbooks/slo-burn.md
- alert: TimeToReadySlowBurn
expr: |
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[30m]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[30m])), 1e-9)
)
) > 0.06
and
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[6h]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[6h])), 1e-9)
)
) > 0.06
for: 15m
labels:
severity: warning
slo: time-to-ready
window: slow
annotations:
summary: Share of jobs slower than 30s is burning the ready-time budget (30m and 6h)
runbook: infra/grafana/runbooks/slo-burn.md
+6
View File
@@ -0,0 +1,6 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# One SeaweedFS process: master, volume, filer, S3. The filer UI is off.
# Anonymous identity has no actions. The API user is limited to one bucket.
set -eu
: "${S3_BUCKET:?}"
: "${S3_ACCESS_KEY_ID:?}"
: "${S3_SECRET_ACCESS_KEY:?}"
cat > /tmp/s3.json <<EOF
{
"identities": [
{
"name": "anonymous",
"actions": []
},
{
"name": "messenger-app",
"credentials": [
{
"accessKey": "${S3_ACCESS_KEY_ID}",
"secretKey": "${S3_SECRET_ACCESS_KEY}"
}
],
"actions": [
"Read:${S3_BUCKET}",
"Read:${S3_BUCKET}/*",
"Write:${S3_BUCKET}",
"Write:${S3_BUCKET}/*",
"List:${S3_BUCKET}",
"Tagging:${S3_BUCKET}/*",
"Admin:${S3_BUCKET}"
]
}
]
}
EOF
exec weed server \
-dir=/data \
-ip.bind=0.0.0.0 \
-master.port=9333 \
-volume.port=8080 \
-filer \
-filer.port=8888 \
-filer.exposeDirectoryData=false \
-s3 \
-s3.port=9000 \
-s3.config=/tmp/s3.json
+12
View File
@@ -0,0 +1,12 @@
# SLI и SLO
Окно цели: 30 суток. Бюджет ошибок: 1% у каждого SLO. Пороги burn rate — 14.4x (быстрое выгорание, окна 5 минут и 1 час) и 6x (медленное, окна 30 минут и 6 часов). Оба окна пары должны выполниться одновременно.
| SLI | Хорошее событие | SLO | Единица |
| --- | --- | --- | --- |
| Доступность API | бизнес-запрос со `status_class` не `5xx` | 99% | доля запросов |
| Время до ready | job, у которой `messenger_time_to_ready_seconds` попала в bucket `le=30` | 99% готовы не дольше 30 секунд | секунды от durable acceptance до `ready` |
Health, `/docs` и `/openapi.json` в SLI API не входят. 401 и 404 остаются в знаменателе, но не в числителе ошибок: это не отказ сервиса. Процентили дашборда считаются `histogram_quantile` по bucket, не средним значений и не средним p99 реплик.
Правила лежат в `infra/prometheus/alerts.yml`. Runbook: `infra/grafana/runbooks/`.
+28
View File
@@ -0,0 +1,28 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks