forked from mtusi2026/mtusi2026lab6
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dab4a0600c | ||
|
|
503126f29c |
+2
-14
@@ -1,20 +1,8 @@
|
||||
.git
|
||||
.github
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets
|
||||
certs
|
||||
volumes
|
||||
data
|
||||
backups
|
||||
*.key
|
||||
*.pem
|
||||
*.p12
|
||||
*.pfx
|
||||
*.jks
|
||||
.venv
|
||||
__pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
**/__pycache__
|
||||
.venv
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
*.sh text eol=lf
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM python:3.12.12-slim-bookworm
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=/app/src
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY src ./src
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
CMD ["python", "-m", "app"]
|
||||
@@ -1,37 +1,42 @@
|
||||
# Отчёт — лабораторная 6
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор и группа — Шемрук Марк, БВТ2304.
|
||||
- Целевая оценка — 5. Трек 1. Цена наблюдаемости.
|
||||
- Ветка решения — `solution/bvt2304-shemruk`. Ссылка на PR появится после отправки.
|
||||
- Источники — контракт курса, собственная ЛР1, официальные руководства используемых компонентов. Codex помог с реализацией, проверками и отчётом. Присланные чужие реализации использовались для сверки тем и сценариев курса.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Запуск
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
На Windows команды выполняются в PowerShell из корня репозитория. Нужны Python 3.11+, Docker Desktop с Linux Engine и Compose. Образ API использует Python 3.12.12. Подготовьте свободные локальные порты. Рабочие файлы .env и secrets создаёт bootstrap. Точные версии зависимостей находятся в `requirements.txt` и `compose.yaml`.
|
||||
|
||||
## Архитектура и решения
|
||||
```powershell
|
||||
python -X utf8 scripts/check_contract.py
|
||||
python -X utf8 scripts/bootstrap.py
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build --wait
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
На Linux вместо `python -X utf8` можно использовать `python3 -X utf8`. Безопасная остановка — `docker compose down`. Она сохраняет named volumes. Преднамеренный сброс отдельного учебного окружения — `docker compose down -v`.
|
||||
|
||||
## Доказательства критериев
|
||||
## Архитектура и границы гарантий
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
API, relay и worker отправляют три сигнала через OTLP HTTP → OTel Collector. Collector экспортирует метрики для Prometheus, логи в Loki и трассы в Tempo. Grafana получает источники и dashboard через provisioning. Логи содержат стабильное имя маршрута, код, длительность, request ID и при наличии trace/span ID. Пароли, токены, текст сообщения и изображение в telemetry не передаются.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Контекст traceparent сохраняется вместе с outbox и передаётся в сообщение Streams. Producer и consumer spans открываются в цепочке upload, publish, consume, S3, DB. Метрики HTTP и длительность фоновой обработки группируются по маршруту, классу статуса и исходу. p50/p95/p99 считаются из bucket всех реплик. Очередь, пулы, занятость worker, CPU и RSS отражаются на панели. SDK и Collector имеют ограниченные очереди, batch, timeout, а Collector также memory_limiter. Правила Prometheus проверяют долю 5xx и возраст старейшей операции. Контрольное учебное окно показывает долю 5xx ≤10% и максимальный возраст ожидающей задачи ≤20 с. Цифры используются для демонстрации, SLO для производственного трафика потребует определения пользовательского профиля и окна.
|
||||
|
||||
## Эксперименты и отказы
|
||||
## Проверки и результаты
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
```powershell
|
||||
python -X utf8 tests/smoke.py
|
||||
python -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd
|
||||
python -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd
|
||||
docker compose start api
|
||||
```
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
Статическая проверка контракта, синтаксис и конфигурация Compose прошли. Публичный HTTP smoke прошёл на локальном PostgreSQL 18.0 с тестовой заменой Redis. S3 является тестовой заменой Moto. OTLP export отключён для локального прогона. Этот прогон проверяет API. Фактические отказы контейнеров и Compose-эксперименты требуют отдельного запуска.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
В Grafana на localhost:3000 открыть «Мессенджер МТУСИ». Пароль администратора создаёт bootstrap в локальном `secrets/grafana_password`. `python -X utf8 student-tests/trace_demo.py` возвращает известный trace ID живого upload. В Tempo Explore искать этот Trace ID, а в Loki запросить `{service_name=~"messenger-api|messenger-worker"} | json` и найти тот же ID в логе. В соседнем терминале можно создать нагрузку `python -X utf8 tests/load.py --duration 30 --concurrency 8`.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
`python -X utf8 student-tests/worker_pause.py --pause 45 --no-restart` позволяет увидеть рост возраста задач и после запуска worker спад. В Prometheus открыть Alerts. Для второго инцидента на изолированном стенде задать временный блок таблицы messages с помощью BEGIN, LOCK, pg_sleep и ROLLBACK в отдельном сеансе и параллельно писать сообщения. Readiness проверяет SELECT 1, а DB span записи покажет ожидание блокировки. Наблюдения firing/resolved, логи и реальные trace IDs записываются после запуска полного стенда.
|
||||
|
||||
`python -X utf8 scripts/telemetry_experiment.py` выполняет одинаковую нагрузку в режимах off, 100%, 25%, 5% и фиксирует latency, ошибки, CPU/RAM, принятые/неотправленные spans и объём Tempo при доступном счётчике. При 5% обычные трассы, включая часть редких медленных и ошибочных запросов, могут не выбираться. Логи и агрегированные метрики работают отдельно от head sampling. Результаты сравнения и выбор конфигурации следует сделать по данным стенда.
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
x-telemetry: &telemetry
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://collector:4318
|
||||
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-1}
|
||||
TRACE_SAMPLE_RATE: ${TRACE_SAMPLE_RATE:-1}
|
||||
|
||||
x-app: &app
|
||||
build: .
|
||||
image: shemruk-messenger-lab6:local
|
||||
cpus: 1.0
|
||||
mem_limit: 320m
|
||||
init: true
|
||||
environment:
|
||||
<<: *telemetry
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
S3_ACCESS_KEY_FILE: /run/secrets/s3_access
|
||||
S3_SECRET_KEY_FILE: /run/secrets/s3_secret
|
||||
secrets: [database_url, cache_url, cursor_key, s3_access, s3_secret]
|
||||
|
||||
x-job-env: &job-env
|
||||
<<: *telemetry
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
S3_ACCESS_KEY_FILE: /run/secrets/s3_access
|
||||
S3_SECRET_KEY_FILE: /run/secrets/s3_secret
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
JOB_MAX_ATTEMPTS: 5
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:17.6-bookworm
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
secrets: [db_password]
|
||||
volumes: [postgres_data:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, pg_isready -U messenger -d messenger -h 127.0.0.1]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
cache:
|
||||
image: redis:7.4.6-bookworm
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
command: [redis-server, /run/secrets/redis_config]
|
||||
secrets: [redis_config, cache_password]
|
||||
volumes: [redis_data:/data]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'REDISCLI_AUTH=$$(cat /run/secrets/cache_password) redis-cli ping | grep -qx PONG']
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
migrate:
|
||||
<<: *app
|
||||
command: [python, -m, db]
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
broker:
|
||||
image: redis:7.4.6-bookworm
|
||||
cpus: 0.5
|
||||
mem_limit: 160m
|
||||
command: [redis-server, /run/secrets/broker_config]
|
||||
secrets: [broker_config, broker_password]
|
||||
volumes: [broker_data:/data]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'REDISCLI_AUTH=$$(cat /run/secrets/broker_password) redis-cli ping | grep -qx PONG']
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
relay:
|
||||
<<: *app
|
||||
cpus: 0.25
|
||||
mem_limit: 120m
|
||||
command: [python, -m, pipeline, relay]
|
||||
environment: *job-env
|
||||
secrets: [database_url, broker_url]
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
broker: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
worker:
|
||||
<<: *app
|
||||
cpus: 1.0
|
||||
mem_limit: 704m
|
||||
command: [python, -m, pipeline, worker]
|
||||
environment: *job-env
|
||||
secrets: [database_url, broker_url, s3_access, s3_secret]
|
||||
stop_grace_period: 25s
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
relay: {condition: service_started}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
s3-perms:
|
||||
image: busybox:1.37.0
|
||||
command: ["chown", "10001:10001", "/data"]
|
||||
volumes: [object_data:/data]
|
||||
s3:
|
||||
image: rustfs/rustfs:1.0.7
|
||||
cpus: 0.75
|
||||
mem_limit: 512m
|
||||
env_file: ./secrets/s3_root.env
|
||||
environment:
|
||||
RUSTFS_VOLUMES: /data
|
||||
RUSTFS_ADDRESS: :9000
|
||||
RUSTFS_CONSOLE_ENABLE: "false"
|
||||
volumes: [object_data:/data]
|
||||
depends_on:
|
||||
s3-perms: {condition: service_completed_successfully}
|
||||
healthcheck:
|
||||
test: [CMD, curl, -fsS, "http://127.0.0.1:9000/health/ready"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
s3-init:
|
||||
image: rustfs/rc:v0.1.38
|
||||
cpus: 0.25
|
||||
mem_limit: 96m
|
||||
env_file: ./secrets/s3_root.env
|
||||
entrypoint: ["/bin/sh", "/bootstrap/s3-init.sh"]
|
||||
volumes: ["./infra/s3:/bootstrap:ro"]
|
||||
secrets: [s3_access, s3_secret]
|
||||
depends_on:
|
||||
s3: {condition: service_healthy}
|
||||
api:
|
||||
<<: *app
|
||||
scale: ${API_REPLICAS:-2}
|
||||
cpus: ${API_CPUS:-0.75}
|
||||
mem_limit: ${API_MEMORY:-448m}
|
||||
stop_grace_period: 12s
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
cache: {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=3)"]
|
||||
interval: 2s
|
||||
timeout: 4s
|
||||
retries: 20
|
||||
lb:
|
||||
image: haproxy:3.2.28-trixie
|
||||
cpus: 0.5
|
||||
mem_limit: 96m
|
||||
ports: ["127.0.0.1:${HTTP_PORT:-8080}:8080"]
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
depends_on: [api]
|
||||
collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.139.0
|
||||
cpus: 0.5
|
||||
mem_limit: 192m
|
||||
volumes: ["./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro"]
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.5.0
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=3d"]
|
||||
ports: ["127.0.0.1:${PROM_PORT:-9090}:9090"]
|
||||
volumes:
|
||||
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yml:ro
|
||||
- prometheus_data:/prometheus
|
||||
loki:
|
||||
image: grafana/loki:3.5.7
|
||||
cpus: 0.75
|
||||
mem_limit: 384m
|
||||
command: ["-config.file=/etc/loki/local-config.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/loki.yaml:/etc/loki/local-config.yaml:ro
|
||||
- loki_data:/loki
|
||||
tempo:
|
||||
image: grafana/tempo:2.8.3
|
||||
user: "0:0"
|
||||
cpus: 0.75
|
||||
mem_limit: 384m
|
||||
command: ["-config.file=/etc/tempo.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/tempo.yaml:/etc/tempo.yaml:ro
|
||||
- tempo_data:/var/tempo
|
||||
grafana:
|
||||
image: grafana/grafana:12.2.1
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password
|
||||
secrets: [grafana_password]
|
||||
ports: ["127.0.0.1:${GRAFANA_PORT:-3000}:3000"]
|
||||
volumes:
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- grafana_data:/var/lib/grafana
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
object_data:
|
||||
broker_data:
|
||||
prometheus_data:
|
||||
loki_data:
|
||||
tempo_data:
|
||||
grafana_data:
|
||||
|
||||
secrets:
|
||||
database_url: {file: ./secrets/database_url}
|
||||
db_password: {file: ./secrets/db_password}
|
||||
cache_url: {file: ./secrets/cache_url}
|
||||
cache_password: {file: ./secrets/cache_password}
|
||||
cursor_key: {file: ./secrets/cursor_key}
|
||||
redis_config: {file: ./secrets/redis.conf}
|
||||
s3_access: {file: ./secrets/s3_access}
|
||||
s3_secret: {file: ./secrets/s3_secret}
|
||||
broker_config: {file: ./secrets/broker.conf}
|
||||
broker_password: {file: ./secrets/broker_password}
|
||||
broker_url: {file: ./secrets/broker_url}
|
||||
grafana_password: {file: ./secrets/grafana_password}
|
||||
@@ -0,0 +1,2 @@
|
||||
PASS: public lab6 API smoke on native PostgreSQL 18.0, fake Redis Streams and Moto S3.
|
||||
This run used TELEMETRY_ENABLED=0. Docker Compose telemetry, Grafana, alerts and comparative measurements remain pending.
|
||||
@@ -0,0 +1,354 @@
|
||||
{
|
||||
"uid": "messenger-mtusi",
|
||||
"title": "Мессенджер МТУСИ",
|
||||
"tags": [
|
||||
"mtusi"
|
||||
],
|
||||
"schemaVersion": 40,
|
||||
"refresh": "10s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "API – запросы в секунду",
|
||||
"id": 1,
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m]))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "API – доля 5xx",
|
||||
"id": 2,
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m])),0.001)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "API – задержка",
|
||||
"id": 3,
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 7,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5,sum by(le)(rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[2m])))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[2m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "histogram_quantile(0.99,sum by(le)(rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[2m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Worker – задачи по исходу, в секунду",
|
||||
"id": 4,
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 7,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by(outcome)(rate(messenger_jobs_total[1m]))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Worker – p95 обработки",
|
||||
"id": 5,
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 14,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[2m])))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Время до ready – p95",
|
||||
"id": 6,
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 14,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Очередь – глубина",
|
||||
"id": 7,
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 21,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max by(queue)(messenger_queue_depth)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Возраст старейшей задачи",
|
||||
"id": 8,
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 21,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max by(queue)(messenger_oldest_job_age_seconds)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Пул PostgreSQL",
|
||||
"id": 9,
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 28,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by(role)(messenger_db_pool_used)",
|
||||
"legendFormat": "занято {{role}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "sum by(role)(messenger_db_pool_waiting)",
|
||||
"legendFormat": "ожидание {{role}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Загрузка worker",
|
||||
"id": 10,
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 28,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_worker_busy)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "RSS процесса",
|
||||
"id": 11,
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 35,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max by(role)(messenger_process_rss_bytes)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "CPU процесса",
|
||||
"id": 12,
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 35,
|
||||
"w": 12,
|
||||
"h": 7
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "cores"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by(role)(rate(messenger_process_cpu_time_seconds[1m]))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: messenger
|
||||
type: file
|
||||
folder: MTUSI
|
||||
options: {path: /var/lib/grafana/dashboards}
|
||||
@@ -0,0 +1,5 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- {name: Prometheus, uid: prometheus, type: prometheus, access: proxy, url: "http://prometheus:9090", isDefault: true}
|
||||
- {name: Loki, uid: loki, type: loki, access: proxy, url: "http://loki:3100"}
|
||||
- {name: Tempo, uid: tempo, type: tempo, access: proxy, url: "http://tempo:3200"}
|
||||
@@ -0,0 +1,31 @@
|
||||
global
|
||||
maxconn 128
|
||||
log stdout format raw local0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
timeout connect 1s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
timeout http-request 8s
|
||||
timeout queue 2s
|
||||
timeout check 1s
|
||||
retries 0
|
||||
|
||||
resolvers docker
|
||||
nameserver internal 127.0.0.11:53
|
||||
resolve_retries 2
|
||||
timeout resolve 500ms
|
||||
timeout retry 500ms
|
||||
hold valid 2s
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend messenger
|
||||
|
||||
backend messenger
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
server-template api 8 api:8080 check inter 500ms fall 2 rise 1 resolvers docker resolve-prefer ipv4 init-addr none
|
||||
@@ -0,0 +1,15 @@
|
||||
groups:
|
||||
- name: messenger
|
||||
rules:
|
||||
- alert: MessengerHttpErrorRatioHigh
|
||||
expr: |
|
||||
sum(rate(messenger_http_requests_total{route!~"/health/.*",status_class="5xx"}[1m]))
|
||||
/ clamp_min(sum(rate(messenger_http_requests_total{route!~"/health/.*"}[1m])), 0.001) > 0.10
|
||||
for: 20s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: "Проверьте trace API и доступность PostgreSQL по readiness."}
|
||||
- alert: MessengerOldestImageJobHigh
|
||||
expr: max(messenger_oldest_job_age_seconds) > 20
|
||||
for: 15s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: "Проверьте worker, очередь и доступность S3, затем дождитесь уменьшения backlog."}
|
||||
@@ -0,0 +1,41 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 128
|
||||
spike_limit_mib: 24
|
||||
batch:
|
||||
send_batch_size: 128
|
||||
send_batch_max_size: 256
|
||||
timeout: 1s
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
metric_expiration: 45s
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 3s
|
||||
sending_queue: {queue_size: 64, num_consumers: 1}
|
||||
retry_on_failure: {initial_interval: 1s, max_interval: 3s, max_elapsed_time: 10s}
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
timeout: 3s
|
||||
sending_queue: {queue_size: 64, num_consumers: 1}
|
||||
retry_on_failure: {initial_interval: 1s, max_interval: 3s, max_elapsed_time: 10s}
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
pipelines:
|
||||
metrics: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheus]}
|
||||
logs: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki]}
|
||||
traces: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/tempo]}
|
||||
@@ -0,0 +1,31 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
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_config:
|
||||
resource_attributes:
|
||||
ignore_defaults: true
|
||||
attributes_config:
|
||||
- action: index_label
|
||||
attributes: [service.name]
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,14 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
rule_files: [/etc/prometheus/alerts.yml]
|
||||
scrape_configs:
|
||||
- job_name: messenger
|
||||
static_configs:
|
||||
- targets: [collector:8889]
|
||||
- job_name: collector
|
||||
static_configs:
|
||||
- targets: [collector:8888]
|
||||
- job_name: tempo
|
||||
static_configs:
|
||||
- targets: [tempo:3200]
|
||||
@@ -0,0 +1,20 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 72h
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::attachments"]},
|
||||
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::attachments/original/*", "arn:aws:s3:::attachments/staging/*",
|
||||
"arn:aws:s3:::attachments/results/*"]}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export HOME=/tmp
|
||||
rc alias set lab http://s3:9000 "$RUSTFS_ACCESS_KEY" "$RUSTFS_SECRET_KEY"
|
||||
rc mb --ignore-existing lab/attachments
|
||||
access=$(cat /run/secrets/s3_access)
|
||||
secret=$(cat /run/secrets/s3_secret)
|
||||
rc admin user add lab/ "$access" "$secret"
|
||||
rc admin policy create lab/ messenger-objects /bootstrap/api-policy.json
|
||||
rc admin policy attach lab/ messenger-objects --user "$access"
|
||||
@@ -0,0 +1,7 @@
|
||||
psycopg[binary]==3.2.13
|
||||
psycopg-pool==3.2.8
|
||||
redis==6.4.0
|
||||
boto3==1.40.67
|
||||
Pillow==12.2.0
|
||||
opentelemetry-sdk==1.38.0
|
||||
opentelemetry-exporter-otlp-proto-http==1.38.0
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Create local credentials once. Run from the repository on Windows or Linux."""
|
||||
|
||||
from pathlib import Path
|
||||
from secrets import token_hex
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / "secrets"
|
||||
|
||||
|
||||
def keep(path, value):
|
||||
try:
|
||||
with path.open("x", encoding="utf-8", newline="\n") as stream:
|
||||
stream.write(value + "\n")
|
||||
except FileExistsError:
|
||||
pass
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def main():
|
||||
LOCAL.mkdir(mode=0o700, exist_ok=True)
|
||||
db = keep(LOCAL / "db_password", token_hex(24))
|
||||
cache = keep(LOCAL / "cache_password", token_hex(24))
|
||||
broker = keep(LOCAL / "broker_password", token_hex(24))
|
||||
keep(LOCAL / "database_url", f"postgresql://messenger:{db}@db:5432/messenger")
|
||||
keep(LOCAL / "cache_url", f"redis://:{cache}@cache:6379/0")
|
||||
keep(LOCAL / "broker_url", f"redis://:{broker}@broker:6379/0")
|
||||
keep(LOCAL / "cursor_key", token_hex(32))
|
||||
keep(LOCAL / "grafana_password", token_hex(24))
|
||||
keep(LOCAL / "s3_root.env",
|
||||
f"RUSTFS_ACCESS_KEY=labroot{token_hex(8)}\nRUSTFS_SECRET_KEY={token_hex(24)}")
|
||||
keep(LOCAL / "s3_access", "messenger" + token_hex(6))
|
||||
keep(LOCAL / "s3_secret", token_hex(24))
|
||||
config = "\n".join((
|
||||
"bind 0.0.0.0", "protected-mode yes", "dir /data",
|
||||
"appendonly yes", "appendfsync always", "maxmemory 64mb",
|
||||
"maxmemory-policy noeviction",
|
||||
))
|
||||
keep(LOCAL / "redis.conf", f"{config}\nrequirepass {cache}")
|
||||
keep(LOCAL / "broker.conf", f"{config}\nrequirepass {broker}")
|
||||
keep(ROOT / ".env", "HTTP_PORT=8080\nSESSION_TTL_SECONDS=3600")
|
||||
print("Локальная конфигурация готова.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Map a live process alias to a Compose container, then control that container."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROBE = """
|
||||
import urllib.request
|
||||
response = urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=3)
|
||||
print(response.headers["X-Instance-Id"])
|
||||
"""
|
||||
|
||||
|
||||
def docker(*args, capture=True):
|
||||
return subprocess.run(
|
||||
("docker", *args), cwd=ROOT, capture_output=capture, text=True,
|
||||
check=True, timeout=60,
|
||||
).stdout
|
||||
|
||||
|
||||
def replicas():
|
||||
result = {}
|
||||
for container in docker("compose", "ps", "-q", "api").split():
|
||||
try:
|
||||
alias = docker("exec", container, "python", "-c", PROBE).strip()
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
if alias and alias not in result:
|
||||
result[alias] = container
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("operation", choices=("list", "stop"))
|
||||
args = parser.parse_args()
|
||||
mapping = replicas()
|
||||
if args.operation == "list":
|
||||
print(json.dumps(mapping, indent=2))
|
||||
return
|
||||
alias = os.environ.get("TARGET_INSTANCE_ID")
|
||||
if not alias or alias not in mapping:
|
||||
raise SystemExit("TARGET_INSTANCE_ID must match a running API process")
|
||||
docker("stop", "--timeout", "10", mapping[alias], capture=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose ps lb api db cache s3 broker worker relay || exit /b 1
|
||||
docker compose restart db cache s3 broker || exit /b 1
|
||||
docker compose restart api lb relay worker || exit /b 1
|
||||
docker compose ps lb api db cache s3 broker worker relay
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose ps lb api db cache s3 broker worker relay
|
||||
docker compose restart db cache s3 broker
|
||||
docker compose restart api lb relay worker
|
||||
docker compose ps lb api db cache s3 broker worker relay
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts/replicas.py stop
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/replicas.py stop
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Repeat a fixed workload while changing OTLP and trace sampling settings."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
SERVICES = ("api", "worker", "relay", "collector", "tempo", "loki", "prometheus")
|
||||
|
||||
|
||||
def docker(env, *args):
|
||||
result = subprocess.run(["docker", *args], check=True, cwd=ROOT, env=env,
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=100)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def apply(env, address):
|
||||
docker(env, "compose", "up", "-d", "--no-deps", "--wait", "api", "relay", "worker")
|
||||
client = Client(address, timeout=3)
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.4)
|
||||
raise RuntimeError("Messenger did not become ready")
|
||||
|
||||
|
||||
def scrape(base, query):
|
||||
url = base.rstrip("/") + "/api/v1/query?" + urllib.parse.urlencode({"query": query})
|
||||
with urllib.request.urlopen(url, timeout=4) as response:
|
||||
data = json.load(response)["data"]["result"]
|
||||
return float(data[0]["value"][1]) if data else None
|
||||
|
||||
|
||||
def profile(env, args):
|
||||
containers = docker(env, "compose", "ps", "-q", *SERVICES).split()
|
||||
load = [sys.executable, "-X", "utf8", "tests/load.py", "--base-url", args.base_url,
|
||||
"--concurrency", str(args.concurrency), "--duration", str(args.seconds)]
|
||||
samples = []
|
||||
with subprocess.Popen(load, cwd=ROOT, stdout=subprocess.PIPE, text=True, encoding="utf-8") as running:
|
||||
deadline = time.monotonic() + args.seconds + 25
|
||||
while running.poll() is None and time.monotonic() < deadline:
|
||||
raw = docker(env, "stats", "--no-stream", "--format", "{{json .}}", *containers)
|
||||
fields = [json.loads(line) for line in raw.splitlines() if line]
|
||||
samples.append([{"name": row["Name"], "cpu": row["CPUPerc"], "memory": row["MemUsage"]}
|
||||
for row in fields])
|
||||
time.sleep(2)
|
||||
if running.poll() is None:
|
||||
running.kill()
|
||||
raise RuntimeError("workload exceeded its deadline")
|
||||
stdout, _ = running.communicate(timeout=5)
|
||||
if running.returncode:
|
||||
raise RuntimeError(stdout)
|
||||
time.sleep(6)
|
||||
window = args.seconds + 12
|
||||
queries = {
|
||||
"accepted_spans": "otelcol_receiver_accepted_spans(_total)?",
|
||||
"dropped_spans": "otelcol_exporter_send_failed_spans(_total)?",
|
||||
"tempo_ingest_bytes": "tempo_distributor_bytes_received_total",
|
||||
}
|
||||
values = {label: scrape(args.prom_url, f'sum(increase({{__name__=~"{metric}"}}[{window}s]))')
|
||||
for label, metric in queries.items()}
|
||||
return {"workload": json.loads(stdout), "containers": samples, "ingest": values}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prom-url", default="http://localhost:9090")
|
||||
parser.add_argument("--seconds", type=int, default=30)
|
||||
parser.add_argument("--concurrency", type=int, default=8)
|
||||
parser.add_argument("--repeat", type=int, default=3)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "evidence/telemetry-overhead.json")
|
||||
args = parser.parse_args()
|
||||
baseline = dict(os.environ)
|
||||
output = []
|
||||
try:
|
||||
for label, enabled, fraction in (("off", "0", "0"), ("all", "1", "1"),
|
||||
("quarter", "1", "0.25"), ("twentieth", "1", "0.05")):
|
||||
env = {**baseline, "TELEMETRY_ENABLED": enabled, "TRACE_SAMPLE_RATE": fraction}
|
||||
apply(env, args.base_url)
|
||||
# Allow old samples to expire before each new measurement window.
|
||||
time.sleep(args.seconds + 12)
|
||||
output.append({"mode": label, "sampling": float(fraction),
|
||||
"runs": [profile(env, args) for _ in range(args.repeat)]})
|
||||
finally:
|
||||
apply(baseline, args.base_url)
|
||||
args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Saved {len(output)} observed telemetry profiles.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
"""HTTP entry point for the persistent messenger (based on lab 1)."""
|
||||
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import psycopg
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import PoolTimeout
|
||||
from redis.exceptions import RedisError
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from attachments import BadImage, MAX_UPLOAD, Objects, PixelLimit, spool, verify_image
|
||||
from auth import Sessions, USERNAME, parse_basic, parse_bearer, password_hash, valid_password, verify_password
|
||||
from db import KeyConflict, MissingAttachment, Store, UnusableAttachment, setting
|
||||
import telemetry as tm
|
||||
|
||||
|
||||
MAX_BODY = 64 * 1024
|
||||
QUERY_LIMIT = re.compile(r"[0-9]{1,6}")
|
||||
LENGTH = re.compile(r"[0-9]{1,12}")
|
||||
IDEMPOTENCY_KEY = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
FIRST = (dt.datetime.min.replace(tzinfo=dt.timezone.utc), UUID(int=0))
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def bad(message="Некорректный запрос"):
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def not_found():
|
||||
return ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
|
||||
def unauthorized(scheme):
|
||||
challenge = f'{scheme} realm="messenger"'
|
||||
if scheme == "Basic":
|
||||
challenge += ', charset="UTF-8"'
|
||||
return ApiError(401, "unauthorized", "Нужна аутентификация", {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def clean_text(value, min_len, max_len, field):
|
||||
if not isinstance(value, str) or not min_len <= len(value) <= max_len or not value.strip():
|
||||
raise bad(f"Поле {field} имеет недопустимую длину или тип")
|
||||
try:
|
||||
value.encode("utf-8")
|
||||
except UnicodeEncodeError:
|
||||
raise bad(f"Поле {field} содержит недопустимые символы")
|
||||
if "\x00" in value:
|
||||
raise bad(f"Поле {field} содержит NUL")
|
||||
return value
|
||||
|
||||
|
||||
def parse_uuid(value):
|
||||
if not isinstance(value, str):
|
||||
raise bad("Некорректный UUID")
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
raise bad("Некорректный UUID")
|
||||
|
||||
|
||||
def only_fields(body, required, optional=()):
|
||||
if not isinstance(body, dict) or set(required) - body.keys() or body.keys() - set(required + optional):
|
||||
raise bad("Неверный набор полей")
|
||||
|
||||
|
||||
def json_value(value):
|
||||
if isinstance(value, dt.datetime):
|
||||
return value.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
if isinstance(value, UUID):
|
||||
return str(value)
|
||||
raise TypeError("Unsupported JSON value")
|
||||
|
||||
|
||||
def encode_cursor(scope, row, key):
|
||||
raw = json.dumps([scope, row["created_at"], row["id"]], default=json_value).encode()
|
||||
signature = hmac.digest(key, raw, "sha256")
|
||||
return base64.urlsafe_b64encode(raw + signature).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor, scope, key):
|
||||
try:
|
||||
if len(cursor) > 512 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
|
||||
raise ValueError
|
||||
envelope = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
||||
raw, signature = envelope[:-32], envelope[-32:]
|
||||
if not hmac.compare_digest(hmac.digest(key, raw, "sha256"), signature):
|
||||
raise ValueError
|
||||
actual_scope, timestamp, item_id = json.loads(raw)
|
||||
if actual_scope != scope:
|
||||
raise ValueError
|
||||
return dt.datetime.fromisoformat(timestamp.replace("Z", "+00:00")), UUID(item_id)
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise bad("Некорректный cursor")
|
||||
|
||||
|
||||
def page(ctx, scope, read):
|
||||
limit = ctx.param("limit", "50")
|
||||
cursor = ctx.param("cursor")
|
||||
if not QUERY_LIMIT.fullmatch(limit) or not 1 <= int(limit) <= 100:
|
||||
raise bad("limit должен быть целым числом от 1 до 100")
|
||||
count = int(limit)
|
||||
key = ctx.server.cursor_key
|
||||
rows = read(decode_cursor(cursor, scope, key) if cursor is not None else FIRST, count + 1)
|
||||
return {"items": rows[:count],
|
||||
"next_cursor": encode_cursor(scope, rows[count - 1], key) if len(rows) > count else None}
|
||||
|
||||
|
||||
def create_user(ctx):
|
||||
body = ctx.json_body()
|
||||
only_fields(body, ("username", "display_name", "password"))
|
||||
username = body["username"]
|
||||
if not isinstance(username, str) or not USERNAME.fullmatch(username):
|
||||
raise bad("Некорректный username")
|
||||
name = clean_text(body["display_name"], 1, 100, "display_name")
|
||||
if not valid_password(body["password"]):
|
||||
raise bad("Некорректный password")
|
||||
try:
|
||||
return 201, ctx.store.register(username, name, password_hash(body["password"]))
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409, "conflict", "Username уже занят")
|
||||
|
||||
|
||||
def login(ctx):
|
||||
if ctx.content_length():
|
||||
raise bad("Вход принимает только Basic Authorization")
|
||||
credentials = parse_basic(ctx.header("Authorization"))
|
||||
if not credentials:
|
||||
raise unauthorized("Basic")
|
||||
username, password = credentials
|
||||
user, stored = ctx.store.credential(username)
|
||||
if not verify_password(password, stored):
|
||||
raise unauthorized("Basic")
|
||||
token, expires = ctx.server.sessions.issue(user["id"])
|
||||
return 201, {"token": token, "token_type": "Bearer", "expires_at": expires, "user": user}
|
||||
|
||||
|
||||
def logout(ctx):
|
||||
if not ctx.server.sessions.revoke(ctx.token):
|
||||
raise unauthorized("Bearer")
|
||||
return 204, None
|
||||
|
||||
|
||||
def get_me(ctx):
|
||||
return 200, ctx.user
|
||||
|
||||
|
||||
def create_chat(ctx):
|
||||
body = ctx.json_body()
|
||||
only_fields(body, ("title", "member_ids"))
|
||||
title = clean_text(body["title"], 1, 100, "title")
|
||||
ids = body["member_ids"]
|
||||
if not isinstance(ids, list) or not 1 <= len(ids) <= 100:
|
||||
raise bad("member_ids: от 1 до 100 элементов")
|
||||
members = [parse_uuid(value) for value in ids]
|
||||
if len(set(members)) != len(members) or ctx.user["id"] not in members:
|
||||
raise bad("member_ids: дубликаты или нет вызывающего")
|
||||
try:
|
||||
return 201, ctx.store.create_chat(title, members)
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise bad("member_ids: неизвестный пользователь")
|
||||
|
||||
|
||||
def list_chats(ctx):
|
||||
user_id = ctx.user["id"]
|
||||
return 200, page(ctx, f"chats:{user_id}", lambda cursor, n: ctx.store.chats(user_id, cursor, n))
|
||||
|
||||
|
||||
def visible_chat(ctx, chat_id):
|
||||
chat = ctx.store.chat(ctx.user["id"], parse_uuid(chat_id))
|
||||
if chat is None:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
|
||||
def get_chat(ctx, chat_id):
|
||||
return 200, visible_chat(ctx, chat_id)
|
||||
|
||||
|
||||
def create_message(ctx, chat_id):
|
||||
chat = visible_chat(ctx, chat_id)
|
||||
body = ctx.json_body()
|
||||
only_fields(body, ("text",), ("attachment_ids",))
|
||||
items = body.get("attachment_ids", [])
|
||||
if not isinstance(items, list) or len(items) > 10:
|
||||
raise bad("attachment_ids: от 0 до 10 элементов")
|
||||
attachment_ids = [parse_uuid(value) for value in items]
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise bad("attachment_ids: дубликаты")
|
||||
raw_text = body["text"]
|
||||
if raw_text == "" and attachment_ids:
|
||||
text = ""
|
||||
else:
|
||||
text = clean_text(raw_text, 1, 4000, "text")
|
||||
key = ctx.header("Idempotency-Key")
|
||||
if not IDEMPOTENCY_KEY.fullmatch(key):
|
||||
raise bad("Некорректный или отсутствующий Idempotency-Key")
|
||||
try:
|
||||
with tm.span("db.message.write", tm.SpanKind.CLIENT):
|
||||
return 201, ctx.store.message(ctx.user["id"], chat["id"], text, key, attachment_ids)
|
||||
except KeyConflict:
|
||||
raise ApiError(409, "conflict", "Ключ уже использован для другого сообщения")
|
||||
except MissingAttachment:
|
||||
raise not_found()
|
||||
except UnusableAttachment:
|
||||
raise ApiError(409, "conflict", "Вложение недоступно")
|
||||
|
||||
|
||||
def list_messages(ctx, chat_id):
|
||||
cid = visible_chat(ctx, chat_id)["id"]
|
||||
return 200, page(ctx, f"messages:{cid}", lambda cursor, n: ctx.store.messages(cid, cursor, n))
|
||||
|
||||
|
||||
def upload_attachment(ctx, chat_id):
|
||||
chat = visible_chat(ctx, chat_id)
|
||||
filename = clean_text(ctx.param("filename"), 1, 255, "filename")
|
||||
if any(char in "/\\" or unicodedata.category(char) == "Cc" for char in filename):
|
||||
raise bad("Некорректное имя файла")
|
||||
mime = ctx.header("Content-Type").split(";")[0].strip().lower()
|
||||
if mime not in ("image/jpeg", "image/png"):
|
||||
raise ApiError(415, "unsupported_media_type", "Поддерживаются PNG и JPEG")
|
||||
with ctx.server.image_slot, spool() as file:
|
||||
length = ctx.stream_body(file)
|
||||
try:
|
||||
verify_image(file, mime)
|
||||
except BadImage:
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение")
|
||||
except PixelLimit:
|
||||
raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей")
|
||||
objects = ctx.server.objects
|
||||
row = ctx.store.save_attachment(
|
||||
chat["id"], ctx.user["id"], filename, mime, length,
|
||||
lambda item: objects.put(objects.key(item, "staging"), file, mime, length),
|
||||
Jsonb(tm.carrier()),
|
||||
)
|
||||
return 202, public_attachment(row)
|
||||
|
||||
|
||||
def public_attachment(row):
|
||||
return {key: value for key, value in row.items() if key != "pipeline_version"}
|
||||
|
||||
|
||||
def get_metadata(ctx, attachment_id):
|
||||
row = ctx.store.attachment(ctx.user["id"], parse_uuid(attachment_id))
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return 200, public_attachment(row)
|
||||
|
||||
|
||||
def download_attachment(ctx, attachment_id):
|
||||
row = ctx.store.attachment(ctx.user["id"], parse_uuid(attachment_id))
|
||||
if row is None:
|
||||
raise not_found()
|
||||
if row["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "Вложение ещё недоступно")
|
||||
variant = ctx.param("variant", "original")
|
||||
variants = {item["name"]: item["content_type"] for item in row["variants"]}
|
||||
if variant != "original" and variant not in variants:
|
||||
raise not_found()
|
||||
objects = ctx.server.objects
|
||||
ctx.content_type = row["content_type"] if variant == "original" else variants[variant]
|
||||
key = objects.result_key(row["id"], row["pipeline_version"], variant)
|
||||
return 200, objects.get(key)
|
||||
|
||||
|
||||
def live(ctx):
|
||||
return 200, {"status": "ok"}
|
||||
|
||||
|
||||
def ready(ctx):
|
||||
if ctx.server.stopping.is_set():
|
||||
raise ApiError(503, "unavailable", "Сервер завершает работу")
|
||||
with tm.span("db.readiness", tm.SpanKind.CLIENT):
|
||||
ctx.store.ready()
|
||||
with tm.span("redis.readiness", tm.SpanKind.CLIENT):
|
||||
ctx.server.sessions.redis.ping()
|
||||
with tm.span("s3.readiness", tm.SpanKind.CLIENT):
|
||||
ctx.server.objects.ready()
|
||||
return live(ctx)
|
||||
|
||||
|
||||
ROUTES = [(method, re.compile(path), action, authenticated) for method, path, action, authenticated in (
|
||||
("GET", r"/health/live", live, False),
|
||||
("GET", r"/health/ready", ready, False),
|
||||
("POST", r"/api/v1/users", create_user, False),
|
||||
("POST", r"/api/v1/auth/sessions", login, False),
|
||||
("DELETE", r"/api/v1/auth/sessions/current", logout, True),
|
||||
("GET", r"/api/v1/users/me", get_me, True),
|
||||
("POST", r"/api/v1/chats", create_chat, True),
|
||||
("GET", r"/api/v1/chats", list_chats, True),
|
||||
("GET", r"/api/v1/chats/([^/]+)", get_chat, True),
|
||||
("POST", r"/api/v1/chats/([^/]+)/messages", create_message, True),
|
||||
("GET", r"/api/v1/chats/([^/]+)/messages", list_messages, True),
|
||||
("POST", r"/api/v1/chats/([^/]+)/attachments", upload_attachment, True),
|
||||
("GET", r"/api/v1/attachments/([^/]+)", get_metadata, True),
|
||||
("GET", r"/api/v1/attachments/([^/]+)/content", download_attachment, True),
|
||||
)]
|
||||
|
||||
|
||||
class Context:
|
||||
def __init__(self, handler):
|
||||
self.handler = handler
|
||||
self.server = handler.server
|
||||
self.store = self.server.store
|
||||
self.user = self.token = None
|
||||
self.body_read = False
|
||||
self.route = "unmatched"
|
||||
self.content_type = None
|
||||
|
||||
def header(self, name):
|
||||
values = self.handler.headers.get_all(name, [])
|
||||
return values[0] if len(values) == 1 else ""
|
||||
|
||||
def param(self, name, default=None):
|
||||
values = self.query.get(name, [])
|
||||
if len(values) > 1:
|
||||
raise bad(f"Повторяющийся параметр {name}")
|
||||
return values[0] if values else default
|
||||
|
||||
def content_length(self):
|
||||
if self.handler.headers.get_all("Transfer-Encoding"):
|
||||
raise bad("Нужен запрос с Content-Length")
|
||||
if not self.handler.headers.get_all("Content-Length"):
|
||||
return 0
|
||||
value = self.header("Content-Length")
|
||||
if not LENGTH.fullmatch(value):
|
||||
raise bad("Некорректный Content-Length")
|
||||
return int(value)
|
||||
|
||||
def read_body(self, limit):
|
||||
length = self.content_length()
|
||||
if length > limit:
|
||||
raise ApiError(413, "payload_too_large", "Слишком большое тело запроса")
|
||||
try:
|
||||
raw = self.handler.rfile.read(length)
|
||||
except TimeoutError:
|
||||
raise bad("Таймаут чтения тела")
|
||||
self.body_read = True
|
||||
if len(raw) != length:
|
||||
raise bad("Тело запроса получено не полностью")
|
||||
return raw
|
||||
|
||||
def json_body(self):
|
||||
raw = self.read_body(MAX_BODY)
|
||||
if self.header("Content-Type").split(";")[0].strip().lower() != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
except (ValueError, RecursionError):
|
||||
raise bad("Некорректный JSON")
|
||||
|
||||
def stream_body(self, file):
|
||||
length = self.content_length()
|
||||
if length > MAX_UPLOAD:
|
||||
raise ApiError(413, "payload_too_large", "Слишком большой файл")
|
||||
remaining = length
|
||||
deadline = time.monotonic() + 10
|
||||
while remaining:
|
||||
timeout = deadline - time.monotonic()
|
||||
if timeout <= 0:
|
||||
raise bad("Таймаут загрузки")
|
||||
self.handler.connection.settimeout(timeout)
|
||||
try:
|
||||
chunk = self.handler.rfile.read1(min(remaining, 64 * 1024))
|
||||
except TimeoutError:
|
||||
raise bad("Таймаут загрузки")
|
||||
if not chunk:
|
||||
raise bad("Тело запроса получено не полностью")
|
||||
file.write(chunk)
|
||||
remaining -= len(chunk)
|
||||
self.body_read = True
|
||||
file.seek(0)
|
||||
return length
|
||||
|
||||
def authenticate(self):
|
||||
self.token = parse_bearer(self.header("Authorization"))
|
||||
if self.token:
|
||||
user_id = self.server.sessions.get(self.token)
|
||||
if user_id:
|
||||
self.user = self.store.user(user_id)
|
||||
if self.user:
|
||||
return
|
||||
raise unauthorized("Bearer")
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
server_version = "messenger"
|
||||
sys_version = ""
|
||||
timeout = 8
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def dispatch(self, ctx):
|
||||
try:
|
||||
parts = urlsplit(self.path)
|
||||
ctx.query = parse_qs(parts.query, keep_blank_values=True, max_num_fields=32)
|
||||
except ValueError:
|
||||
raise bad("Некорректный URL")
|
||||
for method, pattern, action, authenticated in ROUTES:
|
||||
if method == self.command and (match := pattern.fullmatch(parts.path)):
|
||||
resource = "{attachment_id}" if pattern.pattern.startswith("/api/v1/attachments/") else "{chat_id}"
|
||||
ctx.route = pattern.pattern.replace("([^/]+)", resource)
|
||||
if self.server.stopping.is_set() and action != live:
|
||||
raise ApiError(503, "unavailable", "Сервер завершает работу")
|
||||
if authenticated:
|
||||
ctx.authenticate()
|
||||
return action(ctx, *match.groups())
|
||||
raise not_found()
|
||||
|
||||
def handle_any(self):
|
||||
incoming = {name: self.headers.get(name, "") for name in ("traceparent", "tracestate")}
|
||||
with tm.span("HTTP", tm.SpanKind.SERVER, incoming) as active:
|
||||
self.respond(active)
|
||||
|
||||
def respond(self, active):
|
||||
started = time.monotonic()
|
||||
request_id = str(uuid4())
|
||||
ctx = Context(self)
|
||||
headers = {}
|
||||
error = None
|
||||
try:
|
||||
status, payload = self.dispatch(ctx)
|
||||
except ApiError as exc:
|
||||
error = exc
|
||||
except (RedisError, BotoCoreError, ClientError, PoolTimeout, psycopg.OperationalError, psycopg.errors.QueryCanceled,
|
||||
psycopg.errors.LockNotAvailable):
|
||||
error = ApiError(503, "unavailable", "Хранилище временно недоступно")
|
||||
except Exception as exc:
|
||||
tm.record("http_exception", request_id=request_id, exception_type=type(exc).__name__)
|
||||
error = ApiError(500, "internal_error", "Внутренняя ошибка")
|
||||
if error:
|
||||
status, headers = error.status, error.headers
|
||||
payload = {"error": {"code": error.code, "message": error.message, "request_id": request_id}}
|
||||
self.close_connection = True # Rejected bodies are never parsed as a next request.
|
||||
if isinstance(payload, bytes):
|
||||
data, content_type = payload, ctx.content_type
|
||||
else:
|
||||
content_type = "application/json; charset=utf-8"
|
||||
data = b"" if status == 204 else json.dumps(payload, default=json_value, ensure_ascii=False).encode()
|
||||
try:
|
||||
self.send_response(status)
|
||||
if status != 204:
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("X-Request-Id", request_id)
|
||||
self.send_header("X-Instance-Id", self.server.instance_id)
|
||||
self.send_header("Connection", "close")
|
||||
for name, value in headers.items():
|
||||
self.send_header(name, value)
|
||||
self.end_headers()
|
||||
if data:
|
||||
self.wfile.write(data)
|
||||
except (OSError, TimeoutError):
|
||||
pass
|
||||
duration = time.monotonic() - started
|
||||
tm.observe_http(active, self.command, ctx.route, status, duration)
|
||||
tm.observe_process(ctx.store.pool)
|
||||
tm.record("http_request", method=self.command, route=ctx.route, status=status,
|
||||
duration_ms=round(duration * 1000, 2), request_id=request_id)
|
||||
|
||||
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
|
||||
|
||||
|
||||
class Server(ThreadingHTTPServer):
|
||||
request_queue_size = 64
|
||||
daemon_threads = False
|
||||
|
||||
def __init__(self, address):
|
||||
super().__init__(address, Handler)
|
||||
self.stopping = threading.Event()
|
||||
self.instance_id = uuid4().hex
|
||||
self.workers = threading.BoundedSemaphore(16)
|
||||
self.cursor_key = setting("CURSOR_KEY").encode()
|
||||
self.store = Store()
|
||||
self.sessions = Sessions()
|
||||
self.objects = Objects()
|
||||
self.image_slot = threading.BoundedSemaphore(1)
|
||||
|
||||
def process_request(self, request, address):
|
||||
if not self.workers.acquire(blocking=False):
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
try:
|
||||
super().process_request(request, address)
|
||||
except BaseException:
|
||||
self.workers.release()
|
||||
raise
|
||||
|
||||
def process_request_thread(self, request, address):
|
||||
try:
|
||||
super().process_request_thread(request, address)
|
||||
finally:
|
||||
self.workers.release()
|
||||
|
||||
|
||||
def main():
|
||||
address = os.environ.get("APP_HOST", "0.0.0.0"), int(os.environ.get("APP_PORT", "8080"))
|
||||
with Server(address) as server:
|
||||
tm.setup("api", server.instance_id)
|
||||
def stop(signum, frame):
|
||||
if not server.stopping.is_set():
|
||||
server.stopping.set()
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
server.server_close()
|
||||
server.store.pool.close()
|
||||
server.sessions.redis.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Validate binary uploads and keep original data in a private S3 bucket."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import warnings
|
||||
from contextlib import closing
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from PIL import Image
|
||||
|
||||
from db import setting
|
||||
|
||||
MAX_UPLOAD = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
MEDIA_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||
|
||||
|
||||
class BadImage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PixelLimit(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def verify_image(file, mime):
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(file) as image:
|
||||
if image.width * image.height > MAX_PIXELS:
|
||||
raise PixelLimit()
|
||||
if MEDIA_TYPES.get(image.format) != mime:
|
||||
raise BadImage()
|
||||
if getattr(image, "n_frames", 1) != 1:
|
||||
raise BadImage()
|
||||
image.verify()
|
||||
file.seek(0)
|
||||
with Image.open(file) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise PixelLimit() from None
|
||||
except (OSError, SyntaxError, ValueError):
|
||||
raise BadImage() from None
|
||||
finally:
|
||||
file.seek(0)
|
||||
|
||||
|
||||
class Objects:
|
||||
def __init__(self):
|
||||
self.bucket = os.environ.get("S3_BUCKET", "attachments")
|
||||
self.client = boto3.client(
|
||||
"s3", endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
|
||||
aws_access_key_id=setting("S3_ACCESS_KEY"),
|
||||
aws_secret_access_key=setting("S3_SECRET_KEY"),
|
||||
region_name="us-east-1", verify=os.environ.get("S3_CA_FILE") or True,
|
||||
config=Config(connect_timeout=2, read_timeout=4, retries={"total_max_attempts": 1},
|
||||
max_pool_connections=16, s3={"addressing_style": "path"},
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required"),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def key(attachment_id, variant="original"):
|
||||
return f"{variant}/{attachment_id}"
|
||||
|
||||
@staticmethod
|
||||
def result_key(attachment_id, version, variant):
|
||||
if version == 0:
|
||||
return Objects.key(attachment_id, variant)
|
||||
return f"results/v{version}/{variant}/{attachment_id}"
|
||||
|
||||
def ready(self):
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
|
||||
def put(self, key, file, mime, length):
|
||||
digest = hashlib.file_digest(file, "sha256").hexdigest()
|
||||
file.seek(0)
|
||||
self.client.put_object(Bucket=self.bucket, Key=key, Body=file,
|
||||
ContentType=mime, ContentLength=length)
|
||||
return digest
|
||||
|
||||
def get(self, key):
|
||||
result = self.client.get_object(Bucket=self.bucket, Key=key)
|
||||
with closing(result["Body"]) as body:
|
||||
data = body.read(MAX_UPLOAD + 1)
|
||||
if len(data) > MAX_UPLOAD:
|
||||
raise ValueError("object exceeds configured limit")
|
||||
return data
|
||||
|
||||
def has(self, key):
|
||||
try:
|
||||
self.client.head_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as error:
|
||||
if str(error.response["Error"]["Code"]) in ("404", "NotFound", "NoSuchKey"):
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
def delete(self, key):
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
|
||||
|
||||
def spool():
|
||||
return tempfile.SpooledTemporaryFile(max_size=512 * 1024, mode="w+b")
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
"""Password verification and revocable Redis-backed sessions."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from redis import Redis
|
||||
|
||||
from db import setting
|
||||
|
||||
|
||||
USERNAME = re.compile(r"[a-z0-9_]{3,32}")
|
||||
TOKEN = re.compile(r"[A-Za-z0-9_-]{43}")
|
||||
|
||||
|
||||
def valid_password(password):
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
return False
|
||||
try:
|
||||
password.encode("utf-8")
|
||||
except UnicodeEncodeError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def password_hash(password, salt=None):
|
||||
if salt is None:
|
||||
salt = secrets.token_bytes(16)
|
||||
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=3)
|
||||
return f"scrypt:{salt.hex()}:{digest.hex()}"
|
||||
|
||||
|
||||
DUMMY_HASH = password_hash("dummy unknown account")
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
_, salt, _ = (stored or DUMMY_HASH).split(":")
|
||||
actual = password_hash(password, bytes.fromhex(salt))
|
||||
return hmac.compare_digest(actual, stored or DUMMY_HASH) and stored is not None
|
||||
|
||||
|
||||
def parse_basic(value):
|
||||
scheme, _, data = value.partition(" ")
|
||||
if scheme.lower() != "basic" or not 1 <= len(data) <= 1024:
|
||||
return None
|
||||
try:
|
||||
username, sep, password = base64.b64decode(data, validate=True).decode("utf-8").partition(":")
|
||||
except (ValueError, UnicodeError):
|
||||
return None
|
||||
if sep and USERNAME.fullmatch(username) and valid_password(password):
|
||||
return username, password
|
||||
return None
|
||||
|
||||
|
||||
def parse_bearer(value):
|
||||
scheme, _, token = value.partition(" ")
|
||||
if scheme.lower() == "bearer" and TOKEN.fullmatch(token):
|
||||
return token
|
||||
return None
|
||||
|
||||
|
||||
class Sessions:
|
||||
def __init__(self):
|
||||
self.redis = Redis.from_url(
|
||||
setting("CACHE_URL"), socket_timeout=2, socket_connect_timeout=2,
|
||||
max_connections=24, decode_responses=True,
|
||||
)
|
||||
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
if self.ttl < 1:
|
||||
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
||||
|
||||
@staticmethod
|
||||
def key(token):
|
||||
return "messenger:session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
def issue(self, user_id):
|
||||
token = secrets.token_urlsafe(32)
|
||||
seconds, micros = self.redis.time()
|
||||
expires_ms = seconds * 1000 + micros // 1000 + self.ttl * 1000
|
||||
self.redis.set(self.key(token), str(user_id), pxat=expires_ms)
|
||||
return token, datetime.fromtimestamp(expires_ms / 1000, timezone.utc)
|
||||
|
||||
def get(self, token):
|
||||
return self.redis.get(self.key(token))
|
||||
|
||||
def revoke(self, token):
|
||||
return bool(self.redis.delete(self.key(token)))
|
||||
@@ -0,0 +1,221 @@
|
||||
"""PostgreSQL migrations, transactional writes and keyset reads."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
def setting(name):
|
||||
path = os.environ.get(name + "_FILE")
|
||||
return Path(path).read_text(encoding="utf-8").strip() if path else os.environ[name]
|
||||
|
||||
|
||||
def connection_string():
|
||||
return make_conninfo(
|
||||
setting("DATABASE_URL"),
|
||||
connect_timeout=3,
|
||||
options="-c statement_timeout=4000 -c lock_timeout=2500",
|
||||
)
|
||||
|
||||
|
||||
def migrate():
|
||||
with psycopg.connect(connection_string(), autocommit=True) as connection:
|
||||
migrations = Path(__file__).with_name("migrations")
|
||||
with connection.transaction():
|
||||
connection.execute("SELECT pg_advisory_xact_lock(17002026)")
|
||||
connection.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
""")
|
||||
for file in sorted(migrations.glob("*.sql")):
|
||||
with connection.transaction():
|
||||
connection.execute("SELECT pg_advisory_xact_lock(17002026)")
|
||||
if connection.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE name = %s", (file.name,)
|
||||
).fetchone():
|
||||
continue
|
||||
connection.execute(file.read_text(encoding="utf-8"))
|
||||
connection.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (file.name,))
|
||||
|
||||
|
||||
class KeyConflict(Exception):
|
||||
"""The same active idempotency key has a different canonical request."""
|
||||
|
||||
|
||||
class MissingAttachment(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnusableAttachment(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def lock_attachment(connection, attachment_id):
|
||||
connection.execute(
|
||||
"SELECT pg_advisory_xact_lock(hashtextextended(%s, 4412))", (str(attachment_id),)
|
||||
)
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.pool = ConnectionPool(
|
||||
connection_string(), min_size=1, max_size=8, timeout=2, open=False,
|
||||
kwargs={"row_factory": dict_row},
|
||||
)
|
||||
self.pool.open()
|
||||
|
||||
def ready(self):
|
||||
with self.pool.connection() as connection:
|
||||
connection.execute("SELECT 1")
|
||||
|
||||
def register(self, username, display_name, password_hash):
|
||||
with self.pool.connection() as connection:
|
||||
return connection.execute("""
|
||||
INSERT INTO users(id, username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""", (uuid4(), username, display_name, password_hash)).fetchone()
|
||||
|
||||
def credential(self, username):
|
||||
with self.pool.connection() as connection:
|
||||
user = connection.execute("""
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = %s
|
||||
""", (username,)).fetchone()
|
||||
if user:
|
||||
return user, user.pop("password_hash")
|
||||
return None, None
|
||||
|
||||
def user(self, user_id):
|
||||
with self.pool.connection() as connection:
|
||||
return connection.execute("""
|
||||
SELECT id, username, display_name, created_at FROM users WHERE id = %s
|
||||
""", (user_id,)).fetchone()
|
||||
|
||||
def create_chat(self, title, members):
|
||||
with self.pool.connection() as connection:
|
||||
chat = connection.execute("""
|
||||
INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING *
|
||||
""", (uuid4(), title)).fetchone()
|
||||
connection.execute("""
|
||||
INSERT INTO chat_members(chat_id, user_id, position)
|
||||
SELECT %s, member, ord FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(member, ord)
|
||||
""", (chat["id"], members))
|
||||
return {**chat, "member_ids": members}
|
||||
|
||||
def chat(self, user_id, chat_id):
|
||||
with self.pool.connection() as connection:
|
||||
return connection.execute("""
|
||||
SELECT c.*, ARRAY(SELECT user_id FROM chat_members m
|
||||
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
|
||||
FROM chats c JOIN chat_members membership ON membership.chat_id = c.id
|
||||
WHERE membership.user_id = %s AND c.id = %s
|
||||
""", (user_id, chat_id)).fetchone()
|
||||
|
||||
def chats(self, user_id, cursor, count):
|
||||
with self.pool.connection() as connection:
|
||||
return connection.execute("""
|
||||
SELECT c.*, ARRAY(SELECT m.user_id FROM chat_members m
|
||||
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
|
||||
FROM chats c JOIN chat_members membership ON membership.chat_id = c.id
|
||||
WHERE membership.user_id = %s
|
||||
AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)
|
||||
ORDER BY c.created_at, c.id LIMIT %s
|
||||
""", (user_id, *cursor, count)).fetchall()
|
||||
|
||||
def message(self, user_id, chat_id, text, key, attachment_ids):
|
||||
scope = (user_id, chat_id, key)
|
||||
# Existing text-only requests still compare the same after migration.
|
||||
body = {"text": text}
|
||||
if attachment_ids:
|
||||
body["attachment_ids"] = [str(value) for value in attachment_ids]
|
||||
fingerprint = hashlib.sha256(json.dumps(body, separators=(",", ":")).encode()).digest()
|
||||
with self.pool.connection() as connection:
|
||||
accepted = connection.execute("""
|
||||
INSERT INTO message_requests(user_id, chat_id, request_key, fingerprint)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON CONFLICT (user_id, chat_id, request_key) DO UPDATE
|
||||
SET fingerprint = EXCLUDED.fingerprint, message_id = NULL,
|
||||
expires_at = clock_timestamp() + interval '24 hours'
|
||||
WHERE message_requests.expires_at <= clock_timestamp()
|
||||
RETURNING request_key
|
||||
""", (*scope, fingerprint)).fetchone()
|
||||
if accepted:
|
||||
self.check_attachments(connection, chat_id, attachment_ids)
|
||||
message = self.insert_message(connection, user_id, chat_id, text, attachment_ids)
|
||||
connection.execute("""
|
||||
UPDATE message_requests SET message_id = %s
|
||||
WHERE user_id = %s AND chat_id = %s AND request_key = %s
|
||||
""", (message["id"], *scope))
|
||||
return message
|
||||
existing = connection.execute("""
|
||||
SELECT m.*, r.fingerprint
|
||||
FROM message_requests r JOIN messages m ON m.id = r.message_id
|
||||
WHERE r.user_id = %s AND r.chat_id = %s AND r.request_key = %s
|
||||
""", scope).fetchone()
|
||||
if existing.pop("fingerprint") != fingerprint:
|
||||
raise KeyConflict()
|
||||
return existing
|
||||
|
||||
def check_attachments(self, connection, chat_id, attachment_ids):
|
||||
if not attachment_ids:
|
||||
return
|
||||
rows = connection.execute("""
|
||||
SELECT id, status FROM attachments
|
||||
WHERE chat_id = %s AND id = ANY(%s::uuid[])
|
||||
ORDER BY id FOR SHARE
|
||||
""", (chat_id, attachment_ids)).fetchall()
|
||||
if len(rows) != len(attachment_ids):
|
||||
raise MissingAttachment()
|
||||
if any(row["status"] == "failed" for row in rows):
|
||||
raise UnusableAttachment()
|
||||
|
||||
def insert_message(self, connection, user_id, chat_id, text, attachment_ids):
|
||||
return connection.execute("""
|
||||
INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids)
|
||||
VALUES (%s, %s, %s, %s, %s::uuid[])
|
||||
RETURNING *
|
||||
""", (uuid4(), chat_id, user_id, text, attachment_ids)).fetchone()
|
||||
|
||||
def save_attachment(self, chat_id, user_id, filename, mime, length, store_original, trace_context):
|
||||
attachment_id = uuid4()
|
||||
with self.pool.connection() as connection:
|
||||
lock_attachment(connection, attachment_id)
|
||||
digest = store_original(attachment_id)
|
||||
attachment = connection.execute("""
|
||||
INSERT INTO attachments(id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, status, pipeline_version)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued', 1) RETURNING *
|
||||
""", (attachment_id, chat_id, user_id, filename, mime, length, digest)).fetchone()
|
||||
connection.execute("""
|
||||
INSERT INTO image_jobs(id, attachment_id, pipeline_version, trace_context)
|
||||
VALUES (%s, %s, 1, %s)
|
||||
""", (uuid4(), attachment_id, trace_context))
|
||||
return attachment
|
||||
|
||||
def attachment(self, user_id, attachment_id):
|
||||
with self.pool.connection() as connection:
|
||||
return connection.execute("""
|
||||
SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id
|
||||
WHERE a.id = %s AND m.user_id = %s
|
||||
""", (attachment_id, user_id)).fetchone()
|
||||
|
||||
def messages(self, chat_id, cursor, count):
|
||||
with self.pool.connection() as connection:
|
||||
return connection.execute("""
|
||||
SELECT * FROM messages
|
||||
WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid)
|
||||
ORDER BY created_at, id LIMIT %s
|
||||
""", (chat_id, *cursor, count)).fetchall()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
migrate()
|
||||
@@ -0,0 +1,33 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE INDEX chats_page ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
position integer NOT NULL CHECK (position > 0),
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
UNIQUE (chat_id, position)
|
||||
);
|
||||
CREATE INDEX chat_members_by_user ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX messages_page ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE message_requests (
|
||||
user_id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL,
|
||||
request_key text NOT NULL,
|
||||
fingerprint bytea NOT NULL,
|
||||
expires_at timestamptz NOT NULL DEFAULT (clock_timestamp() + interval '24 hours'),
|
||||
message_id uuid REFERENCES messages(id),
|
||||
PRIMARY KEY (user_id, chat_id, request_key),
|
||||
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL,
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready', 'failed')),
|
||||
variants jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX attachments_recent ON attachments(created_at, id);
|
||||
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT ARRAY[]::uuid[];
|
||||
@@ -0,0 +1,19 @@
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
|
||||
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE TABLE image_jobs (
|
||||
id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version > 0),
|
||||
attempt integer NOT NULL DEFAULT 0,
|
||||
state text NOT NULL DEFAULT 'waiting' CHECK (state IN ('waiting', 'leased', 'done', 'failed')),
|
||||
next_run timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
leased_until timestamptz,
|
||||
published_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
trace_context jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
UNIQUE (attachment_id, pipeline_version)
|
||||
);
|
||||
|
||||
CREATE INDEX image_jobs_pending ON image_jobs(next_run, id) WHERE state IN ('waiting', 'leased');
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
"""Durable PostgreSQL outbox, Redis Streams relay and leased image processing."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import psycopg
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import PoolTimeout
|
||||
from redis import Redis
|
||||
from redis.exceptions import RedisError, ResponseError
|
||||
|
||||
from attachments import Objects
|
||||
from db import Store, setting
|
||||
import telemetry as tm
|
||||
|
||||
STREAM = "messenger:images"
|
||||
GROUP = "image-workers"
|
||||
MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))
|
||||
LEASE_SECONDS = 45
|
||||
CHILD_TIMEOUT = 15
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
|
||||
|
||||
class PermanentImageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def connect_broker():
|
||||
return Redis.from_url(setting("BROKER_URL"), socket_timeout=3, socket_connect_timeout=2,
|
||||
decode_responses=True)
|
||||
|
||||
|
||||
def settle(connection, job, outcome, code=None):
|
||||
waiting = outcome == "waiting"
|
||||
delay = min(20, 2 ** job["attempt"]) * random.uniform(0.8, 1.2) if waiting else 0
|
||||
connection.execute("""
|
||||
UPDATE image_jobs SET state = %s, leased_until = NULL, published_at = NULL,
|
||||
next_run = clock_timestamp() + %s * interval '1 second'
|
||||
WHERE id = %s
|
||||
""", (outcome, delay, job["id"]))
|
||||
if outcome != "done":
|
||||
connection.execute("""
|
||||
UPDATE attachments SET status = %s, error_code = %s, updated_at = clock_timestamp()
|
||||
WHERE id = %s AND pipeline_version = %s
|
||||
""", ("queued" if waiting else "failed", None if waiting else code,
|
||||
job["attachment_id"], job["pipeline_version"]))
|
||||
|
||||
|
||||
def relay_once(store, broker):
|
||||
with store.pool.connection() as connection:
|
||||
row = connection.execute("""
|
||||
SELECT * FROM image_jobs
|
||||
WHERE ((state = 'waiting' AND next_run <= clock_timestamp())
|
||||
OR (state = 'leased' AND leased_until <= clock_timestamp()))
|
||||
AND (published_at IS NULL OR published_at <= clock_timestamp() - interval '50 seconds')
|
||||
ORDER BY next_run, id FOR UPDATE SKIP LOCKED LIMIT 1
|
||||
""").fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
message = {
|
||||
"schema_version": 1, "job_id": str(row["id"]), "type": JOB_TYPE,
|
||||
"attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"],
|
||||
"attempt": row["attempt"] + 1,
|
||||
"created_at": row["created_at"].astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
with tm.span("image.publish", tm.SpanKind.PRODUCER, row["trace_context"]):
|
||||
message.update(tm.carrier())
|
||||
broker.xadd(STREAM, {"job": json.dumps(message, separators=(",", ":"))})
|
||||
tm.record("job_published", job_type=JOB_TYPE)
|
||||
connection.execute("UPDATE image_jobs SET published_at = clock_timestamp() WHERE id = %s",
|
||||
(row["id"],))
|
||||
return True
|
||||
|
||||
|
||||
def claim(store, message):
|
||||
with store.pool.connection() as connection:
|
||||
job = connection.execute("""
|
||||
SELECT j.*, a.content_type, a.sha256, a.size_bytes,
|
||||
a.pipeline_version AS active_version,
|
||||
j.leased_until > clock_timestamp() AS lease_active,
|
||||
j.next_run > clock_timestamp() AS too_early
|
||||
FROM image_jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = %s FOR UPDATE OF j, a
|
||||
""", (UUID(message["job_id"]),)).fetchone()
|
||||
if not job or job["state"] in ("done", "failed"):
|
||||
return None
|
||||
if job["pipeline_version"] != job["active_version"]:
|
||||
settle(connection, job, "done")
|
||||
return None
|
||||
if job["lease_active"] or job["too_early"]:
|
||||
return None
|
||||
if job["attempt"] >= MAX_ATTEMPTS:
|
||||
settle(connection, job, "failed", "retry_exhausted")
|
||||
return None
|
||||
job["attempt"] += 1
|
||||
connection.execute("""
|
||||
UPDATE image_jobs SET state = 'leased', attempt = %s,
|
||||
leased_until = clock_timestamp() + %s * interval '1 second'
|
||||
WHERE id = %s
|
||||
""", (job["attempt"], LEASE_SECONDS, job["id"]))
|
||||
connection.execute("""
|
||||
UPDATE attachments SET status='processing', updated_at = clock_timestamp() WHERE id=%s
|
||||
""", (job["attachment_id"],))
|
||||
return job
|
||||
|
||||
|
||||
def encode_images(original, version):
|
||||
with tempfile.TemporaryDirectory(prefix="messenger-image-") as name:
|
||||
root = Path(name)
|
||||
(root / "source").write_bytes(original)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "variants", str(root), str(version)], check=False,
|
||||
timeout=CHILD_TIMEOUT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
if result.returncode == 2:
|
||||
raise PermanentImageError()
|
||||
if result.returncode != 0:
|
||||
raise OSError("image subprocess failed")
|
||||
descriptors = json.loads((root / "variants.json").read_text(encoding="utf-8"))
|
||||
return [(descriptor, (root / descriptor["name"]).read_bytes()) for descriptor in descriptors]
|
||||
|
||||
|
||||
def try_publish(store, objects, job):
|
||||
attachment_id, version = job["attachment_id"], job["pipeline_version"]
|
||||
with tm.span("s3.staging.get", tm.SpanKind.CLIENT):
|
||||
original = objects.get(objects.key(attachment_id, "staging"))
|
||||
processed = encode_images(original, version)
|
||||
with store.pool.connection() as connection:
|
||||
current = connection.execute("""
|
||||
SELECT j.attempt, j.state, a.pipeline_version,
|
||||
j.leased_until > clock_timestamp() AS lease_active
|
||||
FROM image_jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = %s FOR UPDATE OF j,a
|
||||
""", (job["id"],)).fetchone()
|
||||
if not current or current["state"] != "leased" or current["attempt"] != job["attempt"]:
|
||||
return "stale"
|
||||
if current["pipeline_version"] != version or not current["lease_active"]:
|
||||
return "stale"
|
||||
with tm.span("s3.variants.put", tm.SpanKind.CLIENT):
|
||||
digest = objects.put(objects.result_key(attachment_id, version, "original"),
|
||||
io.BytesIO(original), job["content_type"], len(original))
|
||||
if digest != job["sha256"] or len(original) != job["size_bytes"]:
|
||||
raise PermanentImageError()
|
||||
variants = []
|
||||
for descriptor, data in processed:
|
||||
name, mime = descriptor["name"], descriptor["content_type"]
|
||||
digest = objects.put(objects.result_key(attachment_id, version, name),
|
||||
io.BytesIO(data), mime, len(data))
|
||||
variants.append({**descriptor, "size_bytes": len(data), "sha256": digest})
|
||||
with tm.span("db.result.update", tm.SpanKind.CLIENT):
|
||||
connection.execute("""
|
||||
UPDATE attachments SET status = 'ready', error_code = NULL, variants = %s,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE id = %s AND pipeline_version = %s
|
||||
""", (Jsonb(variants), attachment_id, version))
|
||||
settle(connection, job, "done")
|
||||
tm.READY_TIME.record((datetime.now(timezone.utc) - job["created_at"]).total_seconds(),
|
||||
{"job_type": JOB_TYPE})
|
||||
return "ready"
|
||||
|
||||
|
||||
def fail(store, job, permanent):
|
||||
with store.pool.connection() as connection:
|
||||
current = connection.execute("""
|
||||
SELECT state, attempt FROM image_jobs WHERE id = %s FOR UPDATE
|
||||
""", (job["id"],)).fetchone()
|
||||
if current != {"state": "leased", "attempt": job["attempt"]}:
|
||||
return "stale"
|
||||
if permanent or job["attempt"] >= MAX_ATTEMPTS:
|
||||
settle(connection, job, "failed", "invalid_image" if permanent else "retry_exhausted")
|
||||
return "failed"
|
||||
settle(connection, job, "waiting")
|
||||
return "retry"
|
||||
|
||||
|
||||
def process(store, objects, message):
|
||||
job = claim(store, message)
|
||||
if job is None:
|
||||
return "ignored"
|
||||
try:
|
||||
return try_publish(store, objects, job)
|
||||
except PermanentImageError:
|
||||
return fail(store, job, permanent=True)
|
||||
except (OSError, subprocess.TimeoutExpired, BotoCoreError, ClientError):
|
||||
return fail(store, job, permanent=False)
|
||||
|
||||
|
||||
def operate_worker(store, broker, stop):
|
||||
try:
|
||||
broker.xgroup_create(STREAM, GROUP, id="0-0", mkstream=True)
|
||||
except ResponseError as exc:
|
||||
if not str(exc).startswith("BUSYGROUP"):
|
||||
raise
|
||||
consumer = uuid4().hex
|
||||
objects = Objects()
|
||||
reclaim_cursor = "0-0"
|
||||
while not stop.is_set():
|
||||
reclaim_cursor, entries, _ = broker.xautoclaim(
|
||||
STREAM, GROUP, consumer, LEASE_SECONDS * 1000, reclaim_cursor, count=1
|
||||
)
|
||||
if not entries:
|
||||
streams = broker.xreadgroup(GROUP, consumer, {STREAM: ">"}, block=500, count=1)
|
||||
entries = streams[0][1] if streams else []
|
||||
for entry_id, fields in entries:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
message = json.loads(fields["job"])
|
||||
if message.get("schema_version") != 1 or message.get("type") != JOB_TYPE:
|
||||
raise ValueError
|
||||
UUID(message["job_id"])
|
||||
except (ValueError, KeyError, TypeError, AttributeError):
|
||||
tm.record("job_invalid")
|
||||
else:
|
||||
with tm.span("image.consume", tm.SpanKind.CONSUMER, message) as active:
|
||||
tm.WORKER_BUSY.set(1)
|
||||
try:
|
||||
outcome = process(store, objects, message)
|
||||
finally:
|
||||
tm.WORKER_BUSY.set(0)
|
||||
elapsed = time.monotonic() - started
|
||||
attributes = {"job_type": JOB_TYPE, "outcome": outcome}
|
||||
active.set_attributes(attributes)
|
||||
if outcome in ("retry", "failed"):
|
||||
active.set_status(tm.Status(tm.StatusCode.ERROR))
|
||||
tm.JOB_COUNT.add(1, attributes)
|
||||
tm.JOB_TIME.record(elapsed, attributes)
|
||||
tm.observe_process(store.pool)
|
||||
tm.record("job_processed", outcome=outcome, duration_s=round(elapsed, 4))
|
||||
# XACK plus XDEL atomically. There is one consumer group on this stream.
|
||||
with broker.pipeline(transaction=True) as pipe:
|
||||
pipe.xack(STREAM, GROUP, entry_id).xdel(STREAM, entry_id).execute()
|
||||
|
||||
|
||||
def backlog(store):
|
||||
with store.pool.connection() as connection:
|
||||
pending = connection.execute("""
|
||||
SELECT count(*) AS depth,
|
||||
COALESCE(EXTRACT(epoch FROM clock_timestamp() - min(created_at)), 0)::float AS oldest
|
||||
FROM image_jobs WHERE state IN ('waiting', 'leased')
|
||||
""").fetchone()
|
||||
tm.QUEUE.set(pending["depth"], {"queue": "images"})
|
||||
tm.OLDEST.set(pending["oldest"], {"queue": "images"})
|
||||
|
||||
|
||||
def main():
|
||||
role = sys.argv[1]
|
||||
stop = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
store, broker = Store(), connect_broker()
|
||||
tm.setup(role, uuid4().hex)
|
||||
next_sample = 0
|
||||
try:
|
||||
while not stop.is_set():
|
||||
try:
|
||||
if role == "worker":
|
||||
operate_worker(store, broker, stop)
|
||||
elif role == "relay":
|
||||
if time.monotonic() >= next_sample:
|
||||
backlog(store)
|
||||
tm.observe_process(store.pool)
|
||||
next_sample = time.monotonic() + 5
|
||||
if not relay_once(store, broker):
|
||||
stop.wait(0.25)
|
||||
else:
|
||||
raise ValueError("Expected worker or relay")
|
||||
except (RedisError, psycopg.OperationalError, psycopg.errors.LockNotAvailable,
|
||||
psycopg.errors.QueryCanceled, PoolTimeout) as exc:
|
||||
tm.record("worker_dependency_unavailable", error_type=type(exc).__name__)
|
||||
stop.wait(1)
|
||||
finally:
|
||||
broker.close()
|
||||
store.pool.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Bounded OTLP SDK pipelines shared by API, relay and worker."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
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.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
PROPAGATOR = TraceContextTextMapPropagator()
|
||||
LOGGER = logging.getLogger("messenger")
|
||||
LOGGER.setLevel(logging.INFO)
|
||||
LOGGER.propagate = False
|
||||
SERVICE = "messenger"
|
||||
METER = metrics.get_meter("messenger")
|
||||
TRACER = trace.get_tracer("messenger")
|
||||
HTTP_COUNT = METER.create_counter("messenger_http_requests")
|
||||
HTTP_TIME = METER.create_histogram("messenger_http_duration", unit="s")
|
||||
JOB_COUNT = METER.create_counter("messenger_jobs")
|
||||
JOB_TIME = METER.create_histogram("messenger_job_duration", unit="s")
|
||||
READY_TIME = METER.create_histogram("messenger_time_to_ready", unit="s")
|
||||
QUEUE = METER.create_gauge("messenger_queue_depth")
|
||||
OLDEST = METER.create_gauge("messenger_oldest_job_age", unit="s")
|
||||
POOL_USED = METER.create_gauge("messenger_db_pool_used")
|
||||
POOL_WAITING = METER.create_gauge("messenger_db_pool_waiting")
|
||||
WORKER_BUSY = METER.create_gauge("messenger_worker_busy")
|
||||
RSS = METER.create_gauge("messenger_process_rss", unit="By")
|
||||
CPU = METER.create_gauge("messenger_process_cpu_time", unit="s")
|
||||
BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60)
|
||||
|
||||
|
||||
def setup(role, instance):
|
||||
global SERVICE
|
||||
SERVICE = f"messenger-{role}"
|
||||
if os.environ.get("TELEMETRY_ENABLED", "1") == "0":
|
||||
return
|
||||
resource = Resource.create({
|
||||
"service.name": SERVICE, "service.version": "lab6",
|
||||
"service.instance.id": instance, "deployment.environment.name": "lab",
|
||||
})
|
||||
ratio = float(os.environ.get("TRACE_SAMPLE_RATE", "1"))
|
||||
sampler = ParentBased(TraceIdRatioBased(ratio), remote_parent_sampled=ALWAYS_OFF if ratio == 0 else TraceIdRatioBased(1))
|
||||
spans = TracerProvider(resource=resource, sampler=sampler)
|
||||
spans.add_span_processor(BatchSpanProcessor(
|
||||
OTLPSpanExporter(timeout=2), max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=500,
|
||||
))
|
||||
trace.set_tracer_provider(spans)
|
||||
logs = LoggerProvider(resource=resource)
|
||||
logs.add_log_record_processor(BatchLogRecordProcessor(
|
||||
OTLPLogExporter(timeout=2), max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=500,
|
||||
))
|
||||
LOGGER.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logs))
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(timeout=2), export_interval_millis=5000, export_timeout_millis=2500,
|
||||
)
|
||||
views = [View(instrument_name=name, aggregation=ExplicitBucketHistogramAggregation(boundaries=BUCKETS))
|
||||
for name in ("messenger_http_duration", "messenger_job_duration", "messenger_time_to_ready")]
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader], views=views))
|
||||
|
||||
|
||||
def carrier():
|
||||
headers = {}
|
||||
PROPAGATOR.inject(headers)
|
||||
return headers
|
||||
|
||||
|
||||
def span(name, kind, parent=None):
|
||||
return TRACER.start_as_current_span(
|
||||
name, kind=kind, context=PROPAGATOR.extract(parent) if parent is not None else None,
|
||||
record_exception=False, set_status_on_exception=False,
|
||||
)
|
||||
|
||||
|
||||
def observe_http(active, method, route, status, duration):
|
||||
method = method if method in ("GET", "POST", "DELETE", "PUT", "PATCH") else "other"
|
||||
attributes = {"method": method, "route": route, "status_class": f"{status // 100}xx"}
|
||||
active.update_name(f"{method} {route}")
|
||||
active.set_attributes(attributes)
|
||||
active.set_attribute("http.response.status_code", status)
|
||||
if status >= 500:
|
||||
active.set_status(Status(StatusCode.ERROR))
|
||||
HTTP_COUNT.add(1, attributes)
|
||||
HTTP_TIME.record(duration, attributes)
|
||||
|
||||
|
||||
def observe_process(pool):
|
||||
stats = pool.get_stats()
|
||||
dimensions = {"role": SERVICE}
|
||||
POOL_USED.set(stats["pool_size"] - stats["pool_available"], dimensions)
|
||||
POOL_WAITING.set(stats["requests_waiting"], dimensions)
|
||||
CPU.set(time.process_time(), dimensions)
|
||||
path = Path("/proc/self/status")
|
||||
if path.is_file():
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith("VmRSS:"):
|
||||
RSS.set(int(line.split()[1]) * 1024, dimensions)
|
||||
break
|
||||
|
||||
|
||||
def record(event, **fields):
|
||||
context = trace.get_current_span().get_span_context()
|
||||
if context.is_valid:
|
||||
fields.update(trace_id=f"{context.trace_id:032x}", span_id=f"{context.span_id:016x}")
|
||||
severity = logging.ERROR if fields.get("status", 0) >= 500 else logging.INFO
|
||||
data = {"timestamp": datetime.now(timezone.utc).isoformat(), "severity": logging.getLevelName(severity),
|
||||
"service.name": SERVICE, "event": event, **fields}
|
||||
raw = json.dumps(data, ensure_ascii=False)
|
||||
print(raw, flush=True)
|
||||
LOGGER.log(severity, raw)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Bounded child process for the CPU-intensive image conversion."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from attachments import MAX_PIXELS
|
||||
|
||||
|
||||
def fit(image, limit):
|
||||
longest = max(image.size)
|
||||
if longest <= limit:
|
||||
return image
|
||||
size = tuple(max(1, side * limit // longest) for side in image.size)
|
||||
return image.resize(size, Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def convert(root, version):
|
||||
try:
|
||||
with Image.open(root / "source") as source:
|
||||
if source.width * source.height > MAX_PIXELS or source.format not in ("PNG", "JPEG"):
|
||||
return 2
|
||||
with ImageOps.exif_transpose(source).convert("RGBA") as image:
|
||||
rgb = Image.new("RGB", image.size, "white")
|
||||
rgb.paste(image, mask=image.getchannel("A"))
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError, SyntaxError, OSError):
|
||||
return 2
|
||||
jpeg_quality, webp_quality = (85, 82) if version == 1 else (89, 84)
|
||||
outputs = [
|
||||
("thumbnail", fit(rgb, 256), "JPEG", "image/jpeg", jpeg_quality),
|
||||
("crop", ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS), "JPEG", "image/jpeg", jpeg_quality),
|
||||
("optimized", fit(rgb, 1280), "WEBP", "image/webp", webp_quality),
|
||||
]
|
||||
descriptors = []
|
||||
for name, image, format_name, mime, quality in outputs:
|
||||
image.info.clear()
|
||||
image.save(root / name, format=format_name, quality=quality)
|
||||
descriptors.append({"name": name, "content_type": mime, "width": image.width, "height": image.height})
|
||||
(root / "variants.json").write_text(json.dumps(descriptors), encoding="utf-8")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(convert(Path(sys.argv[1]), int(sys.argv[2])))
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Create one known trace, then print the trace ID for Grafana Explore."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from secrets import token_hex
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
actor, peer, _, chat = client.bootstrap()
|
||||
trace_id = token_hex(16)
|
||||
parent = token_hex(8)
|
||||
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
upload = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=trace.png", 202,
|
||||
raw=image, actor=actor, headers={"Content-Type": "image/png",
|
||||
"traceparent": f"00-{trace_id}-{parent}-01"}, schema="Attachment")
|
||||
ready = client.wait_ready(peer, upload["json"])
|
||||
print(json.dumps({"trace_id": trace_id, "request_id": upload["headers"]["X-Request-Id"],
|
||||
"status": ready["status"]}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproduce the worker-offline trajectory on a running test stack."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check
|
||||
from image_probe import jpeg_size
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, timeout=90)
|
||||
|
||||
|
||||
def wait_api(client):
|
||||
end = time.monotonic() + 45
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure("API did not recover")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--pause", type=int, default=0, help="Extra seconds with worker stopped")
|
||||
parser.add_argument("--no-restart", action="store_true", help="Keep API up during telemetry demo")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
actor, peer, _, chat = client.bootstrap()
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
upload, original = client.attachment(actor, chat)
|
||||
message = client.message(actor, chat, "", attachments=[upload["id"]])["json"]
|
||||
check(message["attachment_ids"] == [upload["id"]], "message lost queued attachment")
|
||||
meta = "/api/v1/attachments/" + upload["id"]
|
||||
client.call("GET", meta + "/content", 409, actor=peer)
|
||||
print("202 queued, привязка к сообщению 201, скачивание 409.", flush=True)
|
||||
if args.pause:
|
||||
time.sleep(args.pause)
|
||||
if not args.no_restart:
|
||||
compose("restart", "broker", "api")
|
||||
wait_api(client)
|
||||
queued = client.call("GET", meta, actor=peer, schema="Attachment")["json"]
|
||||
check(queued["status"] == "queued", "restart lost the pending job")
|
||||
print("После рестарта без worker задача осталась queued.", flush=True)
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
ready = client.wait_ready(peer, upload)
|
||||
variants = {item["name"]: item for item in ready["variants"]}
|
||||
check({"thumbnail", "crop", "optimized"} <= variants.keys(), "missing generated variants")
|
||||
downloaded = client.call("GET", meta + "/content", actor=peer)["bytes"]
|
||||
thumb = client.call("GET", meta + "/content?variant=thumbnail", actor=peer)["bytes"]
|
||||
check(downloaded == original, "original changed")
|
||||
check(jpeg_size(thumb) == (256, 160), "thumbnail dimensions changed")
|
||||
check(variants["thumbnail"]["sha256"] == hashlib.sha256(thumb).hexdigest(), "thumbnail hash changed")
|
||||
print(json.dumps({"status": ready["status"], "thumbnail": "256x160",
|
||||
"variants": sorted(variants), "original_matches": True}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user