Author SHA1 Message Date
ALMiron 6b5a6d4ba1 +commit pr 2026-11-21 00:12:34 +03:00
ALMiron 1b349de454 lab 6 observability 2026-11-21 00:02:11 +03:00
69 changed files with 8694 additions and 4877 deletions
+13
View File
@@ -0,0 +1,13 @@
FROM python:3.12.11-slim-bookworm
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
RUN addgroup --system app && adduser --system --ingroup app app
COPY requirements.txt ./requirements.txt
RUN python -m pip install --no-cache-dir -r requirements.txt
COPY src ./src
COPY migrations ./migrations
COPY scripts ./scripts
USER app
EXPOSE 8080
STOPSIGNAL SIGTERM
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "10", "--proxy-headers"]
+101
View File
@@ -0,0 +1,101 @@
# Отчёт - лабораторная 6
- Автор, группа: Алексей Миронов, БВТ2302
- Целевая оценка: **4** (трек 5 не заявляется)
- Commit/PR: 1b349de lab 6 observability, (https://gitea.privcloud.tech/mtusi2026/mtusi2026lab6/pulls/66); ветка solution/bvt2302-mironov)
- Источники, библиотеки, помощь ИИ: lab5 как база; OpenTelemetry Python SDK 1.45.1 (instrumentation 0.66b1), OTel Collector contrib 0.131.0, Prometheus v3.5.0, Loki 3.5.3, Tempo 2.8.2, Grafana 12.1.1; использовалась помощь ИИ
## Запуск из чистого clone
Нужны Docker Engine + Compose v2, GNU Make, Python 3.9+ (для тестов).
```bash
cp .env.example .env # заполнить пароли (синтетические), .env в git не коммитить
make check && make validate
docker compose --env-file .env config --quiet
docker compose --env-file .env up --build # (или -d --build)
until curl -fs http://localhost:8080/health/ready; do sleep 2; done
make test # публичный smoke lab6
python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
python3 student-tests/level4_observability.py all | tee evidence/level4-observability.txt
```
Что делает `level4_observability.py all`: `trace_chain` - upload вложения, поиск trace по логу `attachment_accepted` (Loki) и проверка в Tempo цепочки API(SERVER) -> dispatcher(PRODUCER) -> worker(CONSUMER); `queue_lag` - остановка worker, ожидание алерта `QueueLagGrowing`, запуск worker, ожидание resolved; `db_slow` - блокировка таблицы `messages` на 150 с под нагрузкой, ожидание `HighApiErrorRate`, снятие блокировки, ожидание resolved; `telemetry_down` - остановка prometheus/loki/tempo, 90 с записей и upload при работающем API, замер памяти Collector, запуск хранилищ.
Grafana: http://localhost:3000 (admin / GRAFANA_ADMIN_PASSWORD из .env); datasources и dashboard «Messenger: observability (lab 6)» подключаются сами (provisioning из Git). Остановка с сохранением данных: `docker compose --env-file .env down`; удаление учебных данных: `docker compose --env-file .env down -v`.
## Архитектура и решения
```
API x2 / worker / dispatcher --OTLP/HTTP--> OTel Collector --[memory_limiter -> batch]--> Prometheus (metrics, remote write)
\-> Loki (logs, OTLP) \-> Tempo (traces, OTLP)
Grafana читает Prometheus + Loki + Tempo. Правила алертов — в Prometheus.
```
Перенесено из lab5 без изменения бизнес-API: API, PostgreSQL, Redis, S3, Kafka, outbox, worker, dispatcher, sweeper, HAProxy. Добавлено: `src/telemetry.py`, инструментация, Collector, три хранилища, Grafana, alerts, runbooks.
Назначение хранилищ: Prometheus — числовые ряды (скорость, доли, гистограммы); Loki — события с контекстом (почему); Tempo — путь одного запроса/задачи (где). Collector — не БД, а приёмник/процессор/экспортёр; Grafana — только интерфейс.
**Контекст трассы через очередь.** `jobs.enqueue` внутри span `outbox.enqueue` кладёт `traceparent` (W3C) в JSON-payload job (поле из `jobs.schema.json`). Dispatcher читает его, создаёт PRODUCER span `attachment-jobs publish` (child), записывает в payload **свой** traceparent и публикует. Worker делает `extract` и создаёт CONSUMER span (child продюсера); retry идёт через `enqueue` внутри worker-span, поэтому цепочка продолжается в том же trace. Ограничение: retry после истечения lease (reaper) начинает новый корень trace.
## Соответствие сигналов (contracts/observability.md)
| Сигнал | Имя в коде → Prometheus | Единица / измерения |
| --- | --- | --- |
| HTTP requests + duration | `http.server.request.duration` → `http_server_request_duration_seconds_{bucket,sum,count}` | s; method, route-шаблон, status class (health исключён) |
| Jobs processed/failed | `messenger.jobs.processed` → `messenger_jobs_processed_total` | job_type, outcome (success/retry/failed/lost/noop/error) |
| Job duration | `messenger.job.duration` → `messenger_job_duration_seconds_*` | s; job_type, outcome |
| Time to ready | `messenger.job.time_to_ready` → `messenger_job_time_to_ready_seconds_*` | s |
| Queue depth / oldest age | `messenger_queue_depth`, `messenger_queue_oldest_job_age_seconds` | jobs / s; queue_name (считает dispatcher по PostgreSQL) |
| DB pool | `messenger_db_pool_{used,waiting}` | connections |
| Worker saturation | `messenger_worker_{busy,capacity}` | jobs |
| CPU/RAM | `process_cpu_time_seconds_total`, `process_memory_usage_bytes` | s, bytes |
Resource: service.name = messenger-api / messenger-worker / messenger-dispatcher, service.version, service.instance.id, deployment.environment.name=lab. Логи: JSON в stdout и OTLP в Loki, поля timestamp, severity, service.name, event, trace_id, span_id (+ технические job_id/attachment_id/request_id для синтетических данных). В метки не попадают user/chat/message/attachment/request id. Токены, пароли, тела, картинки не экспортируются; Redis намеренно не инструментируется (ключи сессий производны от токена).
## SLI / SLO / alerts
- SLI доступности: 1 − 5xx / все бизнес-запросы (4xx не ошибки). **SLO 99 % за 30 дней.** Retention Prometheus = 30d.
- `HighApiErrorRate`: 5xx > 5 % за 2 мин и RPS > 0.2, `for: 1m`. `QueueLagGrowing`: `max(messenger_queue_oldest_job_age_seconds) > 30`, `for: 1m`. Runbooks: `runbooks/`.
- Percentile считается `histogram_quantile` из суммы buckets всех реплик, не из средних.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Структура, контракт | `make check && make validate` | `PASS: offline skeleton structure...`; `PASS: full OpenAPI 3.1 and JSON Schema validation` | evidence/evidence.txt |
| Стенд из Git, provisioning | `docker compose --env-file .env config --quiet`; `up --build` | конфиг валиден; образы loki, prometheus, otel-collector, tempo, grafana загружены, образ API собран с OTel-зависимостями; `/health/ready` -> `{"status":"ok"}` | evidence/evidence.txt |
| Публичный smoke при включённой телеметрии | `make test` | `PASS: lab6 public API scenario` | evidence/evidence.txt |
| Нагрузка | `tests/load.py --duration 30 --concurrency 4` | 1499 успешных, 0 ошибок, 49.9 RPS; p50 60.5 мс, p95 203.5 мс, p99 322.2 мс (предыдущий прогон в консоли: 1278 успешных, 42.5 RPS, p95 236.9 мс, 0 ошибок) | evidence/load.json |
| Trace API -> очередь -> worker -> S3/DB | `level4_observability.py trace_chain` | `PASS trace_chain`, trace `dcc088e178af4fd97d573719cf4161a5`: spans API (server, `outbox.enqueue`, INSERT/SELECT, S3.PutObject), `messenger-dispatcher:attachment-jobs publish`, `messenger-worker:attachment-jobs process`, `job.claim`, `job.pipeline`, `s3.download_staging`, `imgproc.run`, `s3.upload_final`, `job.commit_ready`, UPDATE, S3.Get/Head/Put/DeleteObject; consumer является потомком producer-span | evidence/level4-observability.txt |
| Связь лог <-> trace | `trace_chain` | trace_id найден по логу `attachment_accepted` (Loki, фильтр `attachment_id`), затем открыт в Tempo | evidence/level4-observability.txt |
| Инцидент 1: остановлен worker | `queue_lag` | `QueueLagGrowing` FIRING через ~117 с, `oldest_job_age=105 с`, `depth=1`; после запуска worker job ready, RESOLVED через ~23 с | evidence/level4-observability.txt |
| Инцидент 2: медленная БД | `db_slow` | `HighApiErrorRate` FIRING через ~89 с, 5xx: 111 из 133 запросов; после снятия блокировки RESOLVED через ~49 с | evidence/level4-observability.txt |
| Backend телеметрии недоступен | `telemetry_down` | 0 неуспешных записей при остановленных prometheus/loki/tempo; память Collector 79.39 MiB из 256 MiB; хранилища запущены обратно | evidence/level4-observability.txt |
В выводе `db_slow` перед PASS печатаются строки `FATAL: terminating connection due to administrator command` и `connection to server was lost`: это ожидаемо, сценарий сам завершает psql-сессию, держащую блокировку (`pg_terminate_backend`).
## Эксперименты и отказы
Стенд: Docker Desktop (Windows 11, WSL), Compose v2; значения ОС/CPU/RAM/версий Docker - TODO вставить из `docker version` / `docker compose version` (как в отчёте lab4).
| Воздействие | Что ожидали | Что наблюдали | Восстановление / потеря данных |
| --- | --- | --- | --- |
| `docker compose stop worker` + upload | рост возраста очереди, `QueueLagGrowing` | firing через ~117 с, `oldest_job_age=105 с`, `depth=1` | после старта worker job ready, resolved через ~23 с; потерь нет |
| `LOCK TABLE messages` 150 с под нагрузкой | 503 по `statement_timeout`, `HighApiErrorRate` | firing через ~89 с, 5xx 111 из 133 | resolved через ~49 с после снятия блокировки; данные целы |
| stop prometheus + loki + tempo на 90 с | API без ошибок, ограниченная память Collector | 0 неуспешных записей, upload ready; память Collector 79.39 MiB / 256 MiB | телеметрия за период простоя может быть потеряна (очереди и retry Collector ограничены), данные приложения целы |
## Разбор двух инцидентов и шаги диагностики
Диагностика ведётся только по сохранённым наблюдениям (Grafana: метрики, Loki, Tempo), без `docker logs`. Числа в строках «Наблюдали» взяты из `evidence/level4-observability.txt`.
### Инцидент 1. Остановлен worker (`docker compose stop worker`, затем upload)
1. **Симптом (метрики):** `messenger_queue_depth` и `messenger_queue_oldest_job_age_seconds` растут, `messenger_worker_busy` пропадает/0; через ~1 мин после порога 30 с `QueueLagGrowing` переходит pending → firing. API при этом отвечает 202: приём не равен обработке.
2. **Локализация:** `messenger_job_duration_seconds` не меняется (нет завершённых попыток), значит дело не в медленной обработке, а в отсутствии потребителя. Dispatcher жив: запись `dispatcher_cycle` в Loki, producer-span `attachment-jobs publish` есть в trace upload, а consumer-span отсутствует.
3. **Причина:** в Loki нет свежих событий `job_claimed` от `messenger-worker`. Исправление: `docker compose up -d worker`.
4. **Восстановление:** появляются `job_claimed` → `job_ready`, backlog уменьшается, `QueueLagGrowing` resolved. **Наблюдали** (`queue_lag`): алерт firing через ~117 с, `oldest_job_age` = 105 с, `depth` = 1; после `up -d worker` job стала ready, алерт resolved через ~23 с.
### Инцидент 2. Медленная БД (ACCESS EXCLUSIVE lock на `messages`, 150 с, под нагрузкой POST /messages)
1. **Симптом (метрики):** растут p95 API (до `statement_timeout` = 5 с) и доля 5xx, `HighApiErrorRate` pending → firing.
2. **Отличие от медленного handler:** в трассе POST /messages почти всё время внутри дочернего psycopg-span `INSERT` со статусом ERROR; промежутков «без дочерних spans» нет, CPU API не растёт. Медленный Python-код дал бы длинный server-span без длинного DB-span.
3. **Лог:** `{service_name="messenger-api"} | event="db_error"`, по `trace_id` находится та же трасса; панель DB pool: при нехватке соединений растёт `messenger_db_pool_waiting`.
4. **Подтверждение на БД:** `pg_stat_activity` с `wait_event_type=Lock`. Снятие блокировки → ошибки прекращаются, `HighApiErrorRate` resolved после очистки окна 2 мин. **Наблюдали** (`db_slow`): алерт firing через ~89 с; 111 из 133 запросов завершились 5xx (~83 %); после снятия блокировки алерт resolved через ~49 с.
## Ограничения и следующие шаги
Один Docker-host; Collector буферизует только в памяти (очередь 200 батчей, повтор 30 с, затем drop). Tempo под root в учебном стенде. TLS/mTLS и права — lab7. Retry по lease-reaper теряет связь с исходным trace.
+416
View File
@@ -0,0 +1,416 @@
# Lab 6: lab 5 stack + observability (OTel Collector -> Prometheus / Loki / Tempo -> Grafana).
name: mtusi-lab6
x-otel-env: &otel-env # SDK exporter settings shared by api, worker and dispatcher (service.name is set in code)
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
SERVICE_VERSION: "1.6.0"
services:
postgres:
image: postgres:17.6-alpine
environment:
POSTGRES_DB: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
volumes:
- postgres_data:/var/lib/postgresql/data
networks: [backend]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 3s
retries: 20
cpus: 1.0
mem_limit: 768m
restart: unless-stopped
redis:
image: redis:7.4.2-alpine
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
volumes:
- redis_data:/data
networks: [backend]
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
cpus: 0.25
mem_limit: 256m
restart: unless-stopped
s3:
image: pgsty/silo:RELEASE.2026-10-15T00-00-00Z
command: ["server", "/data", "--address", ":9000"]
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
MINIO_BROWSER: "off" # admin web console disabled; no ports are published at all
volumes:
- s3_data:/data
networks: [backend]
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 5s
timeout: 5s
retries: 20
cpus: 1.0
mem_limit: 512m
restart: unless-stopped
s3_init:
image: pgsty/silo:RELEASE.2026-10-15T00-00-00Z
entrypoint: ["/bin/sh", "/infra/s3-init.sh"]
environment:
S3_ENDPOINT: http://s3:9000
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env}
SWEEPER_S3_ACCESS_KEY_ID: ${SWEEPER_S3_ACCESS_KEY_ID:?Set SWEEPER_S3_ACCESS_KEY_ID in .env}
SWEEPER_S3_SECRET_ACCESS_KEY: ${SWEEPER_S3_SECRET_ACCESS_KEY:?Set SWEEPER_S3_SECRET_ACCESS_KEY in .env}
volumes:
- ./infra/s3-init.sh:/infra/s3-init.sh:ro
networks: [backend]
depends_on:
s3:
condition: service_started
restart: "no"
kafka:
image: apache/kafka:3.9.0
environment:
KAFKA_NODE_ID: "1"
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: "1"
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: "1"
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: "1"
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: "0"
KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false"
KAFKA_LOG_DIRS: /var/lib/kafka/data
KAFKA_HEAP_OPTS: "-Xms256m -Xmx512m"
volumes:
- kafka_data:/var/lib/kafka/data
networks: [backend]
healthcheck:
test: ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 >/dev/null 2>&1"]
interval: 5s
timeout: 10s
retries: 30
start_period: 15s
cpus: 1.0
mem_limit: 1g
restart: unless-stopped
kafka_init:
image: apache/kafka:3.9.0
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -e
T=/opt/kafka/bin/kafka-topics.sh
$$T --bootstrap-server kafka:9092 --create --if-not-exists --topic $${JOBS_TOPIC} --partitions 3 --replication-factor 1 --config min.insync.replicas=1 --config retention.ms=604800000
$$T --bootstrap-server kafka:9092 --list
environment:
JOBS_TOPIC: ${JOBS_TOPIC:-attachment-jobs}
networks: [backend]
depends_on:
kafka:
condition: service_healthy
restart: "no"
migrate:
build: .
image: mtusi-lab6-api:1.0.0
command: ["python", "scripts/migrate.py"]
environment:
PGHOST: postgres
PGPORT: "5432"
PGDATABASE: ${POSTGRES_DB:-messenger}
PGUSER: ${POSTGRES_USER:-messenger}
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
networks: [backend]
depends_on:
postgres:
condition: service_healthy
restart: "no"
cpus: 0.5
mem_limit: 384m
api:
build: .
image: mtusi-lab6-api:1.0.0
environment:
APP_HOST: 0.0.0.0
APP_PORT: "8080"
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
DB_POOL_MIN_SIZE: ${DB_POOL_MIN_SIZE:-1}
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-10}
DB_POOL_TIMEOUT_SECONDS: ${DB_POOL_TIMEOUT_SECONDS:-5}
PGHOST: postgres
PGPORT: "5432"
PGDATABASE: ${POSTGRES_DB:-messenger}
PGUSER: ${POSTGRES_USER:-messenger}
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
REDIS_URL: redis://redis:6379/0
S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
IMAGE_DECODE_CONCURRENCY: ${IMAGE_DECODE_CONCURRENCY:-1}
<<: *otel-env
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
deploy:
replicas: 2
expose: ["8080"]
networks: [backend]
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_healthy
s3_init:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"]
interval: 5s
timeout: 5s
retries: 10
start_period: 20s
stop_grace_period: 15s
cpus: 1.0
mem_limit: 512m
restart: unless-stopped
worker:
build: .
image: mtusi-lab6-api:1.0.0
command: ["python", "-m", "src.worker"]
environment:
PGHOST: postgres
PGPORT: "5432"
PGDATABASE: ${POSTGRES_DB:-messenger}
PGUSER: ${POSTGRES_USER:-messenger}
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env}
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
JOBS_TOPIC: ${JOBS_TOPIC:-attachment-jobs}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
LEASE_GRACE_SECONDS: ${LEASE_GRACE_SECONDS:-15}
JOB_BACKOFF_BASE_SECONDS: ${JOB_BACKOFF_BASE_SECONDS:-2}
JOB_BACKOFF_CAP_SECONDS: ${JOB_BACKOFF_CAP_SECONDS:-60}
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
IMG_MEMORY_MB: ${IMG_MEMORY_MB:-1024}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
FAULT_WORKER_EXIT_AFTER_S3: ${FAULT_WORKER_EXIT_AFTER_S3:-0}
<<: *otel-env
networks: [backend]
depends_on:
migrate:
condition: service_completed_successfully
kafka_init:
condition: service_completed_successfully
s3_init:
condition: service_completed_successfully
stop_grace_period: 30s
cpus: 1.0
mem_limit: 1g
restart: unless-stopped
dispatcher:
build: .
image: mtusi-lab6-api:1.0.0
command: ["python", "-m", "src.dispatcher"]
environment:
PGHOST: postgres
PGPORT: "5432"
PGDATABASE: ${POSTGRES_DB:-messenger}
PGUSER: ${POSTGRES_USER:-messenger}
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
JOBS_TOPIC: ${JOBS_TOPIC:-attachment-jobs}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
LEASE_GRACE_SECONDS: ${LEASE_GRACE_SECONDS:-15}
JOB_BACKOFF_BASE_SECONDS: ${JOB_BACKOFF_BASE_SECONDS:-2}
JOB_BACKOFF_CAP_SECONDS: ${JOB_BACKOFF_CAP_SECONDS:-60}
FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH: ${FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH:-0}
<<: *otel-env
networks: [backend]
depends_on:
migrate:
condition: service_completed_successfully
kafka_init:
condition: service_completed_successfully
s3_init:
condition: service_completed_successfully
cpus: 0.25
mem_limit: 192m
restart: unless-stopped
s3_sweeper:
build: .
image: mtusi-lab6-api:1.0.0
command: ["python", "scripts/s3_sweep.py", "--loop", "--apply"]
environment:
PGHOST: postgres
PGPORT: "5432"
PGDATABASE: ${POSTGRES_DB:-messenger}
PGUSER: ${POSTGRES_USER:-messenger}
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID: ${SWEEPER_S3_ACCESS_KEY_ID:?Set SWEEPER_S3_ACCESS_KEY_ID in .env}
S3_SECRET_ACCESS_KEY: ${SWEEPER_S3_SECRET_ACCESS_KEY:?Set SWEEPER_S3_SECRET_ACCESS_KEY in .env}
SWEEP_GRACE_SECONDS: ${SWEEP_GRACE_SECONDS:-3600}
SWEEP_INTERVAL_SECONDS: ${SWEEP_INTERVAL_SECONDS:-600}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
networks: [backend]
depends_on:
migrate:
condition: service_completed_successfully
s3_init:
condition: service_completed_successfully
cpus: 0.25
mem_limit: 128m
restart: unless-stopped
# ---------------- Lab 6: observability ----------------
otel-collector:
image: otel/opentelemetry-collector-contrib:0.131.0
command: ["--config=/etc/otelcol/collector.yaml"]
volumes:
- ./infra/otel/collector.yaml:/etc/otelcol/collector.yaml:ro
networks: [backend] # OTLP :4318/:4317 and self-metrics :8888 are NOT published to the host
# No healthcheck: the image has no shell/curl. Liveness extension health_check listens on :13133 inside the network.
cpus: 0.5
mem_limit: 256m # memory_limiter in collector.yaml stays below this (limit_mib: 192)
restart: unless-stopped
prometheus:
image: prom/prometheus:v3.5.0
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=30d
- --web.enable-remote-write-receiver # the Collector pushes metrics here (prometheusremotewrite)
volumes:
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./infra/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
- prometheus_data:/prometheus
networks: [backend]
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:9090/-/ready"]
interval: 10s
timeout: 3s
retries: 10
cpus: 0.5
mem_limit: 512m
restart: unless-stopped
loki:
image: grafana/loki:3.5.3
command: ["-config.file=/etc/loki/loki.yaml"]
volumes:
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
- loki_data:/loki
networks: [backend]
cpus: 0.5
mem_limit: 512m
restart: unless-stopped
tempo:
image: grafana/tempo:2.8.2
command: ["-config.file=/etc/tempo/tempo.yaml"]
user: "0" # named volume must be writable on first start (learning stand; lab 7 hardens this)
volumes:
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
- tempo_data:/var/tempo
networks: [backend]
cpus: 0.5
mem_limit: 512m
restart: unless-stopped
grafana:
image: grafana/grafana:12.1.1
environment:
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env}
GF_USERS_ALLOW_SIGN_UP: "false"
GF_ANALYTICS_REPORTING_ENABLED: "false"
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
ports:
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000" # the only observability port on the host, loopback only
volumes:
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
- grafana_data:/var/lib/grafana
networks: [frontend, backend]
depends_on:
prometheus:
condition: service_healthy
loki:
condition: service_started
tempo:
condition: service_started
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/api/health"]
interval: 10s
timeout: 3s
retries: 10
cpus: 0.5
mem_limit: 512m
restart: unless-stopped
load_balancer:
image: haproxy:3.2.5-alpine
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
volumes:
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
networks: [frontend, backend]
depends_on:
api:
condition: service_healthy
healthcheck:
test: ["CMD", "haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
interval: 10s
timeout: 3s
retries: 3
cpus: 0.5
mem_limit: 128m
restart: unless-stopped
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true # no route to/from the host or internet: S3, PostgreSQL, Redis, Kafka, API and the telemetry stack are reachable only inside
volumes:
postgres_data:
redis_data:
s3_data:
kafka_data:
prometheus_data:
loki_data:
tempo_data:
grafana_data:
+68
View File
@@ -0,0 +1,68 @@
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
make check && make validate
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
python3 scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
docker compose --env-file .env config --quiet
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
User@DESKTOP-8Q26HPT MINGW64 ~/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork (solution/bvt2302-mironov)
$ docker compose --env-file .env up --build
[+] Running 28/28
✔ loki Pulled 41.0s
✔ prometheus Pulled 106.1s
✔ otel-collector Pulled 119.1s
✔ tempo Pulled 25.7s
✔ grafana Pulled 166.1s
[+] Building 87.0s (8/12) docker:desktop-linux
=> => resolve docker.io/library/python:3.12.11-slim-bookworm@sha256:519591d6871b7bc437060736b9f7 0.1s
=> CACHED [migrate 2/8] WORKDIR /app 0.0s
=> CACHED [migrate 3/8] RUN addgroup --system app && adduser --system --ingroup app app 0.0s
=> [migrate 4/8] COPY requirements.txt ./requirements.txt 0.0s
=> [migrate 5/8] RUN python -m pip install --no-cache-dir -r requirements.txt 81.5s
=> => # Downloading opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl (206 kB)
=> => # Downloading opentelemetry_util_http-0.66b1-py3-none-any.whl (8.4 kB)
=> => # Downloading psycopg_binary-3.2.9-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4
=> => # .4 MB)
=> => # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.4/4.4 MB 1.4 MB/s eta 0:00:00
=> => # Downloading botocore-1.40.76-py3-none-any.whl (14.2 MB)
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
until curl -fs http://localhost:8080/health/ready; do sleep 2; done
{"status":"ok"}thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
make test
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
{
"lab": 6,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.078,
"concurrency": 4,
"successful_requests": 1278,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 42.49,
"successful_latency_ms": {
"p50": 69.861,
"p95": 236.929,
"p99": 397.268
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
+22
View File
@@ -0,0 +1,22 @@
PASS trace_chain: trace dcc088e178af4fd97d573719cf4161a5 spans: ['messenger-api:INSERT', 'messenger-api:POST /api/v1/chats/{chat_id}/attachments', 'messenger-api:POST /api/v1/chats/{chat_id}/attachments http receive', 'messenger-api:POST /api/v1/chats/{chat_id}/attachments http send', 'messenger-api:S3.PutObject', 'messenger-api:SELECT', 'messenger-api:outbox.enqueue', 'messenger-dispatcher:attachment-jobs publish', 'messenger-worker:INSERT', 'messenger-worker:S3.DeleteObject', 'messenger-worker:S3.GetObject', 'messenger-worker:S3.HeadObject', 'messenger-worker:S3.PutObject', 'messenger-worker:SELECT', 'messenger-worker:UPDATE', 'messenger-worker:attachment-jobs process', 'messenger-worker:imgproc.run', 'messenger-worker:job.claim', 'messenger-worker:job.commit_ready', 'messenger-worker:job.pipeline', 'messenger-worker:s3.download_staging', 'messenger-worker:s3.upload_final']
queue_lag: FIRING after ~117s, oldest_job_age=105s, depth=1
PASS queue_lag: ready after worker restart; RESOLVED after ~23s
db_slow: FIRING after ~89s; 5xx so far: 111 of 133
PASS db_slow: lock released; RESOLVED after ~49s
PASS telemetry_down: 0 failed writes with all telemetry stores down; collector memory 79.39MiB / 256MiB (limit 256MiB); stores restarted
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$ python3 student-tests/level4_observability.py all | tee evidence/level4-observability.txt
FATAL: terminating connection due to administrator command
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
connection to server was lost
PASS trace_chain: trace dcc088e178af4fd97d573719cf4161a5 spans: ['messenger-api:INSERT', 'messenger-api:POST /api/v1/chats/{chat_id}/attachments', 'messenger-api:POST /api/v1/chats/{chat_id}/attachments http receive', 'messenger-api:POST /api/v1/chats/{chat_id}/attachments http send', 'messenger-api:S3.PutObject', 'messenger-api:SELECT', 'messenger-api:outbox.enqueue', 'messenger-dispatcher:attachment-jobs publish', 'messenger-worker:INSERT', 'messenger-worker:S3.DeleteObject', 'messenger-worker:S3.GetObject', 'messenger-worker:S3.HeadObject', 'messenger-worker:S3.PutObject', 'messenger-worker:SELECT', 'messenger-worker:UPDATE', 'messenger-worker:attachment-jobs process', 'messenger-worker:imgproc.run', 'messenger-worker:job.claim', 'messenger-worker:job.commit_ready', 'messenger-worker:job.pipeline', 'messenger-worker:s3.download_staging', 'messenger-worker:s3.upload_final']
queue_lag: FIRING after ~117s, oldest_job_age=105s, depth=1
PASS queue_lag: ready after worker restart; RESOLVED after ~23s
db_slow: FIRING after ~89s; 5xx so far: 111 of 133
PASS db_slow: lock released; RESOLVED after ~49s
PASS telemetry_down: 0 failed writes with all telemetry stores down; collector memory 79.39MiB / 256MiB (limit 256MiB); stores restarted
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab6/mtusi2026lab6-fork$
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 6,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.042,
"concurrency": 4,
"successful_requests": 1499,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 49.897,
"successful_latency_ms": {
"p50": 60.461,
"p95": 203.526,
"p99": 322.168
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+16 -5
View File
@@ -1,7 +1,18 @@
# Инфраструктура студента # Инфраструктура (lab6)
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. | Роль | Service (compose) | Версия | Health | Volume | Сеть/порт | Credentials |
| --- | --- | --- | --- | --- | --- | --- |
| API (x2) | api | python 3.12.11 + FastAPI 0.116.1 | /health/ready | — | backend, через LB | env из .env |
| Load balancer | load_balancer | haproxy 3.2.5 | haproxy -c | — | 127.0.0.1:8080 | — |
| PostgreSQL | postgres | 17.6 | pg_isready | postgres_data | backend | .env |
| Redis (сессии) | redis | 7.4.2 | redis-cli ping | redis_data | backend | — |
| S3 | s3 / s3_init | MinIO-совместимый | mc ready | s3_data | backend | .env |
| Broker | kafka / kafka_init | Apache Kafka 3.9.0 | broker-api-versions | kafka_data | backend | — |
| Worker / dispatcher | worker, dispatcher | образ api | — | — | backend | .env |
| OTel Collector | otel-collector | contrib 0.131.0 | extension health_check :13133 | — | backend (OTLP 4318/4317, 8888) | — |
| Метрики | prometheus | v3.5.0 | /-/ready | prometheus_data | backend | — |
| Логи | loki | 3.5.3 | — | loki_data | backend | — |
| Трассы | tempo | 2.8.2 | — | tempo_data | backend | — |
| UI | grafana | 12.1.1 | /api/health | grafana_data | 127.0.0.1:3000 | GRAFANA_ADMIN_* в .env |
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. Конфиги: `otel/collector.yaml`, `prometheus/{prometheus,alerts}.yml`, `loki/loki.yaml`, `tempo/tempo.yaml`, `grafana/provisioning/*`, `grafana/dashboards/*.json`. Provisioning применяется автоматически при старте Grafana (ручной набор не нужен).
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
@@ -0,0 +1,670 @@
{
"uid": "messenger-observability",
"title": "Messenger: observability (lab 6)",
"tags": [
"messenger",
"lab6"
],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {
"from": "now-30m",
"to": "now"
},
"editable": false,
"panels": [
{
"id": 1,
"type": "stat",
"title": "API availability SLI (SLO 99 % / 30 d)",
"description": "SLI = 1 - 5xx / all business requests (health excluded; 4xx are client errors). Window = dashboard time range (set 30d to read the SLO). Query: 1 - sum(increase(http_server_request_duration_seconds_count{5xx}[$__range])) / sum(increase(..._count[$__range])).",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 8,
"h": 4
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "1 - (sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_class=\"5xx\"}[$__range])) / sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__range])))",
"legendFormat": "availability"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0.9,
"max": 1,
"decimals": 3,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": null
},
{
"color": "green",
"value": 0.99
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "background",
"reduceOptions": {
"calcs": [
"lastNotNull"
]
}
}
},
{
"id": 2,
"type": "timeseries",
"title": "Alert state (pending / firing)",
"description": "ALERTS{} series written by Prometheus rule evaluation: shows pending -> firing -> gone (resolved).",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 0,
"w": 16,
"h": 4
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (alertname, alertstate) (ALERTS)",
"legendFormat": "{{alertname}} {{alertstate}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 3,
"type": "timeseries",
"title": "API RPS by route",
"description": "Query: sum by (http_route)(rate(http_server_request_duration_seconds_count[1m])). Unit: requests/s. Route is a TEMPLATE, never a real UUID.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 4,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (http_route) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[1m]))",
"legendFormat": "{{http_route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {}
},
{
"id": 4,
"type": "timeseries",
"title": "API 5xx error ratio",
"description": "numerator = 5xx business requests, denominator = all business requests (health excluded). Unit: ratio 0..1.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 4,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_class=\"5xx\"}[2m])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[2m]))",
"legendFormat": "5xx / all"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0
},
"overrides": []
},
"options": {}
},
{
"id": 5,
"type": "timeseries",
"title": "API latency p50 / p95 / p99",
"description": "histogram_quantile(q, sum by (le)(rate(http_server_request_duration_seconds_bucket[2m]))): buckets of ALL replicas are summed first. Averages of per-replica percentiles are mathematically wrong. Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 4,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 6,
"type": "timeseries",
"title": "Jobs by outcome",
"description": "Counter of finished attempts: success | retry | failed | lost | noop | error. Unit: attempts/s.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 12,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {}
},
{
"id": 7,
"type": "timeseries",
"title": "Worker job duration p50 / p95 / p99",
"description": "Processing time of one attempt (claim -> outcome). Does NOT include waiting in the queue (that is queue age). Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 12,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 8,
"type": "timeseries",
"title": "Time to ready p50 / p95 / p99",
"description": "End-to-end: durable acceptance (job row) -> ready commit, incl. backlog, retries and backoff. Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 12,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 9,
"type": "timeseries",
"title": "Queue depth",
"description": "Jobs with status=queued whose backoff has elapsed (waiting for a worker). Computed by the dispatcher from PostgreSQL. Unit: jobs.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max by (queue_name) (messenger_queue_depth)",
"legendFormat": "{{queue_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 10,
"type": "timeseries",
"title": "Oldest waiting job age",
"description": "now - min(next_attempt_at) over due queued jobs; 0 when empty. Alert QueueLagGrowing: > 30 s for 1 m. Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 6,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max by (queue_name) (messenger_queue_oldest_job_age_seconds)",
"legendFormat": "{{queue_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 11,
"type": "timeseries",
"title": "Worker busy vs capacity",
"description": "busy = jobs handled right now, capacity = WORKER_CONCURRENCY. Saturation = busy / capacity. Unit: jobs.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_busy)",
"legendFormat": "busy"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_capacity)",
"legendFormat": "capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 12,
"type": "timeseries",
"title": "DB pool used / waiting (API)",
"description": "psycopg_pool stats: connections checked out, requests waiting for a connection. waiting > 0 = pool saturation. Unit: connections / requests.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 18,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_instance_id) (messenger_db_pool_used)",
"legendFormat": "used {{service_instance_id}}"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_waiting)",
"legendFormat": "waiting (all)"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 13,
"type": "timeseries",
"title": "CPU by service (cores)",
"description": "rate of process CPU seconds (user+system) of the main process. Unit: CPU cores.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 28,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (rate(process_cpu_time_seconds_total[1m]))",
"legendFormat": "{{service_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 14,
"type": "timeseries",
"title": "Memory (RSS) by service",
"description": "Resident set size of the main process. Unit: bytes.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 28,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name, service_instance_id) (process_memory_usage_bytes)",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {}
},
{
"id": 15,
"type": "timeseries",
"title": "Telemetry loss in the Collector",
"description": "Failed exporter sends and memory_limiter refusals (spans / metric points / log records per second). Non-zero while a backend is down: telemetry is lost, the API is not affected.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 28,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (__name__) (rate({__name__=~\"otelcol_(exporter_send_failed|processor_refused)_.*_total\",job=\"otel-collector\"}[1m]))",
"legendFormat": "{{__name__}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 16,
"type": "logs",
"title": "Warnings and errors (all services)",
"description": "Loki (OTLP). Click trace_id to open the trace in Tempo. Filter one trace: {service_name=~\"messenger-.+\"} | trace_id=\"<id>\".",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 36,
"w": 24,
"h": 10
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "loki",
"uid": "loki"
},
"expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"WARN|ERROR|CRITICAL\"",
"legendFormat": ""
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"showTime": true,
"wrapLogMessage": true,
"enableLogDetails": true,
"sortOrder": "Descending"
}
}
],
"templating": {
"list": []
},
"annotations": {
"list": []
}
}
@@ -0,0 +1,9 @@
apiVersion: 1
providers:
- name: messenger
type: file
disableDeletion: true
allowUiUpdates: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,20 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 15s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
+32
View File
@@ -0,0 +1,32 @@
global
log stdout format raw local0
maxconn 1024
defaults
log global
mode http
option httplog
option http-keep-alive
timeout connect 2s
timeout client 30s
timeout server 30s
timeout check 2s
resolvers docker
nameserver docker-dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 2s
frontend public_http
bind :8080
default_backend api_replicas
backend api_replicas
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
default-server inter 1s fall 2 rise 1
server-template api 10 api:8080 check resolvers docker init-addr libc,none
+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 # OTLP attributes (trace_id, span_id, event, ...) are stored as structured metadata
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
analytics:
reporting_enabled: false
+81
View File
@@ -0,0 +1,81 @@
# OpenTelemetry Collector (contrib 0.131.0). It is a receiver/processor/exporter, NOT a database:
# API/worker/dispatcher -> OTLP -> [memory_limiter -> batch] -> Prometheus (metrics) | Loki (logs) | Tempo (traces).
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318 # app SDKs (OTLP/HTTP protobuf); reachable only inside the internal backend network
grpc:
endpoint: 0.0.0.0:4317
processors:
# FIRST in every pipeline. Container limit is 256 MiB; soft limit 192 MiB, hard limit = limit_mib (192), spike margin 48.
# Above the soft limit (limit - spike = 144 MiB) the Collector starts refusing data: SDK exporters retry with bounded queues
# and then drop => telemetry is lost, the API keeps serving and RAM stays bounded.
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 2s
send_batch_size: 512
send_batch_max_size: 1024
exporters:
prometheusremotewrite:
endpoint: http://prometheus:9090/api/v1/write
timeout: 5s
resource_to_telemetry_conversion:
enabled: true # service.name / service.instance.id become labels (service_name, service_instance_id)
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s # after 30 s of failures the batch is DROPPED (bounded buffering)
remote_write_queue:
enabled: true
queue_size: 200 # bounded in-memory buffer (batches); full queue => new data is dropped and counted
num_consumers: 2
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 5s
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
sending_queue: {enabled: true, num_consumers: 2, queue_size: 200}
otlp/tempo:
endpoint: tempo:4317
timeout: 5s
tls:
insecure: true # internal network only; TLS/mTLS is lab 7
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
sending_queue: {enabled: true, num_consumers: 2, queue_size: 200}
service:
extensions: [health_check]
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
telemetry:
logs:
level: info
metrics:
level: normal
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888 # Collector self-metrics (dropped/refused/failed counters) scraped by Prometheus
+32
View File
@@ -0,0 +1,32 @@
groups:
- name: messenger-slo
rules:
# SLI (availability): 1 - 5xx / all BUSINESS requests (health excluded; 4xx such as a wrong password are NOT errors).
# SLO: 99 % over a rolling 30 days (error budget 1 %). Alert = fast symptom: >5 % 5xx for 1 m with real traffic.
- alert: HighApiErrorRate
expr: |
(
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_class="5xx"}[2m]))
/
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))
) > 0.05
and
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m])) > 0.2
for: 1m
labels:
severity: page
annotations:
summary: "API 5xx ratio above 5 % (2m window)"
description: "More than 5 % of business requests end with 5xx for 1 minute. Runbook: runbooks/high-error-rate.md"
runbook: runbooks/high-error-rate.md
# Queue lag: the oldest due job waits for a worker longer than 30 s for 1 m (worker stopped / too slow / broker problem).
# Backlog (age of waiting jobs) is NOT processing latency: processing time is messenger_job_duration_seconds.
- alert: QueueLagGrowing
expr: max(messenger_queue_oldest_job_age_seconds{queue_name="attachment-jobs"}) > 30
for: 1m
labels:
severity: page
annotations:
summary: "Oldest waiting job is older than 30 s"
description: "Jobs wait for a worker. Check messenger_worker_busy/capacity, messenger_queue_depth and the worker logs. Runbook: runbooks/queue-lag.md"
runbook: runbooks/queue-lag.md
+14
View File
@@ -0,0 +1,14 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
scrape_configs:
# Application metrics arrive by remote write from the Collector (push). Only the Collector's own health is scraped:
# this is how telemetry LOSS is measured when a backend is down.
- job_name: otel-collector
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# Idempotent bootstrap of the private bucket, the restricted application user
# and the separate sweeper user (safe to re-run).
set -eu
: "${S3_ENDPOINT:?}" "${S3_BUCKET:?}" "${MINIO_ROOT_USER:?}" "${MINIO_ROOT_PASSWORD:?}"
: "${S3_ACCESS_KEY_ID:?}" "${S3_SECRET_ACCESS_KEY:?}"
: "${SWEEPER_S3_ACCESS_KEY_ID:?}" "${SWEEPER_S3_SECRET_ACCESS_KEY:?}"
[ "$S3_ACCESS_KEY_ID" != "$MINIO_ROOT_USER" ] || { echo "app key must differ from root user" >&2; exit 1; }
[ "$SWEEPER_S3_ACCESS_KEY_ID" != "$MINIO_ROOT_USER" ] || { echo "sweeper key must differ from root user" >&2; exit 1; }
[ "$S3_ACCESS_KEY_ID" != "$SWEEPER_S3_ACCESS_KEY_ID" ] || { echo "app and sweeper keys must differ" >&2; exit 1; }
i=0
until mc alias set local "$S3_ENDPOINT" "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null 2>&1; do
i=$((i+1)); [ "$i" -lt 60 ] || { echo "S3 not reachable" >&2; exit 1; }; sleep 1
done
mc mb --ignore-existing "local/$S3_BUCKET"
mc anonymous set none "local/$S3_BUCKET"
printf ok | mc pipe "local/$S3_BUCKET/attachments/.ready"
# --- app policy: exact keys only, NO ListBucket ---
cat > /tmp/policy-app.json <<POLICY
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::$S3_BUCKET/attachments/*","arn:aws:s3:::$S3_BUCKET/staging/*"]}]}
POLICY
# --- sweeper policy: ListBucket for enumeration + Get/Delete, NO PutObject ---
cat > /tmp/policy-sweeper.json <<POLICY
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::$S3_BUCKET"]},
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::$S3_BUCKET/attachments/*","arn:aws:s3:::$S3_BUCKET/staging/*"]}]}
POLICY
# MinIO's `policy create` does not overwrite an existing policy, so remove first.
mc admin policy remove local messenger-app --force >/dev/null 2>&1 || true
mc admin policy remove local messenger-sweeper --force >/dev/null 2>&1 || true
mc admin policy create local messenger-app /tmp/policy-app.json
mc admin policy create local messenger-sweeper /tmp/policy-sweeper.json
# `user add` is idempotent (re-running updates the secret).
mc admin user add local "$S3_ACCESS_KEY_ID" "$S3_SECRET_ACCESS_KEY"
mc admin user add local "$SWEEPER_S3_ACCESS_KEY_ID" "$SWEEPER_S3_SECRET_ACCESS_KEY"
out=$(mc admin policy attach local messenger-app --user "$S3_ACCESS_KEY_ID" 2>&1) || {
echo "$out" | grep -qi "already" || { echo "$out" >&2; exit 1; }
}
out=$(mc admin policy attach local messenger-sweeper --user "$SWEEPER_S3_ACCESS_KEY_ID" 2>&1) || {
echo "$out" | grep -qi "already" || { echo "$out" >&2; exit 1; }
}
echo "PASS: bucket $S3_BUCKET private"
echo " app=$S3_ACCESS_KEY_ID (Put/Get/Delete on attachments/* and staging/*, no ListBucket)"
echo " sweeper=$SWEEPER_S3_ACCESS_KEY_ID (ListBucket + Get/Delete, no PutObject)"
+20
View File
@@ -0,0 +1,20 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
ingester:
max_block_duration: 5m
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+32
View File
@@ -0,0 +1,32 @@
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username VARCHAR(32) NOT NULL UNIQUE,
display_name VARCHAR(100) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_nonblank CHECK (length(btrim(display_name)) > 0)
);
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY,
title VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT chats_title_nonblank CHECK (length(btrim(title)) > 0)
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
position INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (chat_id, user_id)
);
ALTER TABLE chat_members ADD COLUMN IF NOT EXISTS position INTEGER NOT NULL DEFAULT 0;
CREATE INDEX IF NOT EXISTS chat_members_user_chat_idx ON chat_members(user_id, chat_id);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id),
text VARCHAR(4000) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT messages_text_nonblank CHECK (length(btrim(text)) > 0)
);
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx ON messages(chat_id, created_at, id);
+11
View File
@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS idempotency_records (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
response_body JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, chat_id, idempotency_key),
CONSTRAINT idempotency_key_format CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$')
);
CREATE INDEX IF NOT EXISTS idempotency_records_created_at_idx ON idempotency_records(created_at);
+24
View File
@@ -0,0 +1,24 @@
CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users(id),
filename VARCHAR(255) NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
sha256 CHAR(64) NOT NULL,
s3_key TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT attachments_filename_nonblank CHECK (length(btrim(filename)) > 0),
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$')
);
CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id);
CREATE TABLE IF NOT EXISTS message_attachments (
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id UUID NOT NULL REFERENCES attachments(id),
position INTEGER NOT NULL,
PRIMARY KEY (message_id, attachment_id)
);
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments(attachment_id);
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_nonblank;
+58
View File
@@ -0,0 +1,58 @@
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'ready';
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code TEXT;
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key TEXT;
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS pipeline_version INTEGER NOT NULL DEFAULT 1;
ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status;
ALTER TABLE attachments ADD CONSTRAINT attachments_status CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
CREATE INDEX IF NOT EXISTS attachments_staging_idx ON attachments(staging_key) WHERE staging_key IS NOT NULL;
CREATE TABLE IF NOT EXISTS attachment_variants (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL,
name TEXT NOT NULL,
s3_key TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
width INTEGER NOT NULL,
height INTEGER NOT NULL,
sha256 CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (attachment_id, pipeline_version, name),
CONSTRAINT variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized'))
);
CREATE TABLE IF NOT EXISTS attachment_jobs (
job_id UUID PRIMARY KEY,
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL,
attempt INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL,
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
lease_until TIMESTAMPTZ,
worker_id TEXT,
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
CONSTRAINT jobs_effect_key UNIQUE (attachment_id, pipeline_version)
);
CREATE INDEX IF NOT EXISTS attachment_jobs_status_idx ON attachment_jobs(status, lease_until);
CREATE TABLE IF NOT EXISTS job_events (
id BIGSERIAL PRIMARY KEY,
job_id UUID NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE,
at TIMESTAMPTZ NOT NULL DEFAULT now(),
event TEXT NOT NULL,
detail TEXT
);
CREATE INDEX IF NOT EXISTS job_events_job_idx ON job_events(job_id, id);
CREATE TABLE IF NOT EXISTS outbox (
id BIGSERIAL PRIMARY KEY,
job_id UUID NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE,
topic TEXT NOT NULL,
msg_key TEXT NOT NULL,
payload JSONB NOT NULL,
available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS outbox_pending_idx ON outbox(available_at, id) WHERE published_at IS NULL;
+14
View File
@@ -0,0 +1,14 @@
fastapi==0.116.1
uvicorn[standard]==0.35.0
psycopg[pool,binary]==3.2.9
argon2-cffi==25.1.0
redis==6.4.0
boto3==1.40.20
Pillow==11.3.0
confluent-kafka==2.10.1
opentelemetry-api==1.45.1
opentelemetry-sdk==1.45.1
opentelemetry-exporter-otlp-proto-http==1.45.1
opentelemetry-instrumentation-fastapi==0.66b1
opentelemetry-instrumentation-psycopg==0.66b1
opentelemetry-instrumentation-botocore==0.66b1
+13
View File
@@ -0,0 +1,13 @@
# Runbook: HighApiErrorRate (5xx > 5 % за 2 мин, держится 1 мин)
**Что значит.** Доля 5xx среди бизнес-запросов API выше 5 %. 4xx (неверный пароль, чужой чат) сюда не входят.
1. Grafana → дашборд *Messenger: observability* → панели *API 5xx error ratio* и *API RPS by route*: какие маршруты и какая реплика (`service_instance_id`).
2. Панель *DB pool used / waiting*: `waiting > 0` и `used = max` — упёрлись в пул/медленную БД. Нули — проблема не в пуле.
3. Логи: Explore → Loki → `{service_name="messenger-api"} | event=~"db_error|db_pool_timeout|s3_error|session_store_error|unhandled_exception"`. Поле `event` сразу называет зависимость; `reason` — тип исключения.
4. Трасса: из строки лога по `trace_id` (Derived field *Open trace*) открыть трассу. Смотреть **длинный дочерний span**:
- длинный `INSERT/SELECT` (psycopg span) → медленная/заблокированная БД (статус ERROR после `statement_timeout`);
- длинный `S3.PutObject` → хранилище объектов;
- пустое время между спанами внутри server span → медленный Python-код handler'а, а не зависимость.
5. Подтвердить на стороне БД: `docker compose exec postgres psql -U messenger -c "select pid,state,wait_event_type,left(query,60) from pg_stat_activity where state<>'idle'"`.
6. Устранить причину (снять блокировку, восстановить зависимость). Алерт перейдёт в *resolved*, когда окно 2 мин очистится от ошибок.
+10
View File
@@ -0,0 +1,10 @@
# Runbook: QueueLagGrowing (самая старая ожидающая job > 30 с, держится 1 мин)
**Что значит.** Задачи ждут worker'а: backlog растёт. Это не время обработки (оно в `messenger_job_duration_seconds`).
1. Панели *Queue depth* и *Oldest waiting job age*: растут оба — worker'ы не разбирают очередь.
2. Панель *Worker busy vs capacity*: серия `busy` отсутствует/0 при росте очереди → worker остановлен или не подключён к Kafka; `busy = capacity` → worker перегружен (медленные задачи, см. *Worker job duration p95*).
3. `docker compose ps worker dispatcher kafka` и логи: `{service_name="messenger-worker"} | event=~"worker_started|job_attempt_failed|job_lease_lost"`.
4. Если растёт `retry`/`failed` в панели *Jobs by outcome* → причина в логе `job_attempt_failed` (`reason`), трасса задачи: `{service_name="messenger-worker"} | event="job_attempt_failed"` → `trace_id` → span `job.pipeline`/`s3.*`.
5. Если очередь растёт, а worker жив и свободен → проверить dispatcher (`event="outbox_publish_unconfirmed"`) и Kafka: сообщения не доходят до топика.
6. Устранить причину (`docker compose up -d worker`). Backlog уменьшается, алерт переходит в *resolved*.
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Apply SQL migrations once, before any API replica is started."""
from pathlib import Path
import os
import time
import psycopg
ROOT = Path(__file__).resolve().parents[1]
CONNINFO = os.getenv("DATABASE_URL", "")
def main():
last_error = None
for _ in range(30):
try:
with psycopg.connect(CONNINFO, connect_timeout=3) as conn:
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
conn.commit()
for path in sorted((ROOT / "migrations").glob("*.sql")):
version = path.name
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (version,)).fetchone():
continue
sql = path.read_text(encoding="utf-8")
with conn.transaction():
for statement in sql.split(";"):
if statement.strip():
conn.execute(statement)
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (version,))
print(f"APPLIED {version}", flush=True)
print("PASS: migrations complete", flush=True)
return
except Exception as exc:
last_error = exc
time.sleep(1)
raise SystemExit(f"Migration failed after retries: {type(last_error).__name__}")
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Operator tool: failed-job registry and SAFE explicit replay (lab5, level 4).
docker compose exec worker python scripts/replay_failed.py --list
docker compose exec worker python scripts/replay_failed.py --job-id <uuid> --reason "ticket-123"
Replay never executes a duplicate of a successful job: it requires status=failed, that the staging source still exists,
and that the effect (all variants of the pipeline version) is NOT already present. Everything happens in ONE transaction
(state change + audit event + outbox row), so the new attempt is delivered by the normal dispatcher path.
"""
import argparse
import os
import sys
import psycopg
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src import jobs # noqa: E402
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--list", action="store_true")
p.add_argument("--job-id")
p.add_argument("--reason", default="operator replay")
a = p.parse_args()
with psycopg.connect(connect_timeout=5) as conn:
if a.list or not a.job_id:
for r in conn.execute("SELECT job_id, attachment_id, error_code, attempt, updated_at FROM attachment_jobs WHERE status='failed' ORDER BY updated_at"):
print(*r, sep="\t")
return 0
row = conn.execute("SELECT j.status, j.attachment_id, j.pipeline_version, a.staging_key FROM attachment_jobs j "
"JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s FOR UPDATE OF j", (a.job_id,)).fetchone()
if row is None:
print("REFUSED: unknown job"); return 1
status, att_id, pv, staging_key = row
if status != "failed":
print(f"REFUSED: job is {status}, only failed jobs can be replayed"); return 1
done = conn.execute("SELECT count(*) FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s", (att_id, pv)).fetchone()[0]
if done >= len(jobs.VARIANT_ORDER):
print("REFUSED: the effect already exists (all variants present)"); return 1
if not staging_key:
print("REFUSED: staging source expired (retention), upload the file again"); return 1
conn.execute("UPDATE attachment_jobs SET status='queued', attempt=0, error_code=NULL, lease_until=NULL, next_attempt_at=now(), updated_at=now() WHERE job_id=%s", (a.job_id,))
conn.execute("UPDATE attachments SET status='queued', error_code=NULL, updated_at=now() WHERE id=%s", (att_id,))
jobs.add_event(conn, a.job_id, "replay", a.reason[:200])
jobs.enqueue(conn, a.job_id, att_id, pv, 1)
print(f"REPLAYED job={a.job_id} attachment={att_id}")
return 0
if __name__ == "__main__":
sys.exit(main())
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
# Restart ALL state stores (PostgreSQL, Redis, S3, Kafka + Prometheus, Loki, Tempo), then API, dispatcher, worker, Collector, Grafana; named volumes are preserved.
docker compose restart postgres redis s3 kafka prometheus loki tempo
docker compose restart api dispatcher worker otel-collector grafana
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
set -eu
# Sequential replacement-equivalent exercise for Compose (which has no native rolling-update primitive).
# Run a load generator in another terminal while this script executes.
replicas="$(docker compose ps -q --all api)"
[ -n "$replicas" ] || { echo "No API containers found; start the stack first" >&2; exit 1; }
for id in $replicas; do
# Remove one replica; the LB excludes it after health-check failure.
docker stop --time 10 "$id" >/dev/null || true
docker rm -f "$id" >/dev/null
docker compose up -d --no-deps --scale api=2 api
# Wait for at least two healthy API containers before moving to the next one.
tries=0
while [ "$tries" -lt 30 ]; do
healthy=0
for candidate in $(docker compose ps -q api); do
status=$(docker inspect --format '{{.State.Health.Status}}' "$candidate" 2>/dev/null || echo starting)
[ "$status" = healthy ] && healthy=$((healthy+1))
done
[ "$healthy" -ge 2 ] && break
tries=$((tries+1)); sleep 1
done
[ "$healthy" -ge 2 ] || { echo "Fewer than two healthy replicas after replacement" >&2; exit 1; }
done
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Orphan sweeper (lab5): staging/ and attachments/ cleanup, retention of failed staging (see run_once).
Safety: only objects older than --grace-seconds are candidates (default 3600, far above the few seconds between
PUT and COMMIT), and the DB is re-checked immediately before each delete. Default mode is --dry-run.
"""
import argparse, os, sys, time
from datetime import datetime, timezone
import boto3, psycopg
from botocore.config import Config
def run_once(s3, conn, bucket, grace, apply, retention):
"""Lab5 cleanup rules (documented in REPORT.md):
1) staging/<k> without any attachments.staging_key row older than grace = orphan of a crash between PUT and COMMIT -> delete
(staging of ready attachments is deleted by the worker and its staging_key set to NULL, so a leftover is also an orphan);
2) attachments/<id>/... whose attachment row no longer exists -> delete;
3) staging of FAILED attachments older than retention -> delete object and NULL staging_key (replay is then impossible).
Current work (queued/processing, or failed within retention) is never touched; the DB is re-checked right before each delete."""
now = datetime.now(timezone.utc)
seen = old = orphans = deleted = 0
for prefix in ("staging/", "attachments/"):
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
for obj in page.get("Contents", []):
seen += 1
key = obj["Key"]
if key == "attachments/.ready" or (now - obj["LastModified"]).total_seconds() < grace:
continue # fresh: may still be between PUT and COMMIT
old += 1
if prefix == "staging/":
referenced = lambda: conn.execute("SELECT 1 FROM attachments WHERE staging_key=%s", (key,)).fetchone()
else:
att = key.split("/")[1] if key.count("/") >= 2 else ""
referenced = lambda: conn.execute("SELECT 1 FROM attachments WHERE id::text=%s", (att,)).fetchone()
if referenced():
continue
orphans += 1
print(("DELETE " if apply else "WOULD-DELETE ") + key, flush=True)
if apply and not referenced():
s3.delete_object(Bucket=bucket, Key=key); deleted += 1
expired = conn.execute("SELECT id, staging_key FROM attachments WHERE status='failed' AND staging_key IS NOT NULL "
"AND updated_at < now() - make_interval(secs=>%s)", (retention,)).fetchall()
for att_id, skey in expired:
print(("EXPIRE-STAGING " if apply else "WOULD-EXPIRE-STAGING ") + skey, flush=True)
if apply:
s3.delete_object(Bucket=bucket, Key=skey)
conn.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s", (att_id,))
deleted += 1
print(f"sweep: seen={seen} older_than_grace={old} orphans={orphans} failed_expired={len(expired)} deleted={deleted} apply={apply}", flush=True)
return orphans, deleted
def main():
p = argparse.ArgumentParser()
p.add_argument("--apply", action="store_true", help="really delete (default: dry-run)")
p.add_argument("--grace-seconds", type=int, default=int(os.getenv("SWEEP_GRACE_SECONDS", "3600")))
p.add_argument("--loop", action="store_true"); p.add_argument("--interval", type=int, default=int(os.getenv("SWEEP_INTERVAL_SECONDS", "600")))
p.add_argument("--retention-seconds", type=int, default=int(os.getenv("STAGING_RETENTION_SECONDS", "86400")))
a = p.parse_args()
if a.grace_seconds < 0: sys.exit("grace must be >= 0")
s3 = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"], region_name=os.getenv("S3_REGION", "us-east-1"),
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"], aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}))
bucket = os.environ["S3_BUCKET"]
while True:
try:
with psycopg.connect(connect_timeout=5, autocommit=True) as conn:
run_once(s3, conn, bucket, a.grace_seconds, a.apply, a.retention_seconds)
except Exception as exc: # keep looping through outages
print("sweep failed:", type(exc).__name__, flush=True)
if not a.loop: raise
if not a.loop: return
time.sleep(a.interval)
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID must be supplied by tests/resilience.py}"
found=""
for id in $(docker compose ps -q api); do
host=$(docker inspect --format '{{.Config.Hostname}}' "$id")
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
found="$id"
break
fi
done
if [ -z "$found" ]; then
echo "No running API container matches TARGET_INSTANCE_ID" >&2
exit 1
fi
# Stop exactly one API replica and intentionally leave it stopped for the failover check.
docker stop --time 10 "$found" >/dev/null
View File
+138
View File
@@ -0,0 +1,138 @@
"""Lab 6 dispatcher (lab 5 + OpenTelemetry): transactional-outbox relay + lease reaper + queue gauges.
* relay : outbox rows (committed together with the state change) -> Kafka (acks=all, idempotent producer, delivery report)
* reaper : processing job with an expired lease (worker died) -> queued again (or failed when attempts are exhausted)
"""
from __future__ import annotations
import json
import logging
import os
import time
from pathlib import Path
import psycopg
from confluent_kafka import Producer
from opentelemetry import metrics, trace
from opentelemetry.propagate import extract, inject
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import jobs, telemetry
telemetry.init("messenger-dispatcher", instrument=("psycopg",))
log = logging.getLogger("dispatcher")
TRACER = telemetry.tracer()
# ---- Lab 6: queue gauges are computed HERE (not in the worker) so they stay visible when the worker is stopped. ----
QUEUE_SAMPLE_SECONDS = 5.0
_queue = {"depth": 0.0, "oldest": 0.0, "at": None}
def _queue_gauge(key: str):
def callback(_options):
at = _queue["at"]
if at is not None and time.monotonic() - at < 30: # stale (DB down) => no observation instead of a fake value
yield metrics.Observation(_queue[key], {"queue.name": jobs.JOBS_TOPIC})
return callback
telemetry.meter().create_observable_gauge("messenger.queue.depth", callbacks=[_queue_gauge("depth")], unit="{job}",
description="Jobs waiting for a worker: status=queued and due (backoff elapsed)")
telemetry.meter().create_observable_gauge("messenger.queue.oldest_job_age", callbacks=[_queue_gauge("oldest")], unit="s",
description="Age of the oldest waiting job (now - time it became due); 0 if the queue is empty")
telemetry.register_process_metrics()
def sample_queue(conn) -> None:
depth, oldest = conn.execute(
"SELECT count(*), COALESCE(EXTRACT(EPOCH FROM (now() - min(next_attempt_at))), 0) "
"FROM attachment_jobs WHERE status='queued' AND next_attempt_at <= now()").fetchone()
_queue.update(depth=float(depth), oldest=max(0.0, float(oldest)), at=time.monotonic())
POLL_SECONDS = float(os.getenv("DISPATCH_POLL_SECONDS", "1"))
BATCH = int(os.getenv("OUTBOX_BATCH", "100"))
FAULT_FLAG = Path("/tmp/dispatcher_fault_done")
FAULT_EXIT_BEFORE_PUBLISH = os.getenv("FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH", "0") == "1" # test hook: crash between COMMIT and publish
def relay(conn, producer: Producer) -> int:
with conn.transaction():
rows = conn.execute("SELECT id, topic, msg_key, payload::text FROM outbox WHERE published_at IS NULL AND available_at <= now() "
"ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED", (BATCH,)).fetchall()
if not rows:
return 0
if FAULT_EXIT_BEFORE_PUBLISH and not FAULT_FLAG.exists():
FAULT_FLAG.touch()
log.error("FAULT: exiting after reading the outbox, before publishing (COMMIT happened, publish did not)")
os._exit(137)
delivered, errors = set(), {}
for oid, topic, key, payload in rows:
msg = json.loads(payload)
# PRODUCER span: child of the span that wrote the outbox row (API upload / worker retry); the payload then
# carries THIS span's traceparent, so the worker's CONSUMER span becomes its child.
span = TRACER.start_span(f"{topic} publish", context=extract(msg), kind=SpanKind.PRODUCER,
attributes={"messaging.system": "kafka", "messaging.destination.name": topic,
"messaging.operation.type": "publish", "job.id": msg.get("job_id", ""),
"job.attempt": msg.get("attempt", 0)})
with trace.use_span(span, end_on_exit=False):
inject(msg)
def cb(err, _m, oid=oid, span=span):
if err:
errors[oid] = str(err)
span.set_status(Status(StatusCode.ERROR, "delivery not confirmed"))
else:
delivered.add(oid) # publisher confirm arrives here
span.end()
producer.produce(topic, key=key.encode(), value=json.dumps(msg).encode(), on_delivery=cb)
producer.flush(15)
if delivered:
conn.execute("UPDATE outbox SET published_at=now() WHERE id = ANY(%s)", (list(delivered),))
if errors:
telemetry.log_event(log, logging.WARNING, "outbox_publish_unconfirmed", f"{len(errors)} outbox rows not confirmed by the broker, will retry", count=len(errors))
return len(delivered)
def reap(conn) -> int:
n = 0
with conn.transaction():
for job_id, att_id, attempt, max_attempts, pv in conn.execute(
"SELECT job_id, attachment_id, attempt, max_attempts, pipeline_version FROM attachment_jobs "
"WHERE status='processing' AND lease_until < now() FOR UPDATE SKIP LOCKED").fetchall():
if attempt >= max_attempts:
jobs.fail_job(conn, job_id, att_id, "retry_exhausted", attempt)
else:
conn.execute("UPDATE attachment_jobs SET status='queued', lease_until=NULL, next_attempt_at=now(), updated_at=now() WHERE job_id=%s", (job_id,))
conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s", (att_id,))
jobs.add_event(conn, job_id, "lease_expired", f"attempt={attempt}")
jobs.enqueue(conn, job_id, att_id, pv, attempt + 1)
n += 1
return n
def main() -> None:
producer = Producer({"bootstrap.servers": jobs.KAFKA_BOOTSTRAP, "acks": "all", "enable.idempotence": True,
"message.timeout.ms": 15000, "linger.ms": 5})
telemetry.log_event(log, logging.INFO, "dispatcher_started", f"dispatcher started (poll={POLL_SECONDS:.1f}s)")
last_sample = 0.0
while True:
try:
with psycopg.connect(connect_timeout=5, autocommit=True, options="-c statement_timeout=20000") as conn:
while True:
done = reap(conn)
sent = relay(conn, producer)
if done or sent:
telemetry.log_event(log, logging.INFO, "dispatcher_cycle", f"reaped={done} published={sent}", count=sent)
if time.monotonic() - last_sample >= QUEUE_SAMPLE_SECONDS:
sample_queue(conn)
last_sample = time.monotonic()
if not sent:
time.sleep(POLL_SECONDS)
except psycopg.Error as exc:
log.warning("database unavailable: %s", type(exc).__name__); time.sleep(2)
except Exception as exc:
log.warning("dispatcher iteration failed: %s", type(exc).__name__); time.sleep(2)
if __name__ == "__main__":
main()
+97
View File
@@ -0,0 +1,97 @@
"""Image pipeline v1. Runs in a CHILD process with hard CPU/address-space limits (called by worker.py).
python -m src.imgproc <input-file> <output-dir>
Writes thumbnail.jpg, crop.jpg, optimized.webp and prints JSON metadata on stdout.
Exit codes: 0 ok, 2 invalid image, 3 too many pixels, 4 out of memory, other = unexpected (treated as transient).
"""
from __future__ import annotations
import hashlib
import json
import os
import resource
import sys
from pathlib import Path
from PIL import Image, ImageOps
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
THUMB_BOX, CROP_SIZE, OPT_BOX = 256, 128, 1280
JPEG_QUALITY, WEBP_QUALITY = 85, 80 # documented in REPORT.md
EXIT_INVALID, EXIT_TOO_LARGE, EXIT_OOM = 2, 3, 4
def fit_box(w: int, h: int, box: int) -> tuple[int, int]:
"""Fit (w,h) into box x box, keep aspect ratio, never upscale, floor, min 1 px. Integer math: 320x200 -> 256x160."""
if w <= box and h <= box:
return w, h
if w >= h:
return box, max(1, h * box // w)
return max(1, w * box // h), box
def flatten_on_white(img: Image.Image) -> Image.Image:
"""RGB image; any alpha is composited on white (JPEG has no alpha)."""
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
bg = Image.new("RGB", rgba.size, (255, 255, 255))
bg.paste(rgba, mask=rgba.getchannel("A"))
return bg
return img.convert("RGB")
def save(img: Image.Image, path: Path, fmt: str, **opts) -> dict:
img.save(path, fmt, **opts) # no exif=/icc_profile= passed => metadata is stripped
data = path.read_bytes()
return {"size_bytes": len(data), "width": img.width, "height": img.height, "sha256": hashlib.sha256(data).hexdigest()}
def process(src: Path, out: Path) -> dict:
with Image.open(src) as img:
if img.format not in ("PNG", "JPEG"):
raise ValueError("unsupported format")
if img.width < 1 or img.height < 1:
raise ValueError("empty image")
if img.width * img.height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists
raise OverflowError("too many pixels")
img.load()
base = ImageOps.exif_transpose(img) # apply EXIF orientation once; result has no orientation tag
base.load()
result = {}
# thumbnail: JPEG, fit 256x256, no upscale, alpha -> white
flat = flatten_on_white(base)
t = flat.resize(fit_box(*flat.size, THUMB_BOX), Image.LANCZOS) if fit_box(*flat.size, THUMB_BOX) != flat.size else flat
result["thumbnail"] = {"content_type": "image/jpeg", **save(t, out / "thumbnail.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)}
# crop: JPEG, centered square 128x128 (small sources may be upscaled)
c = ImageOps.fit(flat, (CROP_SIZE, CROP_SIZE), Image.LANCZOS, centering=(0.5, 0.5))
result["crop"] = {"content_type": "image/jpeg", **save(c, out / "crop.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)}
# optimized: WebP, fit 1280x1280, no upscale, keeps alpha, lossy q=80, no EXIF/ICC
o = base if base.mode in ("RGB", "RGBA") else (base.convert("RGBA") if "A" in base.getbands() or base.mode == "P" else base.convert("RGB"))
size = fit_box(*o.size, OPT_BOX)
if size != o.size:
o = o.resize(size, Image.LANCZOS)
result["optimized"] = {"content_type": "image/webp", **save(o, out / "optimized.webp", "WEBP", quality=WEBP_QUALITY, method=4)}
return result
def main() -> int:
mem_mb, cpu_s = int(os.getenv("IMG_MEMORY_MB", "1024")), int(os.getenv("IMG_CPU_SECONDS", "60"))
resource.setrlimit(resource.RLIMIT_AS, (mem_mb * 1024 * 1024, mem_mb * 1024 * 1024))
resource.setrlimit(resource.RLIMIT_CPU, (cpu_s, cpu_s + 5))
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
try:
print(json.dumps(process(Path(sys.argv[1]), Path(sys.argv[2]))))
return 0
except OverflowError:
return EXIT_TOO_LARGE
except Image.DecompressionBombError:
return EXIT_TOO_LARGE
except MemoryError:
return EXIT_OOM
except (ValueError, OSError, SyntaxError, Image.UnidentifiedImageError):
return EXIT_INVALID
if __name__ == "__main__":
sys.exit(main())
+88
View File
@@ -0,0 +1,88 @@
"""Shared constants and helpers for the API, the worker and the dispatcher (lab 5)."""
from __future__ import annotations
import json
import os
import random
import uuid
from datetime import datetime, timezone
import boto3
from botocore.config import Config as BotoConfig
from opentelemetry import trace
from opentelemetry.propagate import inject
KAFKA_BOOTSTRAP = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "kafka:9092")
JOBS_TOPIC = os.getenv("JOBS_TOPIC", "attachment-jobs")
PIPELINE_VERSION = 1
JOB_TYPE = "attachment.process.v1"
JOB_MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
JOB_TIMEOUT_SECONDS = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
LEASE_GRACE_SECONDS = int(os.getenv("LEASE_GRACE_SECONDS", "15"))
LEASE_SECONDS = JOB_TIMEOUT_SECONDS + LEASE_GRACE_SECONDS # lease > hard job timeout: a live worker never loses it
BACKOFF_BASE_SECONDS = float(os.getenv("JOB_BACKOFF_BASE_SECONDS", "2"))
BACKOFF_CAP_SECONDS = float(os.getenv("JOB_BACKOFF_CAP_SECONDS", "60"))
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
STAGING_PREFIX = "staging/"
FINAL_PREFIX = "attachments/"
VARIANT_ORDER = ("thumbnail", "crop", "optimized")
def final_key(attachment_id, pipeline_version: int, name: str) -> str:
"""Deterministic key: the effect key (attachment_id, pipeline_version, variant) maps 1:1 to an S3 object."""
return f"{FINAL_PREFIX}{attachment_id}/v{pipeline_version}/{name}"
def make_s3():
return boto3.client(
"s3", endpoint_url=S3_ENDPOINT, region_name=S3_REGION,
aws_access_key_id=os.getenv("S3_ACCESS_KEY_ID", ""), aws_secret_access_key=os.getenv("S3_SECRET_ACCESS_KEY", ""),
config=BotoConfig(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=20,
retries={"max_attempts": 2, "mode": "standard"},
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
def backoff_seconds(attempt: int) -> float:
"""Exponential backoff with 'equal jitter': delay in [d/2, d], d = min(cap, base * 2^(attempt-1))."""
d = min(BACKOFF_CAP_SECONDS, BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1)))
return random.uniform(d / 2, d)
def iso_now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def add_event(conn, job_id, event: str, detail: str | None = None) -> None:
conn.execute("INSERT INTO job_events(job_id,event,detail) VALUES (%s,%s,%s)", (job_id, event, detail))
def enqueue(conn, job_id, attachment_id, pipeline_version: int, attempt: int, delay_seconds: float = 0.0) -> None:
"""Record the intent to publish a job message in the SAME transaction as the state change (transactional outbox).
The message carries only IDs (jobs.schema.json): no bytes, no credentials, no URLs.
Lab 6: the W3C trace context of the CURRENT span is stored in the payload (traceparent/tracestate), so the causal
link survives the outbox -> dispatcher -> Kafka -> worker hops (and the retry loop: worker -> enqueue -> ...).
"""
payload = {"schema_version": 1, "job_id": str(job_id), "type": JOB_TYPE, "attachment_id": str(attachment_id),
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": iso_now()}
with trace.get_tracer("messenger").start_as_current_span(
"outbox.enqueue", attributes={"messaging.system": "kafka", "messaging.destination.name": JOBS_TOPIC, "job.attempt": attempt}):
inject(payload) # adds "traceparent" (+ "tracestate" when present): carrier = the JSON payload itself
conn.execute(
"INSERT INTO outbox(job_id,topic,msg_key,payload,available_at) VALUES (%s,%s,%s,%s::jsonb, now() + make_interval(secs => %s))",
(job_id, JOBS_TOPIC, str(attachment_id), json.dumps(payload), delay_seconds))
def new_job_id() -> uuid.UUID:
return uuid.uuid4()
def fail_job(conn, job_id, att_id, code: str, attempt: int) -> None:
conn.execute("UPDATE attachment_jobs SET status='failed', error_code=%s, lease_until=NULL, updated_at=now() WHERE job_id=%s", (code, job_id))
conn.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", (code, att_id))
add_event(conn, job_id, "failed", code)
+811
View File
@@ -0,0 +1,811 @@
"""Lab 6 REST API: lab 5 business API (FastAPI + PostgreSQL + Redis + S3 + Kafka outbox) + OpenTelemetry (traces, metrics, logs)."""
from __future__ import annotations
import asyncio
import anyio
import base64
import hashlib
import json
import logging
import os
import re
import secrets
import socket
import tempfile
import time
import unicodedata
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import quote
import psycopg
from psycopg_pool import ConnectionPool, PoolTimeout
import anyio
import boto3
import redis
from botocore.config import Config as BotoConfig
from botocore.exceptions import BotoCoreError, ClientError
from PIL import Image
from redis.exceptions import RedisError
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response, StreamingResponse
from starlette.concurrency import iterate_in_threadpool, run_in_threadpool
from starlette.requests import ClientDisconnect
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from opentelemetry import metrics, trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from . import jobs, telemetry
# Lab 6: JSON logs on stdout + OTLP (traces, metrics, logs) to the Collector. psycopg/botocore spans are automatic.
telemetry.init("messenger-api", instrument=("psycopg", "botocore"))
log = logging.getLogger("messenger")
DATABASE_URL = os.getenv("DATABASE_URL", "")
INSTANCE_ID = os.getenv("INSTANCE_ID") or socket.gethostname()
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if SESSION_TTL_SECONDS < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be positive")
# Redis uses its connection pool; session keys contain only a hash of the opaque token.
session_store = redis.Redis.from_url(REDIS_URL, decode_responses=True, socket_connect_timeout=3, socket_timeout=3, health_check_interval=30)
DB_POOL_MIN_SIZE = int(os.getenv("DB_POOL_MIN_SIZE", "1"))
DB_POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "10"))
DB_POOL_TIMEOUT_SECONDS = float(os.getenv("DB_POOL_TIMEOUT_SECONDS", "5"))
if DB_POOL_MIN_SIZE < 1 or DB_POOL_MAX_SIZE < DB_POOL_MIN_SIZE:
raise RuntimeError("Invalid PostgreSQL pool size configuration")
# Every pooled connection gets bounded connect/query/idle-transaction timeouts.
db_pool = ConnectionPool(
conninfo=DATABASE_URL,
min_size=DB_POOL_MIN_SIZE,
max_size=DB_POOL_MAX_SIZE,
timeout=DB_POOL_TIMEOUT_SECONDS,
kwargs={
"connect_timeout": 5,
"options": "-c statement_timeout=5000 -c idle_in_transaction_session_timeout=10000",
},
open=False,
name="messenger-postgres",
)
# ---- Lab 4: S3 / attachment limits (names follow .env.example of the lab) ----
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID", "")
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "")
S3_KEY_PREFIX = "attachments/"
STAGING_PREFIX = jobs.STAGING_PREFIX # lab5: durable staging (private S3 prefix) for bytes accepted but not yet processed
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
UPLOAD_IDLE_TIMEOUT_SECONDS = float(os.getenv("UPLOAD_IDLE_TIMEOUT_SECONDS", "10"))
UPLOAD_TOTAL_TIMEOUT_SECONDS = float(os.getenv("UPLOAD_TOTAL_TIMEOUT_SECONDS", "60"))
IMAGE_DECODE_CONCURRENCY = int(os.getenv("IMAGE_DECODE_CONCURRENCY", "1"))
SPOOL_MEMORY_BYTES = 1024 * 1024 # larger bodies roll over to an anonymous temp file, never to RAM
CHUNK_BYTES = 64 * 1024
# Pillow's own bomb guard is a second line of defence behind the explicit check below.
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
# Credentials are the restricted application user created by s3_init, never the MinIO root user.
_s3_common = dict(endpoint_url=S3_ENDPOINT, region_name=S3_REGION, aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY)
s3 = boto3.client("s3", **_s3_common, config=BotoConfig(
signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=20,
retries={"max_attempts": 2, "mode": "standard"}, max_pool_connections=32,
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
# Readiness probe client: one attempt and tight timeouts so HAProxy's 2 s check never hangs on it.
s3_probe = boto3.client("s3", **_s3_common, config=BotoConfig(
signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=1, read_timeout=1,
retries={"max_attempts": 1}, request_checksum_calculation="when_required", response_checksum_validation="when_required"))
decode_limiter = anyio.CapacityLimiter(IMAGE_DECODE_CONCURRENCY)
IMAGE_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
PASSWORDS = PasswordHasher()
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict[str, str] | None = None):
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
def fail(status: int, code: str, message: str, headers: dict[str, str] | None = None):
raise ApiError(status, code, message, headers)
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class RegisterBody(StrictModel):
username: str
display_name: str
password: str
class ChatBody(StrictModel):
title: str
member_ids: list[str] = Field(min_length=1, max_length=100)
class MessageBody(StrictModel):
text: str
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
# ---- Lab 6: HTTP metrics (names/units: REPORT.md). Labels are LOW cardinality: method, route TEMPLATE, status class. ----
HTTP_DURATION = telemetry.meter().create_histogram(
"http.server.request.duration", unit="s", description="Server-side duration of business HTTP requests (health excluded)",
explicit_bucket_boundaries_advisory=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60])
KNOWN_METHODS = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
def observe_http(request: Request, status: int, started: float) -> None:
if request.url.path.startswith("/health/"):
return # error ratio denominator = business requests, health probes are excluded
route = getattr(request.scope.get("route"), "path", None) or "unmatched" # "/api/v1/chats/{chat_id}/messages", never a real UUID
HTTP_DURATION.record(time.perf_counter() - started, {
"http.request.method": request.method if request.method in KNOWN_METHODS else "OTHER",
"http.route": route, "http.response.status_class": f"{status // 100}xx"})
def _pool_gauge(field: str):
def callback(_options):
stats = db_pool.get_stats()
value = stats["pool_size"] - stats["pool_available"] if field == "used" else stats[field]
yield metrics.Observation(value, {"pool.name": "messenger-postgres"})
return callback
for _name, _field, _desc in (("messenger.db.pool.used", "used", "Connections checked out of the pool"),
("messenger.db.pool.waiting", "requests_waiting", "Requests waiting for a free pooled connection")):
telemetry.meter().create_observable_gauge(_name, callbacks=[_pool_gauge(_field)], unit="{connection}", description=_desc)
telemetry.register_process_metrics()
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request.state.request_id = uuid.uuid4().hex
started = time.perf_counter()
# X-Request-Id <-> trace: the id is stored on the server span; logs carry both request_id and trace_id.
trace.get_current_span().set_attribute("messenger.request_id", request.state.request_id)
try:
response = await call_next(request)
except Exception as exc:
telemetry.log_event(log, logging.ERROR, "unhandled_exception", "Unhandled API exception", request_id=request.state.request_id, reason=type(exc).__name__)
response = JSONResponse(status_code=500, content={"error": {"code": "internal_error", "message": "Internal server error", "request_id": request.state.request_id}})
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
observe_http(request, response.status_code, started)
return response
# Added LAST => outermost middleware: the server span is active inside request_id_middleware. No metrics from the instrumentor:
# our own histogram above is the only HTTP metric (no duplicate instruments). Health probes produce no spans.
FastAPIInstrumentor.instrument_app(app, excluded_urls="/health/(live|ready)", meter_provider=metrics.NoOpMeterProvider())
def error_response(status: int, code: str, message: str, request_id: str, headers: dict[str, str] | None = None):
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id}}, headers=headers or {})
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers)
@app.exception_handler(PoolTimeout)
async def database_pool_timeout_handler(request: Request, exc: PoolTimeout):
telemetry.log_event(log, logging.WARNING, "db_pool_timeout", "Database connection pool timed out", request_id=request.state.request_id)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(psycopg.Error)
async def database_error_handler(request: Request, exc: psycopg.Error):
telemetry.log_event(log, logging.WARNING, "db_error", "Database operation failed", request_id=request.state.request_id, reason=type(exc).__name__)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(RedisError)
async def redis_error_handler(request: Request, exc: RedisError):
telemetry.log_event(log, logging.WARNING, "session_store_error", "Session store operation failed", request_id=request.state.request_id)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(BotoCoreError)
async def s3_core_error_handler(request: Request, exc: BotoCoreError):
telemetry.log_event(log, logging.WARNING, "s3_error", "Object storage failure", request_id=request.state.request_id, reason=type(exc).__name__)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(ClientError)
async def s3_client_error_handler(request: Request, exc: ClientError):
telemetry.log_event(log, logging.WARNING, "s3_error", "Object storage error", request_id=request.state.request_id, reason=str(exc.response.get("Error", {}).get("Code")))
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(400, "invalid_request", "Invalid request", request.state.request_id)
@app.exception_handler(StarletteHTTPException)
async def http_error_handler(request: Request, exc: StarletteHTTPException):
status = exc.status_code
code = "not_found" if status == 404 else "invalid_request"
message = "Object not found" if status == 404 else "Invalid request"
headers = dict(exc.headers or {})
return error_response(status, code, message, request.state.request_id, headers)
def db():
"""Borrow a bounded pooled connection; context exit commits/rolls back and returns it."""
return db_pool.connection(timeout=DB_POOL_TIMEOUT_SECONDS)
@app.on_event("startup")
def startup():
# Migrations run once in the dedicated `migrate` service before API replicas.
db_pool.open(wait=False)
last_error = None
for _ in range(30):
try:
with db() as conn:
conn.execute("SELECT 1")
conn.execute("SELECT 1 FROM idempotency_records LIMIT 0")
conn.execute("SELECT 1 FROM outbox LIMIT 0")
session_store.ping()
s3.head_object(Bucket=S3_BUCKET, Key=S3_KEY_PREFIX + ".ready")
telemetry.log_event(log, logging.INFO, "api_ready", f"PostgreSQL, Redis and S3 bucket are ready; instance={INSTANCE_ID}")
return
except Exception as exc:
last_error = exc
time.sleep(1)
raise RuntimeError("PostgreSQL schema, Redis or S3 bucket unavailable during startup") from last_error
@app.on_event("shutdown")
def shutdown():
session_store.close()
db_pool.close()
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def user_dict(row: dict[str, Any]) -> dict[str, Any]:
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": iso(row["created_at"])}
def chat_dict(row: dict[str, Any], member_ids: list[str]) -> dict[str, Any]:
return {"id": str(row["id"]), "title": row["title"], "member_ids": member_ids, "created_at": iso(row["created_at"])}
def message_dict(row: dict[str, Any], attachment_ids: list[str] | None = None) -> dict[str, Any]:
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": iso(row["created_at"]), "attachment_ids": attachment_ids or []}
def validate_unicode(value: str, label: str) -> str:
"""Reject unpaired UTF-16 surrogates before sending text to PostgreSQL/KDF."""
try:
value.encode("utf-8")
except UnicodeEncodeError:
fail(400, "invalid_request", "Invalid Unicode in " + label)
return value
def parse_uuid(value: str, label: str = "UUID") -> uuid.UUID:
try:
# Keep the canonical UUID representation used by the Lab 1 API.
if not isinstance(value, str) or len(value) != 36:
raise ValueError("non-canonical UUID")
parsed = uuid.UUID(value)
if str(parsed) != value:
raise ValueError("non-canonical UUID")
return parsed
except (ValueError, TypeError, AttributeError):
fail(400, "invalid_request", "Invalid " + label)
def validate_body_type(request: Request):
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type != "application/json":
fail(415, "unsupported_media_type", "Content-Type must be application/json")
async def parse_body(request: Request, model):
validate_body_type(request)
try:
raw = await request.body()
data = json.loads(raw.decode("utf-8"))
return model.model_validate(data)
except (UnicodeDecodeError, json.JSONDecodeError, ValidationError, TypeError):
fail(400, "invalid_request", "Invalid JSON request body")
def challenge(scheme: str) -> dict[str, str]:
if scheme == "Basic":
return {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
return {"WWW-Authenticate": 'Bearer realm="messenger"'}
def current_user(request: Request) -> dict[str, Any]:
auth = request.headers.get("authorization", "")
if not auth.startswith("Bearer ") or not auth[7:].strip():
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
token_hash = hashlib.sha256(auth[7:].strip().encode("utf-8")).hexdigest()
session_json = session_store.get("session:" + token_hash)
if session_json is None:
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
try:
session = json.loads(session_json)
user_id = uuid.UUID(session["user_id"])
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
# Corrupt session data is invalidated instead of trusted.
session_store.delete("session:" + token_hash)
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
if expires_at <= now_utc():
session_store.delete("session:" + token_hash)
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
with db() as conn:
row = conn.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", (user_id,)).fetchone()
if row is None:
session_store.delete("session:" + token_hash)
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3], "expires_at": expires_at, "user": {"id": str(row[0]), "username": row[1], "display_name": row[2], "created_at": iso(row[3])}, "token_hash": token_hash}
def ensure_member(actor_id: uuid.UUID, chat_id: uuid.UUID):
with db() as conn:
row = conn.execute("SELECT 1 FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s", (chat_id, actor_id)).fetchone()
if row is None:
fail(404, "not_found", "Object not found")
def parse_page_args(limit: int | None, cursor: str | None, resource: str):
actual_limit = 50 if limit is None else limit
if isinstance(actual_limit, bool) or actual_limit < 1 or actual_limit > 100:
fail(400, "invalid_request", "limit must be an integer from 1 to 100")
after = None
if cursor is not None:
if not cursor:
fail(400, "invalid_request", "Invalid cursor")
try:
decoded = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("utf-8")
obj = json.loads(decoded)
if obj.get("resource") != resource:
fail(400, "invalid_request", "Cursor belongs to another resource")
after = (datetime.fromisoformat(obj["created_at"].replace("Z", "+00:00")), uuid.UUID(obj["id"]))
except ApiError:
raise
except Exception:
fail(400, "invalid_request", "Invalid cursor")
return actual_limit, after
def make_cursor(resource: str, created_at: datetime, item_id: uuid.UUID) -> str:
raw = json.dumps({"resource": resource, "created_at": iso(created_at), "id": str(item_id)}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def json_rows(cursor, query: str, params=()):
with db() as conn:
cur = conn.execute(query, params)
names = [d.name for d in cur.description]
return [dict(zip(names, row)) for row in cur.fetchall()]
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready():
try:
with db() as conn:
conn.execute("SELECT 1")
session_store.ping()
s3_probe.head_object(Bucket=S3_BUCKET, Key=S3_KEY_PREFIX + ".ready") # S3 is critical: uploads/downloads are part of the mandatory path
return {"status": "ok"}
except (psycopg.Error, PoolTimeout, RedisError, BotoCoreError, ClientError):
fail(503, "unavailable", "Required storage is unavailable")
@app.post("/api/v1/users", status_code=201)
async def register(request: Request):
body = await parse_body(request, RegisterBody)
if not USERNAME_RE.fullmatch(body.username):
fail(400, "invalid_request", "Invalid username")
validate_unicode(body.display_name, "display_name")
validate_unicode(body.password, "password")
if not body.display_name.strip() or len(body.display_name) > 100:
fail(400, "invalid_request", "Invalid display_name")
if not 12 <= len(body.password) <= 128:
fail(400, "invalid_request", "Password must contain 12 to 128 Unicode code points")
user_id = uuid.uuid4()
password_hash = PASSWORDS.hash(body.password)
try:
with db() as conn:
row = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at", (user_id, body.username, body.display_name, password_hash)).fetchone()
except psycopg.errors.UniqueViolation:
fail(409, "conflict", "Username already exists")
return user_dict(dict(zip(("id", "username", "display_name", "created_at"), row)))
@app.get("/api/v1/users/me")
def me(request: Request):
return current_user(request)["user"]
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
if await request.body():
fail(400, "invalid_request", "Session creation does not accept a request body")
auth = request.headers.get("authorization", "")
if not auth[:6].lower() == "basic ":
fail(401, "unauthorized", "Valid Basic credentials required", challenge("Basic"))
try:
decoded = base64.b64decode(auth[6:], validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
try:
validate_unicode(password, "password")
except ApiError:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
if not password or len(password) < 12 or len(password) > 128:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
with db() as conn:
row = conn.execute("SELECT id,username,display_name,password_hash,created_at FROM users WHERE username=%s", (username,)).fetchone()
if row is None:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
try:
PASSWORDS.verify(row[3], password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(token.encode()).hexdigest()
expires_at = now_utc() + timedelta(seconds=SESSION_TTL_SECONDS)
session_json = json.dumps({"user_id": str(row[0]), "expires_at": iso(expires_at)}, separators=(",", ":"))
# Redis TTL enforces expiry; AOF + named volume make active sessions survive stack restarts.
session_store.setex("session:" + token_hash, SESSION_TTL_SECONDS, session_json)
user = user_dict({"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[4]})
return {"token": token, "token_type": "Bearer", "expires_at": iso(expires_at), "user": user}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(request: Request):
actor = current_user(request)
session_store.delete("session:" + actor["token_hash"])
return Response(status_code=204)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
actor = current_user(request)
body = await parse_body(request, ChatBody)
validate_unicode(body.title, "title")
if not body.title.strip() or len(body.title) > 100:
fail(400, "invalid_request", "Invalid title")
ids = [parse_uuid(value, "member UUID") for value in body.member_ids]
if len(ids) != len(set(ids)) or actor["id"] not in ids:
fail(400, "invalid_request", "Members must be unique and include the caller")
chat_id = uuid.uuid4()
try:
with db() as conn:
existing = conn.execute("SELECT id FROM users WHERE id = ANY(%s)", (ids,)).fetchall()
if len(existing) != len(ids):
fail(400, "invalid_request", "Unknown chat member")
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at", (chat_id, body.title)).fetchone()
# psycopg 3: executemany exists on cursors, not on Connection (fix of a latent lab3 bug)
with conn.cursor() as cur:
cur.executemany("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", [(chat_id, uid, position) for position, uid in enumerate(ids)])
except psycopg.errors.ForeignKeyViolation:
fail(400, "invalid_request", "Unknown chat member")
return chat_dict({"id": row[0], "title": row[1], "created_at": row[2]}, [str(x) for x in ids])
@app.get("/api/v1/chats")
def list_chats(request: Request, limit: int | None = None, cursor: str | None = None):
actor = current_user(request)
chat_list_resource = "chats:" + str(actor["id"])
actual_limit, after = parse_page_args(limit, cursor, chat_list_resource)
params: list[Any] = [actor["id"]]
where = "m.user_id=%s"
if after:
where += " AND (c.created_at,c.id)>(%s,%s)"
params.extend(after)
params.append(actual_limit + 1)
rows = json_rows(None, f"SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE {where} ORDER BY c.created_at,c.id LIMIT %s", tuple(params))
more = len(rows) > actual_limit
rows = rows[:actual_limit]
items = []
for row in rows:
members = json_rows(None, "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position,user_id", (row["id"],))
items.append(chat_dict(row, [str(m["user_id"]) for m in members]))
next_cursor = make_cursor(chat_list_resource, rows[-1]["created_at"], rows[-1]["id"]) if more and rows else None
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, request: Request):
actor = current_user(request)
parsed = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed)
rows = json_rows(None, "SELECT id,title,created_at FROM chats WHERE id=%s", (parsed,))
members = json_rows(None, "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position,user_id", (parsed,))
return chat_dict(rows[0], [str(m["user_id"]) for m in members])
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(chat_id: str, request: Request):
actor = current_user(request)
parsed_chat = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed_chat)
body = await parse_body(request, MessageBody)
validate_unicode(body.text, "text")
attachment_ids = [parse_uuid(value, "attachment UUID") for value in body.attachment_ids]
if len(attachment_ids) != len(set(attachment_ids)):
fail(400, "invalid_request", "attachment_ids must be unique")
if len(body.text) > 4000 or (not body.text.strip() and not attachment_ids):
fail(400, "invalid_request", "Message needs 1 to 4000 non-whitespace code points of text or at least one attachment")
key = request.headers.get("Idempotency-Key", "")
if not IDEMPOTENCY_KEY_RE.fullmatch(key):
fail(400, "invalid_request", "Idempotency-Key must contain 1 to 128 ASCII letters, digits, '.', '_', ':', or '-'")
# Hash semantic JSON rather than raw bytes, so insignificant JSON formatting does not matter.
# attachment_ids is part of the hash only when non-empty: absent == [] and lab3 records stay valid.
canonical = {"text": body.text}
if attachment_ids:
canonical["attachment_ids"] = [str(x) for x in attachment_ids]
canonical_body = json.dumps(canonical, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
request_hash = hashlib.sha256(canonical_body.encode("utf-8")).hexdigest()
scope = f"{actor['id']}|POST|/api/v1/chats/{parsed_chat}/messages|{key}"
# The advisory transaction lock serializes the same key across every API replica.
# Message and idempotency result are committed atomically in the same PostgreSQL transaction.
with db() as conn:
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
existing = conn.execute(
"SELECT request_hash, response_body FROM idempotency_records "
"WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s AND created_at >= now() - interval '24 hours'",
(actor["id"], parsed_chat, key),
).fetchone()
if existing is not None:
if existing[0] != request_hash:
fail(409, "conflict", "Idempotency-Key was already used with a different request body")
replay = dict(existing[1])
replay.setdefault("attachment_ids", [])
return JSONResponse(status_code=201, content=replay)
# Keys are guaranteed for 24 hours; expired records may be replaced by a new attempt.
conn.execute(
"DELETE FROM idempotency_records WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s AND created_at < now() - interval '24 hours'",
(actor["id"], parsed_chat, key),
)
if attachment_ids:
# Foreign, unknown and other-chat attachments are indistinguishable: all -> 404.
found = conn.execute("SELECT count(*) FROM attachments WHERE id = ANY(%s) AND chat_id=%s", (attachment_ids, parsed_chat)).fetchone()[0]
if found != len(attachment_ids):
fail(404, "not_found", "Object not found")
# lab5: queued/processing attachments may be attached, failed ones may not
if conn.execute("SELECT 1 FROM attachments WHERE id = ANY(%s) AND status='failed' LIMIT 1", (attachment_ids,)).fetchone():
fail(409, "conflict", "Attachment processing failed")
row = conn.execute(
"INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) "
"RETURNING id,chat_id,sender_id,text,created_at",
(uuid.uuid4(), parsed_chat, actor["id"], body.text),
).fetchone()
result = message_dict(dict(zip(("id", "chat_id", "sender_id", "text", "created_at"), row)), [str(x) for x in attachment_ids])
if attachment_ids:
with conn.cursor() as cur:
cur.executemany("INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)", [(row[0], aid, i) for i, aid in enumerate(attachment_ids)])
conn.execute(
"INSERT INTO idempotency_records(user_id,chat_id,idempotency_key,request_hash,response_body) "
"VALUES (%s,%s,%s,%s,%s::jsonb)",
(actor["id"], parsed_chat, key, request_hash, json.dumps(result, ensure_ascii=False)),
)
return result
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request, limit: int | None = None, cursor: str | None = None):
actor = current_user(request)
parsed_chat = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed_chat)
actual_limit, after = parse_page_args(limit, cursor, "messages:" + str(parsed_chat))
params: list[Any] = [parsed_chat]
where = "chat_id=%s"
if after:
where += " AND (created_at,id)>(%s,%s)"
params.extend(after)
params.append(actual_limit + 1)
rows = json_rows(None, f"SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE {where} ORDER BY created_at,id LIMIT %s", tuple(params))
more = len(rows) > actual_limit
rows = rows[:actual_limit]
links: dict[Any, list[str]] = {}
if rows:
link_rows = json_rows(None, "SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY(%s) ORDER BY message_id, position", ([r["id"] for r in rows],))
for link in link_rows:
links.setdefault(link["message_id"], []).append(str(link["attachment_id"]))
items = [message_dict(row, links.get(row["id"])) for row in rows]
next_cursor = make_cursor("messages:" + str(parsed_chat), rows[-1]["created_at"], rows[-1]["id"]) if more and rows else None
return {"items": items, "next_cursor": next_cursor}
# ======================= Lab 4: attachments =======================
def attachment_dict(row: dict[str, Any], variants: list[dict[str, Any]] | None = None) -> dict[str, Any]:
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), "filename": row["filename"],
"content_type": row["content_type"], "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": row["status"],
"variants": variants or [], "error_code": row["error_code"] if row["status"] == "failed" else None,
"created_at": iso(row["created_at"]), "updated_at": iso(row["updated_at"])}
def validate_filename(values: list[str]) -> str:
"""filename is display-only: it never reaches a path or an S3 key, but dangerous values are still rejected."""
if len(values) != 1:
fail(400, "invalid_request", "Exactly one filename query parameter is required")
name = values[0]
validate_unicode(name, "filename")
if not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."):
fail(400, "invalid_request", "Invalid filename")
if "/" in name or "\\" in name or any(unicodedata.category(ch) == "Cc" for ch in name):
fail(400, "invalid_request", "Invalid filename")
return name
def sniff_image_type(head: bytes) -> str | None:
if head.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if head.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
return None
async def read_body_to_spool(request: Request, declared: str):
"""Stream the request body into a bounded spool while hashing; abort as soon as a limit is broken.
RAM per upload stays ~1 MiB: bodies above SPOOL_MEMORY_BYTES roll over to an anonymous (already unlinked) temp file.
"""
spool = tempfile.SpooledTemporaryFile(max_size=SPOOL_MEMORY_BYTES)
digest, total, head = hashlib.sha256(), 0, b""
try:
iterator = request.stream().__aiter__()
with anyio.fail_after(UPLOAD_TOTAL_TIMEOUT_SECONDS):
while True:
try:
chunk = await asyncio.wait_for(iterator.__anext__(), UPLOAD_IDLE_TIMEOUT_SECONDS)
except StopAsyncIteration:
break
if not chunk:
continue
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
fail(413, "payload_too_large", "Attachment exceeds the size limit")
if len(head) < 8:
head += chunk[: 8 - len(head)]
if len(head) >= 8 and sniff_image_type(head) != declared:
fail(415, "unsupported_media_type", "Content does not match the declared image type")
digest.update(chunk)
spool.write(chunk)
except ApiError:
spool.close()
raise
except (TimeoutError, asyncio.TimeoutError):
spool.close()
fail(400, "invalid_request", "Upload timed out")
except BaseException: # ClientDisconnect, cancellation: nothing was written to S3 yet
spool.close()
raise
if total == 0 or sniff_image_type(head) != declared:
spool.close()
fail(415, "unsupported_media_type", "Content is not a supported image")
return spool, total, digest.hexdigest()
def decode_image_checked(spool, declared: str) -> None:
"""Runs in a worker thread: header -> pixel limit -> full decode. Raises ApiError for every user mistake."""
try:
spool.seek(0)
with Image.open(spool) as img:
if IMAGE_TYPES.get(img.format or "") != declared:
fail(415, "unsupported_media_type", "Content does not match the declared image type")
width, height = img.size
if width < 1 or height < 1:
fail(415, "unsupported_media_type", "Corrupt image")
if width * height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists
fail(413, "payload_too_large", "Image has too many pixels")
img.load() # full decode detects truncated/corrupt data
except ApiError:
raise
except Image.DecompressionBombError:
fail(413, "payload_too_large", "Image has too many pixels")
except MemoryError:
fail(503, "unavailable", "Temporarily unable to process the image")
except Exception: # Pillow raises OSError/SyntaxError/ValueError/struct.error/... for corrupt input
fail(415, "unsupported_media_type", "Corrupt or unsupported image")
finally:
spool.seek(0)
def s3_put(key: str, spool, size: int, content_type: str) -> None:
spool.seek(0)
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=spool, ContentLength=size, ContentType=content_type)
def s3_delete_quietly(key: str) -> None:
try:
s3.delete_object(Bucket=S3_BUCKET, Key=key)
except Exception:
# The periodic sweeper (scripts/s3_sweep.py) removes it after the grace period.
log.warning("Compensation delete failed; orphan left for sweeper key=%s", key)
async def compensate(key: str) -> None:
with anyio.CancelScope(shield=True):
await run_in_threadpool(s3_delete_quietly, key)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(chat_id: str, request: Request):
actor = current_user(request)
parsed_chat = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed_chat)
filename = validate_filename(request.query_params.getlist("filename"))
declared = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if declared not in ("image/png", "image/jpeg"):
fail(415, "unsupported_media_type", "Content-Type must be image/png or image/jpeg")
length = request.headers.get("content-length")
if length is not None:
if not length.isascii() or not length.isdigit():
fail(400, "invalid_request", "Invalid Content-Length")
if int(length) > MAX_UPLOAD_BYTES: # reject before reading a single body byte
fail(413, "payload_too_large", "Attachment exceeds the size limit")
spool, size, sha256 = await read_body_to_spool(request, declared)
key = STAGING_PREFIX + secrets.token_hex(16) # server-chosen random STAGING key, unrelated to filename or attachment id
try:
await anyio.to_thread.run_sync(decode_image_checked, spool, declared, limiter=decode_limiter)
await run_in_threadpool(s3_put, key, spool, size, declared)
except ApiError: # user error found by validation, before any S3 write
spool.close()
raise
except BaseException:
spool.close()
await compensate(key) # a PUT whose reply was lost may still have stored the object
raise
spool.close()
attachment_id, job_id = uuid.uuid4(), uuid.uuid4()
final_original = jobs.final_key(attachment_id, jobs.PIPELINE_VERSION, "original")
try:
# ONE transaction: metadata + job + outbox row. 202 is returned only after this COMMIT (durable handoff).
with db() as conn:
row = conn.execute(
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,s3_key,staging_key,status,pipeline_version) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued',%s) "
"RETURNING id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at",
(attachment_id, parsed_chat, actor["id"], filename, declared, size, sha256, final_original, key, jobs.PIPELINE_VERSION)).fetchone()
conn.execute("INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,status,max_attempts) VALUES (%s,%s,%s,'queued',%s)",
(job_id, attachment_id, jobs.PIPELINE_VERSION, jobs.JOB_MAX_ATTEMPTS))
jobs.add_event(conn, job_id, "accepted")
jobs.enqueue(conn, job_id, attachment_id, jobs.PIPELINE_VERSION, 1)
except BaseException:
await compensate(key) # staging PUT succeeded but the COMMIT did not: remove the unaccounted object
raise
telemetry.log_event(log, logging.INFO, "attachment_accepted", "Attachment accepted, job queued", job_id=str(job_id), attachment_id=str(attachment_id))
cols = ("id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "status", "error_code", "created_at", "updated_at")
return JSONResponse(status_code=202, content=attachment_dict(dict(zip(cols, row))))
ATT_COLS = ("id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "s3_key", "status", "error_code", "created_at", "updated_at")
def load_attachment(attachment_id: str, request: Request) -> dict[str, Any]:
actor = current_user(request)
parsed = parse_uuid(attachment_id, "attachment UUID")
rows = json_rows(None, "SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256,a.s3_key,a.status,a.error_code,a.created_at,a.updated_at "
"FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=%s AND m.user_id=%s", (parsed, actor["id"]))
if not rows:
fail(404, "not_found", "Object not found")
return rows[0]
def variant_rows(attachment_id, pipeline_version: int = jobs.PIPELINE_VERSION) -> list[dict[str, Any]]:
rows = json_rows(None, "SELECT name,s3_key,content_type,size_bytes,width,height,sha256 FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s", (attachment_id, pipeline_version))
return sorted(rows, key=lambda r: jobs.VARIANT_ORDER.index(r["name"]))
@app.get("/api/v1/attachments/{attachment_id}")
def get_attachment(attachment_id: str, request: Request):
row = load_attachment(attachment_id, request)
variants = []
if row["status"] == "ready": # variants are published only together with ready (one COMMIT in the worker)
variants = [{k: v[k] for k in ("name", "content_type", "size_bytes", "width", "height", "sha256")} for v in variant_rows(row["id"])]
return attachment_dict(row, variants)
@app.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(attachment_id: str, request: Request, variant: str = "original"):
row = load_attachment(attachment_id, request)
if variant != "original" and variant not in jobs.VARIANT_ORDER:
fail(400, "invalid_request", "Unknown variant")
if row["status"] != "ready":
fail(409, "conflict", "Attachment is not ready") # queued, processing and failed: no content
key, content_type, size = row["s3_key"], row["content_type"], row["size_bytes"]
if variant != "original":
found = [v for v in variant_rows(row["id"]) if v["name"] == variant]
if not found:
fail(404, "not_found", "Object not found")
key, content_type, size = found[0]["s3_key"], found[0]["content_type"], found[0]["size_bytes"]
try:
obj = s3.get_object(Bucket=S3_BUCKET, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
log.error("INTEGRITY: metadata without object attachment=%s variant=%s", row["id"], variant)
fail(500, "internal_error", "Internal server error")
raise
body = obj["Body"]
async def stream():
try:
async for chunk in iterate_in_threadpool(body.iter_chunks(CHUNK_BYTES)):
yield chunk
finally:
body.close()
headers = {"Content-Length": str(size), "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store",
"Content-Disposition": "inline; filename*=UTF-8''" + quote(row["filename"], safe="")}
return StreamingResponse(stream(), media_type=content_type, headers=headers)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host=os.getenv("APP_HOST", "0.0.0.0"), port=int(os.getenv("APP_PORT", "8080")), timeout_graceful_shutdown=5)
+145
View File
@@ -0,0 +1,145 @@
"""Lab 6: one OpenTelemetry bootstrap shared by the API, the worker and the dispatcher.
* traces -> BatchSpanProcessor -> OTLP/HTTP -> Collector -> Tempo
* metrics -> PeriodicExportingMetricReader -> OTLP/HTTP -> Collector -> Prometheus (remote write)
* logs -> stdout (JSON) + BatchLogRecordProcessor -> OTLP/HTTP -> Collector -> Loki
Telemetry is best effort: every queue is bounded and exporters have short timeouts, so a dead Collector or
backend can only cost telemetry (dropped batches), never an API response or a job.
"""
from __future__ import annotations
import json
import logging
import os
import socket
import sys
from datetime import datetime, timezone
from opentelemetry import metrics, trace
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
SERVICE_NAME = "unknown"
EXPORT_TIMEOUT_S = 3 # a dead Collector must not block the exporter thread for long
METRIC_INTERVAL_MS = 10_000
# Technical (synthetic) identifiers allowed in logs/traces; never in metric labels, never bodies/tokens/URLs.
LOG_FIELDS = ("job_id", "attachment_id", "attempt", "request_id", "outcome", "reason", "topic", "count")
class _EventFilter(logging.Filter):
"""Every record gets an `event` (contract: logs have `event`); explicit extra={"event": ...} wins."""
def filter(self, record: logging.LogRecord) -> bool:
if not hasattr(record, "event"):
record.event = record.name
return True
class _NoOtelSelfLogs(logging.Filter):
"""Exporter errors are logged by the opentelemetry package itself: never feed them back into the OTLP handler."""
def filter(self, record: logging.LogRecord) -> bool:
return not record.name.startswith(("opentelemetry", "urllib3"))
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
ctx = trace.get_current_span().get_span_context()
doc = {
"timestamp": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
"severity": record.levelname,
"service.name": SERVICE_NAME,
"event": getattr(record, "event", record.name),
"message": record.getMessage(),
}
if ctx.is_valid:
doc["trace_id"] = format(ctx.trace_id, "032x")
doc["span_id"] = format(ctx.span_id, "016x")
for field in LOG_FIELDS:
if hasattr(record, field):
doc[field] = getattr(record, field)
if record.exc_info and record.exc_info[0]:
doc["exception.type"] = record.exc_info[0].__name__ # type only: no stack trace, no SQL, no values
return json.dumps(doc, ensure_ascii=False)
def log_event(logger: logging.Logger, level: int, event: str, message: str, **fields) -> None:
"""Structured log: `event` + whitelisted technical fields; trace_id/span_id come from the active span."""
logger.log(level, message, extra={"event": event, **fields})
def init(service_name: str, instrument: tuple[str, ...] = ()) -> None:
"""Configure providers once per process. `instrument` selects auto-instrumentation libraries."""
global SERVICE_NAME
SERVICE_NAME = service_name
instance = os.getenv("INSTANCE_ID") or socket.gethostname()
resource = Resource.create({
"service.name": service_name,
"service.version": os.getenv("SERVICE_VERSION", "1.6.0"),
"service.instance.id": instance,
"deployment.environment.name": os.getenv("DEPLOYMENT_ENVIRONMENT", "lab"),
})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(BatchSpanProcessor(
OTLPSpanExporter(timeout=EXPORT_TIMEOUT_S),
max_queue_size=2048, max_export_batch_size=512, schedule_delay_millis=2000, export_timeout_millis=EXPORT_TIMEOUT_S * 1000))
trace.set_tracer_provider(tracer_provider)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(timeout=EXPORT_TIMEOUT_S), export_interval_millis=METRIC_INTERVAL_MS, export_timeout_millis=5000)
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
OTLPLogExporter(timeout=EXPORT_TIMEOUT_S),
max_queue_size=2048, max_export_batch_size=512, schedule_delay_millis=2000, export_timeout_millis=EXPORT_TIMEOUT_S * 1000))
otlp_handler = LoggingHandler(level=logging.NOTSET, logger_provider=logger_provider)
otlp_handler.addFilter(_NoOtelSelfLogs())
otlp_handler.addFilter(_EventFilter())
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(JsonFormatter())
stdout_handler.addFilter(_EventFilter())
root = logging.getLogger()
root.handlers[:] = [stdout_handler, otlp_handler]
root.setLevel(os.getenv("LOG_LEVEL", "INFO"))
if "psycopg" in instrument:
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
PsycopgInstrumentor().instrument()
if "botocore" in instrument:
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
BotocoreInstrumentor().instrument()
# Redis is deliberately NOT auto-instrumented: session keys are derived from the session token.
def tracer(name: str = "messenger") -> trace.Tracer:
return trace.get_tracer(name)
def meter(name: str = "messenger") -> metrics.Meter:
return metrics.get_meter(name)
def _rss_bytes() -> int:
with open("/proc/self/statm") as f:
return int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
def register_process_metrics() -> None:
"""Process CPU/RAM of this container's main process (own gauges: no psutil dependency)."""
m = meter()
m.create_observable_counter("process.cpu.time", callbacks=[lambda _o: [metrics.Observation(sum(os.times()[:2]))]],
unit="s", description="CPU seconds (user+system) used by this process")
m.create_observable_gauge("process.memory.usage", callbacks=[lambda _o: [metrics.Observation(_rss_bytes())]],
unit="By", description="Resident set size of this process")
+294
View File
@@ -0,0 +1,294 @@
"""Lab 6 worker (lab 5 + OpenTelemetry): Kafka consumer -> claim (lease) in PostgreSQL -> staging -> pipeline -> final S3 + COMMIT -> offset commit.
PostgreSQL is the source of truth for job state; Kafka is the at-least-once transport. The Kafka offset is committed
only AFTER the durable effect (final objects + COMMIT of the result) or after a durable decision (retry scheduled / failed).
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import psycopg
from botocore.exceptions import BotoCoreError, ClientError
from boto3.s3.transfer import TransferConfig
from confluent_kafka import Consumer, TopicPartition
from opentelemetry import metrics, trace
from opentelemetry.propagate import extract
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import jobs, telemetry
telemetry.init("messenger-worker", instrument=("psycopg", "botocore"))
log = logging.getLogger("worker")
TRACER = telemetry.tracer()
NO_THREADS = TransferConfig(use_threads=False) # s3transfer threads would lose the trace context: keep transfers in the job thread
WORKER_ID = os.getenv("INSTANCE_ID") or socket.gethostname()
CONCURRENCY = int(os.getenv("WORKER_CONCURRENCY", "2"))
FAULT_EXIT_AFTER_S3 = os.getenv("FAULT_WORKER_EXIT_AFTER_S3", "0") == "1" # test hook: crash after the S3 write, before COMMIT/ack
IMG_MEMORY_MB = os.getenv("IMG_MEMORY_MB", "1024")
CODE_BY_EXIT = {2: "invalid_image", 3: "image_too_large", 4: "image_too_complex"} # permanent errors of imgproc
STOP = False
# ---- Lab 6 metrics. Labels: job.type + outcome only (never job_id / attachment_id). ----
_M = telemetry.meter()
JOBS_PROCESSED = _M.create_counter("messenger.jobs.processed", unit="{job}", description="Finished job attempts by outcome: success|retry|failed|lost|noop|error")
JOB_DURATION = _M.create_histogram("messenger.job.duration", unit="s", description="Worker processing time of one attempt (claim -> outcome), backlog wait excluded",
explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120])
TIME_TO_READY = _M.create_histogram("messenger.job.time_to_ready", unit="s", description="End-to-end: durable acceptance (job row created) -> ready committed",
explicit_bucket_boundaries_advisory=[0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1800])
_busy, _busy_lock = 0, threading.Lock()
_M.create_observable_gauge("messenger.worker.busy", callbacks=[lambda _o: [metrics.Observation(_busy)]], unit="{job}", description="Jobs being handled right now")
_M.create_observable_gauge("messenger.worker.capacity", callbacks=[lambda _o: [metrics.Observation(CONCURRENCY)]], unit="{job}", description="WORKER_CONCURRENCY")
telemetry.register_process_metrics()
class Permanent(Exception):
def __init__(self, code: str):
super().__init__(code)
self.code = code
class Transient(Exception):
pass
def connect():
return psycopg.connect(connect_timeout=5, options="-c statement_timeout=10000")
def parse_job(raw: bytes) -> dict | None:
"""Validate against jobs.schema.json (the subset that matters). Poison messages are logged and skipped."""
try:
m = json.loads(raw)
assert m["schema_version"] == 1 and m["type"] == jobs.JOB_TYPE
uuid.UUID(m["job_id"]); uuid.UUID(m["attachment_id"])
assert isinstance(m["pipeline_version"], int) and m["pipeline_version"] >= 1
return m
except Exception:
telemetry.log_event(log, logging.ERROR, "job_poison_skipped", f"poison message skipped (schema violation), size={len(raw)}")
return None
def claim(msg: dict) -> dict | None:
"""queued -> processing with a lease. Returns None when this delivery must be a no-op (ack)."""
with connect() as conn:
row = conn.execute(
"SELECT status, attempt, max_attempts, attachment_id, pipeline_version, "
"(next_attempt_at <= now()) AS due, (lease_until IS NOT NULL AND lease_until < now()) AS lease_expired "
"FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (msg["job_id"],)).fetchone()
if row is None:
telemetry.log_event(log, logging.WARNING, "job_unknown", "job unknown, skipped", job_id=msg["job_id"]); return None
status, attempt, max_attempts, att_id, pv, due, expired = row
if pv != msg["pipeline_version"]:
return None # stale job of another pipeline version never overwrites the newer one
if status in ("ready", "failed"):
telemetry.log_event(log, logging.INFO, "job_duplicate_noop", f"job already {status}: duplicate delivery is a no-op", job_id=msg["job_id"]); return None
if status == "queued" and not due:
return None # early duplicate: the delayed outbox row will deliver it later
if status == "processing" and not expired:
telemetry.log_event(log, logging.INFO, "job_leased_skip", "job is leased by another worker: skip", job_id=msg["job_id"]); return None
if attempt >= max_attempts: # lease expired and no attempts left
jobs.fail_job(conn, msg["job_id"], att_id, "retry_exhausted", attempt)
return None
attempt += 1
conn.execute("UPDATE attachment_jobs SET status='processing', attempt=%s, worker_id=%s, "
"lease_until=now()+make_interval(secs=>%s), updated_at=now() WHERE job_id=%s",
(attempt, WORKER_ID, jobs.LEASE_SECONDS, msg["job_id"]))
conn.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (att_id,))
jobs.add_event(conn, msg["job_id"], "claimed", f"attempt={attempt} worker={WORKER_ID}")
telemetry.log_event(log, logging.INFO, "job_claimed", "job claimed", job_id=msg["job_id"], attempt=attempt)
a = conn.execute("SELECT sha256, staging_key, s3_key, content_type, filename FROM attachments WHERE id=%s", (att_id,)).fetchone()
return {"job_id": msg["job_id"], "attachment_id": att_id, "pv": pv, "attempt": attempt, "max_attempts": max_attempts,
"sha256": a[0].strip(), "staging_key": a[1], "original_key": a[2], "content_type": a[3]}
def run_pipeline(s3, c: dict) -> dict:
"""Download staging -> verify -> child process with limits -> idempotent PUTs of deterministic keys."""
if not c["staging_key"]:
raise Permanent("staging_missing")
with tempfile.TemporaryDirectory(prefix="job-") as tmp:
src, out = Path(tmp) / "in.bin", Path(tmp) / "out"
out.mkdir()
try:
with TRACER.start_as_current_span("s3.download_staging"):
s3.download_file(jobs.S3_BUCKET, c["staging_key"], str(src), Config=NO_THREADS)
except ClientError as e:
if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
raise Permanent("staging_missing")
raise
if hashlib.sha256(src.read_bytes()).hexdigest() != c["sha256"]:
raise Permanent("integrity_error") # bytes differ from what the API accepted
try:
with TRACER.start_as_current_span("imgproc.run"):
r = subprocess.run([sys.executable, "-m", "src.imgproc", str(src), str(out)], capture_output=True, text=True,
timeout=jobs.JOB_TIMEOUT_SECONDS, env={"PATH": os.environ.get("PATH", ""), "IMG_MEMORY_MB": IMG_MEMORY_MB,
"IMG_CPU_SECONDS": str(jobs.JOB_TIMEOUT_SECONDS),
"MAX_IMAGE_PIXELS": os.getenv("MAX_IMAGE_PIXELS", "40000000")}) # no secrets in the child
except subprocess.TimeoutExpired:
raise Transient("job timeout") # child is killed by subprocess.run
if r.returncode in CODE_BY_EXIT:
raise Permanent(CODE_BY_EXIT[r.returncode])
if r.returncode != 0:
raise Transient(f"imgproc exit {r.returncode}")
meta = json.loads(r.stdout)
files = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}
# 1) original into the final prefix (same key every time => repeated PUT is harmless)
with TRACER.start_as_current_span("s3.upload_final"):
s3.upload_file(str(src), jobs.S3_BUCKET, c["original_key"], ExtraArgs={"ContentType": c["content_type"]}, Config=NO_THREADS)
# 2) variants
for name in jobs.VARIANT_ORDER:
key = jobs.final_key(c["attachment_id"], c["pv"], name)
s3.upload_file(str(out / files[name]), jobs.S3_BUCKET, key, ExtraArgs={"ContentType": meta[name]["content_type"]}, Config=NO_THREADS)
meta[name]["s3_key"] = key
return meta
def commit_ready(c: dict, meta: dict) -> bool:
"""Atomically publish the result. False if this attempt no longer owns the job (lease lost to a newer attempt)."""
with connect() as conn:
row = conn.execute("SELECT status, attempt FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (c["job_id"],)).fetchone()
if row is None or row[0] != "processing" or row[1] != c["attempt"]:
telemetry.log_event(log, logging.WARNING, "job_lease_lost", "attempt lost ownership, result not committed", job_id=c["job_id"], attempt=c["attempt"]); return False
for name in jobs.VARIANT_ORDER:
v = meta[name]
conn.execute("INSERT INTO attachment_variants(attachment_id,pipeline_version,name,s3_key,content_type,size_bytes,width,height,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (attachment_id,pipeline_version,name) DO NOTHING",
(c["attachment_id"], c["pv"], name, v["s3_key"], v["content_type"], v["size_bytes"], v["width"], v["height"], v["sha256"]))
waited = conn.execute("UPDATE attachment_jobs SET status='ready', error_code=NULL, lease_until=NULL, updated_at=now() WHERE job_id=%s "
"RETURNING EXTRACT(EPOCH FROM (now() - created_at))", (c["job_id"],)).fetchone()[0]
TIME_TO_READY.record(float(waited), {"job.type": jobs.JOB_TYPE})
conn.execute("UPDATE attachments SET status='ready', error_code=NULL, staging_key=NULL, updated_at=now() WHERE id=%s", (c["attachment_id"],))
jobs.add_event(conn, c["job_id"], "ready", f"attempt={c['attempt']}")
return True
def record_failure(c: dict, exc: Exception) -> None:
"""Permanent -> failed in the PostgreSQL registry. Transient -> queued with backoff+jitter (delayed outbox row) or failed when attempts are exhausted."""
with connect() as conn:
row = conn.execute("SELECT status, attempt FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (c["job_id"],)).fetchone()
if row is None or row[0] != "processing" or row[1] != c["attempt"]:
return
if isinstance(exc, Permanent):
jobs.fail_job(conn, c["job_id"], c["attachment_id"], exc.code, c["attempt"])
elif c["attempt"] >= c["max_attempts"]:
jobs.fail_job(conn, c["job_id"], c["attachment_id"], "retry_exhausted", c["attempt"])
else:
delay = jobs.backoff_seconds(c["attempt"])
conn.execute("UPDATE attachment_jobs SET status='queued', lease_until=NULL, next_attempt_at=now()+make_interval(secs=>%s), "
"error_code=NULL, updated_at=now() WHERE job_id=%s", (delay, c["job_id"]))
conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s", (c["attachment_id"],))
jobs.add_event(conn, c["job_id"], "retry_scheduled", f"attempt={c['attempt']} delay={delay:.1f}s reason={type(exc).__name__}")
jobs.enqueue(conn, c["job_id"], c["attachment_id"], c["pv"], c["attempt"] + 1, delay_seconds=delay)
def _process(s3, msg: dict, span) -> str:
"""The lab 5 job logic, now with stage spans. Returns the outcome label used by metrics and the consumer span."""
with TRACER.start_as_current_span("job.claim"):
c = claim(msg)
if c is None:
return "noop"
span.set_attribute("job.attempt", c["attempt"])
try:
with TRACER.start_as_current_span("job.pipeline"):
meta = run_pipeline(s3, c)
if FAULT_EXIT_AFTER_S3 and c["attempt"] == 1:
log.error("FAULT: exiting after S3 write, before COMMIT and offset commit")
os._exit(137)
with TRACER.start_as_current_span("job.commit_ready"):
committed = commit_ready(c, meta)
if not committed:
return "lost"
telemetry.log_event(log, logging.INFO, "job_ready", "job ready", job_id=c["job_id"], attempt=c["attempt"], outcome="success")
try:
s3.delete_object(Bucket=jobs.S3_BUCKET, Key=c["staging_key"]) # staging cleanup after the safe COMMIT
except Exception:
log.warning("staging cleanup failed; sweeper will remove it")
return "success"
except (Permanent, Transient, ClientError, BotoCoreError, OSError, json.JSONDecodeError) as exc:
final = isinstance(exc, Permanent) or c["attempt"] >= c["max_attempts"]
outcome = "failed" if final else "retry"
span.record_exception(exc, attributes={"exception.escaped": False})
telemetry.log_event(log, logging.WARNING, "job_attempt_failed", f"job attempt failed: {type(exc).__name__}",
job_id=c["job_id"], attempt=c["attempt"], outcome=outcome, reason=getattr(exc, "code", type(exc).__name__))
with TRACER.start_as_current_span("job.record_failure"):
record_failure(c, exc)
return outcome
def handle(s3, raw: bytes) -> None:
global _busy
msg = parse_job(raw)
if msg is None:
return
# W3C trace context travels in the message: this CONSUMER span is a child of the dispatcher's PRODUCER span.
with TRACER.start_as_current_span(
f"{jobs.JOBS_TOPIC} process", context=extract(msg), kind=SpanKind.CONSUMER,
attributes={"messaging.system": "kafka", "messaging.destination.name": jobs.JOBS_TOPIC, "messaging.operation.type": "process",
"job.type": jobs.JOB_TYPE, "job.id": msg["job_id"], "attachment.id": msg["attachment_id"], "job.attempt": msg.get("attempt", 0)}) as span:
started, outcome = time.perf_counter(), "error"
with _busy_lock:
_busy += 1
try:
outcome = _process(s3, msg, span)
finally: # unexpected exception: outcome stays "error", the exception propagates (process exits)
with _busy_lock:
_busy -= 1
attrs = {"job.type": jobs.JOB_TYPE, "outcome": outcome}
JOBS_PROCESSED.add(1, attrs)
if outcome != "noop":
JOB_DURATION.record(time.perf_counter() - started, attrs)
span.set_attribute("job.outcome", outcome)
if outcome in ("retry", "failed", "lost", "error"):
span.set_status(Status(StatusCode.ERROR, outcome))
def main() -> None:
def request_stop(*_):
global STOP
STOP = True
signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
s3 = jobs.make_s3()
consumer = Consumer({
"bootstrap.servers": jobs.KAFKA_BOOTSTRAP, "group.id": "attachment-workers",
"enable.auto.commit": False, "auto.offset.reset": "earliest", "isolation.level": "read_committed",
"max.poll.interval.ms": 600000, "session.timeout.ms": 30000,
"queued.max.messages.kbytes": 1024, "fetch.max.bytes": 1048576, # bounded client-side prefetch
})
consumer.subscribe([jobs.JOBS_TOPIC])
telemetry.log_event(log, logging.INFO, "worker_started", f"worker {WORKER_ID} started, concurrency={CONCURRENCY}, max_attempts={jobs.JOB_MAX_ATTEMPTS}, lease={jobs.LEASE_SECONDS}s")
with ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
while not STOP:
msgs = consumer.consume(num_messages=CONCURRENCY, timeout=1.0) # at most CONCURRENCY jobs in flight
batch = []
for m in msgs:
if m.error():
log.warning("kafka error: %s", m.error()); continue
batch.append(m)
if not batch:
continue
futures = [pool.submit(handle, s3, m.value()) for m in batch]
for f in futures:
f.result() # unexpected exception => process exits, offsets stay uncommitted, Kafka redelivers
# ACK boundary: commit the highest processed offset+1 per partition, only after every job of the batch is durable
top = {}
for m in batch:
top[(m.topic(), m.partition())] = max(top.get((m.topic(), m.partition()), -1), m.offset() + 1)
consumer.commit(offsets=[TopicPartition(t, p, o) for (t, p), o in top.items()], asynchronous=False)
consumer.close()
if __name__ == "__main__":
main()
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Lab5 level-4 failure scenarios against a RUNNING compose stack (stdlib only; run from the repo root).
python3 student-tests/level4_failures.py all # or: worker_down | commit_publish_gap | crash_after_s3 | replay | s3_outage
Each scenario drives `docker compose` (never `down -v`: volumes stay) and prints PASS/FAIL with the observed facts.
"""
import base64, json, os, subprocess, sys, time, urllib.error, urllib.request, uuid
from pathlib import Path
BASE = os.getenv("BASE_URL", "http://localhost:8080")
PNG = (Path(__file__).resolve().parents[1] / "tests/fixtures/sample.png").read_bytes()
DC = ["docker", "compose", "--env-file", ".env"]
def sh(*args, env=None, check=True):
r = subprocess.run(list(args), capture_output=True, text=True, env={**os.environ, **(env or {})})
if check and r.returncode:
raise SystemExit(f"command failed: {' '.join(args)}\n{r.stderr[-500:]}")
return r.stdout.strip()
def sql(query):
return sh(*DC, "exec", "-T", "postgres", "sh", "-c", f'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At -c "{query}"')
def http(method, path, token=None, body=None, headers=None, raw=None):
h = dict(headers or {})
if token:
h["Authorization"] = "Bearer " + token
data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
if body is not None:
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=30) as r:
payload = r.read()
return r.status, (json.loads(payload) if payload and "json" in r.headers.get("Content-Type", "") else payload)
except urllib.error.HTTPError as e:
payload = e.read()
try:
return e.code, json.loads(payload)
except ValueError:
return e.code, payload
def setup():
name = "u" + uuid.uuid4().hex[:10]
pw = "correct-horse-battery"
st, user = http("POST", "/api/v1/users", body={"username": name, "display_name": "Tester", "password": pw})
assert st == 201, (st, user)
cred = base64.b64encode(f"{name}:{pw}".encode()).decode()
st, sess = http("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
token = sess["token"]
st, chat = http("POST", "/api/v1/chats", token, {"title": "lab5", "member_ids": [user["id"]]})
return token, chat["id"]
def upload(token, chat):
st, att = http("POST", f"/api/v1/chats/{chat}/attachments?filename=sample.png", token, raw=PNG, headers={"Content-Type": "image/png"})
assert st == 202 and att["status"] == "queued", (st, att)
return att["id"]
def wait(token, aid, want, timeout=90):
end, last = time.time() + timeout, None
while time.time() < end:
st, att = http("GET", f"/api/v1/attachments/{aid}", token)
last = att
if st == 200 and att["status"] == want:
return att
time.sleep(1)
raise AssertionError(f"attachment {aid} did not reach {want}; last={last}")
def wait_ready_api(timeout=90):
end = time.time() + timeout
while time.time() < end:
if http("GET", "/health/ready")[0] == 200:
return
time.sleep(1)
raise AssertionError("API not ready")
def check_variants(att):
v = {x["name"]: x for x in att["variants"]}
assert (v["thumbnail"]["width"], v["thumbnail"]["height"], v["thumbnail"]["content_type"]) == (256, 160, "image/jpeg"), v["thumbnail"]
assert (v["crop"]["width"], v["crop"]["height"]) == (128, 128), v["crop"]
assert v["optimized"]["content_type"] == "image/webp"
def events(aid):
return sql(f"SELECT string_agg(event, ',' ORDER BY id) FROM job_events e JOIN attachment_jobs j USING (job_id) WHERE j.attachment_id='{aid}'")
def worker_down():
token, chat = setup()
sh(*DC, "stop", "worker")
aid = upload(token, chat)
st, _ = http("GET", f"/api/v1/attachments/{aid}/content", token)
assert st == 409, st # content of a queued attachment
st, msg = http("POST", f"/api/v1/chats/{chat}/messages", token, {"text": "hi", "attachment_ids": [aid]}, {"Idempotency-Key": "k1"})
assert st == 201, (st, msg) # other features keep working; queued attachment can be attached
sh(*DC, "restart", "api"); wait_ready_api()
assert http("GET", f"/api/v1/attachments/{aid}", token)[1]["status"] == "queued" # accepted work survived the API restart
sh(*DC, "up", "-d", "worker")
att = wait(token, aid, "ready"); check_variants(att)
print("PASS worker_down:", aid, "events:", events(aid))
def commit_publish_gap():
token, chat = setup()
sh(*DC, "up", "-d", "dispatcher", env={"FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH": "1"}, check=True)
sh(*DC, "exec", "-T", "dispatcher", "rm", "-f", "/tmp/dispatcher_fault_done", check=False)
sh(*DC, "restart", "dispatcher") # fresh container process: the fault fires once, on the first outbox batch
time.sleep(3)
aid = upload(token, chat) # COMMIT happens; the dispatcher dies before publishing
att = wait(token, aid, "ready", 90); check_variants(att)
sh(*DC, "up", "-d", "dispatcher") # back to the normal configuration (.env: fault off)
print("PASS commit_publish_gap:", aid, "events:", events(aid))
def crash_after_s3():
token, chat = setup()
env = {"FAULT_WORKER_EXIT_AFTER_S3": "1", "JOB_TIMEOUT_SECONDS": "10", "LEASE_GRACE_SECONDS": "5"}
sh(*DC, "up", "-d", "worker", env=env)
time.sleep(5)
aid = upload(token, chat)
att = wait(token, aid, "ready", 150); check_variants(att)
n = sql(f"SELECT count(*) FROM attachment_variants WHERE attachment_id='{aid}'")
assert n == "3", n # the retry completed the SAME result, no second set of variants
sh(*DC, "up", "-d", "worker") # restore normal worker config
print("PASS crash_after_s3:", aid, "events:", events(aid))
def replay():
token, chat = setup()
sh(*DC, "stop", "worker")
aid = upload(token, chat)
good = sql(f"SELECT sha256 FROM attachments WHERE id='{aid}'")
sql(f"UPDATE attachments SET sha256=repeat('0',64) WHERE id='{aid}'") # simulate corrupted/tampered staging bytes
sh(*DC, "up", "-d", "worker")
att = wait(token, aid, "failed", 60)
assert att["error_code"] == "integrity_error", att # permanent error: failed at once, no retries
st, _ = http("POST", f"/api/v1/chats/{chat}/messages", token, {"text": "", "attachment_ids": [aid]}, {"Idempotency-Key": "k2"})
assert st == 409, st
sql(f"UPDATE attachments SET sha256='{good}' WHERE id='{aid}'") # operator fixes the cause
job = sql(f"SELECT job_id FROM attachment_jobs WHERE attachment_id='{aid}'")
print(sh(*DC, "exec", "-T", "worker", "python", "scripts/replay_failed.py", "--job-id", job, "--reason", "student-test"))
att = wait(token, aid, "ready", 60); check_variants(att)
again = sh(*DC, "exec", "-T", "worker", "python", "scripts/replay_failed.py", "--job-id", job, check=False)
assert "REFUSED" in again, again # replay of a successful job is refused
print("PASS replay:", aid, "events:", events(aid))
def s3_outage():
token, chat = setup()
sh(*DC, "stop", "worker")
aid = upload(token, chat)
sh(*DC, "stop", "s3")
sh(*DC, "up", "-d", "--no-deps", "worker")
time.sleep(15)
ev = events(aid)
assert "retry_scheduled" in ev, ev # temporary error => backoff with jitter, not failed
sh(*DC, "start", "s3"); wait_ready_api()
att = wait(token, aid, "ready", 120); check_variants(att)
print("PASS s3_outage:", aid, "events:", events(aid))
SCENARIOS = {"worker_down": worker_down, "commit_publish_gap": commit_publish_gap, "crash_after_s3": crash_after_s3, "replay": replay, "s3_outage": s3_outage}
if __name__ == "__main__":
which = sys.argv[1] if len(sys.argv) > 1 else "all"
for name, fn in SCENARIOS.items():
if which in ("all", name):
fn()
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Lab6 level-4 observability scenarios against a RUNNING compose stack (stdlib only, run from the repo root).
python3 student-tests/level4_observability.py trace_chain | queue_lag | db_slow | telemetry_down | all
Redirect to evidence: ... all | tee evidence/level4-observability.txt (no tokens are printed)
"""
import json, subprocess, sys, threading, time, urllib.parse
sys.path.insert(0, __import__("pathlib").Path(__file__).parent.as_posix())
from level4_failures import DC, http, setup, upload, wait, sh, sql
def prom(query):
out = sh(*DC, "exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/query?query=" + urllib.parse.quote(query))
return json.loads(out)["data"]["result"]
def firing(name):
return any(r["metric"].get("alertname") == name and r["metric"].get("alertstate") == "firing" for r in prom("ALERTS"))
def wait_alert(name, want, timeout):
end = time.time() + timeout
while time.time() < end:
if firing(name) == want:
return round(timeout - (end - time.time()))
time.sleep(5)
raise AssertionError(f"alert {name} did not become {'firing' if want else 'resolved'} in {timeout}s")
def grafana_get(url):
return sh(*DC, "exec", "-T", "grafana", "wget", "-qO-", url)
def trace_chain():
token, chat = setup(); aid = upload(token, chat); wait(token, aid, "ready")
time.sleep(10) # batch export + ingestion
q = urllib.parse.quote(f'{{service_name="messenger-api"}} | event="attachment_accepted" | attachment_id="{aid}"')
res = json.loads(grafana_get(f"http://loki:3100/loki/api/v1/query_range?query={q}"))["data"]["result"]
tid = res[0]["stream"]["trace_id"]
tr = json.loads(grafana_get(f"http://tempo:3200/api/traces/{tid}"))
spans = {}
for b in tr["batches"]:
svc = [a["value"]["stringValue"] for a in b["resource"]["attributes"] if a["key"] == "service.name"][0]
for ss in b["scopeSpans"]:
for s in ss["spans"]:
spans[s["spanId"]] = (svc, s["name"], s.get("kind"), s.get("parentSpanId", ""))
kinds = {(v[0], v[2]) for v in spans.values()}
assert ("messenger-api", "SPAN_KIND_SERVER") in kinds and ("messenger-dispatcher", "SPAN_KIND_PRODUCER") in kinds and ("messenger-worker", "SPAN_KIND_CONSUMER") in kinds, kinds
consumer = next(v for v in spans.values() if v[2] == "SPAN_KIND_CONSUMER")
assert spans[consumer[3]][2] == "SPAN_KIND_PRODUCER", "consumer must be a child of the producer span"
print("PASS trace_chain: trace", tid, "spans:", sorted({f"{v[0]}:{v[1]}" for v in spans.values()}))
def queue_lag(): # incident 1: worker stopped -> oldest job age grows -> QueueLagGrowing firing -> worker back -> resolved
token, chat = setup(); sh(*DC, "stop", "worker"); aid = upload(token, chat)
t = wait_alert("QueueLagGrowing", True, 240); age = prom("max(messenger_queue_oldest_job_age_seconds)")[0]["value"][1]
print(f"queue_lag: FIRING after ~{t}s, oldest_job_age={float(age):.0f}s, depth={prom('max(messenger_queue_depth)')[0]['value'][1]}")
sh(*DC, "up", "-d", "worker"); wait(token, aid, "ready", 120)
print(f"PASS queue_lag: ready after worker restart; RESOLVED after ~{wait_alert('QueueLagGrowing', False, 240)}s")
def db_slow(): # incident 2: ACCESS EXCLUSIVE lock on messages -> INSERT waits until statement_timeout (5s) -> 503
token, chat = setup(); stop = threading.Event(); codes = []
def load():
i = 0
while not stop.is_set():
i += 1
codes.append(http("POST", f"/api/v1/chats/{chat}/messages", token, {"text": "x"}, {"Idempotency-Key": f"k{threading.get_ident()}-{i}-{time.time()}"})[0])
lock = subprocess.Popen([*DC, "exec", "-T", "postgres", "sh", "-c", 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(150); COMMIT;"'], stdout=subprocess.DEVNULL)
ts = [threading.Thread(target=load) for _ in range(4)]; [t.start() for t in ts]
t = wait_alert("HighApiErrorRate", True, 240)
print(f"db_slow: FIRING after ~{t}s; 5xx so far: {codes.count(503)} of {len(codes)}")
sql("select pg_terminate_backend(pid) from pg_stat_activity where query like '%pg_sleep(150)%' and pid<>pg_backend_pid()")
lock.wait(); print(f"PASS db_slow: lock released; RESOLVED after ~{wait_alert('HighApiErrorRate', False, 300)}s")
stop.set(); [t.join() for t in ts]
def telemetry_down(): # scenario 3: stop all telemetry stores, API keeps working, Collector RAM stays bounded
token, chat = setup(); sh(*DC, "stop", "prometheus", "loki", "tempo")
bad = 0; end = time.time() + 90
while time.time() < end:
bad += http("POST", f"/api/v1/chats/{chat}/messages", token, {"text": "x"}, {"Idempotency-Key": f"t{time.time()}"})[0] != 201
aid = upload(token, chat); wait(token, aid, "ready", 90)
mem = sh("docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", sh(*DC, "ps", "-q", "otel-collector"))
assert bad == 0, bad
sh(*DC, "up", "-d", "prometheus", "loki", "tempo"); time.sleep(60)
print(f"PASS telemetry_down: 0 failed writes with all telemetry stores down; collector memory {mem} (limit 256MiB); stores restarted")
if __name__ == "__main__":
names = {"trace_chain": trace_chain, "queue_lag": queue_lag, "db_slow": db_slow, "telemetry_down": telemetry_down}
for n in (names if sys.argv[1] == "all" else [sys.argv[1]]):
names[n]()