Перенеси реализацию мессенджера из ЛР 6
Application / e2e (pull_request) Blocked by required conditions
Application / unit (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions

Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
This commit is contained in:
2026-11-30 10:54:41 +03:00
parent 20afc2c790
commit 8054913ef9
204 changed files with 23709 additions and 0 deletions
+76
View File
@@ -0,0 +1,76 @@
# The single entry point: round-robin over the API replicas found through
# Docker DNS, with active readiness checks and no client stickiness.
global
log stdout format raw local0 info
maxconn 20000
# The container has at most one CPU; by default HAProxy starts a thread
# per host CPU and fights the quota.
nbthread 1
defaults
mode http
log global
option dontlognull
timeout connect 1s
timeout client 30s
# Above the API's 5 s request deadline: the API answers a slow request
# itself, this only cuts off a hung replica.
timeout server 7s
timeout http-request 10s
timeout http-keep-alive 10s
timeout check 2s
# Below the 500 ms latency objective: excess load gets a fast 503.
timeout queue 300ms
# Re-sent only when nothing reached the API: a timeout or an empty
# response may follow a committed write.
retries 2
option redispatch 1
retry-on conn-failure
# Errors produced by the balancer itself use the contract's envelope.
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"the API replica failed to answer","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"no API replica is available","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"the API replica did not answer in time","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
# `api` resolves to every running replica, re-resolved every second; an
# address that disappears leaves at once.
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 10s
hold obsolete 0s
accepted_payload_size 8192
frontend entry
bind :8080
option httplog
unique-id-format %[uuid(4),regsub(-,,g)]
# Replaces any client value; the API keeps it, so one id spans both logs.
http-request set-header X-Request-Id %[unique-id]
capture response header X-Instance-Id len 32
capture response header X-Request-Id len 40
http-after-response set-log-level silent if { status lt 500 } { env(LB_QUIET) -m str 1 }
default_backend replicas
backend replicas
# Binary handlers have a 30s budget, ordinary API handlers retain 5s.
http-request set-timeout server 35s if { path_reg ^/api/v1/chats/[^/]+/attachments$|^/api/v1/attachments/[^/]+/content$ }
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
# Out within 1.5 s (inter + fastinter), less than the API's 2 s drain delay.
# maxconn 20: the replica's 10 pooled database connections plus requests
# that need no database; the rest waits in the queue.
default-server maxconn "${API_MAXCONN-20}" inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4
# Up to five replicas, doubled while docker rollout replaces them.
server-template api 10 api:8080
listen stats
bind :8404
no log
stats enable
stats uri /
stats refresh 2s
+12
View File
@@ -1,3 +1,15 @@
# Локальный стенд наблюдаемости
API и worker отправляют OTLP/HTTP в otel-collector:4318 по внутренней сети. Prometheus опрашивает метрики приложения и самого Collector каждые 2 с. Loki принимает OTLP logs, Tempo принимает OTLP traces. Данные всех трёх систем хранятся в отдельных Docker volumes.
Откройте [дашборд Messenger reliability](http://localhost:3000/d/messenger) и [состояние правил](http://localhost:9090/alerts). Порты меняются в .env. Дашборд показывает агрегированные перцентили, а также знаменатели обеих SLI. При нулевом знаменателе доля ошибок отсутствует. Prometheus хранит результат проверки правил каждые 2 с. Временную шкалу firing восстанавливает запрос `ALERTS{alertstate="firing"}`.
## Диагностика алертов
- **HighHTTP5xx / APIAvailabilityBudgetBurn.** Проверьте частоту запросов по route и выберите сервис messenger-api в Grafana Explore → Tempo. Найдите ошибочный server span в интервале алерта. Разверните дочерние spans DB и S3, проверьте длительность и статус. Долгий/ошибочный DB span указывает, какую зависимость проверять первой. Сопоставьте с занятыми соединениями и скоростью накопления времени ожидания DB pool. В Explore → Loki запрос `{service_name="messenger-api"} | trace_id="<trace ID>"` возвращает события запроса. Когда доля 5xx упадёт ниже порога, проверьте также успешный бизнес-запрос.
- **QueueLag / AttachmentReadyBudgetBurn.** При растущем возрасте и глубине очереди проверьте наличие актуальной worker capacity и отношение active/capacity. В Tempo найдите upload, раскройте producer и consumer. Отсутствующий consumer вместе с пропавшей capacity указывает на остановку worker. При наличии consumer проверьте длительность и ошибки S3/DB. После восстановления убедитесь, что глубина и возраст падают, а новые загрузки успевают к deadline. Ошибки прошлых когорт сохраняются до выхода из окна.
- **Пустые панели.** Сверьте количество событий в знаменателях, активность нагрузки, время последней точки и `up{job="collector"}`. Для отказа Loki или Tempo сопоставьте очереди и ошибки экспортёров Collector с доступностью API. Экспортёр повторяет отправку группы до 12 с, один запрос ограничен 2 с. Очередь вмещает 16 групп плюс две отправки в работе, максимум 256 записей в группе. При заполнении или исчерпании повторов записи теряются. Сравните приращение счётчиков failed и enqueue_failed соответствующего сигнала с принятыми записями и сохранёнными данными; единичная ошибка попытки не доказывает окончательную потерю.
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
+57
View File
@@ -0,0 +1,57 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 180
spike_limit_mib: 40
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 0.0.0.0:8889
metric_expiration: 10s
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue: &queue
enabled: true
num_consumers: 2
queue_size: 16
retry_on_failure: &retry
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 12s
otlphttp/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue: *queue
retry_on_failure: *retry
service:
telemetry:
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
@@ -0,0 +1,500 @@
{
"uid": "messenger",
"title": "Messenger reliability",
"schemaVersion": 41,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"type": "timeseries",
"id": 1,
"title": "Business request rate",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "{{method}} {{route}}",
"expr": "sum by (method, route) (rate(messenger_http_requests_total[30s]))"
}
]
},
{
"type": "timeseries",
"id": 2,
"title": "Business HTTP 5xx",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "5xx ratio",
"expr": "lab:http_bad_ratio:30s"
}
]
},
{
"type": "timeseries",
"id": 3,
"title": "HTTP latency across replicas",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "p50",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket[30s])))"
},
{
"refId": "B",
"legendFormat": "p95",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[30s])))"
},
{
"refId": "C",
"legendFormat": "p99",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket[30s])))"
}
]
},
{
"type": "timeseries",
"id": 4,
"title": "Job outcomes",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "ops"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "{{outcome}}",
"expr": "sum by (outcome) (rate(messenger_jobs_total[30s]))"
}
]
},
{
"type": "timeseries",
"id": 5,
"title": "Job processing duration",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "p95 {{outcome}}",
"expr": "histogram_quantile(0.95,sum by (le,outcome) (rate(messenger_job_duration_seconds_bucket[2m])))"
}
]
},
{
"type": "timeseries",
"id": 6,
"title": "Acceptance to first ready",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "p95",
"expr": "histogram_quantile(0.95,sum by (le) (rate(messenger_ready_duration_seconds_bucket[2m])))"
}
]
},
{
"type": "timeseries",
"id": 7,
"title": "Queued jobs",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "queued",
"expr": "max(messenger_queue_depth and on(job, instance) lab:queue_snapshot:latest)"
}
]
},
{
"type": "timeseries",
"id": 8,
"title": "Oldest queued job",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "age",
"expr": "max(messenger_queue_oldest_seconds and on(job, instance) lab:queue_snapshot:latest)"
}
]
},
{
"type": "timeseries",
"id": 9,
"title": "DB pool connections",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "acquired {{job}} {{instance}}",
"expr": "messenger_db_pool_acquired"
},
{
"refId": "B",
"legendFormat": "maximum {{job}} {{instance}}",
"expr": "messenger_db_pool_max"
}
]
},
{
"type": "timeseries",
"id": 10,
"title": "DB pool waiting time per second",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "{{job}} {{instance}}",
"expr": "rate(messenger_db_pool_wait_seconds_total[30s])"
}
]
},
{
"type": "timeseries",
"id": 11,
"title": "Worker concurrency",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "active {{instance}}",
"expr": "messenger_worker_active"
},
{
"refId": "B",
"legendFormat": "capacity {{instance}}",
"expr": "messenger_worker_capacity"
}
]
},
{
"type": "timeseries",
"id": 12,
"title": "Process CPU cores",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "{{job}} {{instance}}",
"expr": "rate(messenger_process_cpu_seconds_total[30s])"
}
]
},
{
"type": "timeseries",
"id": 13,
"title": "Resident memory",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "{{job}} {{instance}}",
"expr": "messenger_process_resident_bytes"
}
]
},
{
"type": "timeseries",
"id": 14,
"title": "SLI error ratios",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "http 30s",
"expr": "lab:http_bad_ratio:30s"
},
{
"refId": "B",
"legendFormat": "http 2m",
"expr": "lab:http_bad_ratio:2m"
},
{
"refId": "C",
"legendFormat": "ready 30s",
"expr": "lab:ready_bad_ratio:30s"
},
{
"refId": "D",
"legendFormat": "ready 2m",
"expr": "lab:ready_bad_ratio:2m"
}
]
},
{
"type": "timeseries",
"id": 15,
"title": "Eligible observations",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "http 30s",
"expr": "lab:http_count:30s"
},
{
"refId": "B",
"legendFormat": "http 2m",
"expr": "lab:http_count:2m"
},
{
"refId": "C",
"legendFormat": "ready 30s",
"expr": "lab:ready_count:30s"
},
{
"refId": "D",
"legendFormat": "ready 2m",
"expr": "lab:ready_count:2m"
}
]
},
{
"type": "timeseries",
"id": 16,
"title": "Exporter queue occupancy",
"datasource": {
"type": "prometheus",
"uid": "prom"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"targets": [
{
"refId": "A",
"legendFormat": "queued {{exporter}}",
"expr": "otelcol_exporter_queue_size"
},
{
"refId": "B",
"legendFormat": "capacity {{exporter}}",
"expr": "otelcol_exporter_queue_capacity"
}
]
}
]
}
@@ -0,0 +1,6 @@
apiVersion: 1
providers:
- name: Messenger
type: file
options:
path: /etc/grafana/dashboards
@@ -0,0 +1,33 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prom
type: prometheus
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 2s
- name: Loki
uid: loki
type: loki
url: http://loki:3100
jsonData:
derivedFields:
- name: TraceID
matcherType: label
matcherRegex: "^trace_id$"
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
tags:
- key: service.name
value: service_name
filterByTraceID: true
customQuery: true
query: '{$${__tags}} | trace_id="$${__trace.traceId}"'
+26
View File
@@ -0,0 +1,26 @@
auth_enabled: false
server:
http_listen_port: 3100
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
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
analytics:
reporting_enabled: false
+12
View File
@@ -0,0 +1,12 @@
global:
scrape_interval: 2s
evaluation_interval: 2s
rule_files: [/etc/prometheus/rules.yaml]
scrape_configs:
- job_name: app
honor_labels: true
static_configs:
- targets: ["otel-collector:8889"]
- job_name: collector
static_configs:
- targets: ["otel-collector:8888"]
+45
View File
@@ -0,0 +1,45 @@
groups:
- name: messenger
rules:
- record: lab:queue_snapshot:latest
expr: topk(1, messenger_queue_snapshot_timestamp_seconds)
- record: lab:http_count:30s
expr: sum(increase(messenger_http_requests_total[30s]))
- record: lab:http_bad_ratio:30s
expr: (sum(increase(messenger_http_requests_total{status_class="5xx"}[30s])) or 0 * lab:http_count:30s) / lab:http_count:30s >= 0
- record: lab:ready_count:30s
expr: max(messenger_ready_cohort_total_count{window="30s"} and on(job, instance) lab:queue_snapshot:latest)
- record: lab:ready_bad_ratio:30s
expr: max(messenger_ready_cohort_bad_count{window="30s"} and on(job, instance) lab:queue_snapshot:latest) / lab:ready_count:30s >= 0
- record: lab:http_count:2m
expr: sum(increase(messenger_http_requests_total[2m]))
- record: lab:http_bad_ratio:2m
expr: (sum(increase(messenger_http_requests_total{status_class="5xx"}[2m])) or 0 * lab:http_count:2m) / lab:http_count:2m >= 0
- record: lab:ready_count:2m
expr: max(messenger_ready_cohort_total_count{window="2m"} and on(job, instance) lab:queue_snapshot:latest)
- record: lab:ready_bad_ratio:2m
expr: max(messenger_ready_cohort_bad_count{window="2m"} and on(job, instance) lab:queue_snapshot:latest) / lab:ready_count:2m >= 0
- alert: HighHTTP5xx
expr: lab:http_bad_ratio:30s > 0.20 and lab:http_count:30s >= 3
for: 10s
annotations:
summary: "Over 20% of business requests failed in 30 seconds."
runbook: "infra/otel/README.md"
- alert: QueueLag
expr: max(messenger_queue_oldest_seconds and on(job, instance) lab:queue_snapshot:latest) > 15
for: 10s
annotations:
summary: "Oldest queued job has waited over 15 seconds."
runbook: "infra/otel/README.md"
- alert: APIAvailabilityBudgetBurn
expr: lab:http_bad_ratio:30s > 0.20 and lab:http_bad_ratio:2m > 0.10 and lab:http_count:30s >= 3 and lab:http_count:2m >= 10
for: 10s
annotations:
summary: "API availability error budget is burning above 20x and 10x."
runbook: "infra/otel/README.md"
- alert: AttachmentReadyBudgetBurn
expr: lab:ready_bad_ratio:30s > 0.20 and lab:ready_bad_ratio:2m > 0.10 and lab:ready_count:30s >= 3 and lab:ready_count:2m >= 10
for: 10s
annotations:
summary: "Ready deadline error budget is burning above 20x and 10x."
runbook: "infra/otel/README.md"
+198
View File
@@ -0,0 +1,198 @@
rule_files: [rules.yaml]
evaluation_interval: 2s
tests:
- name: select both windows and sample floors from the freshest replica
interval: 10s
input_series:
- series: 'messenger_queue_snapshot_timestamp_seconds{instance="a",job="api"}'
values: '1+0x4'
- series: 'messenger_ready_cohort_total_count{instance="a",job="api",window="30s"}'
values: '100+0x4'
- series: 'messenger_ready_cohort_bad_count{instance="a",job="api",window="30s"}'
values: '0+0x4'
- series: 'messenger_ready_cohort_total_count{instance="a",job="api",window="2m"}'
values: '100+0x4'
- series: 'messenger_ready_cohort_bad_count{instance="a",job="api",window="2m"}'
values: '0+0x4'
- series: 'messenger_queue_snapshot_timestamp_seconds{instance="b",job="api"}'
values: '2+0x4'
- series: 'messenger_ready_cohort_total_count{instance="b",job="api",window="30s"}'
values: '10+0x4'
- series: 'messenger_ready_cohort_bad_count{instance="b",job="api",window="30s"}'
values: '3+0x4'
- series: 'messenger_ready_cohort_total_count{instance="b",job="api",window="2m"}'
values: '10+0x4'
- series: 'messenger_ready_cohort_bad_count{instance="b",job="api",window="2m"}'
values: '3+0x4'
alert_rule_test:
- eval_time: 30s
alertname: AttachmentReadyBudgetBurn
exp_alerts:
- exp_annotations:
summary: "Ready deadline error budget is burning above 20x and 10x."
runbook: infra/otel/README.md
promql_expr_test:
- expr: lab:ready_count:2m
eval_time: 30s
exp_samples:
- labels: lab:ready_count:2m
value: 10
- name: steady then sustained failure
interval: 10s
input_series:
- series: messenger_queue_snapshot_timestamp_seconds
values: '0+10x18'
- series: 'messenger_http_requests_total{status_class="2xx"}'
values: '0+10x6 60+0x12'
- series: 'messenger_http_requests_total{status_class="5xx"}'
values: '0+0x6 10+10x5 60+0x6'
- series: 'messenger_queue_oldest_seconds'
values: '0+0x6 20+0x5 0+0x6'
- series: 'messenger_ready_cohort_total_count{window="30s"}'
values: '20+0x18'
- series: 'messenger_ready_cohort_bad_count{window="30s"}'
values: '0+0x6 5+0x5 0+0x6'
- series: 'messenger_ready_cohort_total_count{window="2m"}'
values: '20+0x18'
- series: 'messenger_ready_cohort_bad_count{window="2m"}'
values: '0+0x6 5+0x5 0+0x6'
alert_rule_test:
- eval_time: 1m
alertname: HighHTTP5xx
exp_alerts: []
- eval_time: 1m
alertname: QueueLag
exp_alerts: []
- eval_time: 1m
alertname: APIAvailabilityBudgetBurn
exp_alerts: []
- eval_time: 1m
alertname: AttachmentReadyBudgetBurn
exp_alerts: []
- eval_time: 100s
alertname: HighHTTP5xx
exp_alerts:
- exp_annotations:
summary: "Over 20% of business requests failed in 30 seconds."
runbook: infra/otel/README.md
- eval_time: 100s
alertname: QueueLag
exp_alerts:
- exp_annotations:
summary: "Oldest queued job has waited over 15 seconds."
runbook: infra/otel/README.md
- eval_time: 100s
alertname: APIAvailabilityBudgetBurn
exp_alerts:
- exp_annotations:
summary: "API availability error budget is burning above 20x and 10x."
runbook: infra/otel/README.md
- eval_time: 100s
alertname: AttachmentReadyBudgetBurn
exp_alerts:
- exp_annotations:
summary: "Ready deadline error budget is burning above 20x and 10x."
runbook: infra/otel/README.md
- eval_time: 160s
alertname: APIAvailabilityBudgetBurn
exp_alerts: []
- eval_time: 160s
alertname: HighHTTP5xx
exp_alerts: []
- eval_time: 160s
alertname: AttachmentReadyBudgetBurn
exp_alerts: []
- eval_time: 160s
alertname: QueueLag
exp_alerts: []
- name: single four-second burst in steady traffic
interval: 10s
input_series:
- series: messenger_queue_snapshot_timestamp_seconds
values: '0+10x18'
- series: 'messenger_http_requests_total{status_class="2xx"}'
values: '0+10x8 86 96+10x6'
- series: 'messenger_http_requests_total{status_class="5xx"}'
values: '0+0x8 4+0x7'
- series: 'messenger_ready_cohort_total_count{window="30s"}'
values: '20+0x16'
- series: 'messenger_ready_cohort_bad_count{window="30s"}'
values: '0+0x8 2+0x2 0+0x4'
- series: 'messenger_ready_cohort_total_count{window="2m"}'
values: '20+0x16'
- series: 'messenger_ready_cohort_bad_count{window="2m"}'
values: '0+0x8 2+0x2 0+0x4'
alert_rule_test:
- eval_time: 100s
alertname: HighHTTP5xx
exp_alerts: []
- eval_time: 100s
alertname: QueueLag
exp_alerts: []
- eval_time: 100s
alertname: APIAvailabilityBudgetBurn
exp_alerts: []
- eval_time: 100s
alertname: AttachmentReadyBudgetBurn
exp_alerts: []
- eval_time: 120s
alertname: HighHTTP5xx
exp_alerts: []
- eval_time: 120s
alertname: QueueLag
exp_alerts: []
- eval_time: 120s
alertname: APIAvailabilityBudgetBurn
exp_alerts: []
- eval_time: 120s
alertname: AttachmentReadyBudgetBurn
exp_alerts: []
- name: low sample count and empty cohorts
interval: 10s
promql_expr_test:
- expr: lab:ready_bad_ratio:30s
eval_time: 50s
exp_samples: []
- expr: lab:ready_bad_ratio:30s
eval_time: 100s
exp_samples:
- labels: lab:ready_bad_ratio:30s
value: 1
input_series:
- series: messenger_queue_snapshot_timestamp_seconds
values: '0+10x18'
- series: 'messenger_http_requests_total{status_class="5xx"}'
values: '0+0x6 1+0x6'
- series: 'messenger_ready_cohort_total_count{window="30s"}'
values: '0+0x6 1+0x6'
- series: 'messenger_ready_cohort_bad_count{window="30s"}'
values: '0+0x6 1+0x6'
- series: 'messenger_ready_cohort_total_count{window="2m"}'
values: '0+0x6 1+0x6'
- series: 'messenger_ready_cohort_bad_count{window="2m"}'
values: '0+0x6 1+0x6'
alert_rule_test:
- eval_time: 60s
alertname: HighHTTP5xx
exp_alerts: []
- eval_time: 60s
alertname: QueueLag
exp_alerts: []
- eval_time: 60s
alertname: APIAvailabilityBudgetBurn
exp_alerts: []
- eval_time: 60s
alertname: AttachmentReadyBudgetBurn
exp_alerts: []
- eval_time: 100s
alertname: HighHTTP5xx
exp_alerts: []
- eval_time: 100s
alertname: QueueLag
exp_alerts: []
- eval_time: 100s
alertname: APIAvailabilityBudgetBurn
exp_alerts: []
- eval_time: 100s
alertname: AttachmentReadyBudgetBurn
exp_alerts: []
+20
View File
@@ -0,0 +1,20 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
ingester:
trace_idle_period: 5s
max_block_duration: 5m
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+77
View File
@@ -0,0 +1,77 @@
# Private object storage
`s3` runs SeaweedFS 4.53 in one process. The image is pinned by digest in
`compose.yaml` and `internal/testenv/s3.go`. `seaweedfs.options` is shared by
the stand and the disposable integration-test server.
S3 HTTP (8333) and SeaweedFS's companion gRPC (18333) listen on the private
container network. This image has no flag to disable the companion listener;
its identity-cache mutations reject remote peers, which the integration test
checks. Master, volume and filer HTTP/gRPC endpoints bind to loopback.
No host port is published. `/data`
contains both object volumes and the image's LevelDB filer metadata; the
named `s3data` volume must be retained together with PostgreSQL data.
Run `sh scripts/init-secrets.sh` before starting the stand. It preserves the
existing PostgreSQL and Valkey credentials and creates three independent S3
identities plus the static server configuration. Credential values are never
printed. Repeated initialization keeps all existing keys. Set `S3_BUCKET` in
the environment or the local `.env` before the first initialization; changing
it later requires a planned migration of identities and retained data.
The server loads its static identity secret before serving requests. There is
no anonymous identity. The bootstrap identity has administrative rights and
its individual key files are mounted only in `s3-init`. The API identity has
`Read:<bucket>` and `Write:<bucket>`; it cannot list objects or administer
buckets. The reconciler identity adds `List:<bucket>`. All three identities
are necessarily present in the S3 server's own identity configuration secret.
`s3-init` creates the bucket idempotently and waits for storage before API
replicas start. An anonymous 403 and bucket metadata alone do not prove that
retained volume locations have registered with the elected master. Bootstrap
first reads a persistent `.health/storage-v1` marker (creating it only when
absent), then verifies a fresh write/read/delete. This startup-only barrier
uses the caller's deadline, capped at 60 seconds; ordinary S3 operations and
API readiness do not retry through it. The marker is outside the reconciler's
`staging/` and `blobs/` namespaces. `scripts/restart.sh` already runs this
bootstrap before restoring API replicas.
The bootstrap uses `/usr/local/bin/s3init`. The optional `recon` profile runs
`/usr/local/bin/reconcile`, with reconciler credentials mapped to the standard
`S3_ACCESS_KEY_ID_FILE` and `S3_SECRET_ACCESS_KEY_FILE` paths:
```sh
docker compose --profile recon run --rm reconcile
docker compose --profile recon run --rm reconcile --apply
```
The API receives its own standard S3 key files. Its background reconciliation
worker must construct a separate store from
`S3_RECONCILE_ACCESS_KEY_ID_FILE` and `S3_RECONCILE_SECRET_ACCESS_KEY_FILE`;
listing with the API identity is denied. S3 is intentionally absent from API
readiness so text traffic can remain available during an object-store outage.
The S3 cgroup is limited to one CPU, 512 MiB, and 256 processes. Upload limits
are four concurrent requests and 64 MiB in flight; reader buffers have a
32 MiB budget and the chunk cache is disabled. Disk allocation is capped at
64 volumes of approximately 128 MiB each (with normal volume rollover
overhead); this is a lab capacity limit, not a filesystem quota.
Each API replica has 2 GiB and `GOMEMLIMIT=1536MiB`, with one image decoder.
Pixels alone are not the full budget: progressive JPEG retains coefficients,
and a wide RGBA64 PNG keeps two large scanlines beside its pixel buffer.
The 40 MP RGB/CMYK progressive JPEG and wide-PNG measurements are recorded in
`evidence/decoder-memory-*.json`; this does not change the S3 service's 512 MiB limit.
Verify the adapter and real server with Docker running:
```sh
go test -race -count=1 ./internal/platform/s3store
```
`testenv.StartS3(ctx)` returns `Store` with reconciler rights, `APIStore`,
`Admin`, endpoint and credentials. `Recreate(ctx)` replaces only its own
container while keeping its named volume and does not recreate the bucket.
It waits for the same retained-marker and write/read/delete barrier before
returning. `Start(ctx)` does so as well. Always call `Close()` to remove the
fixture's container and volume.
+31
View File
@@ -0,0 +1,31 @@
dir=/data
ip=127.0.0.1
ip.bind=127.0.0.1
master.telemetry=false
master.volumeSizeLimitMB=128
volume.port=9340
volume.max=64
volume.index=leveldb
volume.fileSizeLimitMB=10
volume.concurrentUploadLimitMB=64
volume.concurrentDownloadLimitMB=64
volume.readBufferSizeMB=1
volume.preStopSeconds=1
filer=true
filer.exposeDirectoryData=false
filer.disableDirListing=true
filer.concurrentFileUploadLimit=4
filer.concurrentUploadLimitMB=64
s3=true
s3.ip.bind=0.0.0.0
s3.port=8333
s3.config=/run/secrets/s3_identities
s3.autoCreateBucket=false
s3.iam=false
s3.port.iceberg=0
s3.port.lance=0
s3.concurrentFileUploadLimit=4
s3.concurrentUploadLimitMB=64
s3.readerCacheSizeMB=32
s3.cacheCapacityMB=0
s3.idleTimeout=35
+19
View File
@@ -0,0 +1,19 @@
# Valkey is the only store of user sessions, so it is their source of truth.
# Every write is fsynced before the reply: an acknowledged login survives a
# crash or a restart. Only logins and logouts write; session lookups are reads
# and pay nothing for this.
appendonly yes
appendfsync always
dir /data
# The append-only file already persists everything; RDB snapshots are off.
save ""
# Sessions are never evicted to free memory: once maxmemory is reached the
# store refuses new sessions (login answers 503) instead of silently logging
# users out. A session key takes about a hundred bytes.
maxmemory 256mb
maxmemory-policy noeviction
# requirepass comes from the compose secret, never from the repository.
include /run/secrets/valkey_auth