From 6fdb550abcbe11a0212374a13e15ecd543651e82 Mon Sep 17 00:00:00 2001 From: Ekaterina Zyulina Date: Mon, 23 Nov 2026 19:12:15 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A06=20-=20=D0=91=D0=92=D0=A22302=20-?= =?UTF-8?q?=20=D0=97=D1=8E=D0=BB=D0=B8=D0=BD=D0=B0=20-=20=D0=BD=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 22 +- Dockerfile | 26 ++ REPORT.md | 76 +++- alembic.ini | 37 ++ alembic/env.py | 46 ++ alembic/script.py.mako | 22 + alembic/versions/001_initial.py | 70 +++ alembic/versions/002_history_constraints.py | 35 ++ alembic/versions/003_message_idempotency.py | 30 ++ alembic/versions/004_attachments.py | 38 ++ alembic/versions/005_async_attachments.py | 29 ++ compose.yaml | 230 ++++++++++ entrypoint.sh | 18 + evidence/checks.txt | 15 + infra/minio-bootstrap.sh | 15 + infra/nginx.conf | 42 ++ infra/otel/collector.yaml | 59 +++ .../dashboards-json/messenger-overview.json | 17 + .../provisioning/dashboards/dashboards.yaml | 10 + .../provisioning/datasources/datasources.yaml | 33 ++ infra/otel/loki.yaml | 30 ++ infra/otel/prometheus.yml | 7 + infra/otel/tempo.yaml | 27 ++ requirements.txt | 12 + scripts/restart.bat | 4 + scripts/restart.ps1 | 21 + scripts/stop-one.bat | 4 + scripts/stop-one.ps1 | 22 + src/__init__.py | 1 + src/auth.py | 31 ++ src/database.py | 101 +++++ src/jobs.py | 34 ++ src/main.py | 420 ++++++++++++++++++ src/models.py | 28 ++ src/object_store.py | 14 + src/session_cache.py | 72 +++ src/store.py | 248 +++++++++++ src/telemetry.py | 56 +++ src/worker.py | 151 +++++++ student-tests/s3_unavailable.py | 43 ++ student-tests/worker_recovery.py | 57 +++ 41 files changed, 2233 insertions(+), 20 deletions(-) create mode 100644 Dockerfile create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/001_initial.py create mode 100644 alembic/versions/002_history_constraints.py create mode 100644 alembic/versions/003_message_idempotency.py create mode 100644 alembic/versions/004_attachments.py create mode 100644 alembic/versions/005_async_attachments.py create mode 100644 compose.yaml create mode 100644 entrypoint.sh create mode 100644 evidence/checks.txt create mode 100644 infra/minio-bootstrap.sh create mode 100644 infra/nginx.conf create mode 100644 infra/otel/collector.yaml create mode 100644 infra/otel/grafana/provisioning/dashboards-json/messenger-overview.json create mode 100644 infra/otel/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/otel/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/otel/loki.yaml create mode 100644 infra/otel/prometheus.yml create mode 100644 infra/otel/tempo.yaml create mode 100644 requirements.txt create mode 100644 scripts/restart.bat create mode 100644 scripts/restart.ps1 create mode 100644 scripts/stop-one.bat create mode 100644 scripts/stop-one.ps1 create mode 100644 src/__init__.py create mode 100644 src/auth.py create mode 100644 src/database.py create mode 100644 src/jobs.py create mode 100644 src/main.py create mode 100644 src/models.py create mode 100644 src/object_store.py create mode 100644 src/session_cache.py create mode 100644 src/store.py create mode 100644 src/telemetry.py create mode 100644 src/worker.py create mode 100644 student-tests/s3_unavailable.py create mode 100644 student-tests/worker_recovery.py diff --git a/.env.example b/.env.example index 2b32655..b9414cd 100644 --- a/.env.example +++ b/.env.example @@ -7,11 +7,11 @@ SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres +SESSION_STORE=redis CACHE_URL_FILE=/run/secrets/cache_url API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 +S3_ENDPOINT=http://minio:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id @@ -19,12 +19,24 @@ S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 +WORKER_CONCURRENCY=1 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 STAGING_RETENTION_SECONDS=86400 OTEL_SERVICE_NAME=messenger-api # Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 -OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf +OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 +OTEL_EXPORTER_OTLP_PROTOCOL=grpc OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab + +# Concrete variables consumed by this repository's local compose.yaml. +GRAFANA_PORT=3000 +GRAFANA_PASSWORD=replace-grafana-password-with-random-value +POSTGRES_USER=messenger +POSTGRES_PASSWORD=replace-db-password-with-random-value +POSTGRES_DB=messenger +MINIO_ROOT_USER=minio-admin +MINIO_ROOT_PASSWORD=replace-minio-root-password-with-random-value +S3_ACCESS_KEY=messenger-api +S3_SECRET_KEY=replace-s3-secret-with-random-value +BROKER_URL=redis://redis-broker:6379/0 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..997811e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM python:3.11.10-slim-bookworm + +WORKDIR /app +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 + +# Устанавливаем зависимости +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Копируем код приложения +COPY src/ ./src/ +COPY alembic/ ./alembic/ +COPY alembic.ini . +COPY entrypoint.sh . + +RUN chmod 755 entrypoint.sh && groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app + +USER 10001:10001 + +# Открываем порт +EXPOSE 8080 + +ENTRYPOINT ["./entrypoint.sh"] + +# Команда запуска +CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080", "--limit-concurrency", "64", "--timeout-keep-alive", "5"] diff --git a/REPORT.md b/REPORT.md index b97ae42..3bf4f32 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,83 @@ # Отчёт — лабораторная 6 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Зюлина Екатерина Михайловна, БВТ2302. +- Целевая оценка: 3. +- Commit/PR: +- Источники и помощь ИИ: контракт и материалы skeleton lab6, собственный проект lab5; FastAPI, SQLAlchemy, Alembic, boto3, Pillow, redis-py, OpenTelemetry Python SDK/exporter; Codex использовался для анализа требований, реализации и проверки конфигураций. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Windows PowerShell, Docker Desktop в режиме Linux containers, Docker Compose v2 и Python 3.11. Runtime приложения: Python 3.11.10. Создайте локальные случайные secrets и `.env`: + +```powershell +$values = @{ + 'replace-db-password-with-random-value' = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(24)) + 'replace-minio-root-password-with-random-value' = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(24)) + 'replace-s3-secret-with-random-value' = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) + 'replace-grafana-password-with-random-value' = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(24)) +} +$envText = Get-Content -Raw .env.example +foreach ($key in $values.Keys) { $envText = $envText.Replace($key, $values[$key]) } +[IO.File]::WriteAllText((Join-Path (Get-Location) '.env'), $envText, [Text.UTF8Encoding]::new($false)) +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +do { Start-Sleep -Seconds 2; try { Invoke-WebRequest http://localhost:8080/health/ready -UseBasicParsing | Out-Null; $ready = $true } catch { $ready = $false } } until ($ready) +py -3.11 scripts/check_contract.py +py -3.11 tests/smoke.py --base-url http://localhost:8080 +``` + +После готовности откройте `http://localhost:3000`, пользователь Grafana `admin`, пароль из локального `.env`; dashboard `Messenger observability` загружается provisioning автоматически. `docker compose --env-file .env down` останавливает стенд, сохраняя volumes. Только если нужно удалить локальные учебные данные: `docker compose --env-file .env down --volumes`. Smoke создаёт синтетические данные и не удаляет их автоматически. + +Образы фиксированы: `python:3.11.10-slim-bookworm`, PostgreSQL 16.4, Redis 7.4.2, MinIO RELEASE.2025-09-07T16-13-09Z, nginx 1.27.5, OTel Collector Contrib 0.165.0, Prometheus 3.5.0, Loki 3.5.0, Tempo 2.8.0, Grafana 12.1.1. API/worker собираются из исходников репозитория. Ограничения CPU/RAM заданы в `compose.yaml`; локальный Compose размещает компоненты на одном Docker host. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → Nginx → две API-реплики → PostgreSQL, Redis sessions, MinIO и Redis Streams → worker. API и worker создают traces, metrics и OTLP logs и экспортируют их в Collector. Collector направляет метрики в Prometheus, логи в Loki, traces в Tempo; Grafana подключает эти источники и загружает JSON dashboard из provisioning. + +PostgreSQL — источник истины для пользователей, сессий/метаданных, чатов и сообщений; MinIO хранит исходники и варианты изображений; Redis Streams обеспечивает durable at-least-once queue. Эти части и API поведения перенесены из собственной lab5 реализации. Lab6 добавляет SDK, trace context и телеметрические backends. Контракт API и публичные проверки lab6 сохранены. + +| Роль / service | Образ | Readiness | Volume / сеть | +| --- | --- | --- | --- | +| Load balancer `lb` | `nginx:1.27.5-alpine` | Вход `localhost:8080`; передаёт на api1/api2 | Конфиг read-only; единственная публичная точка API | +| API `api1`, `api2` | собственный `mtusi-messenger-api:6.0.0` | `/health/ready` | Внутренняя сеть; DB/Redis/S3/broker и Collector через Compose environment | +| PostgreSQL `db` | `postgres:16.4-alpine` | `pg_isready` / проверка API | `postgres_data`; внутренний порт 5432 | +| Sessions `redis` | `redis:7.4.2-alpine` | `redis-cli ping` | `redis_data`; внутренний порт 6379 | +| S3 `minio` | `dappros/minio:RELEASE.2025-09-07T16-13-09Z` | `/minio/health/ready` | `minio_data`; приватная внутренняя сеть | +| Broker `redis-broker` | `redis:7.4.2-alpine` | `redis-cli ping` | `broker_data`; AOF `appendfsync always`, внутренний порт 6379 | +| Worker `worker` | собственный `mtusi-messenger-api:6.0.0` | Логи consumer, broker ping | Отдельный процесс; DB/S3/broker/Collector через Compose environment | +| Collector `otel-collector` | `otel/opentelemetry-collector-contrib:0.165.0` | `http://otel-collector:13133/` (health_check extension) | Внутренние OTLP 4317/4318; Prom scrape endpoint 8889 | +| Metrics `prometheus` | `prom/prometheus:v3.5.0` | `/-/ready` | `prometheus_data`; внутренний 9090 | +| Logs `loki` | `grafana/loki:3.5.0` | `/ready` | `loki_data`; внутренний 3100 | +| Traces `tempo` | `grafana/tempo:2.8.0` | `/ready` | `tempo_data`; внутренние OTLP 4317/4318, HTTP 3200 | +| UI `grafana` | `grafana/grafana:12.1.1` | `/api/health` | `grafana_data`; localhost-only `127.0.0.1:3000` | + +DB/storage bootstrap выполняют миграция Alembic и `infra/minio-bootstrap.sh`; Compose `depends_on` дожидается их завершения для API/worker. Настройки и локальные credentials собираются из `.env` и не коммитятся. + +Из `.env.example` Compose использует `APP_PORT`, `SESSION_TTL_SECONDS`, `S3_ENDPOINT`, `S3_REGION`, `S3_BUCKET`, `JOB_MAX_ATTEMPTS`, `OTEL_EXPORTER_OTLP_ENDPOINT` и `OTEL_RESOURCE_ATTRIBUTES`; конкретные compose-only `POSTGRES_*`, `MINIO_ROOT_*`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`, `BROKER_URL`, `GRAFANA_*` заданы в нижнем блоке того же файла. Примеры `*_FILE` — допустимые интерфейсные подсказки skeleton; данный локальный профиль вместо них читает значения из игнорируемого `.env` и передаёт сервисам только нужные переменные. `APP_HOST` задаётся в Dockerfile, число реплик — явно в Compose, upload limits — по обязательному контракту; лишние шаблонные knobs не меняют API. + +HTTP middleware пишет route-template, method, status class, request ID и duration; UUID пользователя/чата/сообщения, URL с UUID, тело сообщений, Authorization, сессии, содержимое файла, signed URL и secrets не экспортируются. Worker передаёт `traceparent`/`tracestate` как отдельные разрешённые контрактом поля job; worker consumer span является дочерним для upload request span. Структурные логи содержат timestamp/severity и идентификаторы trace/span; dashboard ссылается на созданные инструменты OTel `messenger.http.requests`, `messenger.http.duration`, `messenger.jobs.processed`, `messenger.jobs.duration` (Prometheus нормализует имена согласно экспортеру; см. запросы dashboard). + +Collector имеет memory limiter 192 MiB (48 MiB spike) и batch до 1024 записей; exporter queues ограничены 512 элементами, retries — до 30 секунд. SDK использует batch queues до 2048 элементов, период метрик 5 секунд, OTLP timeout 3 секунды. При отказе telemetry могут теряться сигналы после ограниченных очередей, но HTTP/business операции не ждут успешной отправки каждого сигнала. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Проверки skeleton и синтаксис | `scripts/check_contract.py`; `compileall -q src alembic scripts student-tests` в Python 3.11 container | PASS: offline skeleton structure, local refs, Python syntax; contract checker подтвердил, что приложение проверяется отдельно | `evidence/checks.txt` | +| Конфигурация Compose | `docker compose --env-file .env config --quiet` | PASS, exit 0 | `evidence/checks.txt` | +| Сборка и запуск полного стенда | `docker compose --env-file .env up -d --build`; `docker compose ps` | PASS; 11 сервисов работают, обе API healthy, MinIO и broker healthy; Collector сообщает `Everything is ready` | `evidence/checks.txt` | +| Публичный smoke | `tests/smoke.py --base-url http://lb:8080` в одноразовом Python 3.11 container | PASS три запуска: `lab6 public API scenario` | `evidence/checks.txt` | +| Метрики, logs, traces, Grafana | Prometheus API query; Loki range query; Tempo search; Grafana `/api/search` | Найдены HTTP metrics, worker logs; в одном Tempo trace найдены API и worker spans; Grafana вернула dashboard uid `messenger-overview` | `evidence/checks.txt` | +| W3C context и корреляция | Upload в smoke; Tempo API поиск traces service `messenger-api`, просмотр trace | В trace, инициированном API, находится `attachment.process` worker span; Loki хранит `trace_id` и `span_id` | `evidence/checks.txt` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Оценка 3: отдельные лабораторные нагрузочные исследования и контролируемые отказы уровня 4 не заявляются. Публичный smoke создал реальные сигналы по бизнес-сценарию. Отказ backend телеметрии в текущей реализации ограничивается временем экспортёра и очередями SDK/Collector; его фактические потери и влияние требуют измерения. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Docker Compose cold start | Полная сборка и запуск сервисов | PASS после разрешённого доступа к Docker Desktop Linux Engine | Около 4 минут на холодное скачивание образов/зависимостей; это время подготовки, не SLA стенда | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Это учебная локальная топология на одном Docker host; HA PostgreSQL, broker, S3, LB и telemetry backends не заявляется. В lab5 осталось окно между commit attachment metadata и публикацией задания в broker. На этом уровне нет alert rules, queue depth/age, DB pool и тестов отказов storage. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c436590 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,37 @@ +[alembic] +script_location = alembic +sqlalchemy.url = postgresql://postgres:postgres@db:5432/messenger + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..b75cbcf --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,46 @@ +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from alembic import context +import sys +import os + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from src.database import Base, DATABASE_URL + +config = context.config +config.set_main_option("sqlalchemy.url", DATABASE_URL) + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline(): + url = context.config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=None, + ) + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..fe11c3e --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,22 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/alembic/versions/001_initial.py b/alembic/versions/001_initial.py new file mode 100644 index 0000000..1415429 --- /dev/null +++ b/alembic/versions/001_initial.py @@ -0,0 +1,70 @@ +"""Initial schema + +Revision ID: 001 +Revises: +Create Date: 2026-10-12 +""" +from alembic import op +import sqlalchemy as sa + +revision = '001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table('users', + sa.Column('id', sa.String(), nullable=False), + sa.Column('username', sa.String(length=32), nullable=False), + sa.Column('display_name', sa.String(length=100), nullable=False), + sa.Column('password_hash', sa.String(length=255), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id')) + op.create_index('ix_users_username', 'users', ['username'], unique=True) + + op.create_table('sessions', + sa.Column('id', sa.String(), nullable=False), + sa.Column('token', sa.String(length=255), nullable=False), + sa.Column('user_id', sa.String(), nullable=False), + sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id')) + op.create_index('ix_sessions_token', 'sessions', ['token'], unique=True) + + op.create_table('chats', + sa.Column('id', sa.String(), nullable=False), + sa.Column('title', sa.String(length=100), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id')) + + op.create_table('chat_members', + sa.Column('id', sa.String(), nullable=False), + sa.Column('chat_id', sa.String(), nullable=False), + sa.Column('user_id', sa.String(), nullable=False), + sa.ForeignKeyConstraint(['chat_id'], ['chats.id']), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id')) + + op.create_table('messages', + sa.Column('id', sa.String(), nullable=False), + sa.Column('chat_id', sa.String(), nullable=False), + sa.Column('sender_id', sa.String(), nullable=False), + sa.Column('text', sa.Text(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['chat_id'], ['chats.id']), + sa.ForeignKeyConstraint(['sender_id'], ['users.id']), + sa.PrimaryKeyConstraint('id')) + op.create_index('ix_messages_chat_created', 'messages', ['chat_id', 'created_at']) + + +def downgrade(): + op.drop_index('ix_messages_chat_created', table_name='messages') + op.drop_table('messages') + op.drop_table('chat_members') + op.drop_table('chats') + op.drop_index('ix_sessions_token', table_name='sessions') + op.drop_table('sessions') + op.drop_index('ix_users_username', table_name='users') + op.drop_table('users') diff --git a/alembic/versions/002_history_constraints.py b/alembic/versions/002_history_constraints.py new file mode 100644 index 0000000..8d7699b --- /dev/null +++ b/alembic/versions/002_history_constraints.py @@ -0,0 +1,35 @@ +"""Add membership uniqueness and the keyset history index. + +Revision ID: 002 +Revises: 001 +Create Date: 2026-10-14 +""" +from alembic import op +import sqlalchemy as sa + +revision = '002' +down_revision = '001' +branch_labels = None +depends_on = None + + +def upgrade(): + # Older schemas allowed nullable timestamps. Backfill before tightening the + # constraint so the migration also works on an existing populated database. + for table in ('users', 'sessions', 'chats', 'messages'): + op.execute(sa.text(f'UPDATE {table} SET created_at = CURRENT_TIMESTAMP WHERE created_at IS NULL')) + op.alter_column(table, 'created_at', existing_type=sa.DateTime(timezone=True), nullable=False) + + op.create_unique_constraint('uq_chat_member', 'chat_members', ['chat_id', 'user_id']) + op.create_index('ix_chat_members_user_chat', 'chat_members', ['user_id', 'chat_id']) + op.drop_index('ix_messages_chat_created', table_name='messages') + op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id']) + + +def downgrade(): + op.drop_index('ix_messages_chat_created_id', table_name='messages') + op.create_index('ix_messages_chat_created', 'messages', ['chat_id', 'created_at']) + op.drop_index('ix_chat_members_user_chat', table_name='chat_members') + op.drop_constraint('uq_chat_member', 'chat_members', type_='unique') + for table in ('users', 'sessions', 'chats', 'messages'): + op.alter_column(table, 'created_at', existing_type=sa.DateTime(timezone=True), nullable=True) diff --git a/alembic/versions/003_message_idempotency.py b/alembic/versions/003_message_idempotency.py new file mode 100644 index 0000000..890acc9 --- /dev/null +++ b/alembic/versions/003_message_idempotency.py @@ -0,0 +1,30 @@ +"""Persist message idempotency claims in the shared PostgreSQL database.""" +from alembic import op +import sqlalchemy as sa + +revision = "003_message_idempotency" +down_revision = "002" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "message_idempotency", + sa.Column("id", sa.String(), nullable=False), + sa.Column("user_id", sa.String(), nullable=False), + sa.Column("method", sa.String(length=8), nullable=False), + sa.Column("chat_path", sa.String(length=80), nullable=False), + sa.Column("key", sa.String(length=128), nullable=False), + sa.Column("request_hash", sa.String(length=64), nullable=False), + sa.Column("message_id", sa.String(), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(["message_id"], ["messages.id"]), + sa.ForeignKeyConstraint(["user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("user_id", "method", "chat_path", "key", name="uq_idempotency_scope"), + ) + + +def downgrade(): + op.drop_table("message_idempotency") diff --git a/alembic/versions/004_attachments.py b/alembic/versions/004_attachments.py new file mode 100644 index 0000000..5b79c45 --- /dev/null +++ b/alembic/versions/004_attachments.py @@ -0,0 +1,38 @@ +"""Add attachment metadata and message references. + +Revision ID: 004_attachments +Revises: 003_message_idempotency +""" +from alembic import op +import sqlalchemy as sa + +revision = "004_attachments" +down_revision = "003_message_idempotency" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column("messages", sa.Column("attachment_ids", sa.JSON(), nullable=False, + server_default=sa.text("'[]'"))) + op.create_table( + "attachments", + sa.Column("id", sa.String(), primary_key=True), + sa.Column("chat_id", sa.String(), sa.ForeignKey("chats.id"), nullable=False), + sa.Column("owner_id", sa.String(), sa.ForeignKey("users.id"), nullable=False), + sa.Column("filename", sa.String(255), nullable=False), + sa.Column("content_type", sa.String(32), nullable=False), + sa.Column("size_bytes", sa.Integer(), nullable=False), + sa.Column("sha256", sa.String(64), nullable=False), + sa.Column("object_key", sa.String(128), nullable=False, unique=True), + sa.Column("status", sa.String(16), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + ) + op.create_index("ix_attachments_chat_id", "attachments", ["chat_id"]) + + +def downgrade(): + op.drop_index("ix_attachments_chat_id", table_name="attachments") + op.drop_table("attachments") + op.drop_column("messages", "attachment_ids") diff --git a/alembic/versions/005_async_attachments.py b/alembic/versions/005_async_attachments.py new file mode 100644 index 0000000..2c2496b --- /dev/null +++ b/alembic/versions/005_async_attachments.py @@ -0,0 +1,29 @@ +"""Add durable staging and asynchronous attachment job state.""" +from alembic import op +import sqlalchemy as sa + +revision = "005_async_attachments" +down_revision = "004_attachments" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column("attachments", sa.Column("staging_key", sa.String(128), nullable=True)) + op.add_column("attachments", sa.Column("job_id", sa.String(36), nullable=True)) + op.add_column("attachments", sa.Column("error_code", sa.String(64), nullable=True)) + op.add_column("attachments", sa.Column("variants", sa.JSON(), nullable=False, server_default="[]")) + op.execute("UPDATE attachments SET staging_key = object_key, job_id = id") + op.alter_column("attachments", "staging_key", nullable=False) + op.alter_column("attachments", "job_id", nullable=False) + op.create_unique_constraint("uq_attachments_staging_key", "attachments", ["staging_key"]) + op.create_unique_constraint("uq_attachments_job_id", "attachments", ["job_id"]) + + +def downgrade(): + op.drop_constraint("uq_attachments_job_id", "attachments", type_="unique") + op.drop_constraint("uq_attachments_staging_key", "attachments", type_="unique") + op.drop_column("attachments", "variants") + op.drop_column("attachments", "error_code") + op.drop_column("attachments", "job_id") + op.drop_column("attachments", "staging_key") diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..fb956de --- /dev/null +++ b/compose.yaml @@ -0,0 +1,230 @@ +services: + api1: + build: . + image: mtusi-messenger-api:6.0.0 + environment: &api-env + DATABASE_URL: postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?Create a local .env first}@db:5432/${POSTGRES_DB:-messenger} + CACHE_URL: redis://redis:6379/0 + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_REGION: ${S3_REGION:-us-east-1} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:?Create local S3 credentials} + S3_SECRET_KEY: ${S3_SECRET_KEY:?Create local S3 credentials} + BROKER_URL: ${BROKER_URL:-redis://redis-broker:6379/0} + ATTACHMENT_QUEUE: attachment.jobs.v1 + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4317} + OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} + depends_on: + migrate: {condition: service_completed_successfully} + s3-bootstrap: {condition: service_completed_successfully} + db: {condition: service_started} + redis: {condition: service_started} + redis-broker: {condition: service_healthy} + otel-collector: {condition: service_started} + mem_limit: 512m + cpus: 1.0 + stop_grace_period: 15s + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3)"] + interval: 5s + timeout: 4s + retries: 5 + start_period: 15s + + api2: + build: . + image: mtusi-messenger-api:6.0.0 + environment: *api-env + depends_on: + migrate: {condition: service_completed_successfully} + s3-bootstrap: {condition: service_completed_successfully} + db: {condition: service_started} + redis: {condition: service_started} + redis-broker: {condition: service_healthy} + otel-collector: {condition: service_started} + mem_limit: 512m + cpus: 1.0 + stop_grace_period: 15s + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3)"] + interval: 5s + timeout: 4s + retries: 5 + start_period: 15s + + migrate: + build: . + image: mtusi-messenger-api:6.0.0 + command: ["alembic", "upgrade", "head"] + environment: + DATABASE_URL: postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?Create a local .env first}@db:5432/${POSTGRES_DB:-messenger} + depends_on: + db: {condition: service_started} + restart: "no" + + lb: + image: nginx:1.27.5-alpine + ports: + - "${APP_PORT:-8080}:8080" + volumes: + - ./infra/nginx.conf:/etc/nginx/conf.d/default.conf:ro + depends_on: [api1, api2] + mem_limit: 128m + cpus: 0.5 + restart: unless-stopped + + db: + image: postgres:16.4-alpine + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Create a local .env first} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + volumes: ["postgres_data:/var/lib/postgresql/data"] + mem_limit: 1g + cpus: 1.0 + restart: unless-stopped + + redis: + image: redis:7.4.2-alpine + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always"] + volumes: ["redis_data:/data"] + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + + redis-broker: + image: redis:7.4.2-alpine + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always"] + volumes: ["broker_data:/data"] + expose: ["6379"] + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 4s + retries: 12 + + worker: + build: . + image: mtusi-messenger-api:6.0.0 + command: ["python", "-m", "src.worker"] + environment: + DATABASE_URL: postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?Create a local .env first}@db:5432/${POSTGRES_DB:-messenger} + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_REGION: ${S3_REGION:-us-east-1} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:?Create local S3 credentials} + S3_SECRET_KEY: ${S3_SECRET_KEY:?Create local S3 credentials} + BROKER_URL: ${BROKER_URL:-redis://redis-broker:6379/0} + ATTACHMENT_QUEUE: attachment.jobs.v1 + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + OTEL_SERVICE_NAME: messenger-worker + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4317} + OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} + depends_on: + migrate: {condition: service_completed_successfully} + s3-bootstrap: {condition: service_completed_successfully} + redis-broker: {condition: service_healthy} + db: {condition: service_started} + otel-collector: {condition: service_started} + mem_limit: 512m + cpus: 1.0 + stop_grace_period: 30s + restart: unless-stopped + + minio: + image: dappros/minio:RELEASE.2025-09-07T16-13-09Z + command: ["server", "/data", "--address", ":9000", "--console-address", ":9001"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Create local MinIO credentials} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Create local MinIO credentials} + volumes: ["minio_data:/data"] + expose: ["9000"] + mem_limit: 768m + cpus: 1.0 + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-fsS", "http://127.0.0.1:9000/minio/health/ready"] + interval: 5s + timeout: 3s + retries: 10 + + s3-bootstrap: + image: ghcr.io/golithus/mc:RELEASE.2025-08-13T08-35-41Z@sha256:dde55ccc0bc9e65dc582c8e652d652eea1438c6e60d774524f4da15d7b26a900 + entrypoint: ["/bin/sh", "/bootstrap.sh"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Create local MinIO credentials} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Create local MinIO credentials} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:?Create local S3 credentials} + S3_SECRET_KEY: ${S3_SECRET_KEY:?Create local S3 credentials} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + volumes: ["./infra/minio-bootstrap.sh:/bootstrap.sh:ro"] + depends_on: + minio: {condition: service_healthy} + restart: "no" + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.165.0 + command: ["--config=/etc/otelcol-contrib/collector.yaml"] + volumes: ["./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro"] + depends_on: [prometheus, loki, tempo] + expose: ["4317", "4318", "8889", "13133"] + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.5.0 + command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=7d", "--storage.tsdb.retention.size=2GB"] + volumes: ["./infra/otel/prometheus.yml:/etc/prometheus/prometheus.yml:ro", "prometheus_data:/prometheus"] + expose: ["9090"] + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + loki: + image: grafana/loki:3.5.0 + command: ["-config.file=/etc/loki/loki.yaml"] + volumes: ["./infra/otel/loki.yaml:/etc/loki/loki.yaml:ro", "loki_data:/loki"] + expose: ["3100"] + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + tempo: + image: grafana/tempo:2.8.0 + command: ["-config.file=/etc/tempo/tempo.yaml"] + volumes: ["./infra/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro", "tempo_data:/var/tempo"] + expose: ["3200", "4317", "4318"] + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + grafana: + image: grafana/grafana:12.1.1 + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:?Create local Grafana credentials} + ports: ["127.0.0.1:${GRAFANA_PORT:-3000}:3000"] + volumes: ["grafana_data:/var/lib/grafana", "./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro"] + depends_on: [prometheus, loki, tempo] + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + +volumes: + postgres_data: + redis_data: + minio_data: + broker_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..f8e3a2c --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +python - <<'PY' +import os, time +from sqlalchemy import create_engine, text +url = os.environ["DATABASE_URL"] +engine = create_engine(url, connect_args={"connect_timeout": 3}) +for attempt in range(60): + try: + with engine.connect() as connection: + connection.execute(text("SELECT 1")) + break + except Exception: + if attempt == 59: + raise + time.sleep(1) +PY +exec "$@" diff --git a/evidence/checks.txt b/evidence/checks.txt new file mode 100644 index 0000000..6b469ad --- /dev/null +++ b/evidence/checks.txt @@ -0,0 +1,15 @@ +2026-11-23 — local lab6 checks + +PASS — `scripts/check_contract.py` in an ephemeral `python:3.11.10-slim` container: `PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.` +PASS — `python -m compileall -q src alembic scripts student-tests` in the same image; exit 0. +PASS — `docker compose --env-file .env config --quiet`, Docker Compose v2.27.1-desktop.1; exit 0. +PASS — `docker compose --env-file .env up -d --build`; all services started. Both API replicas became healthy; MinIO and Redis broker reported healthy; OTel Collector logged `Everything is ready. Begin running and processing data.` +PASS — final Collector config restarted successfully; internal `http://otel-collector:13133/` health_check extension returned HTTP 200. +PASS — public `tests/smoke.py --base-url http://lb:8080`, run three times in an ephemeral Python 3.11 container on the Compose network: `PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.` +PASS — Prometheus API query returned `messenger_http_requests_total` series with `service_name`, method, route template and status-class attributes. +PASS — Prometheus contained 31 request series, 496 HTTP duration histogram bucket series, 1 worker job counter series and 16 job duration bucket series after smoke. +PASS — Loki range query returned worker logs; stored metadata includes `trace_id` and `span_id`. +PASS — Tempo search returned an API trace containing the worker `attachment.process` span (W3C trace context crosses Redis Streams). +PASS — Grafana `/api/search` returned dashboard title `Messenger observability`, uid `messenger-overview`. + +No credentials or session tokens are recorded. Local `.env` is ignored by Git. Smoke-created synthetic rows and objects remain in project volumes until explicitly removed with the documented `down --volumes` command. diff --git a/infra/minio-bootstrap.sh b/infra/minio-bootstrap.sh new file mode 100644 index 0000000..9c09918 --- /dev/null +++ b/infra/minio-bootstrap.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu +until mc alias set local http://minio:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null 2>&1; do sleep 2; done +mc mb --ignore-existing "local/$S3_BUCKET" +mc anonymous set none "local/$S3_BUCKET" +if ! mc admin user info local "$S3_ACCESS_KEY" >/dev/null 2>&1; then + mc admin user add local "$S3_ACCESS_KEY" "$S3_SECRET_KEY" +fi +cat >/tmp/attachment-policy.json </dev/null 2>&1; then + mc admin policy create local attachments-api /tmp/attachment-policy.json +fi +mc admin policy attach local attachments-api --user "$S3_ACCESS_KEY" diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 0000000..361e419 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,42 @@ +upstream api_backend { + zone api_backend 64k; + resolver 127.0.0.11 valid=2s ipv6=off; + server api1:8080 resolve max_fails=1 fail_timeout=2s; + server api2:8080 resolve max_fails=1 fail_timeout=2s; +} + +server { + listen 8080; + # Leave a small margin so the API returns its documented JSON 413 at 10 MiB. + client_max_body_size 11m; + client_body_timeout 20s; + proxy_connect_timeout 1s; + proxy_send_timeout 20s; + proxy_read_timeout 20s; + error_page 502 504 = @upstream_unavailable; + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Request-Id $request_id; + proxy_intercept_errors on; + # Retry GET/HEAD on a failed backend. Nginx never replays a POST after + # its request has been sent unless `non_idempotent` is enabled; uploads + # therefore remain single-shot, while message retries stay client-led. + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + proxy_next_upstream_timeout 5s; + } + + # Keep the public API error contract when all upstreams are unavailable. + location @upstream_unavailable { + default_type application/json; + add_header X-Request-Id $request_id always; + add_header X-Instance-Id "lb" always; + return 503 '{"error":{"code":"unavailable","message":"API upstream unavailable","request_id":"$request_id"}}'; + } +} diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..959f2a0 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,59 @@ +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + batch: + timeout: 1s + send_batch_size: 512 + send_batch_max_size: 1024 +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_constant_labels: + included: [service.name, service.instance.id, service.version, deployment.environment.name] + otlp_grpc/tempo: + endpoint: tempo:4317 + tls: + insecure: true + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 512 + retry_on_failure: + enabled: true + max_elapsed_time: 30s + otlp_http/loki: + logs_endpoint: http://loki:3100/otlp/v1/logs + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 512 + retry_on_failure: + enabled: true + max_elapsed_time: 30s +extensions: + health_check: + endpoint: 0.0.0.0:13133 +service: + extensions: [health_check] + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_grpc/tempo] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/loki] diff --git a/infra/otel/grafana/provisioning/dashboards-json/messenger-overview.json b/infra/otel/grafana/provisioning/dashboards-json/messenger-overview.json new file mode 100644 index 0000000..8273cb0 --- /dev/null +++ b/infra/otel/grafana/provisioning/dashboards-json/messenger-overview.json @@ -0,0 +1,17 @@ +{ + "uid": "messenger-overview", + "title": "Messenger observability", + "tags": ["lab6", "messenger"], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "time": {"from": "now-15m", "to": "now"}, + "panels": [ + {"id": 1, "type": "timeseries", "title": "HTTP requests per second", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, "targets": [{"expr": "sum by (service_name) (rate(messenger_http_requests_total[1m]))", "legendFormat": "{{service_name}}", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}}, + {"id": 2, "type": "timeseries", "title": "HTTP 5xx per second", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}, "targets": [{"expr": "sum(rate(messenger_http_requests_total{http_response_status_class=\"5xx\"}[1m]))", "legendFormat": "5xx", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}}, + {"id": 3, "type": "timeseries", "title": "HTTP request duration p95", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 0, "y": 8}, "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}}, + {"id": 4, "type": "timeseries", "title": "Attachment jobs by outcome", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 12, "y": 8}, "targets": [{"expr": "sum by (job_outcome) (rate(messenger_jobs_processed_total[1m]))", "legendFormat": "{{job_outcome}}", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []}}, + {"id": 5, "type": "timeseries", "title": "Worker processing duration p95", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 24, "x": 0, "y": 16}, "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_jobs_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}} + ] +} diff --git a/infra/otel/grafana/provisioning/dashboards/dashboards.yaml b/infra/otel/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..21a1217 --- /dev/null +++ b/infra/otel/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,10 @@ +apiVersion: 1 +providers: + - name: messenger + orgId: 1 + folder: Messenger + type: file + disableDeletion: false + editable: true + options: + path: /etc/grafana/provisioning/dashboards-json diff --git a/infra/otel/grafana/provisioning/datasources/datasources.yaml b/infra/otel/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..4662540 --- /dev/null +++ b/infra/otel/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,33 @@ +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 + jsonData: + derivedFields: + - name: TraceID + matcherRegex: 'trace_id="?([a-f0-9]{32})"?' + datasourceUid: tempo + url: '$${__value.raw}' + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: "-1m" + spanEndTimeShift: "1m" + filterByTraceID: true + filterBySpanID: false + customQuery: true + query: '{${__tags}} | trace_id="${__trace.traceId}"' diff --git a/infra/otel/loki.yaml b/infra/otel/loki.yaml new file mode 100644 index 0000000..d504129 --- /dev/null +++ b/infra/otel/loki.yaml @@ -0,0 +1,30 @@ +auth_enabled: false +server: + http_listen_port: 3100 + grpc_listen_port: 9096 +common: + path_prefix: /loki + replication_factor: 1 + ring: + kvstore: + store: inmemory + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules +schema_config: + configs: + - from: "2024-01-01" + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h +limits_config: + allow_structured_metadata: true + retention_period: 168h +compactor: + working_directory: /loki/retention + retention_enabled: true + delete_request_store: filesystem diff --git a/infra/otel/prometheus.yml b/infra/otel/prometheus.yml new file mode 100644 index 0000000..3d60791 --- /dev/null +++ b/infra/otel/prometheus.yml @@ -0,0 +1,7 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s +scrape_configs: + - job_name: otel-collector + static_configs: + - targets: [otel-collector:8889] diff --git a/infra/otel/tempo.yaml b/infra/otel/tempo.yaml new file mode 100644 index 0000000..d68762a --- /dev/null +++ b/infra/otel/tempo.yaml @@ -0,0 +1,27 @@ +stream_over_http_enabled: true +server: + http_listen_port: 3200 + grpc_listen_port: 9095 +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 +ingester: + max_block_duration: 5m + trace_idle_period: 10s +compactor: + compaction: + block_retention: 168h +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + block: + version: vParquet4 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..76e5831 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,12 @@ +fastapi==0.109.0 +uvicorn[standard]==0.27.0 +pydantic==2.5.3 +sqlalchemy==2.0.25 +alembic==1.13.1 +psycopg2-binary==2.9.9 +redis==5.0.1 +boto3==1.35.99 +Pillow==11.0.0 +opentelemetry-api==1.27.0 +opentelemetry-sdk==1.27.0 +opentelemetry-exporter-otlp-proto-grpc==1.27.0 diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 0000000..21fe545 --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1,4 @@ +@echo off +setlocal +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1" +exit /b %errorlevel% diff --git a/scripts/restart.ps1 b/scripts/restart.ps1 new file mode 100644 index 0000000..2e675be --- /dev/null +++ b/scripts/restart.ps1 @@ -0,0 +1,21 @@ +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +function Get-ContainerState($phase) { + foreach ($service in @('db', 'redis', 'redis-broker', 'minio', 'api1', 'api2', 'worker', 'lb')) { + $containers = docker compose --env-file .env ps -q $service + if ($LASTEXITCODE -ne 0) { throw "Cannot list $service containers" } + foreach ($container in $containers) { + $name = docker inspect --format '{{.Name}}' $container + $started = docker inspect --format '{{.State.StartedAt}}' $container + "$phase service=$service container=$name started_at=$started" + } + } +} +$before = @(Get-ContainerState 'before') +docker compose --env-file .env restart db redis redis-broker minio api1 api2 worker lb | Out-Null +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +$after = @(Get-ContainerState 'after') +$stamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss K' +Add-Content -Path (Join-Path $PSScriptRoot '..\evidence\persistence-actions.txt') -Value "[$stamp]" +Add-Content -Path (Join-Path $PSScriptRoot '..\evidence\persistence-actions.txt') -Value $before +Add-Content -Path (Join-Path $PSScriptRoot '..\evidence\persistence-actions.txt') -Value $after diff --git a/scripts/stop-one.bat b/scripts/stop-one.bat new file mode 100644 index 0000000..e2c0c17 --- /dev/null +++ b/scripts/stop-one.bat @@ -0,0 +1,4 @@ +@echo off +setlocal +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1" +exit /b %errorlevel% diff --git a/scripts/stop-one.ps1 b/scripts/stop-one.ps1 new file mode 100644 index 0000000..f96c9ec --- /dev/null +++ b/scripts/stop-one.ps1 @@ -0,0 +1,22 @@ +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +$target = $env:TARGET_INSTANCE_ID +if ([string]::IsNullOrWhiteSpace($target)) { exit 2 } +foreach ($service in @('api1', 'api2')) { + $containers = docker compose --env-file .env ps -q $service + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + foreach ($container in $containers) { + try { + $instance = docker exec $container python -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=2).headers['X-Instance-Id'])" 2>$null + if ($LASTEXITCODE -eq 0 -and $instance.Trim() -eq $target) { + $name = docker inspect --format '{{.Name}}' $container + $stamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss K' + Add-Content -Path (Join-Path $PSScriptRoot '..\evidence\failover-actions.txt') -Value "$stamp target=$target service=$service container=$name" + docker stop --time 5 $container | Out-Null + exit $LASTEXITCODE + } + } catch { } + } +} +Write-Error 'No running API container matched TARGET_INSTANCE_ID' +exit 1 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..fec0e09 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1 @@ +"""MTUSI Messenger service package.""" diff --git a/src/auth.py b/src/auth.py new file mode 100644 index 0000000..02a49ee --- /dev/null +++ b/src/auth.py @@ -0,0 +1,31 @@ +"""scrypt password KDF and opaque, cryptographically random bearer tokens.""" +import base64 +import hashlib +import hmac +import os +import secrets + +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) + + +def hash_password(password: str) -> str: + salt = secrets.token_bytes(16) + digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2**14, r=8, p=1, dklen=32) + return "scrypt$16384$8$1$" + base64.urlsafe_b64encode(salt + digest).decode("ascii") + + +def verify_password(password: str, encoded: str) -> bool: + try: + scheme, n, r, p, raw = encoded.split("$", 4) + if scheme != "scrypt": + return False + data = base64.urlsafe_b64decode(raw.encode("ascii")) + salt, expected = data[:16], data[16:] + actual = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=int(n), r=int(r), p=int(p), dklen=len(expected)) + return hmac.compare_digest(actual, expected) + except (ValueError, TypeError): + return False + + +def new_token() -> str: + return secrets.token_urlsafe(32) diff --git a/src/database.py b/src/database.py new file mode 100644 index 0000000..315faf9 --- /dev/null +++ b/src/database.py @@ -0,0 +1,101 @@ +"""PostgreSQL schema and bounded connection pool.""" +import os +import uuid +from datetime import datetime, timezone +from sqlalchemy import (Column, DateTime, ForeignKey, Index, String, Text, Integer, JSON, + UniqueConstraint, create_engine) +from sqlalchemy.orm import declarative_base, relationship, sessionmaker + +DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@db:5432/messenger") +engine = create_engine(DATABASE_URL, pool_size=5, max_overflow=5, pool_timeout=5, + pool_pre_ping=True, connect_args={"connect_timeout": 5, + "options": "-c statement_timeout=5000"}) +SessionLocal = sessionmaker(bind=engine, expire_on_commit=False) +Base = declarative_base() +now = lambda: datetime.now(timezone.utc) + + +class User(Base): + __tablename__ = "users" + id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) + username = Column(String(32), nullable=False) + display_name = Column(String(100), nullable=False) + password_hash = Column(String(255), nullable=False) + created_at = Column(DateTime(timezone=True), nullable=False, default=now) + __table_args__ = (Index("ix_users_username", "username", unique=True),) + + +class Session(Base): + __tablename__ = "sessions" + id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) + token = Column(String(255), nullable=False) + user_id = Column(String, ForeignKey("users.id"), nullable=False) + expires_at = Column(DateTime(timezone=True), nullable=False) + created_at = Column(DateTime(timezone=True), nullable=False, default=now) + user = relationship("User") + __table_args__ = (Index("ix_sessions_token", "token", unique=True),) + + +class Chat(Base): + __tablename__ = "chats" + id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) + title = Column(String(100), nullable=False) + created_at = Column(DateTime(timezone=True), nullable=False, default=now) + members = relationship("ChatMember", back_populates="chat", cascade="all, delete-orphan") + + +class ChatMember(Base): + __tablename__ = "chat_members" + id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) + chat_id = Column(String, ForeignKey("chats.id"), nullable=False) + user_id = Column(String, ForeignKey("users.id"), nullable=False) + chat = relationship("Chat", back_populates="members") + user = relationship("User") + __table_args__ = (UniqueConstraint("chat_id", "user_id", name="uq_chat_member"), + Index("ix_chat_members_user_chat", "user_id", "chat_id")) + + +class Message(Base): + __tablename__ = "messages" + id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) + chat_id = Column(String, ForeignKey("chats.id"), nullable=False) + sender_id = Column(String, ForeignKey("users.id"), nullable=False) + text = Column(Text, nullable=False) + attachment_ids = Column(JSON, nullable=False, default=list) + created_at = Column(DateTime(timezone=True), nullable=False, default=now) + chat = relationship("Chat") + sender = relationship("User") + __table_args__ = (Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),) + + +class Attachment(Base): + __tablename__ = "attachments" + id = Column(String, primary_key=True) + chat_id = Column(String, ForeignKey("chats.id"), nullable=False, index=True) + owner_id = Column(String, ForeignKey("users.id"), nullable=False) + filename = Column(String(255), nullable=False) + content_type = Column(String(32), nullable=False) + size_bytes = Column(Integer, nullable=False) + sha256 = Column(String(64), nullable=False) + object_key = Column(String(128), nullable=False, unique=True) + staging_key = Column(String(128), nullable=False, unique=True) + status = Column(String(16), nullable=False, default="ready") + job_id = Column(String(36), nullable=False, unique=True) + error_code = Column(String(64), nullable=True) + variants = Column(JSON, nullable=False, default=list) + created_at = Column(DateTime(timezone=True), nullable=False, default=now) + updated_at = Column(DateTime(timezone=True), nullable=False, default=now) + + +class MessageIdempotency(Base): + __tablename__ = "message_idempotency" + id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) + user_id = Column(String, ForeignKey("users.id"), nullable=False) + method = Column(String(8), nullable=False) + chat_path = Column(String(80), nullable=False) + key = Column(String(128), nullable=False) + request_hash = Column(String(64), nullable=False) + message_id = Column(String, ForeignKey("messages.id"), nullable=True) + created_at = Column(DateTime(timezone=True), nullable=False, default=now) + __table_args__ = (UniqueConstraint("user_id", "method", "chat_path", "key", + name="uq_idempotency_scope"),) diff --git a/src/jobs.py b/src/jobs.py new file mode 100644 index 0000000..8244da8 --- /dev/null +++ b/src/jobs.py @@ -0,0 +1,34 @@ +"""Redis Streams producer for durable attachment jobs.""" +import json +import os +from datetime import datetime, timezone +import redis +from opentelemetry.propagate import inject + +QUEUE = os.getenv("ATTACHMENT_QUEUE", "attachment.jobs.v1") +CONSUMER_GROUP = os.getenv("ATTACHMENT_CONSUMER_GROUP", "attachment-workers-v1") +MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5")) + + +def client(): + return redis.Redis.from_url(os.environ["BROKER_URL"], decode_responses=True, + socket_connect_timeout=3, socket_timeout=10, + retry_on_timeout=True) + + +def publish(attachment_id, job_id, attempt=1): + job = {"schema_version": 1, "job_id": job_id, + "type": "attachment.process.v1", "attachment_id": attachment_id, + "pipeline_version": 1, "attempt": attempt, + "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")} + carrier = {} + inject(carrier) + if "traceparent" in carrier: + job["traceparent"] = carrier["traceparent"] + if "tracestate" in carrier: + job["tracestate"] = carrier["tracestate"] + client().xadd(QUEUE, {"body": json.dumps(job, separators=(",", ":"))}) + + +def ping(): + client().ping() diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..edf872c --- /dev/null +++ b/src/main.py @@ -0,0 +1,420 @@ +"""Lab 4 REST API: shared messenger state and private S3 attachments.""" +import base64 +import binascii +import hashlib +import json +import logging +import re +import uuid +import time +import hashlib +import tempfile +import re as regex +from datetime import timezone +from fastapi import FastAPI, Request, Query +from fastapi.responses import JSONResponse, StreamingResponse +from starlette.concurrency import run_in_threadpool +from PIL import Image, UnidentifiedImageError +from botocore.exceptions import BotoCoreError, ClientError +import redis +from fastapi.exceptions import RequestValidationError +from sqlalchemy import text +from sqlalchemy.exc import SQLAlchemyError +from .database import SessionLocal +from .models import CreateUser, CreateChat, CreateMessage +from .store import store, cursor_for_chat, cursor_for_message +from . import session_cache +from . import object_store +from . import jobs +from . import telemetry +from opentelemetry import trace +from opentelemetry.propagate import extract +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator + + +class AppError(Exception): + def __init__(self, status, code, message, headers=None): + self.status, self.code, self.message, self.headers = status, code, message, headers or {} + + +app = FastAPI(title="MTUSI Messenger", version="6.0.0") +INSTANCE_ID = str(uuid.uuid4()) + + +@app.middleware("http") +async def observe_request(request: Request, call_next): + started = time.perf_counter() + request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4()) + request.state.request_id = request_id + carrier = {key.lower(): value for key, value in request.headers.items() if key.lower() in ("traceparent", "tracestate")} + parent = extract(carrier) + with telemetry.tracer.start_as_current_span("http.request", context=parent, kind=trace.SpanKind.SERVER) as span: + span.set_attribute("http.request.method", request.method) + span.set_attribute("messenger.request_id", request_id) + try: + response = await call_next(request) + except Exception: + span.set_attribute("http.response.status_code", 500) + span.record_exception(Exception("unhandled request failure")) + route = request.scope.get("route") + route_name = getattr(route, "path", "unmatched") + attrs = {"http.request.method": request.method, "http.route": route_name, + "http.response.status_class": "5xx"} + elapsed = time.perf_counter() - started + telemetry.http_requests.add(1, attrs) + telemetry.http_duration.record(elapsed, attrs) + logging.getLogger("messenger.api").error("http_request_failed", extra={"request_id": request_id, "http_route": route_name, "http_status": 500, "duration_seconds": round(elapsed, 6)}) + raise + route = request.scope.get("route") + route_name = getattr(route, "path", "unmatched") + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + span.set_attribute("http.route", route_name) + span.set_attribute("http.response.status_code", response.status_code) + attrs = {"http.request.method": request.method, "http.route": route_name, + "http.response.status_class": f"{response.status_code // 100}xx"} + elapsed = time.perf_counter() - started + telemetry.http_requests.add(1, attrs) + telemetry.http_duration.record(elapsed, attrs) + if response.status_code >= 500: + span.set_status(trace.Status(trace.StatusCode.ERROR)) + logging.getLogger("messenger.api").info("http_request_completed", extra={"request_id": request_id, "http_route": route_name, "http_status": response.status_code, "duration_seconds": round(elapsed, 6)}) + return response + + +@app.exception_handler(AppError) +async def app_error_handler(request, exc): + headers = {"X-Request-Id": request.state.request_id, **exc.headers} + headers["X-Instance-Id"] = INSTANCE_ID + return JSONResponse(status_code=exc.status, content={"error":{"code":exc.code,"message":exc.message,"request_id":request.state.request_id}}, headers=headers) + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request, exc): + return JSONResponse(status_code=400, content={"error":{"code":"invalid_request","message":"Invalid request","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID}) + + +@app.exception_handler(SQLAlchemyError) +async def database_error_handler(request, exc): + return JSONResponse(status_code=503, content={"error":{"code":"unavailable","message":"Database unavailable","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID}) + + +@app.exception_handler(Exception) +async def internal_handler(request, exc): + return JSONResponse(status_code=500, content={"error":{"code":"internal_error","message":"Internal server error","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID}) + + +def stamp(value): + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def user_json(user): + return {"id":user.id,"username":user.username,"display_name":user.display_name,"created_at":stamp(user.created_at)} + + +def auth_user(request): + header = request.headers.get("Authorization", "") + if not header.startswith("Bearer ") or not header[7:]: + raise AppError(401,"unauthorized","Authentication required",{"WWW-Authenticate":'Bearer realm="messenger"'}) + try: + found = store.get_session_by_token(header[7:]) + except session_cache.CacheUnavailable: + raise AppError(503,"unavailable","Session cache unavailable") + except SQLAlchemyError: + raise AppError(503,"unavailable","Authentication store unavailable") + if not found: + raise AppError(401,"unauthorized","Invalid or expired session",{"WWW-Authenticate":'Bearer realm="messenger"'}) + return found[0] + + +def chat_json(chat): + return {"id":chat.id,"title":chat.title,"member_ids":[m.user_id for m in chat.members],"created_at":stamp(chat.created_at)} + + +def validate_uuid(value): + try: + uuid.UUID(value) + except (ValueError, AttributeError): + raise AppError(400,"invalid_request","Invalid UUID") + + +@app.get("/health/live") +async def live(): + return {"status":"ok"} + + +@app.get("/health/ready") +async def ready(): + try: + with SessionLocal() as db: + db.execute(text("SELECT 1")) + session_cache.ping() + object_store.s3.list_objects_v2(Bucket=object_store.S3_BUCKET, Prefix="original/", MaxKeys=1) + await run_in_threadpool(jobs.ping) + return {"status":"ok"} + except session_cache.CacheUnavailable: + raise AppError(503,"unavailable","Session cache unavailable") + except SQLAlchemyError: + raise AppError(503,"unavailable","Database unavailable") + except (BotoCoreError, ClientError): + raise AppError(503,"unavailable","Object storage unavailable") + except (redis.exceptions.RedisError, OSError): + raise AppError(503,"unavailable","Attachment queue unavailable") + + +@app.post("/api/v1/users", status_code=201) +async def register(data: CreateUser): + if not data.display_name.strip() or not 12 <= len(data.password) <= 128: + raise AppError(400,"invalid_request","Invalid user fields") + try: + return user_json(store.add_user(data.username,data.display_name,data.password)) + except ValueError as exc: + if str(exc) == "USERNAME_EXISTS": + raise AppError(409,"conflict","Username already exists") + raise AppError(400,"invalid_request","Invalid user fields") + except SQLAlchemyError: + raise AppError(503,"unavailable","Database unavailable") + + +@app.post("/api/v1/auth/sessions", status_code=201) +async def login(request: Request): + header = request.headers.get("Authorization", "") + challenge = {'WWW-Authenticate':'Basic realm="messenger", charset="UTF-8"'} + if not header.startswith("Basic "): + raise AppError(401,"unauthorized","Invalid credentials",challenge) + try: + decoded = base64.b64decode(header[6:], validate=True).decode("utf-8") + username, password = decoded.split(":", 1) + except (binascii.Error, UnicodeError, ValueError): + raise AppError(401,"unauthorized","Invalid credentials",challenge) + try: + user = store.verify_user_password(username,password) + if not user: + raise AppError(401,"unauthorized","Invalid credentials",challenge) + session = store.create_session(user.id) + return {"token":session.token,"token_type":"Bearer","expires_at":stamp(session.expires_at),"user":user_json(user)} + except session_cache.CacheUnavailable: + raise AppError(503,"unavailable","Session cache unavailable") + except SQLAlchemyError: + raise AppError(503,"unavailable","Database unavailable") + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +async def logout(request: Request): + auth_user(request) + try: + store.delete_session(request.headers["Authorization"][7:]) + except session_cache.CacheUnavailable: + raise AppError(503,"unavailable","Session cache unavailable") + except SQLAlchemyError: + raise AppError(503,"unavailable","Authentication store unavailable") + return None + + +@app.get("/api/v1/users/me") +async def me(request: Request): + user_id = auth_user(request) + user = store.get_user_by_id(user_id) + if not user: + raise AppError(401,"unauthorized","Invalid session",{'WWW-Authenticate':'Bearer realm="messenger"'}) + return user_json(user) + + +@app.post("/api/v1/chats", status_code=201) +async def create_chat(data: CreateChat, request: Request): + user_id = auth_user(request) + if not data.title.strip(): + raise AppError(400,"invalid_request","Invalid title") + try: + return chat_json(store.create_chat(data.title,data.member_ids,user_id)) + except ValueError as exc: + if str(exc)=="USER_NOT_FOUND": + raise AppError(400,"invalid_request","Unknown member") + raise AppError(400,"invalid_request","Invalid members") + except SQLAlchemyError: + raise AppError(503,"unavailable","Database unavailable") + + +@app.get("/api/v1/chats") +async def list_chats(request: Request, limit: int = Query(50,ge=1,le=100), cursor: str|None=None): + user_id=auth_user(request) + try: + rows=store.get_user_chats(user_id,cursor,limit+1) + except ValueError: + raise AppError(400,"invalid_request","Invalid cursor") + more=len(rows)>limit + rows=rows[:limit] + return {"items":[chat_json(c) for c in rows],"next_cursor":cursor_for_chat(rows[-1]) if more else None} + + +@app.get("/api/v1/chats/{chat_id}") +async def get_chat(chat_id: str, request: Request): + user_id=auth_user(request) + validate_uuid(chat_id) + if not store.is_chat_member(chat_id,user_id): + raise AppError(404,"not_found","Chat not found") + chat=store.get_chat(chat_id) + if not chat: + raise AppError(404,"not_found","Chat not found") + return chat_json(chat) + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +async def create_message(chat_id: str, data: CreateMessage, request: Request): + user_id=auth_user(request) + validate_uuid(chat_id) + if data.text is None or len(data.text)>4000 or len(data.attachment_ids) != len(set(data.attachment_ids)): + raise AppError(400,"invalid_request","Invalid message text") + for attachment_id in data.attachment_ids: + validate_uuid(attachment_id) + if not data.text.strip() and not data.attachment_ids: + raise AppError(400,"invalid_request","Message must contain text or attachments") + key = request.headers.get("Idempotency-Key", "") + if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key, flags=re.ASCII): + raise AppError(400,"invalid_request","A valid Idempotency-Key is required") + canonical = json.dumps({"text":data.text,"attachment_ids":data.attachment_ids}, ensure_ascii=False, + sort_keys=True, separators=(",", ":")) + request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest() + try: + msg=store.add_message_idempotent(chat_id,user_id,data.text,data.attachment_ids,key,request_hash) + return {"id":msg.id,"chat_id":msg.chat_id,"sender_id":msg.sender_id,"text":msg.text,"created_at":stamp(msg.created_at),"attachment_ids":msg.attachment_ids} + except ValueError as exc: + if str(exc) == "IDEMPOTENCY_CONFLICT": + raise AppError(409,"conflict","Idempotency key was used with a different request") + if str(exc) == "EMPTY_MESSAGE": + raise AppError(400,"invalid_request","Message must contain text or attachments") + if str(exc) == "ATTACHMENT_FAILED": + raise AppError(409,"conflict","Failed attachment cannot be added to a message") + raise AppError(404,"not_found","Chat not found") + except SQLAlchemyError: + raise AppError(503,"unavailable","Database unavailable") + + +@app.get("/api/v1/chats/{chat_id}/messages") +async def list_messages(chat_id: str, request: Request, limit: int=Query(50,ge=1,le=100), cursor: str|None=None): + user_id=auth_user(request) + validate_uuid(chat_id) + if not store.is_chat_member(chat_id,user_id): + raise AppError(404,"not_found","Chat not found") + try: + rows=store.get_messages(chat_id,cursor,limit+1) + except ValueError: + raise AppError(400,"invalid_request","Invalid cursor") + more=len(rows)>limit + rows=rows[:limit] + items=[{"id":m.id,"chat_id":m.chat_id,"sender_id":m.sender_id,"text":m.text,"created_at":stamp(m.created_at),"attachment_ids":m.attachment_ids or []} for m in rows] + return {"items":items,"next_cursor":cursor_for_message(rows[-1]) if more else None} + + +def attachment_json(row): + return {"id":row.id,"chat_id":row.chat_id,"owner_id":row.owner_id,"filename":row.filename, + "content_type":row.content_type,"size_bytes":row.size_bytes,"sha256":row.sha256, + "status":row.status,"variants":row.variants or [],"error_code":row.error_code, + "created_at":stamp(row.created_at),"updated_at":stamp(row.updated_at)} + + +@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202) +async def upload_attachment(chat_id: str, request: Request, filename: str = Query(...)): + user_id = auth_user(request) + validate_uuid(chat_id) + if not store.is_chat_member(chat_id, user_id): + raise AppError(404, "not_found", "Chat not found") + if not 1 <= len(filename) <= 255 or any(ch in filename for ch in "/\\\x00") or any(ord(ch) < 32 or 127 <= ord(ch) < 160 for ch in filename): + raise AppError(400, "invalid_request", "Invalid filename") + declared = request.headers.get("content-type", "").split(";", 1)[0].lower() + if declared not in ("image/png", "image/jpeg"): + raise AppError(415, "unsupported_media_type", "Only PNG and JPEG are accepted") + max_bytes = 10 * 1024 * 1024 + spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b") + digest = hashlib.sha256() + size = 0 + try: + async for chunk in request.stream(): + size += len(chunk) + if size > max_bytes: + raise AppError(413, "payload_too_large", "Image exceeds 10 MiB") + digest.update(chunk) + spool.write(chunk) + if size == 0: + raise AppError(415, "unsupported_media_type", "Empty image") + spool.seek(0) + try: + image = Image.open(spool) + fmt = image.format + width, height = image.size + if width * height > 40_000_000: + raise AppError(413, "payload_too_large", "Image exceeds 40 million pixels") + if (fmt, declared) not in (("PNG", "image/png"), ("JPEG", "image/jpeg")): + raise AppError(415, "unsupported_media_type", "Image content does not match Content-Type") + image.verify() + except AppError: + raise + except (UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning): + raise AppError(415, "unsupported_media_type", "Invalid or unsupported image") + object_id = str(uuid.uuid4()) + object_key = f"original/{object_id}" + staging_key = f"staging/{object_id}" + job_id = str(uuid.uuid4()) + spool.seek(0) + await run_in_threadpool(object_store.s3.put_object, Bucket=object_store.S3_BUCKET, + Key=staging_key, Body=spool, ContentLength=size, ContentType=declared) + row = store.save_attachment(dict(id=object_id, chat_id=chat_id, owner_id=user_id, + filename=filename, content_type=declared, size_bytes=size, sha256=digest.hexdigest(), + object_key=object_key, staging_key=staging_key, status="queued", job_id=job_id, + variants=[], error_code=None)) + await run_in_threadpool(jobs.publish, object_id, job_id) + return attachment_json(row) + except AppError: + raise + except (BotoCoreError, ClientError): + raise AppError(503, "unavailable", "Object storage unavailable") + except (redis.exceptions.RedisError, OSError, RuntimeError): + raise AppError(503, "unavailable", "Attachment queue unavailable") + finally: + spool.close() + + +@app.get("/api/v1/attachments/{attachment_id}") +async def get_attachment(attachment_id: str, request: Request): + user_id = auth_user(request) + validate_uuid(attachment_id) + row = store.get_attachment(attachment_id, user_id) + if not row: + raise AppError(404, "not_found", "Attachment not found") + return attachment_json(row) + + +@app.get("/api/v1/attachments/{attachment_id}/content") +async def download_attachment(attachment_id: str, request: Request, variant: str = "original"): + user_id = auth_user(request) + validate_uuid(attachment_id) + row = store.get_attachment(attachment_id, user_id) + if not row: + raise AppError(404, "not_found", "Attachment not found") + if row.status in ("queued", "processing", "failed"): + raise AppError(409, "conflict", "Attachment content is not ready") + if variant == "original": + key, content_type, length = row.object_key, row.content_type, row.size_bytes + elif variant in {item.get("name") for item in row.variants or []}: + key = f"variants/{attachment_id}/{variant}" + item = next(item for item in row.variants if item.get("name") == variant) + content_type, length = item["content_type"], item["size_bytes"] + else: + raise AppError(404, "not_found", "Attachment variant not found") + try: + obj = await run_in_threadpool(object_store.s3.get_object, Bucket=object_store.S3_BUCKET, Key=key) + except (BotoCoreError, ClientError): + raise AppError(503, "unavailable", "Object storage unavailable") + body = obj["Body"] + def chunks(): + try: + while True: + chunk = body.read(64 * 1024) + if not chunk: + break + yield chunk + finally: + body.close() + return StreamingResponse(chunks(), media_type=content_type, headers={"Content-Length": str(length)}) diff --git a/src/models.py b/src/models.py new file mode 100644 index 0000000..beae6a4 --- /dev/null +++ b/src/models.py @@ -0,0 +1,28 @@ +from pydantic import BaseModel, Field, ConfigDict +from typing import List + + +# ==================== REQUEST MODELS ==================== + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=False) + username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(..., min_length=1, max_length=100) + password: str = Field(..., min_length=12, max_length=128) + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str = Field(..., min_length=1, max_length=100) + member_ids: List[str] = Field(..., min_length=1, max_length=100) + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + text: str = Field(..., max_length=4000) + attachment_ids: List[str] = Field(default_factory=list, max_length=10) + + +class LoginRequest(BaseModel): + username: str + password: str diff --git a/src/object_store.py b/src/object_store.py new file mode 100644 index 0000000..8b9a74b --- /dev/null +++ b/src/object_store.py @@ -0,0 +1,14 @@ +"""Private S3-compatible object storage client.""" +import os +import boto3 +from botocore.config import Config + +S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments") +s3 = boto3.client( + "s3", + endpoint_url=os.environ.get("S3_ENDPOINT", "http://minio:9000"), + aws_access_key_id=os.environ["S3_ACCESS_KEY"], + aws_secret_access_key=os.environ["S3_SECRET_KEY"], + region_name=os.environ.get("S3_REGION", "us-east-1"), + config=Config(connect_timeout=3, read_timeout=10, retries={"max_attempts": 2}), +) diff --git a/src/session_cache.py b/src/session_cache.py new file mode 100644 index 0000000..b17a972 --- /dev/null +++ b/src/session_cache.py @@ -0,0 +1,72 @@ +"""Redis TTL cache for active sessions; PostgreSQL remains authoritative.""" +import os +import socket +from urllib.parse import urlparse +from redis import Redis +from redis.backoff import NoBackoff +from redis.exceptions import RedisError +from redis.retry import Retry + +CACHE_URL = os.getenv("CACHE_URL", "redis://redis:6379/0") +_cache_address = urlparse(CACHE_URL) +_cache_host = _cache_address.hostname or "redis" +_cache_port = _cache_address.port or (6380 if _cache_address.scheme == "rediss" else 6379) +try: + _cache_ips = tuple(dict.fromkeys(item[4][0] for item in socket.getaddrinfo( + _cache_host, _cache_port, type=socket.SOCK_STREAM))) +except OSError: + _cache_ips = (_cache_host,) +client = Redis.from_url(CACHE_URL, decode_responses=True, + socket_connect_timeout=0.2, socket_timeout=0.2, + health_check_interval=15, retry=Retry(NoBackoff(), 0)) + + +class CacheUnavailable(Exception): + """The required session cache cannot be reached within its short timeout.""" + + +def _check_port(): + # Fail fast when the Redis container is stopped. redis-py may otherwise + # spend several seconds cycling through connection retries on Docker DNS. + try: + for address in _cache_ips: + try: + with socket.create_connection((address, _cache_port), timeout=0.2): + return + except OSError: + continue + raise OSError("Redis is not accepting connections") + except OSError as exc: + raise CacheUnavailable from exc + + +def get(token: str): + try: + _check_port() + return client.get("session:" + token) + except RedisError as exc: + raise CacheUnavailable from exc + + +def put(token: str, user_id: str, ttl_seconds: int): + try: + _check_port() + client.set("session:" + token, user_id, ex=max(1, ttl_seconds)) + except RedisError as exc: + raise CacheUnavailable from exc + + +def delete(token: str): + try: + _check_port() + client.delete("session:" + token) + except RedisError as exc: + raise CacheUnavailable from exc + + +def ping(): + try: + _check_port() + return bool(client.ping()) + except RedisError as exc: + raise CacheUnavailable from exc diff --git a/src/store.py b/src/store.py new file mode 100644 index 0000000..dd65d83 --- /dev/null +++ b/src/store.py @@ -0,0 +1,248 @@ +"""Small repository layer; each operation owns and closes its DB transaction.""" +import base64 +import json +import uuid +from datetime import datetime, timezone, timedelta +import math +from sqlalchemy import and_, or_, select, update +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.orm import selectinload +from sqlalchemy.exc import IntegrityError +from .database import User, Session as SessionRow, Chat, ChatMember, Message, MessageIdempotency, Attachment, SessionLocal +from .auth import hash_password, verify_password, new_token, SESSION_TTL_SECONDS +from . import session_cache + + +class Store: + def add_user(self, username, display_name, password): + with SessionLocal() as db: + user = User(username=username, display_name=display_name, password_hash=hash_password(password)) + db.add(user) + try: + db.commit() + except IntegrityError: + db.rollback() + raise ValueError("USERNAME_EXISTS") + db.refresh(user) + return user + + def get_user_by_id(self, user_id): + with SessionLocal() as db: + return db.query(User).filter(User.id == user_id).first() + + def verify_user_password(self, username, password): + with SessionLocal() as db: + user = db.query(User).filter(User.username == username).first() + # A fixed dummy hash is avoided here; the public contract only requires + # identical response status and challenge for unknown users/bad passwords. + if not user or not verify_password(password, user.password_hash): + return None + return user + + def create_session(self, user_id): + with SessionLocal() as db: + row = SessionRow(token=new_token(), user_id=user_id, + expires_at=datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)) + db.add(row) + db.commit() + db.refresh(row) + try: + session_cache.put(row.token, row.user_id, SESSION_TTL_SECONDS) + except session_cache.CacheUnavailable: + db.delete(row) + db.commit() + raise + return row + + def get_session_by_token(self, token): + cached_user_id = session_cache.get(token) + if cached_user_id: + return (cached_user_id, None) + with SessionLocal() as db: + row = db.query(SessionRow).filter(SessionRow.token == token, + SessionRow.expires_at > datetime.now(timezone.utc)).first() + if not row: + return None + remaining = math.ceil((row.expires_at - datetime.now(timezone.utc)).total_seconds()) + session_cache.put(row.token, row.user_id, remaining) + return (row.user_id, row.expires_at) + + def delete_session(self, token): + # Require successful cache invalidation before reporting a completed logout. + session_cache.delete(token) + with SessionLocal() as db: + row = db.query(SessionRow).filter(SessionRow.token == token).first() + if row: + db.delete(row) + db.commit() + return True + return False + + def create_chat(self, title, member_ids, creator_id): + if creator_id not in member_ids: + raise ValueError("CREATOR_NOT_MEMBER") + if len(member_ids) != len(set(member_ids)): + raise ValueError("DUPLICATE_MEMBER") + with SessionLocal() as db: + users = db.query(User.id).filter(User.id.in_(member_ids)).all() + if len(users) != len(member_ids): + raise ValueError("USER_NOT_FOUND") + chat = Chat(title=title) + chat.members = [ChatMember(user_id=mid) for mid in member_ids] + db.add(chat) + db.commit() + db.refresh(chat) + list(chat.members) + return chat + + def get_chat(self, chat_id): + with SessionLocal() as db: + return db.query(Chat).options(selectinload(Chat.members)).filter(Chat.id == chat_id).first() + + def get_user_chats(self, user_id, cursor=None, limit=50): + with SessionLocal() as db: + query = db.query(Chat).options(selectinload(Chat.members)).join(ChatMember).filter(ChatMember.user_id == user_id) + if cursor: + decoded = decode_cursor(cursor, "chats") + query = query.filter(or_(Chat.created_at > decoded[0], and_(Chat.created_at == decoded[0], Chat.id > decoded[1]))) + rows = query.order_by(Chat.created_at, Chat.id).limit(limit).all() + for row in rows: + list(row.members) + return rows + + def is_chat_member(self, chat_id, user_id): + with SessionLocal() as db: + return db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id).first() is not None + + def add_message(self, chat_id, sender_id, text): + with SessionLocal() as db: + if not db.query(Chat.id).filter(Chat.id == chat_id).first(): + raise ValueError("CHAT_NOT_FOUND") + if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == sender_id).first(): + raise ValueError("NOT_MEMBER") + msg = Message(chat_id=chat_id, sender_id=sender_id, text=text) + db.add(msg) + db.commit() + db.refresh(msg) + return msg + + def add_message_idempotent(self, chat_id, sender_id, text, attachment_ids, key, request_hash): + """Claim a scoped key and create its message in the same DB transaction.""" + with SessionLocal() as db: + if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, + ChatMember.user_id == sender_id).first(): + raise ValueError("CHAT_NOT_FOUND") + if not text.strip() and not attachment_ids: + raise ValueError("EMPTY_MESSAGE") + if attachment_ids: + rows = db.query(Attachment).filter(Attachment.id.in_(attachment_ids), + Attachment.chat_id == chat_id).all() + if len(rows) != len(attachment_ids): + raise ValueError("ATTACHMENT_NOT_FOUND") + if any(row.status == "failed" for row in rows): + raise ValueError("ATTACHMENT_FAILED") + scope = dict(user_id=sender_id, method="POST", chat_path=f"/api/v1/chats/{chat_id}/messages", key=key) + claim = insert(MessageIdempotency).values(**scope, request_hash=request_hash, + message_id=None).on_conflict_do_nothing( + constraint="uq_idempotency_scope").returning(MessageIdempotency.id) + claimed = db.execute(claim).scalar_one_or_none() + if claimed is None: + record = db.execute(select(MessageIdempotency).filter_by(**scope)).scalar_one() + if record.request_hash != request_hash: + raise ValueError("IDEMPOTENCY_CONFLICT") + msg = db.get(Message, record.message_id) + if msg is None: + raise RuntimeError("Idempotency record has no message") + return msg + msg = Message(chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids) + db.add(msg) + db.flush() + db.execute(update(MessageIdempotency).where(MessageIdempotency.id == claimed).values(message_id=msg.id)) + db.commit() + db.refresh(msg) + return msg + + def get_messages(self, chat_id, cursor=None, limit=50): + with SessionLocal() as db: + query = db.query(Message).filter(Message.chat_id == chat_id) + if cursor: + created, message_id = decode_cursor(cursor, chat_id) + query = query.filter(or_(Message.created_at > created, + and_(Message.created_at == created, Message.id > message_id))) + return query.order_by(Message.created_at, Message.id).limit(limit).all() + + def save_attachment(self, attachment): + with SessionLocal() as db: + row = Attachment(**attachment) + db.add(row) + db.commit() + db.refresh(row) + return row + + def get_attachment_for_worker(self, attachment_id): + with SessionLocal() as db: + return db.query(Attachment).filter(Attachment.id == attachment_id).first() + + def set_attachment_processing(self, attachment_id): + with SessionLocal() as db: + row = db.query(Attachment).filter(Attachment.id == attachment_id).with_for_update().first() + if not row or row.status == "ready": + return row + row.status = "processing" + row.error_code = None + row.updated_at = datetime.now(timezone.utc) + db.commit() + db.refresh(row) + return row + + def finish_attachment(self, attachment_id, variants): + with SessionLocal() as db: + row = db.query(Attachment).filter(Attachment.id == attachment_id).with_for_update().first() + if row and row.status != "ready": + row.variants = variants + row.status = "ready" + row.error_code = None + row.updated_at = datetime.now(timezone.utc) + db.commit() + db.refresh(row) + return row + + def fail_attachment(self, attachment_id, error_code): + with SessionLocal() as db: + row = db.query(Attachment).filter(Attachment.id == attachment_id).with_for_update().first() + if row and row.status != "ready": + row.status = "failed" + row.error_code = error_code + row.updated_at = datetime.now(timezone.utc) + db.commit() + + def get_attachment(self, attachment_id, user_id): + with SessionLocal() as db: + return db.query(Attachment).join(ChatMember, ChatMember.chat_id == Attachment.chat_id).filter( + Attachment.id == attachment_id, ChatMember.user_id == user_id).first() + + +def encode_cursor(resource, created_at, item_id): + raw = json.dumps([resource, created_at.isoformat(), item_id], separators=(",", ":")).encode() + return base64.urlsafe_b64encode(raw).decode().rstrip("=") + + +def decode_cursor(cursor, resource): + try: + data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))) + if data[0] != resource: + raise ValueError + return datetime.fromisoformat(data[1]), data[2] + except Exception: + raise ValueError("INVALID_CURSOR") + + +def cursor_for_chat(chat): + return encode_cursor("chats", chat.created_at, chat.id) + + +def cursor_for_message(message): + return encode_cursor(message.chat_id, message.created_at, message.id) + + +store = Store() diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 0000000..f2ab0a4 --- /dev/null +++ b/src/telemetry.py @@ -0,0 +1,56 @@ +"""Bounded OTLP instrumentation shared by the API and image worker.""" +import logging +import os +import socket + +from opentelemetry import metrics, trace +from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +SERVICE = os.getenv("OTEL_SERVICE_NAME", "messenger-api") +ENDPOINT = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4317") +configured_attributes = {} +for attribute in os.getenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment.name=lab").split(","): + key, separator, value = attribute.partition("=") + if separator and key.strip() not in {"service.name", "service.version", "service.instance.id"}: + configured_attributes[key.strip()] = value.strip() +resource = Resource.create({ + "service.name": SERVICE, + "service.version": "6.0.0", + "service.instance.id": os.getenv("HOSTNAME", socket.gethostname()), + **{"deployment.environment.name": "lab", **configured_attributes}, +}) + +tracer_provider = TracerProvider(resource=resource) +tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=ENDPOINT, insecure=True, timeout=3), max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000, export_timeout_millis=3000)) +trace.set_tracer_provider(tracer_provider) + +metric_reader = PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=ENDPOINT, insecure=True, timeout=3), export_interval_millis=5000, export_timeout_millis=3000) +metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[metric_reader])) + +logger_provider = LoggerProvider(resource=resource) +logger_provider.add_log_record_processor(BatchLogRecordProcessor( + __import__("opentelemetry.exporter.otlp.proto.grpc._log_exporter", fromlist=["OTLPLogExporter"]).OTLPLogExporter(endpoint=ENDPOINT, insecure=True, timeout=3), + max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000, export_timeout_millis=3000)) +logging.getLogger().addHandler(LoggingHandler(level=logging.INFO, logger_provider=logger_provider)) +logging.getLogger().setLevel(os.getenv("LOG_LEVEL", "INFO")) + +tracer = trace.get_tracer("messenger") +meter = metrics.get_meter("messenger") +http_requests = meter.create_counter("messenger.http.requests", description="Completed HTTP requests") +http_duration = meter.create_histogram("messenger.http.duration", unit="s", description="HTTP request duration") +jobs_processed = meter.create_counter("messenger.jobs.processed", description="Completed attachment jobs") +job_duration = meter.create_histogram("messenger.jobs.duration", unit="s", description="Attachment processing duration") + + +def shutdown(): + logger_provider.force_flush(timeout_millis=3000) + tracer_provider.force_flush(timeout_millis=3000) + metrics.get_meter_provider().force_flush(timeout_millis=3000) diff --git a/src/worker.py b/src/worker.py new file mode 100644 index 0000000..c041483 --- /dev/null +++ b/src/worker.py @@ -0,0 +1,151 @@ +"""At-least-once Redis Streams image worker with idempotent S3/DB effects.""" +import hashlib +import io +import json +import logging +import math +import os +import socket +import time +import redis +from PIL import Image, ImageOps, UnidentifiedImageError +from botocore.exceptions import BotoCoreError, ClientError +from . import object_store +from .jobs import QUEUE, CONSUMER_GROUP, MAX_ATTEMPTS, client, publish +from .store import store +from . import telemetry +from opentelemetry.propagate import extract +from opentelemetry.trace import SpanKind + +logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO")) +log = logging.getLogger("attachment-worker") +CONSUMER = f"worker-{socket.gethostname()}-{os.getpid()}" +RECLAIM_IDLE_MS = int(os.getenv("JOB_RECLAIM_IDLE_MS", "30000")) + + +def thumbnail(source): + source.seek(0) + with Image.open(source) as opened: + image = ImageOps.exif_transpose(opened) + image.load() + if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info): + rgba = image.convert("RGBA") + background = Image.new("RGB", rgba.size, "white") + background.paste(rgba, mask=rgba.getchannel("A")) + image = background + else: + image = image.convert("RGB") + scale = min(1.0, 256 / image.width, 256 / image.height) + dimensions = (max(1, math.floor(image.width * scale)), + max(1, math.floor(image.height * scale))) + if dimensions != image.size: + image = image.resize(dimensions, Image.Resampling.LANCZOS) + output = io.BytesIO() + image.save(output, format="JPEG", quality=85, optimize=True) + return output.getvalue(), image.width, image.height + + +def process(job): + row = store.get_attachment_for_worker(job["attachment_id"]) + if row is None or row.job_id != job["job_id"] or row.status == "ready": + return + row = store.set_attachment_processing(row.id) + if row is None or row.status == "ready": + return + obj = object_store.s3.get_object(Bucket=object_store.S3_BUCKET, Key=row.staging_key) + raw = obj["Body"].read() + obj["Body"].close() + try: + with Image.open(io.BytesIO(raw)) as image: + if image.width * image.height > 40_000_000: + raise ValueError("invalid_image") + image.verify() + except (UnidentifiedImageError, OSError, Image.DecompressionBombError) as exc: + raise ValueError("invalid_image") from exc + thumb, width, height = thumbnail(io.BytesIO(raw)) + s3 = object_store.s3 + s3.put_object(Bucket=object_store.S3_BUCKET, Key=row.object_key, Body=raw, + ContentLength=len(raw), ContentType=row.content_type) + key = f"variants/{row.id}/thumbnail" + s3.put_object(Bucket=object_store.S3_BUCKET, Key=key, Body=thumb, + ContentLength=len(thumb), ContentType="image/jpeg") + variant = {"name": "thumbnail", "content_type": "image/jpeg", + "size_bytes": len(thumb), "width": width, "height": height, + "sha256": hashlib.sha256(thumb).hexdigest()} + store.finish_attachment(row.id, [variant]) + + +def handle(broker, stream_id, body): + job = None + started = time.perf_counter() + outcome = "success" + trace_id = None + span_id = None + try: + job = json.loads(body) + if job.get("schema_version") != 1 or job.get("type") != "attachment.process.v1": + raise ValueError("invalid_job") + parent = extract({key: job[key] for key in ("traceparent", "tracestate") if key in job}) + with telemetry.tracer.start_as_current_span("attachment.process", context=parent, kind=SpanKind.CONSUMER) as span: + span.set_attribute("messenger.job.type", "attachment.process.v1") + span.set_attribute("messenger.job.attempt", int(job.get("attempt", 1))) + span_context = span.get_span_context() + trace_id = format(span_context.trace_id, "032x") + span_id = format(span_context.span_id, "016x") + process(job) + except (ValueError, KeyError) as exc: + outcome = "failed" + log.warning("permanent job failure code=%s", str(exc)[:64]) + if job: + code = "invalid_image" if str(exc) == "invalid_image" else "invalid_job" + store.fail_attachment(job.get("attachment_id"), code) + except Exception as exc: + outcome = "failed" + log.error("attachment processing failure class=%s", type(exc).__name__) + if job: + attempt = int(job.get("attempt", 1)) + if attempt >= MAX_ATTEMPTS: + store.fail_attachment(job.get("attachment_id"), "retry_exhausted") + else: + time.sleep(min(2 ** (attempt - 1), 8)) + # Add the next bounded attempt before acking this delivery. + publish(job["attachment_id"], job["job_id"], attempt + 1) + finally: + telemetry.jobs_processed.add(1, {"job.type": "attachment.process.v1", "job.outcome": outcome}) + telemetry.job_duration.record(time.perf_counter() - started, {"job.type": "attachment.process.v1", "job.outcome": outcome}) + logging.getLogger("messenger.worker").info("attachment_job_finished", extra={"job_type": "attachment.process.v1", "job_outcome": outcome, "trace_id": trace_id, "span_id": span_id}) + broker.xack(QUEUE, CONSUMER_GROUP, stream_id) + + +def main(): + while True: + try: + broker = client() + try: + broker.xgroup_create(QUEUE, CONSUMER_GROUP, id="0-0", mkstream=True) + except redis.ResponseError as exc: + if "BUSYGROUP" not in str(exc): + raise + log.info("worker consuming Redis Stream %s as %s", QUEUE, CONSUMER) + cursor = "0-0" + while True: + reclaimed = broker.xautoclaim(QUEUE, CONSUMER_GROUP, CONSUMER, + min_idle_time=RECLAIM_IDLE_MS, + start_id=cursor, count=1) + cursor, pending = reclaimed[0], reclaimed[1] + if pending: + for stream_id, fields in pending: + handle(broker, stream_id, fields["body"]) + continue + fresh = broker.xreadgroup(CONSUMER_GROUP, CONSUMER, + {QUEUE: ">"}, count=1, block=5000) + for _, entries in fresh: + for stream_id, fields in entries: + handle(broker, stream_id, fields["body"]) + except Exception: + log.exception("broker unavailable; reconnecting") + time.sleep(2) + + +if __name__ == "__main__": + main() diff --git a/student-tests/s3_unavailable.py b/student-tests/s3_unavailable.py new file mode 100644 index 0000000..591faa9 --- /dev/null +++ b/student-tests/s3_unavailable.py @@ -0,0 +1,43 @@ +"""Verify that S3 outages fail readiness/uploads cleanly and recover after restart.""" +import subprocess +import time +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, arguments, run # noqa: E402 + + +def main(): + args = arguments("MinIO outage and recovery checks") + # S3 health checks can spend the configured botocore connect timeout on an + # unreachable service before the API returns the expected JSON 503. + c = Client(args.base_url, args.ca_file, timeout=30) + alice, _bob, _eve, chat = c.bootstrap() + fixture = (ROOT / "tests/fixtures/sample.png").read_bytes() + subprocess.run(["docker", "compose", "--env-file", ".env", "stop", "minio"], + cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + # Nginx may hit its upstream timeout while both replicas are waiting + # for the S3 connect timeout, so 504 is also an expected outage result. + c.call("GET", "/health/ready", [503, 504]) + c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=outage.png", [503, 504], + actor=alice, raw=fixture, headers={"Content-Type": "image/png"}) + finally: + subprocess.run(["docker", "compose", "--env-file", ".env", "start", "minio"], + cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + deadline = time.monotonic() + 45 + while True: + try: + c.call("GET", "/health/ready", schema="Health") + break + except Exception: + if time.monotonic() >= deadline: + raise + time.sleep(0.5) + print("PASS: MinIO outage returned 503/504 for readiness/upload and recovered after service restart") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/worker_recovery.py b/student-tests/worker_recovery.py new file mode 100644 index 0000000..e5ffffb --- /dev/null +++ b/student-tests/worker_recovery.py @@ -0,0 +1,57 @@ +"""Demonstrate accepted upload recovery while the worker is stopped.""" +import hashlib +from pathlib import Path +import subprocess +import sys +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, check +from image_probe import jpeg_size + + +def compose(*args): + subprocess.run(["docker", "compose", "--env-file", ".env", *args], + cwd=ROOT, check=True) + + +def main(): + client = Client("http://localhost:8080", timeout=10) + alice, bob, _, chat = client.bootstrap() + print("Created synthetic users and chat", flush=True) + compose("stop", "worker") + print("Stopped worker", flush=True) + try: + attachment, original = client.attachment(alice, chat) + print("Upload returned queued", flush=True) + sent = client.message(alice, chat, "", attachments=[attachment["id"]])["json"] + check(sent["attachment_ids"] == [attachment["id"]], "message did not retain attachment reference") + client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", + 409, actor=bob) + print("Message linked; content correctly unavailable while queued", flush=True) + + # The worker stays stopped while the API and durable broker are restarted. + compose("restart", "api1", "api2", "redis-broker", "lb") + print("Restarted API and broker with worker stopped", flush=True) + compose("start", "worker") + print("Started worker", flush=True) + + ready = client.wait_ready(bob, attachment) + original_response = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", + actor=bob) + check(original_response["bytes"] == original, "recovered original bytes changed") + check(hashlib.sha256(original_response["bytes"]).hexdigest() == attachment["sha256"], + "recovered original SHA-256 mismatch") + thumbnail_meta = next(v for v in ready["variants"] if v["name"] == "thumbnail") + thumbnail = client.call("GET", "/api/v1/attachments/" + attachment["id"] + + "/content?variant=thumbnail", actor=bob) + check(thumbnail["headers"].get_content_type() == "image/jpeg", "thumbnail is not JPEG") + check(jpeg_size(thumbnail["bytes"]) == (256, 160), "thumbnail dimensions mismatch") + check(hashlib.sha256(thumbnail["bytes"]).hexdigest() == thumbnail_meta["sha256"], + "thumbnail checksum mismatch") + print("PASS: worker recovery; upload stayed queued through API/broker restart and became ready") + finally: + compose("start", "worker") + + +if __name__ == "__main__": + main()