From bf8e4e3cd1dca648108036ca804b08b9a483cf2b Mon Sep 17 00:00:00 2001 From: Artyom Date: Wed, 28 Oct 2026 20:17:51 +0300 Subject: [PATCH] Carry over the lab 3 solution Bring the application, own tests, Dockerfile, toolchain, compose stack, HAProxy and k6 configuration, migrations, hooks, evidence and level 4 scripts and the CI job from the lab 3 solution commit 61c0c28, merge the lab 3 Makefile targets into the lab 4 skeleton Makefile without touching its targets, and append the lab 3 solution variables to the skeleton .env.example. The package and the application follow the contract version 1.4.0, and the image and the throwaway test containers are tagged lab4 so they do not collide with a lab 3 stand on the same host. This is the starting point of the lab 4 cycle: lint, own tests and the offline skeleton check pass before any lab 4 change. Co-Authored-By: Claude Opus 5.5 (1M context) --- .dockerignore | 24 + .env.example | 18 + .github/workflows/application.yml | 77 ++ Dockerfile | 48 ++ Makefile | 116 ++- compose.yaml | 185 +++++ infra/haproxy/haproxy.cfg | 67 ++ infra/k6/messages.js | 106 +++ pyproject.toml | 114 +++ scripts/detection.sh | 20 + scripts/evidence-cache.sh | 24 + scripts/evidence-stack.sh | 48 ++ scripts/evidence-storage.sh | 44 + scripts/failover-each.sh | 19 + scripts/failover-evidence.sh | 28 + scripts/k6.sh | 10 + scripts/lb-wait.sh | 11 + scripts/limits.py | 132 +++ scripts/persistence-evidence.sh | 14 + scripts/probe.py | 436 ++++++++++ scripts/restart.sh | 12 + scripts/restore.sh | 5 + scripts/rolling-update.sh | 20 + scripts/secrets.sh | 20 + scripts/sql/explain-history.sql | 59 ++ scripts/sql/seed-history.sql | 40 + scripts/stop-one.sh | 9 + src/messenger/__init__.py | 0 src/messenger/gunicorn_conf.py | 66 ++ src/messenger/identity/__init__.py | 0 .../identity/application/__init__.py | 0 src/messenger/identity/application/bus.py | 5 + .../identity/application/commands.py | 22 + .../identity/application/handlers.py | 76 ++ src/messenger/identity/application/ports.py | 48 ++ src/messenger/identity/application/queries.py | 43 + src/messenger/identity/config.py | 12 + src/messenger/identity/domain/__init__.py | 0 src/messenger/identity/domain/errors.py | 17 + src/messenger/identity/domain/events.py | 25 + src/messenger/identity/domain/models.py | 62 ++ src/messenger/identity/domain/values.py | 54 ++ .../identity/entrypoints/__init__.py | 0 .../identity/entrypoints/authentication.py | 98 +++ src/messenger/identity/entrypoints/errors.py | 12 + src/messenger/identity/entrypoints/http.py | 57 ++ src/messenger/identity/entrypoints/ioc.py | 112 +++ src/messenger/identity/entrypoints/journal.py | 20 + src/messenger/identity/entrypoints/schemas.py | 42 + .../identity/infrastructure/__init__.py | 0 .../identity/infrastructure/argon2.py | 35 + .../identity/infrastructure/postgres.py | 124 +++ .../identity/infrastructure/valkey.py | 102 +++ src/messenger/main.py | 104 +++ src/messenger/messaging/__init__.py | 0 .../messaging/application/__init__.py | 0 src/messenger/messaging/application/bus.py | 5 + .../messaging/application/commands.py | 21 + .../messaging/application/handlers.py | 62 ++ src/messenger/messaging/application/ports.py | 46 ++ .../messaging/application/queries.py | 73 ++ src/messenger/messaging/config.py | 8 + src/messenger/messaging/domain/__init__.py | 0 src/messenger/messaging/domain/errors.py | 25 + src/messenger/messaging/domain/events.py | 24 + src/messenger/messaging/domain/keys.py | 3 + src/messenger/messaging/domain/models.py | 142 ++++ src/messenger/messaging/domain/values.py | 39 + .../messaging/entrypoints/__init__.py | 0 src/messenger/messaging/entrypoints/errors.py | 16 + src/messenger/messaging/entrypoints/http.py | 89 ++ src/messenger/messaging/entrypoints/ioc.py | 69 ++ .../messaging/entrypoints/journal.py | 27 + .../messaging/entrypoints/schemas.py | 82 ++ .../messaging/infrastructure/__init__.py | 0 .../messaging/infrastructure/cursor.py | 59 ++ .../messaging/infrastructure/postgres.py | 201 +++++ src/messenger/migrate.py | 70 ++ src/messenger/migrations/0001_init.sql | 46 ++ .../migrations/0002_idempotency_keys.sql | 10 + src/messenger/shared/__init__.py | 0 src/messenger/shared/application/__init__.py | 0 src/messenger/shared/application/commands.py | 2 + src/messenger/shared/application/errors.py | 2 + .../shared/application/messagebus.py | 123 +++ src/messenger/shared/application/ports.py | 42 + src/messenger/shared/config.py | 49 ++ src/messenger/shared/domain/__init__.py | 0 src/messenger/shared/domain/errors.py | 4 + src/messenger/shared/domain/events.py | 6 + src/messenger/shared/entrypoints/__init__.py | 0 src/messenger/shared/entrypoints/actor.py | 16 + src/messenger/shared/entrypoints/config.py | 10 + src/messenger/shared/entrypoints/errors.py | 136 ++++ src/messenger/shared/entrypoints/health.py | 25 + src/messenger/shared/entrypoints/ioc.py | 54 ++ src/messenger/shared/entrypoints/pipeline.py | 165 ++++ src/messenger/shared/entrypoints/schemas.py | 21 + .../shared/infrastructure/__init__.py | 0 src/messenger/shared/infrastructure/clock.py | 17 + src/messenger/shared/infrastructure/ids.py | 8 + .../shared/infrastructure/logging.py | 113 +++ .../shared/infrastructure/postgres.py | 118 +++ student-tests/api/test_access.py | 84 ++ student-tests/api/test_bounded_contexts.py | 242 ++++++ student-tests/api/test_cache.py | 118 +++ student-tests/api/test_concurrency.py | 88 ++ student-tests/api/test_consistency.py | 188 +++++ student-tests/api/test_drain.py | 108 +++ student-tests/api/test_events.py | 124 +++ student-tests/api/test_idempotency.py | 145 ++++ student-tests/api/test_instance.py | 64 ++ student-tests/api/test_migrations.py | 77 ++ student-tests/api/test_negative.py | 196 +++++ student-tests/api/test_operability.py | 144 ++++ student-tests/api/test_pagination.py | 155 ++++ student-tests/api/test_pool.py | 27 + student-tests/api/test_sessions.py | 172 ++++ student-tests/api/test_timeout.py | 97 +++ student-tests/api/test_wire_format.py | 68 ++ student-tests/conftest.py | 208 +++++ student-tests/fakes.py | 23 + student-tests/stack/test_faults.py | 229 ++++++ student-tests/stand.py | 132 +++ student-tests/unit/test_authentication.py | 64 ++ student-tests/unit/test_cursor.py | 56 ++ student-tests/unit/test_domain.py | 197 +++++ student-tests/unit/test_timeouts.py | 60 ++ uv.lock | 763 ++++++++++++++++++ 129 files changed, 8698 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/application.yml create mode 100644 Dockerfile create mode 100644 compose.yaml create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 infra/k6/messages.js create mode 100644 pyproject.toml create mode 100755 scripts/detection.sh create mode 100755 scripts/evidence-cache.sh create mode 100755 scripts/evidence-stack.sh create mode 100755 scripts/evidence-storage.sh create mode 100755 scripts/failover-each.sh create mode 100755 scripts/failover-evidence.sh create mode 100755 scripts/k6.sh create mode 100755 scripts/lb-wait.sh create mode 100644 scripts/limits.py create mode 100755 scripts/persistence-evidence.sh create mode 100755 scripts/probe.py create mode 100755 scripts/restart.sh create mode 100755 scripts/restore.sh create mode 100755 scripts/rolling-update.sh create mode 100755 scripts/secrets.sh create mode 100644 scripts/sql/explain-history.sql create mode 100644 scripts/sql/seed-history.sql create mode 100755 scripts/stop-one.sh create mode 100644 src/messenger/__init__.py create mode 100644 src/messenger/gunicorn_conf.py create mode 100644 src/messenger/identity/__init__.py create mode 100644 src/messenger/identity/application/__init__.py create mode 100644 src/messenger/identity/application/bus.py create mode 100644 src/messenger/identity/application/commands.py create mode 100644 src/messenger/identity/application/handlers.py create mode 100644 src/messenger/identity/application/ports.py create mode 100644 src/messenger/identity/application/queries.py create mode 100644 src/messenger/identity/config.py create mode 100644 src/messenger/identity/domain/__init__.py create mode 100644 src/messenger/identity/domain/errors.py create mode 100644 src/messenger/identity/domain/events.py create mode 100644 src/messenger/identity/domain/models.py create mode 100644 src/messenger/identity/domain/values.py create mode 100644 src/messenger/identity/entrypoints/__init__.py create mode 100644 src/messenger/identity/entrypoints/authentication.py create mode 100644 src/messenger/identity/entrypoints/errors.py create mode 100644 src/messenger/identity/entrypoints/http.py create mode 100644 src/messenger/identity/entrypoints/ioc.py create mode 100644 src/messenger/identity/entrypoints/journal.py create mode 100644 src/messenger/identity/entrypoints/schemas.py create mode 100644 src/messenger/identity/infrastructure/__init__.py create mode 100644 src/messenger/identity/infrastructure/argon2.py create mode 100644 src/messenger/identity/infrastructure/postgres.py create mode 100644 src/messenger/identity/infrastructure/valkey.py create mode 100644 src/messenger/main.py create mode 100644 src/messenger/messaging/__init__.py create mode 100644 src/messenger/messaging/application/__init__.py create mode 100644 src/messenger/messaging/application/bus.py create mode 100644 src/messenger/messaging/application/commands.py create mode 100644 src/messenger/messaging/application/handlers.py create mode 100644 src/messenger/messaging/application/ports.py create mode 100644 src/messenger/messaging/application/queries.py create mode 100644 src/messenger/messaging/config.py create mode 100644 src/messenger/messaging/domain/__init__.py create mode 100644 src/messenger/messaging/domain/errors.py create mode 100644 src/messenger/messaging/domain/events.py create mode 100644 src/messenger/messaging/domain/keys.py create mode 100644 src/messenger/messaging/domain/models.py create mode 100644 src/messenger/messaging/domain/values.py create mode 100644 src/messenger/messaging/entrypoints/__init__.py create mode 100644 src/messenger/messaging/entrypoints/errors.py create mode 100644 src/messenger/messaging/entrypoints/http.py create mode 100644 src/messenger/messaging/entrypoints/ioc.py create mode 100644 src/messenger/messaging/entrypoints/journal.py create mode 100644 src/messenger/messaging/entrypoints/schemas.py create mode 100644 src/messenger/messaging/infrastructure/__init__.py create mode 100644 src/messenger/messaging/infrastructure/cursor.py create mode 100644 src/messenger/messaging/infrastructure/postgres.py create mode 100644 src/messenger/migrate.py create mode 100644 src/messenger/migrations/0001_init.sql create mode 100644 src/messenger/migrations/0002_idempotency_keys.sql create mode 100644 src/messenger/shared/__init__.py create mode 100644 src/messenger/shared/application/__init__.py create mode 100644 src/messenger/shared/application/commands.py create mode 100644 src/messenger/shared/application/errors.py create mode 100644 src/messenger/shared/application/messagebus.py create mode 100644 src/messenger/shared/application/ports.py create mode 100644 src/messenger/shared/config.py create mode 100644 src/messenger/shared/domain/__init__.py create mode 100644 src/messenger/shared/domain/errors.py create mode 100644 src/messenger/shared/domain/events.py create mode 100644 src/messenger/shared/entrypoints/__init__.py create mode 100644 src/messenger/shared/entrypoints/actor.py create mode 100644 src/messenger/shared/entrypoints/config.py create mode 100644 src/messenger/shared/entrypoints/errors.py create mode 100644 src/messenger/shared/entrypoints/health.py create mode 100644 src/messenger/shared/entrypoints/ioc.py create mode 100644 src/messenger/shared/entrypoints/pipeline.py create mode 100644 src/messenger/shared/entrypoints/schemas.py create mode 100644 src/messenger/shared/infrastructure/__init__.py create mode 100644 src/messenger/shared/infrastructure/clock.py create mode 100644 src/messenger/shared/infrastructure/ids.py create mode 100644 src/messenger/shared/infrastructure/logging.py create mode 100644 src/messenger/shared/infrastructure/postgres.py create mode 100644 student-tests/api/test_access.py create mode 100644 student-tests/api/test_bounded_contexts.py create mode 100644 student-tests/api/test_cache.py create mode 100644 student-tests/api/test_concurrency.py create mode 100644 student-tests/api/test_consistency.py create mode 100644 student-tests/api/test_drain.py create mode 100644 student-tests/api/test_events.py create mode 100644 student-tests/api/test_idempotency.py create mode 100644 student-tests/api/test_instance.py create mode 100644 student-tests/api/test_migrations.py create mode 100644 student-tests/api/test_negative.py create mode 100644 student-tests/api/test_operability.py create mode 100644 student-tests/api/test_pagination.py create mode 100644 student-tests/api/test_pool.py create mode 100644 student-tests/api/test_sessions.py create mode 100644 student-tests/api/test_timeout.py create mode 100644 student-tests/api/test_wire_format.py create mode 100644 student-tests/conftest.py create mode 100644 student-tests/fakes.py create mode 100644 student-tests/stack/test_faults.py create mode 100644 student-tests/stand.py create mode 100644 student-tests/unit/test_authentication.py create mode 100644 student-tests/unit/test_cursor.py create mode 100644 student-tests/unit/test_domain.py create mode 100644 student-tests/unit/test_timeouts.py create mode 100644 uv.lock diff --git a/.dockerignore b/.dockerignore index bc16e556..bee74195 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,7 +14,31 @@ backups *.pfx *.jks .venv +venv __pycache__ +*.pyc +*.pyo +.pytest_cache +.ruff_cache +.mypy_cache +.ty_cache node_modules evidence +openspec +student-tests +tests +scripts +examples +contracts +infra +*.md +!README.md +Makefile +Dockerfile* +compose*.yaml +.dockerignore +.gitignore .DS_Store +lab.json +requirements-dev.txt +.claude diff --git a/.env.example b/.env.example index d99d26a2..b6d66c7b 100644 --- a/.env.example +++ b/.env.example @@ -18,3 +18,21 @@ S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 +# Solution-specific: published LB ports, replica limits, workers and pool per replica, +# LB queue per replica, drain window before closing the listener on SIGTERM, PostgreSQL +# limits, load generator limits (profile bench), cursor key file. API_PORT/SHORTTTL_PORT of lab2 are gone: +# only the load balancer is published. +LB_HTTP_PORT=8080 +LB_STATS_PORT=8404 +API_CPUS=1 +API_MEMORY=512m +WEB_CONCURRENCY=2 +DB_POOL_MAX_SIZE=8 +API_SERVER_MAXCONN=64 +DRAIN_SECONDS=2 +PG_MAX_CONNECTIONS=200 +PG_CPUS=2 +PG_MEMORY=1g +K6_CPUS=2 +K6_MEMORY=512m +CURSOR_SECRET_FILE=/run/secrets/cursor_secret diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 00000000..bae9be48 --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,77 @@ +name: Application + +on: [push, pull_request] + +permissions: + contents: read + +jobs: + quality: + name: Линт, типы и собственные тесты + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v5 + with: + enable-cache: true + - run: uv sync --locked --group dev + - run: make lint VENV=.venv + - run: make student-test VENV=.venv + + acceptance: + name: Стенд Compose за HAProxy, smoke, отказ реплики, рестарт и отказы зависимостей + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v5 + with: + enable-cache: true + - run: uv sync --locked --group dev + + - name: Поднять стенд из чистого clone + run: make up + + - name: Публичный smoke через балансировщик + run: make test + + - name: Несколько реплик на одном токене и гонка одного ключа + run: make lb-check + + - name: Остановка реплики под запросами, затем возврат + run: | + make test-failover ACTION_SCRIPT=scripts/stop-one.sh + docker compose ps -a api + make restore + + - name: Рестарт LB, API и хранилищ с сохранением volumes + run: make test-persistence ACTION_SCRIPT=scripts/restart.sh + + - name: Отказы Valkey и PostgreSQL, гонка и rollback + run: make test-faults + + - name: Лимиты, порты, секреты, volumes и сети по политике + run: make limits + + - name: Время обнаружения отказа балансировщиком (SIGTERM, kill, pause, PostgreSQL) + run: make detection + + - name: Наружу опубликован только балансировщик + run: | + docker compose ps --format '{{.Service}} {{.Ports}}' | awk '$2 != "" && $1 != "lb" {print; bad=1} END {exit bad}' + + - name: Процессы работают не от root + run: | + docker compose top | awk 'NR>1 && $3=="0" {print; bad=1} END {exit bad}' + + - name: Корректная остановка реплик API по SIGTERM + run: | + start=$(date +%s) + docker compose kill --signal SIGTERM api + codes=$(docker wait $(docker compose ps -aq api) | sort -u) + elapsed=$(( $(date +%s) - start )) + echo "остановка за ${elapsed} с, коды завершения ${codes}" + test "$elapsed" -le 10 && test "$codes" = "0" + + - name: Журналы стенда + if: always() + run: docker compose logs --tail 80 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..1f4e6fed --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS builder + +COPY --from=ghcr.io/astral-sh/uv:0.9.7@sha256:ba4857bf2a068e9bc0e64eed8563b065908a4cd6bfb66b531a9c424c8e25e142 /uv /usr/local/bin/uv + +ENV UV_COMPILE_BYTECODE=1 \ + UV_LINK_MODE=copy \ + UV_PYTHON_DOWNLOADS=never \ + UV_PROJECT_ENVIRONMENT=/opt/venv + +WORKDIR /build + +COPY pyproject.toml uv.lock README.md ./ +RUN uv sync --locked --no-dev --no-install-project --no-editable + +COPY src ./src +RUN uv sync --locked --no-dev --no-editable + + +FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS runtime + +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PATH="/opt/venv/bin:$PATH" \ + HOST=0.0.0.0 \ + PORT=8080 \ + LOG_LEVEL=INFO \ + WEB_CONCURRENCY=2 \ + REQUEST_TIMEOUT_SECONDS=8 \ + DRAIN_SECONDS=2 \ + SHUTDOWN_TIMEOUT_SECONDS=5 + +RUN groupadd --system --gid 10001 messenger \ + && useradd --system --uid 10001 --gid messenger --no-create-home --shell /usr/sbin/nologin messenger + +COPY --from=builder --chown=root:root /opt/venv /opt/venv + +WORKDIR /app + +USER 10001:10001 + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD ["python", "-c", "import urllib.request,sys;sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/live',timeout=2).status==200 else 1)"] + +CMD ["python", "-m", "gunicorn", \ + "--config", "python:messenger.gunicorn_conf", \ + "messenger.main:create_app()"] diff --git a/Makefile b/Makefile index 5d86d171..c3b05ed5 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,27 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +VENV ?= .venv +UV ?= uv +COMPOSE ?= docker compose +RATE ?= 100 +API_IMAGE ?= mtusi-messenger:lab4 +FROM_REV ?= +SCRIPTS_PY = scripts/probe.py scripts/limits.py +PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q + +.PHONY: help check validate test load test-persistence test-failover \ + install lint format typecheck student-test \ + secrets up down reset-data migrate ps logs restore lb-check failover-evidence stack-evidence \ + persistence-evidence storage-evidence cache-evidence test-faults seed explain \ + limits detection failover-each rolling-update level4 help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "install/lint/typecheck/student-test: студенческий тулчейн" + @echo "secrets/up/down/migrate/ps/logs: стенд Docker Compose; reset-data: намеренное удаление volumes" + @echo "restore: вернуть остановленные реплики; lb-check: реплики на одном токене и 20 гонок одного ключа" + @echo "level4 = limits, lb-check, detection, failover-each, rolling-update [FROM_REV=<коммит>]; RATE=$(RATE) rps" check: $(PYTHON) scripts/check_contract.py @@ -28,3 +45,100 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +install: + $(UV) sync --group dev + +lint: + $(VENV)/bin/ruff check src student-tests $(SCRIPTS_PY) + $(VENV)/bin/ruff format --check src student-tests $(SCRIPTS_PY) + $(VENV)/bin/ty check src student-tests + +format: + $(VENV)/bin/ruff check --fix src student-tests $(SCRIPTS_PY) + $(VENV)/bin/ruff format src student-tests $(SCRIPTS_PY) + +typecheck: + $(VENV)/bin/ty check src student-tests + +student-test: + $(VENV)/bin/pytest + +secrets: + sh scripts/secrets.sh + +up: secrets + $(COMPOSE) up -d --build --wait + +down: + $(COMPOSE) down + +reset-data: + @echo "Удаляются volumes с учебными данными стенда" + $(COMPOSE) down -v --remove-orphans + +migrate: + $(COMPOSE) run --rm migrate + +ps: + $(COMPOSE) ps + +logs: + $(COMPOSE) logs --tail 200 + +restore: + scripts/restore.sh + +lb-check: + $(PYTHON) scripts/probe.py check --rounds 20 --out evidence/lb-check.json + +limits: + $(PYTHON) scripts/limits.py --out evidence/limits.txt + +detection: + sh scripts/detection.sh evidence/detection + +failover-each: + RATE=$(RATE) sh scripts/failover-each.sh evidence/failover-each + +rolling-update: +ifneq ($(FROM_REV),) + git archive "$(FROM_REV)" | docker build -q -t "$(API_IMAGE)" - + $(COMPOSE) up -d --no-deps --force-recreate --wait api + scripts/lb-wait.sh +endif + $(COMPOSE) build -q api + RATE=$(RATE) $(PYTHON) scripts/probe.py load --expect replace --duration 90 \ + --out evidence/rolling$(if $(FROM_REV),-from-$(FROM_REV)) \ + -- scripts/rolling-update.sh + +level4: limits lb-check detection failover-each rolling-update + +failover-evidence: + sh scripts/failover-evidence.sh "$(BASE_URL)" + +stack-evidence: + sh scripts/evidence-stack.sh + +persistence-evidence: + sh scripts/persistence-evidence.sh "$(BASE_URL)" > evidence/persistence.txt + cat evidence/persistence.txt + +storage-evidence: + sh scripts/evidence-storage.sh + +cache-evidence: + sh scripts/evidence-cache.sh > evidence/cache.txt + cat evidence/cache.txt + +test-faults: + BASE_URL="$(BASE_URL)" $(VENV)/bin/pytest -m stack -v -s student-tests/stack + +seed: + $(PSQL) -f - < scripts/sql/seed-history.sql + +explain: seed + { echo "date: $$(date -u +%FT%TZ) commit: $$(git rev-parse --short HEAD)"; \ + echo "\$$ make explain # scripts/sql/explain-history.sql"; \ + $(PSQL) -f - < scripts/sql/explain-history.sql; } > evidence/explain-history.txt + cat evidence/explain-history.txt diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..c47342dd --- /dev/null +++ b/compose.yaml @@ -0,0 +1,185 @@ +x-app: &app + image: ${API_IMAGE:-mtusi-messenger:lab4} + networks: [backend] + +services: + lb: + image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b + environment: + API_SERVER_MAXCONN: ${API_SERVER_MAXCONN:-64} + volumes: [./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro] + ports: + - "127.0.0.1:${LB_HTTP_PORT:-8080}:8080" + - "127.0.0.1:${LB_STATS_PORT:-8404}:8404" + networks: [edge, backend] + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/healthz"] + interval: 2s + timeout: 2s + retries: 3 + start_period: 10s + sysctls: + net.ipv4.ip_local_port_range: "10240 65535" + net.ipv4.tcp_tw_reuse: "1" + stop_signal: SIGUSR1 + stop_grace_period: 8s + restart: unless-stopped + read_only: true + cap_drop: [ALL] + deploy: + resources: + limits: {cpus: "${LB_CPUS:-1}", memory: 128m} + + api: + <<: *app + build: . + environment: + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + CURSOR_SECRET_FILE: /run/secrets/cursor_secret + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} + DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-8} + REQUEST_TIMEOUT_SECONDS: ${REQUEST_TIMEOUT_SECONDS:-8} + DB_ACQUIRE_TIMEOUT_SECONDS: ${DB_ACQUIRE_TIMEOUT_SECONDS:-1} + DB_COMMAND_TIMEOUT_SECONDS: ${DB_COMMAND_TIMEOUT_SECONDS:-2} + DRAIN_SECONDS: ${DRAIN_SECONDS:-2} + SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-5} + LOG_LEVEL: ${LOG_LEVEL:-INFO} + secrets: [database_url, cache_url, cursor_secret] + healthcheck: + test: ["CMD", "python", "-c", "import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200)"] + interval: 5s + timeout: 3s + retries: 3 + start_period: 30s + start_interval: 1s + stop_grace_period: 8s + restart: unless-stopped + read_only: true + tmpfs: [/tmp] + depends_on: + migrate: + condition: service_completed_successfully + valkey: + condition: service_started + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: {cpus: "${API_CPUS:-1}", memory: "${API_MEMORY:-512m}"} + + migrate: + <<: *app + pull_policy: never + command: ["python", "-m", "messenger.migrate"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + LOG_LEVEL: ${LOG_LEVEL:-INFO} + secrets: [database_url] + healthcheck: + disable: true + restart: "no" + depends_on: + postgres: + condition: service_healthy + deploy: + resources: + limits: {cpus: "0.5", memory: 256m} + + postgres: + image: postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b + user: "70:70" + command: + - postgres + - -c + - max_connections=${PG_MAX_CONNECTIONS:-200} + - -c + - shared_buffers=${PG_SHARED_BUFFERS:-256MB} + - -c + - shared_preload_libraries=pg_stat_statements + - -c + - pg_stat_statements.track=top + - -c + - track_io_timing=on + - -c + - idle_in_transaction_session_timeout=10s + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: [postgres_password] + volumes: [pgdata:/var/lib/postgresql/data] + shm_size: 256m + healthcheck: + test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "messenger", "-d", "messenger"] + interval: 2s + timeout: 3s + retries: 30 + start_period: 10s + stop_grace_period: 10s + restart: unless-stopped + networks: [backend] + deploy: + resources: + limits: {cpus: "${PG_CPUS:-2}", memory: "${PG_MEMORY:-1g}"} + + valkey: + image: valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a + user: "999:1000" + command: + - valkey-server + - /run/secrets/valkey.conf + - --appendonly + - "yes" + - --appendfsync + - always + - --maxmemory + - 64mb + - --maxmemory-policy + - volatile-lru + secrets: [valkey.conf] + volumes: [valkeydata:/data] + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)\" valkey-cli ping | grep -q PONG"] + interval: 2s + timeout: 3s + retries: 30 + stop_grace_period: 10s + restart: unless-stopped + networks: [backend] + deploy: + resources: + limits: {cpus: "0.5", memory: 128m} + + k6: + image: grafana/k6:2.3.0@sha256:2dd4756ec6e14e62778916e1eb850108e4b499304c02df56760fa0bdb0fba0b8 + profiles: [bench] + environment: + BASE_URL: http://lb:8080 + volumes: [./infra/k6:/scripts:ro] + networks: [edge] + deploy: + resources: + limits: {cpus: "${K6_CPUS:-2}", memory: "${K6_MEMORY:-512m}"} + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + valkey.conf: + file: ./secrets/valkey.conf + cache_url: + file: ./secrets/cache_url + cursor_secret: + file: ./secrets/cursor_secret + +volumes: + pgdata: + valkeydata: + +networks: + edge: + backend: + internal: true diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..c9bcacf1 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,67 @@ +global + log stdout format raw local0 info + maxconn 4096 + hard-stop-after 5s + tune.bufsize 32768 + +resolvers docker + nameserver dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold nx 2s + hold other 2s + hold refused 2s + hold timeout 2s + +defaults + mode http + log global + option dontlognull + option dontlog-normal + log-format "%ci [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] %HM %HPO" + option http-server-close + option redispatch 1 + retries 2 + retry-on conn-failure empty-response + timeout connect 500ms + timeout client 30s + timeout server 10s + timeout http-request 5s + timeout http-keep-alive 5s + timeout queue 3s + timeout check 1s + http-error status 502 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream replica failed","request_id":"%[var(txn.request_id)]"}}' + http-error status 503 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"No ready API replica","request_id":"%[var(txn.request_id)]"}}' + http-error status 504 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream timeout","request_id":"%[var(txn.request_id)]"}}' + +frontend public + bind :8080 + option forwardfor + http-request set-var(txn.request_id) req.fhdr(X-Request-Id) if { req.fhdr(X-Request-Id) -m len 1:200 } + http-request set-var(txn.request_id) uuid(4) unless { var(txn.request_id) -m found } + http-request set-header X-Request-Id %[var(txn.request_id)] + default_backend api + +backend api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb + http-check expect status 200 + acl message_path path_reg ^/api/v1/chats/[^/]+/messages$ + acl has_key req.hdr(Idempotency-Key) -m found + http-request set-var(txn.replay_safe) bool(1) if METH_GET + http-request set-var(txn.replay_safe) bool(1) if METH_POST message_path has_key + http-request disable-l7-retry unless { var(txn.replay_safe) -m bool } + default-server check init-state fully-down inter 1s fastinter 500ms downinter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none maxconn "${API_SERVER_MAXCONN-64}" + server-template api 8 api:8080 + +frontend stats + bind :8404 + monitor-uri /healthz + monitor fail if { nbsrv(api) lt 1 } + http-request use-service prometheus-exporter if { path /metrics } + stats enable + stats uri /stats + stats refresh 5s diff --git a/infra/k6/messages.js b/infra/k6/messages.js new file mode 100644 index 00000000..722cf980 --- /dev/null +++ b/infra/k6/messages.js @@ -0,0 +1,106 @@ +import http from 'k6/http'; +import { check } from 'k6'; +import encoding from 'k6/encoding'; +import exec from 'k6/execution'; + +const BASE = __ENV.BASE_URL || 'http://lb:8080'; +const RATE = Number(__ENV.RATE || 50); +const WARMUP = Number(__ENV.WARMUP || 10); +const DURATION = Number(__ENV.DURATION || 60); +const USERS = Math.max(2, Number(__ENV.USERS || 20)); +const READ_RATIO = Number(__ENV.READ_RATIO || 0.2); +const VUS = Number(__ENV.VUS || Math.max(10, Math.ceil(RATE / 10))); +const MAX_VUS = Number(__ENV.MAX_VUS || Math.max(VUS, Math.min(VUS * 4, 1000))); +const RUN = __ENV.RUN_ID || Date.now().toString(36); +const SUMMARY = __ENV.SUMMARY || '/out/summary.json'; +const JSON_HEADERS = { 'Content-Type': 'application/json' }; + +const phase = (startTime, duration) => ({ + executor: 'constant-arrival-rate', + rate: RATE, + timeUnit: '1s', + startTime: `${startTime}s`, + duration: `${duration}s`, + preAllocatedVUs: VUS, + maxVUs: MAX_VUS, + gracefulStop: '5s', +}); + +const measured = ['http_reqs', 'http_req_failed', 'http_req_duration', 'dropped_iterations', 'iterations']; + +export const options = { + setupTimeout: '180s', + summaryTrendStats: ['avg', 'min', 'med', 'p(90)', 'p(95)', 'p(99)', 'max'], + scenarios: Object.assign(WARMUP > 0 ? { warmup: phase(0, WARMUP) } : {}, { measure: phase(WARMUP, DURATION) }), + thresholds: Object.fromEntries([ + ...measured.map((metric) => [`${metric}{scenario:measure}`, []]), + ['http_req_duration{scenario:measure,name:post_message}', []], + ['http_req_duration{scenario:measure,name:get_history}', []], + ]), +}; + +function created(response, what) { + if (response.status !== 201) { + throw new Error(`${what}: HTTP ${response.status}`); + } + return response.json(); +} + +const bearer = (token, extra) => Object.assign({ Authorization: `Bearer ${token}` }, extra || {}); + +export function setup() { + const actors = []; + for (let i = 0; i < USERS; i++) { + const username = `k6_${RUN}_${i}`.slice(0, 32); + const password = `K6-${RUN}-${i}-synthetic`; + const user = created( + http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: `k6 ${i}`, password }), { headers: JSON_HEADERS }), + 'register', + ); + const basic = encoding.b64encode(`${username}:${password}`); + const session = created( + http.post(`${BASE}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${basic}` } }), + 'login', + ); + actors.push({ id: user.id, token: session.token }); + } + const chats = []; + for (let i = 0; i < USERS; i += 2) { + const [a, b] = [actors[i], actors[(i + 1) % USERS]]; + const body = JSON.stringify({ title: `k6 ${RUN} ${i}`, member_ids: [a.id, b.id] }); + const chat = created(http.post(`${BASE}/api/v1/chats`, body, { headers: bearer(a.token, JSON_HEADERS) }), 'chat'); + chats.push({ id: chat.id, tokens: [a.token, b.token] }); + } + console.log('LOAD-START'); + return { chats }; +} + +export default function (data) { + const n = exec.scenario.iterationInTest; + const chat = data.chats[n % data.chats.length]; + const token = chat.tokens[Math.floor(n / data.chats.length) % 2]; + if (Math.random() < READ_RATIO) { + const response = http.get(`${BASE}/api/v1/chats/${chat.id}/messages?limit=50`, { + headers: bearer(token), + tags: { name: 'get_history' }, + timeout: '10s', + }); + check(response, { 'history 200': (r) => r.status === 200 }); + return; + } + const key = `${RUN}-${exec.scenario.name}-${n}`; + const response = http.post(`${BASE}/api/v1/chats/${chat.id}/messages`, JSON.stringify({ text: `k6 ${key}` }), { + headers: bearer(token, Object.assign({ 'Idempotency-Key': key }, JSON_HEADERS)), + tags: { name: 'post_message' }, + timeout: '10s', + }); + check(response, { 'message 201': (r) => r.status === 201 }); +} + +export function handleSummary(data) { + delete data.setup_data; + const reqs = data.metrics['http_reqs{scenario:measure}']; + const failed = data.metrics['http_req_failed{scenario:measure}']; + const line = `measure: ${reqs ? reqs.values.count : 0} requests, failed ratio ${failed ? failed.values.rate : 'n/a'}\n`; + return { [SUMMARY]: JSON.stringify(data, null, 1), stdout: line }; +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..4b4b10ed --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,114 @@ +[project] +name = "mtusi-messenger" +version = "1.4.0" +description = "Лабораторная 4 «S3-хранилище и вложения», МТУСИ" +requires-python = ">=3.14,<3.15" +dependencies = [ + "fastapi>=0.118.0", + "uvicorn[standard]>=0.37.0", + "pydantic>=2.11.0", + "pydantic-settings>=2.11.0", + "dishka>=1.7.0", + "structlog>=26.1.0", + "gunicorn>=26.2.0", + "orjson>=3.12.0", + "asyncpg>=0.32.0", + "argon2-cffi>=25.1.0", + "uvicorn-worker>=0.4.0", + "redis>=8.1.0", +] + +[dependency-groups] +dev = [ + "pytest>=8.4.0", + "pytest-asyncio>=1.2.0", + "httpx>=0.28.0", + "ruff>=0.14.0", + "ty>=0.0.1a21", +] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/messenger"] + +[tool.ruff] +line-length = 100 +target-version = "py314" +src = ["src", "student-tests"] +extend-exclude = ["tests", "scripts/check_contract.py", "scripts/validate_openapi.py"] +per-file-target-version = { "scripts/*.py" = "py39" } + +[tool.ruff.format] +indent-style = "space" +quote-style = "double" + +[tool.ruff.lint] +select = [ + "E", + "W", + "F", + "I", + "N", + "UP", + "B", + "A", + "C4", + "DTZ", + "T20", + "SIM", + "TID", + "PTH", + "RUF", + "ASYNC", + "S", + "ARG", + "PL", +] +ignore = [ + "PLR0913", + "RUF001", + "RUF002", + "RUF003", + "S104", + "BLE001", +] + +[tool.ruff.lint.per-file-ignores] +"student-tests/**" = ["S101", "S105", "S106", "S603", "S607", "PLR2004", "ARG001", "T20", "TID251"] +"scripts/*.py" = ["T20", "S603", "S607", "S310", "PLR2004", "TID251"] +"src/messenger/*/infrastructure/**" = ["TID251", "ARG002"] +"src/messenger/*/domain/errors.py" = ["N818"] +"src/messenger/*/application/errors.py" = ["N818"] +"src/messenger/*/entrypoints/**" = ["TID251", "N818", "PLR0917", "S105"] +"src/messenger/shared/config.py" = ["ARG002", "ARG003"] +"src/messenger/main.py" = ["TID251"] +"src/messenger/migrate.py" = ["TID251"] +"src/messenger/gunicorn_conf.py" = ["TID251", "ARG002", "RUF012"] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"messenger.shared.infrastructure".msg = "Домен и слой приложения не импортируют инфраструктуру: зависимость идёт через порт." +"messenger.identity.infrastructure".msg = "Домен и слой приложения не импортируют инфраструктуру: зависимость идёт через порт." +"messenger.messaging.infrastructure".msg = "Домен и слой приложения не импортируют инфраструктуру: зависимость идёт через порт." + +[tool.ruff.lint.isort] +known-first-party = ["messenger"] + +[tool.ty.src] +include = ["src", "student-tests"] + +[tool.ty.rules] +unresolved-import = "error" +invalid-argument-type = "error" +possibly-missing-attribute = "warn" + +[tool.pytest.ini_options] +testpaths = ["student-tests"] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +addopts = "-q --strict-markers -m 'not stack'" +markers = [ + "stack: black-box проверки против поднятого compose-стенда (make test-faults)", +] diff --git a/scripts/detection.sh b/scripts/detection.sh new file mode 100755 index 00000000..5ef0d35a --- /dev/null +++ b/scripts/detection.sh @@ -0,0 +1,20 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +out=${1:-evidence/detection} +mkdir -p "$out" +scripts/restore.sh +replica() { docker compose ps -q "${API_SERVICE:-api}" | head -1; } +detect() { python3 scripts/probe.py detect "$@"; } +failed=0 +detect --max 1.5 --within-action --restore scripts/restore.sh --out "$out/sigterm.json" \ + -- docker stop -t "${STOP_TIMEOUT:-6}" "$(replica)" || failed=1 +detect --max 1.5 --restore scripts/restore.sh --out "$out/kill.json" \ + -- docker kill "$(replica)" || failed=1 +hung=$(replica) +detect --max 3.5 --restore "docker unpause $hung && scripts/lb-wait.sh" --out "$out/pause.json" \ + -- docker pause "$hung" || failed=1 +db=$(docker compose ps -q postgres) +detect --max 1.5 --until 0 --lb-status 503 --restore "docker start $db && scripts/lb-wait.sh" \ + --out "$out/postgres.json" -- docker stop "$db" || failed=1 +exit "$failed" diff --git a/scripts/evidence-cache.sh b/scripts/evidence-cache.sh new file mode 100755 index 00000000..ad017628 --- /dev/null +++ b/scripts/evidence-cache.sh @@ -0,0 +1,24 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +cli() { docker compose exec -T valkey sh -c "REDISCLI_AUTH=\"\$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)\" valkey-cli $1"; } +psql() { docker compose exec -T postgres psql -U messenger -d messenger -tA -c "$1"; } +echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)" +echo "\$ valkey-cli config get appendonly appendfsync maxmemory maxmemory-policy" +cli "config get appendonly" ; cli "config get appendfsync"; cli "config get maxmemory"; cli "config get maxmemory-policy" +echo "\$ valkey-cli info persistence | grep aof_enabled,aof_last_write_status" +cli "info persistence" | grep -E '^aof_enabled|^aof_last_write_status' +echo "\$ valkey-cli dbsize; info stats | grep keyspace" +cli dbsize +cli "info stats" | grep -E '^keyspace_(hits|misses)' +key=$(cli "--scan --pattern session:* --count 1000" | head -1) +hash=${key#session:} +echo "\$ сравнение срока ключа кэша и срока сессии для одного ключа (значение и токен не печатаются)" +echo "valkey pexpiretime, ms: $(cli "pexpiretime $key")" +echo "postgres expires_at, ms: $(psql "SELECT (extract(epoch FROM expires_at) * 1000)::bigint FROM sessions WHERE token_hash = decode('$hash', 'hex')")" +echo "\$ количество отметок отзыва и закэшированных сессий" +revoked=0; cached=0 +for k in $(cli "--scan --pattern session:* --count 1000"); do + if [ "$(cli "get $k")" = "-" ]; then revoked=$((revoked + 1)); else cached=$((cached + 1)); fi +done +echo "tombstones: $revoked, cached sessions: $cached" diff --git a/scripts/evidence-stack.sh b/scripts/evidence-stack.sh new file mode 100755 index 00000000..8d33f590 --- /dev/null +++ b/scripts/evidence-stack.sh @@ -0,0 +1,48 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +base=${1:-http://$(docker compose port lb 8080)} +stats=http://$(docker compose port lb 8404)/stats\;csv +header() { echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)"; } +{ + header + echo "\$ docker compose --env-file .env config --quiet && echo valid" + docker compose --env-file .env config --quiet && echo valid + echo "\$ docker compose ps --format '{{.Service}} {{.Name}} {{.Status}} {{.Ports}}'" + docker compose ps --format '{{.Service}} {{.Name}} {{.Status}} {{.Ports}}' + echo "\$ docker compose config | grep -c container_name" + docker compose config | grep -c container_name || true + echo "\$ docker port <каждая реплика api> # реплики не публикуют порт" + for id in $(docker compose ps -q api); do echo "$(docker inspect -f '{{.Config.Hostname}}' "$id"): [$(docker port "$id")]"; done + echo "\$ docker inspect: hostname = X-Instance-Id, сети, лимиты CPU (nano) и памяти" + for id in $(docker compose ps -q); do + docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Config.Hostname}} {{.Name}} nets={{range $k, $v := .NetworkSettings.Networks}}{{$k}},{{end}} cpus={{.HostConfig.NanoCpus}} mem={{.HostConfig.Memory}} user={{.Config.User}} ro={{.HostConfig.ReadonlyRootfs}}' "$id" + done | sort + echo "\$ curl LB stats: backend api, server status check" + curl -fsS "$stats" | python3 -c 'import csv,sys +for r in csv.DictReader(sys.stdin.read().lstrip("# ").splitlines()): + if r["pxname"] == "api" and r["status"] != "MAINT (resolution)": + print(r["svname"], r["status"], r["check_status"], r["check_code"])' + echo "\$ for i in 1..6: curl -D - $base/health/live | X-Instance-Id" + for _ in 1 2 3 4 5 6; do curl -fsS -D - -o /dev/null "$base/health/live" | tr -d '\r' | grep -i '^x-instance-id'; done +} > evidence/stack.txt +{ + header + echo "host: $(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m), $(sysctl -n hw.ncpu 2>/dev/null) CPU, $(($(sysctl -n hw.memsize 2>/dev/null || echo 0) / 1073741824)) GiB RAM, $(sw_vers -productName 2>/dev/null) $(sw_vers -productVersion 2>/dev/null)" + echo "docker: $(docker version -f '{{.Server.Version}}'), VM: $(docker info -f '{{.NCPU}}') CPU, $(docker info -f '{{.MemTotal}}') bytes" + echo "compose: $(docker compose version --short)" + echo "images:" + grep -h -E 'image:|@sha256' compose.yaml Dockerfile | sed 's/^ */ /' + echo "python in image: $(docker exec "$(docker compose ps -q api | head -1)" python -V)" + echo "haproxy: $(docker compose exec -T lb haproxy -v | head -1)" + echo "packages (uv.lock):" + for name in fastapi uvicorn uvicorn-worker gunicorn asyncpg argon2-cffi pydantic pydantic-settings dishka structlog redis; do + printf ' %s %s\n' "$name" "$(sed -n "/^name = \"$name\"$/{n;s/version = \"\(.*\)\"/\1/p;}" uv.lock)" + done + echo "process users (service uid command):" + for id in $(docker compose ps -q); do + service=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}}' "$id") + docker top "$id" -eo pid,uid,comm | awk -v s="$service" 'NR > 1 {print " " s, $2, $3}' + done | sort -u +} > evidence/environment.txt +cat evidence/stack.txt evidence/environment.txt diff --git a/scripts/evidence-storage.sh b/scripts/evidence-storage.sh new file mode 100755 index 00000000..567b33d0 --- /dev/null +++ b/scripts/evidence-storage.sh @@ -0,0 +1,44 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +psql() { docker compose exec -T postgres psql -U messenger -d messenger -c "$1"; } +header() { echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)"; } +counts="SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages, (SELECT count(*) FROM idempotency_keys) keys, (SELECT count(*) FROM schema_migrations) versions" +kdf="SELECT substring(password_hash from '^[$]argon2id[$]v=[0-9]+[$]m=[0-9]+,t=[0-9]+,p=[0-9]+[$]') AS kdf_prefix, count(*) AS users, min(length(password_hash)) AS hash_length FROM users GROUP BY 1" +tokens="SELECT octet_length(token_hash) AS stored_bytes, count(*) AS sessions FROM sessions GROUP BY 1" +{ + header + for table in users sessions chats chat_members messages idempotency_keys schema_migrations; do + echo "\$ psql -c '\\d+ $table'" + psql "\\d+ $table" + done + echo "\$ psql -c 'SELECT version, left(checksum, 12), applied_at FROM schema_migrations'" + psql "SELECT version, left(checksum, 12) AS checksum, applied_at FROM schema_migrations" +} > evidence/schema.txt +{ + header + echo "\$ psql -c \"$counts\"" + psql "$counts" + echo "\$ make migrate" + docker compose run --rm migrate 2>/dev/null + echo "\$ psql -c \"$counts\"" + psql "$counts" +} > evidence/migrations.txt +{ + header + echo "\$ psql -c \"$kdf\"" + psql "$kdf" + echo "\$ psql -c \"$tokens\"" + psql "$tokens" +} > evidence/kdf.txt +{ + header + echo "\$ git ls-files secrets .env backups volumes" + git ls-files secrets .env backups volumes + echo "(пусто: секретов, .env, дампов и volumes в Git нет)" + echo "\$ git check-ignore -v secrets/database_url secrets/postgres_password .env backups/" + git check-ignore -v secrets/database_url secrets/postgres_password .env backups/ + echo "\$ docker volume ls --filter name=mtusi2026lab4" + docker volume ls --filter name=mtusi2026lab4 +} > evidence/secrets.txt +echo "evidence/{schema,migrations,kdf,secrets}.txt обновлены" diff --git a/scripts/failover-each.sh b/scripts/failover-each.sh new file mode 100755 index 00000000..64050ef7 --- /dev/null +++ b/scripts/failover-each.sh @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +out=${1:-evidence/failover-each} +rm -rf "$out" +mkdir -p "$out" +scripts/restore.sh +hosts=$(docker inspect -f '{{.Config.Hostname}}' $(docker compose ps -q "${API_SERVICE:-api}")) +failed=0 +set -- +for host in $hosts; do + TARGET_INSTANCE_ID=$host python3 scripts/probe.py load --expect dip --out "$out/$host" \ + -- sh -c "scripts/stop-one.sh && sleep ${HOLD:-10} && scripts/restore.sh" || failed=1 + scripts/restore.sh + set -- "$@" "$out/$host/result.json" +done +python3 -c 'import json,sys; print(json.dumps([json.load(open(p)) for p in sys.argv[1:]], ensure_ascii=False, indent=2))' "$@" > "$out/summary.tmp" +mv "$out/summary.tmp" "$out/summary.json" +exit "$failed" diff --git a/scripts/failover-evidence.sh b/scripts/failover-evidence.sh new file mode 100755 index 00000000..fb30bd36 --- /dev/null +++ b/scripts/failover-evidence.sh @@ -0,0 +1,28 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +replicas() { + docker inspect -f '{{.Config.Hostname}} {{.State.Status}} started={{.State.StartedAt}} finished={{.State.FinishedAt}}' $(docker compose ps -aq "${API_SERVICE:-api}") +} +tmp=evidence/failover.tmp +since=$(date -u +%FT%TZ) +{ + echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)" + echo "== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt" + replicas + echo "\$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh" + make --no-print-directory test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL="${1:-http://localhost:8080}" + echo "== after: api replicas" + replicas +} > "$tmp" 2>&1 +stopped=$(replicas | awk '$2 == "exited" {print $1}') +{ + echo "== stopped replica: $stopped; shutdown: signal, drain window with readiness 503, close, exit" + docker logs --since "$since" "$stopped" 2>&1 | grep -E 'Handling signal|Draining|"status":503|Shutting down|Waiting for conn|Finished server|service.stopped|SIGTERM' | tail -16 + echo "\$ scripts/restore.sh" + scripts/restore.sh + echo "== after restore" + replicas +} >> "$tmp" 2>&1 +mv "$tmp" "evidence/failover-$stopped.txt" +cat "evidence/failover-$stopped.txt" diff --git a/scripts/k6.sh b/scripts/k6.sh new file mode 100755 index 00000000..01d95f29 --- /dev/null +++ b/scripts/k6.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +out=${1:?usage: k6.sh [k6 run args]} +shift +mkdir -p "$out" +out=$(cd "$out" && pwd) +cd "$(dirname "$0")/.." +exec docker compose --profile bench run --rm --no-deps -T -u "$(id -u):$(id -g)" -v "$out:/out" \ + -e RATE -e WARMUP -e DURATION -e USERS -e READ_RATIO -e VUS -e MAX_VUS -e RUN_ID \ + k6 run --quiet "$@" "/scripts/${K6_SCRIPT:-messages.js}" diff --git a/scripts/lb-wait.sh b/scripts/lb-wait.sh new file mode 100755 index 00000000..f1ead888 --- /dev/null +++ b/scripts/lb-wait.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +service=${API_SERVICE:-api} +want=${1:-$(docker compose ps -q "$service" | wc -l | tr -d ' ')} +url=${LB_STATS_URL:-http://$(docker compose port lb 8404)/stats;csv} +deadline=$(($(date +%s) + ${WAIT_TIMEOUT:-60})) +until [ "$(curl -fsS "$url" | awk -F, -v b="$service" '$1 == b && $2 != "BACKEND" && $18 == "UP"' | wc -l)" -ge "$want" ]; do + [ "$(date +%s)" -lt "$deadline" ] || { echo "LB does not see $want UP $service servers" >&2; exit 4; } + sleep 0.5 +done diff --git a/scripts/limits.py b/scripts/limits.py new file mode 100644 index 00000000..2547ea0c --- /dev/null +++ b/scripts/limits.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +POLICY = { + "lb": {"secrets": [], "volumes": [], "networks": ["backend", "edge"], "ports": True}, + "api": { + "secrets": ["cache_url", "cursor_secret", "database_url"], + "volumes": [], + "networks": ["backend"], + }, + "migrate": {"secrets": ["database_url"], "volumes": [], "networks": ["backend"]}, + "postgres": {"secrets": ["postgres_password"], "volumes": ["pgdata"], "networks": ["backend"]}, + "valkey": {"secrets": ["valkey.conf"], "volumes": ["valkeydata"], "networks": ["backend"]}, + "k6": {"secrets": [], "volumes": [], "networks": ["edge"]}, +} + + +def run(*command): + done = subprocess.run(command, cwd=str(ROOT), capture_output=True, text=True, check=False) + return done.returncode, done.stdout.strip() + + +def declared(name, service, networks, problems): + limits = service.get("deploy", {}).get("resources", {}).get("limits", {}) + secrets = sorted(s["source"] for s in service.get("secrets", [])) + volumes = sorted(v["source"] for v in service.get("volumes", []) if v["type"] == "volume") + nets = sorted(service.get("networks", {})) + ports = [ + f"{p.get('host_ip', '0.0.0.0')}:{p.get('published')}" for p in service.get("ports", []) + ] + want = POLICY.get(name) + if want is None: + problems.append(f"{name}: service is not covered by the policy") + want = {"secrets": [], "volumes": [], "networks": []} + if not limits.get("cpus") or not limits.get("memory"): + problems.append(f"{name}: no CPU or memory limit") + if "container_name" in service: + problems.append(f"{name}: container_name prevents scaling") + for kind, actual in (("secrets", secrets), ("volumes", volumes), ("networks", nets)): + if actual != want[kind]: + problems.append(f"{name}: {kind} {actual}, policy {want[kind]}") + if ports and not want.get("ports"): + problems.append(f"{name}: publishes {ports} in bypass of the balancer") + if any(not port.startswith("127.0.0.1:") for port in ports): + problems.append(f"{name}: publishes {ports} beyond loopback") + if name == "api" and not service.get("read_only"): + problems.append("api: root filesystem is writable") + internal = [n for n in nets if networks.get(n, {}).get("internal")] + return [ + name, + f"{limits.get('cpus', '-')}/{int(limits.get('memory') or 0) >> 20}MiB", + ",".join(ports) or "-", + ",".join(secrets) or "-", + ",".join(volumes) or "-", + ",".join(f"{n}{'(internal)' if n in internal else ''}" for n in nets), + str(service.get("read_only", False)).lower(), + ] + + +def running(problems): + _, ids = run("docker", "compose", "ps", "-q") + template = ( + '{{index .Config.Labels "com.docker.compose.service"}} {{.Config.Hostname}} ' + "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}} {{json .HostConfig.PortBindings}}" + ) + _, found = run("docker", "inspect", "-f", template, *ids.split()) + rows = [] + for line in found.splitlines(): + service, host, cpus, memory, bindings = line.split(" ", 4) + published = [ + f"{b['HostIp']}:{b['HostPort']}->{port}" + for port, items in (json.loads(bindings) or {}).items() + for b in items or [] + ] + if int(cpus) <= 0 or int(memory) <= 0: + problems.append(f"container {service}/{host}: no CPU or memory limit applied") + if published and service != "lb": + problems.append(f"container {service}/{host}: publishes {published}") + rows.append( + [service, host, f"{int(cpus) / 1e9:g}", f"{int(memory) >> 20}MiB", ",".join(published)] + ) + return sorted(rows) + + +def table(header, rows): + widths = [max(len(str(r[i])) for r in [header, *rows]) for i in range(len(header))] + lines = [header, ["-" * w for w in widths], *rows] + return [" ".join(str(c).ljust(w) for c, w in zip(r, widths)).rstrip() for r in lines] + + +def main(): + parser = argparse.ArgumentParser(description="limits, ports, secrets, volumes and networks") + parser.add_argument("--out", help="text report, written only after a complete check") + args = parser.parse_args() + problems = [] + _, raw = run("docker", "compose", "--profile", "bench", "config", "--format", "json") + config = json.loads(raw) + services = [ + declared(name, service, config.get("networks", {}), problems) + for name, service in sorted(config["services"].items()) + ] + containers = running(problems) + if not any(row[0] == "api" for row in containers): + problems.append("no running api replicas to inspect") + lines = [ + f"date: {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}", + "$ docker compose --profile bench config --format json (declared)", + *table(["service", "cpus/mem", "ports", "secrets", "volumes", "networks", "ro"], services), + "", + "$ docker inspect (running containers: hostname = X-Instance-Id, applied limits)", + *table(["service", "hostname", "cpus", "memory", "published"], containers), + "", + *(f"FAIL: {p}" for p in problems), + "PASS: limits, ports, secrets, volumes and networks match the policy" + if not problems + else f"FAIL: {len(problems)} violation(s)", + ] + text = "\n".join(lines) + "\n" + if args.out: + Path(args.out).write_text(text) + print(text, end="") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/persistence-evidence.sh b/scripts/persistence-evidence.sh new file mode 100755 index 00000000..f10ce0c8 --- /dev/null +++ b/scripts/persistence-evidence.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +started() { + for id in $(docker compose ps -aq); do + docker inspect --format '{{index .Config.Labels "com.docker.compose.service"}} {{.Config.Hostname}} {{.State.StartedAt}} {{.State.Status}}' "$id" + done | sort +} +echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)" +echo "== before: service hostname StartedAt status" +started +make --no-print-directory test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL="${1:-http://localhost:8080}" +echo "== after: service hostname StartedAt status" +started diff --git a/scripts/probe.py b/scripts/probe.py new file mode 100755 index 00000000..a624bd0b --- /dev/null +++ b/scripts/probe.py @@ -0,0 +1,436 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import collections +import functools +import json +import os +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +COUNTERS = ("wretr", "wredis", "econ", "eresp", "hrsp_5xx") + + +@functools.cache +def published(port, fallback): + command = ["docker", "compose", "port", "lb", str(port)] + found = subprocess.run(command, cwd=str(ROOT), capture_output=True, text=True, check=False) + return found.stdout.strip() or fallback + + +def base_url(): + return os.environ.get("BASE_URL") or "http://" + published(8080, "localhost:8080") + + +def stats_url(): + return os.environ.get("LB_STATS_URL") or f"http://{published(8404, '127.0.0.1:8404')}/stats;csv" + + +def call(method, path, body=None, headers=None, timeout=2.0): + data = None if body is None else json.dumps(body, ensure_ascii=False).encode() + head = {"Accept": "application/json"} + if data is not None: + head["Content-Type"] = "application/json" + head.update(headers or {}) + request = urllib.request.Request( + base_url().rstrip("/") + path, data=data, headers=head, method=method + ) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + payload = json.loads(response.read() or b"null") + return response.status, response.headers.get("X-Instance-Id", ""), payload + except urllib.error.HTTPError as error: + try: + payload = json.loads(error.read() or b"null") + except (OSError, ValueError): + payload = None + return error.code, error.headers.get("X-Instance-Id", ""), payload + except (OSError, ValueError): + return 0, "", None + + +def emit(report, out=None): + text = json.dumps(report, ensure_ascii=False, indent=2) + if out: + Path(out).parent.mkdir(parents=True, exist_ok=True) + Path(out).write_text(text + "\n") + print(text) + + +def created(result, what): + if result[0] != 201: + raise SystemExit(f"{what} failed: HTTP {result[0]}") + return result[2] + + +def actor(label): + username = f"p_{label}_{uuid.uuid4().hex[:12]}" + password = "Probe-" + uuid.uuid4().hex + body = {"username": username, "display_name": "probe " + label, "password": password} + user = created(call("POST", "/api/v1/users", body, timeout=10), "register") + basic = base64.b64encode(f"{username}:{password}".encode()).decode() + login = call( + "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}, timeout=10 + ) + return { + "id": user["id"], + "auth": {"Authorization": "Bearer " + created(login, "login")["token"]}, + } + + +def chat_of(owner, other): + body = {"title": "probe", "member_ids": [owner["id"], other["id"]]} + return created(call("POST", "/api/v1/chats", body, owner["auth"], timeout=10), "chat")["id"] + + +def send(owner, chat, text, key): + headers = dict(owner["auth"], **{"Idempotency-Key": key}) + return call("POST", f"/api/v1/chats/{chat}/messages", {"text": text}, headers) + + +def lb_rows(backend="api"): + try: + with urllib.request.urlopen(stats_url(), timeout=2) as response: + lines = response.read().decode().splitlines() + except OSError: + return None + header = lines[0].lstrip("# ").split(",") + rows = [dict(zip(header, line.split(","))) for line in lines[1:] if line] + return [r for r in rows if r["pxname"] == backend] + + +def lb_up(): + rows = lb_rows() + if rows is None: + return None + return sum(1 for r in rows if r["svname"] != "BACKEND" and r["status"].startswith("UP")) + + +def lb_counters(): + row = next((r for r in lb_rows() or [] if r["svname"] == "BACKEND"), {}) + return {name: int(row.get(name) or 0) for name in COUNTERS} + + +def run_k6(out, env, on_start=None): + Path(out).mkdir(parents=True, exist_ok=True) + started = [] + process = subprocess.Popen( + [str(ROOT / "scripts/k6.sh"), str(out)], + env=dict(os.environ, **env), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + with (Path(out) / "k6.txt").open("w") as log: + for line in process.stdout: + log.write(line) + if not started and "LOAD-START" in line: + started.append(time.time()) + if on_start: + on_start() + return process.wait(), started[0] if started else None + + +def k6_metrics(path, duration): + metrics = json.loads(Path(path).read_text())["metrics"] + + def value(name, field): + return metrics.get(name + "{scenario:measure}", {}).get("values", {}).get(field, 0.0) + + count = value("http_reqs", "count") + return { + "requests": int(count), + "rps": round(count / duration, 2), + "ok_rps": round(count * (1 - value("http_req_failed", "rate")) / duration, 2), + "failed_ratio": round(value("http_req_failed", "rate"), 5), + "dropped_iterations": int(value("dropped_iterations", "count")), + "p50_ms": round(value("http_req_duration", "med"), 2), + "p95_ms": round(value("http_req_duration", "p(95)"), 2), + "p99_ms": round(value("http_req_duration", "p(99)"), 2), + } + + +def race(alice, chat, parallel): + key, text = uuid.uuid4().hex, "same key " + uuid.uuid4().hex + barrier, results = threading.Barrier(parallel), [] + + def worker(): + barrier.wait() + results.append(send(alice, chat, text, key)) + + threads = [threading.Thread(target=worker) for _ in range(parallel)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + bodies = [r[2] for r in results if r[0] == 201] + identical = bool(bodies) and all(b == bodies[0] for b in bodies) + return text, results, identical, send(alice, chat, text + " changed", key)[0] + + +def check(args): + alice, bob = actor("alice"), actor("bob") + chat = chat_of(alice, bob) + seen = collections.Counter( + call("GET", "/api/v1/users/me", headers=alice["auth"])[1] for _ in range(args.samples) + ) + rounds = [race(alice, chat, args.parallel) for _ in range(min(args.rounds, 100))] + page = call("GET", f"/api/v1/chats/{chat}/messages?limit=100", headers=bob["auth"])[2] + copies = collections.Counter(m.get("text") for m in (page or {"items": []})["items"]) + statuses = collections.Counter(r[0] for _, results, _, _ in rounds for r in results) + served = collections.Counter(r[1] for _, results, _, _ in rounds for r in results) + same = { + "rounds": len(rounds), + "parallel": args.parallel, + "statuses": dict(statuses), + "instances": dict(served), + "identical_bodies_rounds": sum(1 for _, _, identical, _ in rounds if identical), + "single_copy_rounds": sum(1 for text, _, _, _ in rounds if copies[text] == 1), + "conflict_rounds": sum(1 for _, _, _, other in rounds if other == 409), + } + passed = ( + len(seen) >= 2 + and statuses == {201: len(rounds) * args.parallel} + and len(served) >= 2 + and same["identical_bodies_rounds"] == len(rounds) + and same["single_copy_rounds"] == len(rounds) + and same["conflict_rounds"] == len(rounds) + ) + emit({"instances_one_token": dict(seen), "same_key": same, "pass": passed}, args.out) + return 0 if passed else 1 + + +def record(stop, alice, chat): + probes, trace = [], [] + + def prober(): + key = uuid.uuid4().hex + while not stop.is_set(): + started = time.time() + status, instance, _ = send(alice, chat, "probe " + key, key) + probes.append((started, status, round(1000 * (time.time() - started), 1), instance)) + if status == 201: + key = uuid.uuid4().hex + time.sleep(0.1) + + def poller(): + while not stop.is_set(): + trace.append((time.time(), lb_up())) + time.sleep(0.1) + + threads = [threading.Thread(target=t, daemon=True) for t in (prober, poller)] + for thread in threads: + thread.start() + return probes, trace, threads + + +def write_csv(path, header, rows): + with path.open("w") as handle: + handle.write(header + "\n") + handle.writelines(",".join(str(v) for v in row) + "\n" for row in rows) + + +def summarize(args, probes, trace, action, expected): + t0, end = action["start"], action["end"] + label = args.label or os.environ.get("TARGET_INSTANCE_ID", "action") + failures = [t - t0 for t, s, _, _ in probes if s != 201 and t >= t0] + down = [t for t, up in trace if t >= t0 and up is not None and up < expected] + back = [t for t, up in trace if down and t > down[0] and up is not None and up >= expected] + outage = [t for t in down if not back or t < back[0]] or [end] + served = [(t, i) for t, s, _, i in probes if s == 201] + before = collections.Counter(i for t, i in served if t < t0) + during = collections.Counter(i for t, i in served if outage[0] <= t <= outage[-1]) + after = collections.Counter(i for t, i in served if t > end) + return { + "label": label, + "action": args.command, + "action_exit": action["exit"], + "action_seconds": round(end - t0, 3), + "action_finished_before_load_end": end < action["load_end"], + "lb_up_before": expected, + "lb_up_min": min((up for _, up in trace if up is not None), default=None), + "detection_seconds": round(down[0] - t0, 3) if down else None, + "rejoin_seconds": round(back[0] - t0, 3) if back else None, + "probe": { + "attempts": len(probes), + "failed_attempts": sum(1 for _, s, _, _ in probes if s != 201), + "first_failure_s": round(failures[0], 3) if failures else None, + "recovery_s": round(failures[-1], 3) if failures else 0.0, + "instances_before": dict(before), + "instances_during_outage": dict(during), + "instances_after": dict(after), + }, + } + + +def verdict(args, result): + probe, k6 = result["probe"], result["k6"] + checks = { + "action_ok": result["action_exit"] == 0 and result["action_finished_before_load_end"], + "load_errors_ok": k6["exit"] == 0 and k6["failed_ratio"] <= args.max_failed_ratio, + "write_recovery_ok": probe["recovery_s"] <= args.max_recovery, + } + if args.expect == "dip": + checks["detected"] = result["detection_seconds"] is not None + checks["target_excluded"] = probe["instances_during_outage"].get(result["label"], 0) == 0 + checks["rejoined"] = result["rejoin_seconds"] is not None and bool( + probe["instances_after"].get(result["label"]) + ) + if args.expect == "replace": + checks["capacity_kept"] = (result["lb_up_min"] or 0) >= result["lb_up_before"] + old, new = set(probe["instances_before"]), set(probe["instances_after"]) + checks["all_replaced"] = bool(new) and not old & new + return checks + + +def load(args): + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + expected = lb_up() or 0 + alice, bob = actor("alice"), actor("bob") + stop, action = threading.Event(), {} + probes, trace, threads = record(stop, alice, chat_of(alice, bob)) + + def act(): + time.sleep(args.warmup + args.lead) + action["start"] = time.time() + with (out / "action.txt").open("w") as log: + action["exit"] = subprocess.call( + args.command, cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT + ) + action["end"] = time.time() + + runner = threading.Thread(target=act) + env = {"RATE": str(args.rate), "WARMUP": str(args.warmup), "DURATION": str(args.duration)} + counters = lb_counters() + code, load_start = run_k6(out / "k6", env, runner.start) + if load_start is not None: + runner.join() + action["load_end"] = load_start + args.warmup + args.duration + stop.set() + for thread in threads: + thread.join() + if "start" not in action: + raise SystemExit(f"k6 failed before the action (exit {code}), see {out / 'k6/k6.txt'}") + t0 = action["start"] + write_csv( + out / "probe.csv", + "t_rel_s,status,latency_ms,instance", + ((round(t - t0, 3), *r) for t, *r in probes), + ) + write_csv(out / "lb_up.csv", "t_rel_s,up", ((round(t - t0, 3), up) for t, up in trace)) + result = summarize(args, probes, trace, action, expected) + result["lb_counters"] = {k: v - counters[k] for k, v in lb_counters().items()} + result["k6"] = dict( + k6_metrics(out / "k6/summary.json", args.duration), exit=code, rate=args.rate + ) + result["checks"] = verdict(args, result) + result["pass"] = all(result["checks"].values()) + (out / "result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") + print(json.dumps(result, ensure_ascii=False)) + return 0 if result["pass"] else 1 + + +def detect(args): + before = lb_up() or 0 + until = before - 1 if args.until is None else args.until + started = time.time() + process = subprocess.Popen(args.command, cwd=str(ROOT)) + detected = acted = None + while time.time() - started < args.timeout and (detected is None or acted is None): + if acted is None and process.poll() is not None: + acted = time.time() - started + if detected is None and (lb_up() or 0) <= until: + detected = time.time() - started + time.sleep(0.05) + code = process.wait() + acted = time.time() - started if acted is None else acted + status, instance, payload = call("GET", "/health/live") + restored = None + if args.restore: + begun = time.time() + subprocess.call(["sh", "-c", args.restore], cwd=str(ROOT)) + while (lb_up() or 0) < before and time.time() - begun < 3 * args.timeout: + time.sleep(0.1) + restored = round(time.time() - begun, 3) if (lb_up() or 0) >= before else None + checks = { + "action_ok": code == 0, + "detected_in_time": detected is not None and detected <= args.max + args.slack, + "lb_answer_ok": status == args.lb_status, + } + if args.within_action: + checks["excluded_before_action_end"] = detected is not None and detected < acted + if args.restore: + checks["restored"] = restored is not None + report = { + "action": args.command, + "action_exit": code, + "action_seconds": round(acted, 3), + "lb_up_before": before, + "lb_up_counted_as_detected": until, + "detection_seconds": None if detected is None else round(detected, 3), + "declared_max_seconds": args.max, + "measurement_slack_seconds": args.slack, + "lb_answer_after_detection": { + "path": "/health/live", + "status": status, + "x_instance_id_present": bool(instance), + "error_code": ((payload or {}).get("error") or {}).get("code"), + }, + "restore": args.restore, + "restore_seconds": restored, + "lb_up_after_restore": lb_up(), + "checks": checks, + "pass": all(checks.values()), + } + emit(report, args.out) + return 0 if report["pass"] else 1 + + +def main(): + parser = argparse.ArgumentParser(description="LB probes over the public HTTP contract") + sub = parser.add_subparsers(dest="mode", required=True) + one = sub.add_parser("check", help="instances behind one token and same-key races") + one.add_argument("--samples", type=int, default=40) + one.add_argument("--parallel", type=int, default=8) + one.add_argument("--rounds", type=int, default=1) + one.add_argument("--out", help="JSON file, written only after a complete report") + under = sub.add_parser("load", help="run an action under k6 load and measure recovery") + under.add_argument("--out", required=True) + under.add_argument("--label") + under.add_argument("--expect", choices=("dip", "replace"), default="dip") + under.add_argument("--rate", type=int, default=int(os.environ.get("RATE", "50"))) + under.add_argument("--warmup", type=int, default=10) + under.add_argument("--duration", type=int, default=int(os.environ.get("DURATION", "60"))) + under.add_argument("--lead", type=int, default=15) + under.add_argument("--max-failed-ratio", type=float, default=0.01) + under.add_argument("--max-recovery", type=float, default=10.0) + under.add_argument("command", nargs=argparse.REMAINDER) + watch = sub.add_parser("detect", help="time until the LB takes replicas out of rotation") + watch.add_argument("--max", type=float, required=True, help="declared worst detection, s") + watch.add_argument("--slack", type=float, default=0.25, help="docker CLI and polling, s") + watch.add_argument("--until", type=int, help="UP servers counted as detected") + watch.add_argument("--within-action", action="store_true") + watch.add_argument("--lb-status", type=int, default=200) + watch.add_argument("--restore", help="shell command that brings replicas back") + watch.add_argument("--timeout", type=float, default=20) + watch.add_argument("--out", help="JSON file, written only after a complete report") + watch.add_argument("command", nargs=argparse.REMAINDER) + args = parser.parse_args() + if args.mode == "check": + return check(args) + args.command = [c for c in args.command if c != "--"] + if not args.command: + parser.error(f"{args.mode} needs an action command after --") + return load(args) if args.mode == "load" else detect(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..47645b40 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +defined=$(docker compose config --services) +stores="" +for service in ${STATE_SERVICES:-postgres valkey}; do + if printf '%s\n' "$defined" | grep -qx "$service"; then stores="$stores $service"; fi +done +[ -n "$stores" ] || { echo "no state services found" >&2; exit 3; } +docker compose stop lb "${API_SERVICE:-api}" +docker compose restart $stores +docker compose up -d --no-recreate --wait --wait-timeout "${WAIT_TIMEOUT:-75}" diff --git a/scripts/restore.sh b/scripts/restore.sh new file mode 100755 index 00000000..705a092d --- /dev/null +++ b/scripts/restore.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose up -d --no-deps --no-recreate --wait --wait-timeout "${WAIT_TIMEOUT:-60}" "${API_SERVICE:-api}" +scripts/lb-wait.sh diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100755 index 00000000..8bbcb642 --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,20 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +service=${API_SERVICE:-api} +show() { docker inspect -f '{{.Config.Hostname}} image={{slice .Image 7 19}}' "$1"; } +echo "$(date -u +%T) migrate once before the first replacement" +docker compose run --rm --no-deps -T migrate 2>&1 +old=$(docker compose ps -q "$service") +count=$(printf '%s\n' "$old" | grep -c .) +for id in $old; do + running=$(docker compose ps -q "$service") + docker compose up -d --no-deps --no-recreate --wait --wait-timeout "${WAIT_TIMEOUT:-90}" --scale "$service=$((count + 1))" "$service" 2>&1 + scripts/lb-wait.sh $((count + 1)) + new=$(docker compose ps -q "$service" | grep -v -F "$running") + echo "$(date -u +%T) replace $(show "$id") -> $(show "$new")" + docker stop -t "${STOP_TIMEOUT:-6}" "$id" >/dev/null + docker rm "$id" >/dev/null +done +scripts/lb-wait.sh "$count" +echo "$(date -u +%T) done: $count replicas replaced" diff --git a/scripts/secrets.sh b/scripts/secrets.sh new file mode 100755 index 00000000..53997e3c --- /dev/null +++ b/scripts/secrets.sh @@ -0,0 +1,20 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +umask 077 +mkdir -p secrets +random() { od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; } +put() { + if [ ! -s "secrets/$1" ]; then + printf '%s' "$2" > "secrets/$1" + chmod 644 "secrets/$1" + echo "создан secrets/$1" + fi +} +put postgres_password "$(random)" +put database_url "postgresql://messenger:$(cat secrets/postgres_password)@postgres:5432/messenger" +put cursor_secret "$(random)" +put valkey_password "$(random)" +put valkey.conf "requirepass $(cat secrets/valkey_password)" +put cache_url "redis://:$(cat secrets/valkey_password)@valkey:6379/0" +[ -f .env ] || { cp .env.example .env; echo "создан .env из .env.example"; } diff --git a/scripts/sql/explain-history.sql b/scripts/sql/explain-history.sql new file mode 100644 index 00000000..7752625e --- /dev/null +++ b/scripts/sql/explain-history.sql @@ -0,0 +1,59 @@ +\set ON_ERROR_STOP on +\set big '''00000000-0000-7000-8000-00000000c001''' +\set cursor_at '''2026-01-01T02:46:40Z''' +\set cursor_id '''00000000-0000-7000-8001-000000002710''' + +PREPARE history_first (uuid, int) AS +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = $1 +ORDER BY created_at, id +LIMIT $2; + +PREPARE history_after (uuid, timestamptz, uuid, int) AS +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = $1 AND (created_at, id) > ($2, $3) +ORDER BY created_at, id +LIMIT $4; + +PREPARE history_offset (uuid, int, int) AS +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = $1 +ORDER BY created_at, id +LIMIT $2 OFFSET $3; + +SELECT count(*) AS chat_messages FROM messages WHERE chat_id = :big; +SELECT count(*) AS all_messages FROM messages; +SELECT pg_size_pretty(pg_relation_size('messages_history_idx')) AS history_index_size; + +\echo '== Первая страница, limit=50 (запрос HISTORY_FIRST приложения, LIMIT limit+1)' +EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_first(:big, 51); + +\echo '== Глубокая страница: keyset после 10 000-го сообщения (запрос HISTORY_AFTER приложения)' +EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_after(:big, :cursor_at, :cursor_id, 51); + +\echo '== Та же глубокая страница через OFFSET 10000 (не используется приложением, для сравнения)' +EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_offset(:big, 51, 10000); + +\echo '== Проверка: keyset и OFFSET возвращают одну и ту же страницу' +SELECT ( + SELECT array_agg(id ORDER BY created_at, id) FROM ( + SELECT id, created_at FROM messages + WHERE chat_id = :big AND (created_at, id) > (:cursor_at, :cursor_id) + ORDER BY created_at, id LIMIT 51 + ) AS keyset +) = ( + SELECT array_agg(id ORDER BY created_at, id) FROM ( + SELECT id, created_at FROM messages + WHERE chat_id = :big + ORDER BY created_at, id LIMIT 51 OFFSET 10000 + ) AS skipped +) AS same_page; + +\echo '== Контрольный план без индекса истории (DROP INDEX внутри транзакции, затем ROLLBACK)' +BEGIN; +DROP INDEX messages_history_idx; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_after(:big, :cursor_at, :cursor_id, 51); +ROLLBACK; diff --git a/scripts/sql/seed-history.sql b/scripts/sql/seed-history.sql new file mode 100644 index 00000000..842b599a --- /dev/null +++ b/scripts/sql/seed-history.sql @@ -0,0 +1,40 @@ +\set ON_ERROR_STOP on +\set author '''00000000-0000-7000-8000-00000000a001''' +\set big '''00000000-0000-7000-8000-00000000c001''' +\set epoch '''2026-01-01T00:00:00Z''' + +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES (:author, 'seed_author', 'Синтетический автор', '$argon2id$v=19$m=19456,t=2,p=1$c2VlZA$c2VlZA', :epoch) +ON CONFLICT DO NOTHING; + +INSERT INTO chats (id, title, created_at) +SELECT ('00000000-0000-7000-8000-00000000c' || lpad(to_hex(chat), 3, '0'))::uuid, + 'Синтетический чат ' || chat, :epoch +FROM generate_series(1, 21) AS chat +ON CONFLICT DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) +SELECT id, :author, 1, created_at FROM chats WHERE title LIKE 'Синтетический чат %' +ON CONFLICT DO NOTHING; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT ('00000000-0000-7000-8001-' || lpad(to_hex(n), 12, '0'))::uuid, :big, :author, + 'синтетическое сообщение ' || n, :epoch::timestamptz + n * interval '1 second' +FROM generate_series(1, 20000) AS n +ON CONFLICT DO NOTHING; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT ('00000000-0000-7000-8002-' || lpad(to_hex(chat * 1000 + n), 12, '0'))::uuid, + ('00000000-0000-7000-8000-00000000c' || lpad(to_hex(chat), 3, '0'))::uuid, :author, + 'фоновое сообщение ' || n, :epoch::timestamptz + n * interval '1 second' +FROM generate_series(2, 21) AS chat, generate_series(1, 500) AS n +ON CONFLICT DO NOTHING; + +UPDATE chats +SET last_message_at = (SELECT max(created_at) FROM messages WHERE messages.chat_id = chats.id) +WHERE title LIKE 'Синтетический чат %'; + +ANALYZE; + +SELECT count(*) FILTER (WHERE chat_id = :big) AS big_chat_messages, count(*) AS all_messages +FROM messages; diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..222cd887 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +cd "$(dirname "$0")/.." +ids=$(docker compose ps -q "${API_SERVICE:-api}") +[ -n "$ids" ] || { echo "no running ${API_SERVICE:-api} replicas" >&2; exit 3; } +target=$(docker inspect -f '{{.Id}} {{.Config.Hostname}}' $ids | awk -v t="$TARGET_INSTANCE_ID" '$2 == t {print $1}') +[ -n "$target" ] || { echo "no running ${API_SERVICE:-api} replica answers as $TARGET_INSTANCE_ID" >&2; exit 3; } +docker stop -t "${STOP_TIMEOUT:-6}" "$target" >/dev/null diff --git a/src/messenger/__init__.py b/src/messenger/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/gunicorn_conf.py b/src/messenger/gunicorn_conf.py new file mode 100644 index 00000000..4ccd4983 --- /dev/null +++ b/src/messenger/gunicorn_conf.py @@ -0,0 +1,66 @@ +import asyncio +import logging +import os +import sys +from typing import Any + +from gunicorn.arbiter import Arbiter +from gunicorn.glogging import Logger as GunicornBaseLogger +from uvicorn.server import Server +from uvicorn_worker import UvicornWorker + +from messenger.main import LOG_FIELDS +from messenger.shared.entrypoints.health import DRAINING +from messenger.shared.infrastructure.logging import configure + +LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO") +SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5")) +DRAIN_SECONDS = float(os.environ.get("DRAIN_SECONDS", "2")) + + +class StructlogGunicornLogger(GunicornBaseLogger): + def setup(self, cfg: object) -> None: + configure(LOG_LEVEL, LOG_FIELDS) + + def access(self, resp: object, req: object, environ: object, request_time: object) -> None: + return + + +class DrainingServer(Server): + async def main_loop(self) -> None: + await super().main_loop() + if not self.force_exit: + DRAINING.set() + logging.getLogger("uvicorn.error").info("Draining for %.1f s", DRAIN_SECONDS) + await asyncio.sleep(DRAIN_SECONDS) + + +class MessengerWorker(UvicornWorker): + CONFIG_KWARGS: dict[str, Any] = { + "access_log": False, + "server_header": False, + "date_header": False, + "timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS)), + } + + async def _serve(self) -> None: + self.config.app = self.wsgi + server = DrainingServer(config=self.config) + self._install_sigquit_handler() + await server.serve(sockets=self.sockets) + if not server.started: + sys.exit(Arbiter.WORKER_BOOT_ERROR) + + +bind = f"{os.environ.get('HOST', '0.0.0.0')}:{os.environ.get('PORT', '8080')}" +workers = int(os.environ.get("WEB_CONCURRENCY", "2")) +worker_class = "messenger.gunicorn_conf.MessengerWorker" +logger_class = StructlogGunicornLogger +loglevel = LOG_LEVEL.lower() +accesslog = None +errorlog = "-" +timeout = int(float(os.environ.get("REQUEST_TIMEOUT_SECONDS", "8")) + 5) +graceful_timeout = SHUTDOWN_SECONDS +keepalive = 5 +preload_app = False +control_socket_disable = True diff --git a/src/messenger/identity/__init__.py b/src/messenger/identity/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/identity/application/__init__.py b/src/messenger/identity/application/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/identity/application/bus.py b/src/messenger/identity/application/bus.py new file mode 100644 index 00000000..1ce4aa89 --- /dev/null +++ b/src/messenger/identity/application/bus.py @@ -0,0 +1,5 @@ +from messenger.shared.application.messagebus import CommandBus + + +class IdentityCommandBus(CommandBus): + __slots__ = () diff --git a/src/messenger/identity/application/commands.py b/src/messenger/identity/application/commands.py new file mode 100644 index 00000000..c98a4b57 --- /dev/null +++ b/src/messenger/identity/application/commands.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from uuid import UUID + +from messenger.identity.domain.models import Session +from messenger.shared.application.commands import Command + + +@dataclass(frozen=True, slots=True) +class RegisterUser(Command): + username: str + display_name: str + password: str = field(repr=False) + + +@dataclass(frozen=True, slots=True) +class OpenSession(Command): + user_id: UUID + + +@dataclass(frozen=True, slots=True) +class CloseSession(Command): + session: Session diff --git a/src/messenger/identity/application/handlers.py b/src/messenger/identity/application/handlers.py new file mode 100644 index 00000000..b5811ffc --- /dev/null +++ b/src/messenger/identity/application/handlers.py @@ -0,0 +1,76 @@ +from datetime import timedelta + +from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser +from messenger.identity.application.ports import ( + IdentityUnitOfWork, + PasswordHasher, + SessionDirectory, +) +from messenger.identity.domain.events import SessionClosed, SessionOpened +from messenger.identity.domain.models import Session, User +from messenger.identity.domain.values import DisplayName, Password, Username +from messenger.shared.application.ports import Clock, IdGenerator + + +class RegisterUserHandler: + __slots__ = ("_clock", "_hasher", "_ids", "_uow") + + def __init__( + self, uow: IdentityUnitOfWork, clock: Clock, ids: IdGenerator, hasher: PasswordHasher + ) -> None: + self._uow = uow + self._clock = clock + self._ids = ids + self._hasher = hasher + + async def __call__(self, command: RegisterUser) -> User: + username = Username(command.username) + display_name = DisplayName(command.display_name) + password = Password(command.password) + password_hash = await self._hasher.hash(password.value) + user, event = User.register( + user_id=self._ids.new_id(), + username=username, + display_name=display_name, + password_hash=password_hash, + registered_at=self._clock.now(), + ) + async with self._uow.transaction(): + await self._uow.users.add(user) + self._uow.record(event) + await self._uow.commit() + return user + + +class OpenSessionHandler: + __slots__ = ("_clock", "_ttl", "_uow") + + def __init__(self, uow: IdentityUnitOfWork, clock: Clock, ttl: timedelta) -> None: + self._uow = uow + self._clock = clock + self._ttl = ttl + + async def __call__(self, command: OpenSession) -> tuple[str, Session]: + token, session = Session.issue( + user_id=command.user_id, issued_at=self._clock.now(), ttl=self._ttl + ) + async with self._uow.transaction(): + await self._uow.sessions.add(session) + self._uow.record(SessionOpened(user_id=session.user_id, expires_at=session.expires_at)) + await self._uow.commit() + return token, session + + +class CloseSessionHandler: + __slots__ = ("_sessions", "_uow") + + def __init__(self, uow: IdentityUnitOfWork, sessions: SessionDirectory) -> None: + self._uow = uow + self._sessions = sessions + + async def __call__(self, command: CloseSession) -> None: + await self._sessions.invalidate(command.session) + async with self._uow.transaction(): + await self._uow.sessions.remove(command.session.token_hash) + self._uow.record(SessionClosed(user_id=command.session.user_id)) + await self._uow.commit() diff --git a/src/messenger/identity/application/ports.py b/src/messenger/identity/application/ports.py new file mode 100644 index 00000000..bba207e5 --- /dev/null +++ b/src/messenger/identity/application/ports.py @@ -0,0 +1,48 @@ +from datetime import datetime +from typing import Protocol, runtime_checkable +from uuid import UUID + +from messenger.identity.domain.models import Session, User +from messenger.shared.application.ports import UnitOfWork + + +@runtime_checkable +class UserRepository(Protocol): + async def add(self, user: User) -> None: ... + + +@runtime_checkable +class SessionRepository(Protocol): + async def add(self, session: Session) -> None: ... + + async def remove(self, token_hash: bytes) -> None: ... + + +@runtime_checkable +class IdentityUnitOfWork(UnitOfWork, Protocol): + @property + def users(self) -> UserRepository: ... + + @property + def sessions(self) -> SessionRepository: ... + + +@runtime_checkable +class UserDirectory(Protocol): + async def find(self, user_id: UUID) -> User | None: ... + + async def find_by_username(self, username: str) -> User | None: ... + + +@runtime_checkable +class SessionDirectory(Protocol): + async def find(self, token_hash: bytes, now: datetime) -> Session | None: ... + + async def invalidate(self, session: Session) -> None: ... + + +@runtime_checkable +class PasswordHasher(Protocol): + async def hash(self, password: str) -> str: ... + + async def verify(self, password_hash: str | None, password: str) -> bool: ... diff --git a/src/messenger/identity/application/queries.py b/src/messenger/identity/application/queries.py new file mode 100644 index 00000000..cf0c7d8d --- /dev/null +++ b/src/messenger/identity/application/queries.py @@ -0,0 +1,43 @@ +from uuid import UUID + +from messenger.identity.application.ports import PasswordHasher, SessionDirectory, UserDirectory +from messenger.identity.domain.errors import ActorNotIdentified +from messenger.identity.domain.models import Session, User, token_digest +from messenger.shared.application.ports import Clock + + +class GetCurrentUser: + __slots__ = ("_directory",) + + def __init__(self, directory: UserDirectory) -> None: + self._directory = directory + + async def __call__(self, user_id: UUID) -> User: + user = await self._directory.find(user_id) + if user is None: + raise ActorNotIdentified("идентификация не подтверждена") + return user + + +class VerifyCredentials: + __slots__ = ("_directory", "_hasher") + + def __init__(self, directory: UserDirectory, hasher: PasswordHasher) -> None: + self._directory = directory + self._hasher = hasher + + async def __call__(self, username: str, password: str) -> User | None: + user = await self._directory.find_by_username(username) + valid = await self._hasher.verify(user.password_hash if user else None, password) + return user if valid else None + + +class Authenticate: + __slots__ = ("_clock", "_sessions") + + def __init__(self, sessions: SessionDirectory, clock: Clock) -> None: + self._sessions = sessions + self._clock = clock + + async def __call__(self, token: str) -> Session | None: + return await self._sessions.find(token_digest(token), self._clock.now()) diff --git a/src/messenger/identity/config.py b/src/messenger/identity/config.py new file mode 100644 index 00000000..d1e19705 --- /dev/null +++ b/src/messenger/identity/config.py @@ -0,0 +1,12 @@ +from pydantic import Field, SecretStr + +from messenger.shared.config import Settings + + +class IdentitySettings(Settings): + session_ttl_seconds: int = Field(default=3600, ge=1, le=30 * 24 * 3600) + password_hash_concurrency: int = Field(default=2, ge=1, le=64) + cache_url: SecretStr | None = None + session_cache_ttl_seconds: int = Field(default=300, ge=1, le=24 * 3600) + cache_timeout_seconds: float = Field(default=0.2, gt=0, le=5) + cache_cooldown_seconds: float = Field(default=1.0, ge=0, le=60) diff --git a/src/messenger/identity/domain/__init__.py b/src/messenger/identity/domain/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/identity/domain/errors.py b/src/messenger/identity/domain/errors.py new file mode 100644 index 00000000..335a6d25 --- /dev/null +++ b/src/messenger/identity/domain/errors.py @@ -0,0 +1,17 @@ +from messenger.shared.domain.errors import DomainError + + +class IdentityError(DomainError): + pass + + +class InvalidUserData(IdentityError): + pass + + +class UsernameAlreadyTaken(IdentityError): + pass + + +class ActorNotIdentified(IdentityError): + pass diff --git a/src/messenger/identity/domain/events.py b/src/messenger/identity/domain/events.py new file mode 100644 index 00000000..429a0b54 --- /dev/null +++ b/src/messenger/identity/domain/events.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass, field +from datetime import datetime +from uuid import UUID + +from messenger.shared.domain.events import DomainEvent + + +@dataclass(frozen=True, slots=True) +class UserRegistered(DomainEvent): + user_id: UUID + registered_at: datetime + name: str = field(init=False, default="user.registered") + + +@dataclass(frozen=True, slots=True) +class SessionOpened(DomainEvent): + user_id: UUID + expires_at: datetime + name: str = field(init=False, default="session.opened") + + +@dataclass(frozen=True, slots=True) +class SessionClosed(DomainEvent): + user_id: UUID + name: str = field(init=False, default="session.closed") diff --git a/src/messenger/identity/domain/models.py b/src/messenger/identity/domain/models.py new file mode 100644 index 00000000..7f505037 --- /dev/null +++ b/src/messenger/identity/domain/models.py @@ -0,0 +1,62 @@ +import secrets +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from hashlib import sha256 +from uuid import UUID + +from messenger.identity.domain.events import UserRegistered +from messenger.identity.domain.values import DisplayName, Username +from messenger.shared.domain.events import DomainEvent + +TOKEN_BYTES = 32 + + +def token_digest(token: str) -> bytes: + return sha256(token.encode()).digest() + + +@dataclass(frozen=True, slots=True) +class User: + id: UUID + username: Username + display_name: DisplayName + created_at: datetime + password_hash: str = field(repr=False) + + @classmethod + def register( + cls, + *, + user_id: UUID, + username: Username, + display_name: DisplayName, + password_hash: str, + registered_at: datetime, + ) -> tuple[User, DomainEvent]: + user = cls( + id=user_id, + username=username, + display_name=display_name, + created_at=registered_at, + password_hash=password_hash, + ) + return user, UserRegistered(user_id=user.id, registered_at=registered_at) + + +@dataclass(frozen=True, slots=True) +class Session: + token_hash: bytes = field(repr=False) + user_id: UUID + created_at: datetime + expires_at: datetime + + @classmethod + def issue(cls, *, user_id: UUID, issued_at: datetime, ttl: timedelta) -> tuple[str, Session]: + token = secrets.token_urlsafe(TOKEN_BYTES) + session = cls( + token_hash=token_digest(token), + user_id=user_id, + created_at=issued_at, + expires_at=issued_at + ttl, + ) + return token, session diff --git a/src/messenger/identity/domain/values.py b/src/messenger/identity/domain/values.py new file mode 100644 index 00000000..8d6170a3 --- /dev/null +++ b/src/messenger/identity/domain/values.py @@ -0,0 +1,54 @@ +import re +from dataclasses import dataclass, field + +from messenger.identity.domain.errors import InvalidUserData + +USERNAME_PATTERN = re.compile(r"\A[a-z0-9_]{3,32}\Z") +DISPLAY_NAME_MAX = 100 +PASSWORD_MIN = 12 +PASSWORD_MAX = 128 + + +@dataclass(frozen=True, slots=True) +class Username: + value: str + + def __post_init__(self) -> None: + if not isinstance(self.value, str): + raise InvalidUserData("поле username должно быть строкой") + if USERNAME_PATTERN.match(self.value) is None: + raise InvalidUserData("поле username должно соответствовать [a-z0-9_]{3,32}") + + def __str__(self) -> str: + return self.value + + +@dataclass(frozen=True, slots=True) +class DisplayName: + value: str + + def __post_init__(self) -> None: + if not isinstance(self.value, str): + raise InvalidUserData("поле display_name должно быть строкой") + if not self.value.strip(): + raise InvalidUserData("поле display_name не может быть пустым или состоять из пробелов") + if len(self.value) > DISPLAY_NAME_MAX: + raise InvalidUserData(f"поле display_name длиннее {DISPLAY_NAME_MAX} символов Unicode") + + def __str__(self) -> str: + return self.value + + +@dataclass(frozen=True, slots=True) +class Password: + value: str = field(repr=False) + + def __post_init__(self) -> None: + if not isinstance(self.value, str): + raise InvalidUserData("поле password должно быть строкой") + if not self.value.strip(): + raise InvalidUserData("поле password не может состоять из пробелов") + if not PASSWORD_MIN <= len(self.value) <= PASSWORD_MAX: + raise InvalidUserData( + f"поле password: от {PASSWORD_MIN} до {PASSWORD_MAX} символов Unicode" + ) diff --git a/src/messenger/identity/entrypoints/__init__.py b/src/messenger/identity/entrypoints/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/identity/entrypoints/authentication.py b/src/messenger/identity/entrypoints/authentication.py new file mode 100644 index 00000000..1103e3d0 --- /dev/null +++ b/src/messenger/identity/entrypoints/authentication.py @@ -0,0 +1,98 @@ +import re +from base64 import b64decode +from binascii import Error as Base64Error +from typing import Annotated + +from fastapi import Depends, Request +from starlette.types import Scope + +from messenger.identity.application.queries import Authenticate, VerifyCredentials +from messenger.identity.domain.models import Session, User +from messenger.shared.entrypoints.errors import Unauthenticated +from messenger.shared.entrypoints.pipeline import Rejection, header + +LOGIN_PATH = "/api/v1/auth/sessions" +PROTECTED_PREFIX = "/api/v1/" +PUBLIC_ROUTES = frozenset({("POST", "/api/v1/users")}) +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' +BEARER_CHALLENGE = 'Bearer realm="messenger"' +AUTHORIZATION = b"authorization" +TOKEN = re.compile(r"[A-Za-z0-9\-._~+/]{1,512}=*") + + +def normalized(path: str) -> str: + return path.rstrip("/") or "/" + + +def challenge_for(path: str) -> str: + return BASIC_CHALLENGE if normalized(path) == LOGIN_PATH else BEARER_CHALLENGE + + +def basic_credentials(value: str) -> tuple[str, str] | None: + scheme, _, encoded = value.partition(" ") + if scheme.lower() != "basic": + return None + try: + decoded = b64decode(encoded.strip(), validate=True).decode("utf-8") + except Base64Error, UnicodeDecodeError: + return None + username, separator, password = decoded.partition(":") + if not separator or not username.isascii(): + return None + return username, password + + +def bearer_token(value: str) -> str | None: + scheme, _, token = value.partition(" ") + token = token.strip() + if scheme.lower() != "bearer" or TOKEN.fullmatch(token) is None: + return None + return token + + +def rejection(path: str) -> Rejection: + return Rejection(401, "unauthorized", (("www-authenticate", challenge_for(path)),)) + + +async def guard(scope: Scope) -> Rejection | None: + method, path = scope["method"], normalized(scope["path"]) + if not path.startswith(PROTECTED_PREFIX) or (method, path) in PUBLIC_ROUTES: + return None + container = scope["app"].state.dishka_container + state = scope.setdefault("state", {}) + raw = header(scope, AUTHORIZATION) + if (method, path) == ("POST", LOGIN_PATH): + credentials = basic_credentials(raw) + verify = await container.get(VerifyCredentials) + user = await verify(*credentials) if credentials else None + if user is None: + return rejection(path) + state["user"] = user + state["actor"] = user.id + return None + token = bearer_token(raw) + authenticate = await container.get(Authenticate) + session = await authenticate(token) if token else None + if session is None: + return rejection(path) + state["session"] = session + state["actor"] = session.user_id + return None + + +async def verified_user(request: Request) -> User: + user = getattr(request.state, "user", None) + if not isinstance(user, User): + raise Unauthenticated("учётные данные не подтверждены") + return user + + +async def current_session(request: Request) -> Session: + session = getattr(request.state, "session", None) + if not isinstance(session, Session): + raise Unauthenticated("сессия не подтверждена") + return session + + +type VerifiedUser = Annotated[User, Depends(verified_user)] +type CurrentSession = Annotated[Session, Depends(current_session)] diff --git a/src/messenger/identity/entrypoints/errors.py b/src/messenger/identity/entrypoints/errors.py new file mode 100644 index 00000000..3b840f1f --- /dev/null +++ b/src/messenger/identity/entrypoints/errors.py @@ -0,0 +1,12 @@ +from messenger.identity.domain.errors import ( + ActorNotIdentified, + InvalidUserData, + UsernameAlreadyTaken, +) +from messenger.shared.domain.errors import DomainError + +ERROR_CODES: dict[type[DomainError], tuple[str, int]] = { + InvalidUserData: ("invalid_request", 400), + UsernameAlreadyTaken: ("conflict", 409), + ActorNotIdentified: ("unauthorized", 401), +} diff --git a/src/messenger/identity/entrypoints/http.py b/src/messenger/identity/entrypoints/http.py new file mode 100644 index 00000000..e67ec4e6 --- /dev/null +++ b/src/messenger/identity/entrypoints/http.py @@ -0,0 +1,57 @@ +from dishka.integrations.fastapi import FromDishka, inject +from fastapi import APIRouter, Request, Response, status +from fastapi.exceptions import RequestValidationError + +from messenger.identity.application.bus import IdentityCommandBus +from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser +from messenger.identity.application.queries import GetCurrentUser +from messenger.identity.entrypoints.authentication import CurrentSession, VerifiedUser +from messenger.identity.entrypoints.schemas import CreateUserRequest, SessionOut, UserOut +from messenger.shared.entrypoints.actor import Actor + +router = APIRouter(prefix="/api/v1/users", tags=["users"]) +sessions_router = APIRouter(prefix="/api/v1/auth/sessions", tags=["sessions"]) + + +@router.post("", status_code=status.HTTP_201_CREATED) +@inject +async def create_user( + body: CreateUserRequest, + bus: FromDishka[IdentityCommandBus], +) -> UserOut: + user = await bus.execute( + RegisterUser(username=body.username, display_name=body.display_name, password=body.password) + ) + return UserOut.of(user) + + +@router.get("/me") +@inject +async def current_user( + actor: Actor, + query: FromDishka[GetCurrentUser], +) -> UserOut: + return UserOut.of(await query(actor)) + + +@sessions_router.post("", status_code=status.HTTP_201_CREATED) +@inject +async def open_session( + request: Request, + user: VerifiedUser, + bus: FromDishka[IdentityCommandBus], +) -> SessionOut: + if await request.body(): + raise RequestValidationError([]) + token, session = await bus.execute(OpenSession(user_id=user.id)) + return SessionOut.of(token, session, user) + + +@sessions_router.delete("/current", status_code=status.HTTP_204_NO_CONTENT) +@inject +async def close_session( + session: CurrentSession, + bus: FromDishka[IdentityCommandBus], +) -> Response: + await bus.execute(CloseSession(session=session)) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/src/messenger/identity/entrypoints/ioc.py b/src/messenger/identity/entrypoints/ioc.py new file mode 100644 index 00000000..01ae21cc --- /dev/null +++ b/src/messenger/identity/entrypoints/ioc.py @@ -0,0 +1,112 @@ +from collections.abc import AsyncIterator +from datetime import timedelta + +from dishka import Provider, Scope, provide +from redis.asyncio import Redis +from redis.asyncio.retry import Retry +from redis.backoff import NoBackoff + +from messenger.identity.application.bus import IdentityCommandBus +from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser +from messenger.identity.application.handlers import ( + CloseSessionHandler, + OpenSessionHandler, + RegisterUserHandler, +) +from messenger.identity.application.ports import ( + IdentityUnitOfWork, + PasswordHasher, + SessionDirectory, + UserDirectory, +) +from messenger.identity.application.queries import Authenticate, GetCurrentUser, VerifyCredentials +from messenger.identity.config import IdentitySettings +from messenger.identity.infrastructure.argon2 import Argon2PasswordHasher +from messenger.identity.infrastructure.postgres import ( + PostgresIdentityUnitOfWork, + PostgresSessionDirectory, + PostgresUserDirectory, +) +from messenger.identity.infrastructure.valkey import CachedSessionDirectory +from messenger.shared.application.commands import Command +from messenger.shared.application.messagebus import CommandHandler +from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger +from messenger.shared.infrastructure.postgres import Database + + +class IdentityProvider(Provider): + def __init__(self, settings: IdentitySettings) -> None: + super().__init__() + self._settings = settings + + @provide(scope=Scope.APP) + def settings(self) -> IdentitySettings: + return self._settings + + @provide(scope=Scope.APP) + def hasher(self, settings: IdentitySettings) -> PasswordHasher: + return Argon2PasswordHasher(settings.password_hash_concurrency) + + @provide(scope=Scope.APP) + def users(self, database: Database) -> UserDirectory: + return PostgresUserDirectory(database) + + @provide(scope=Scope.APP) + async def sessions( + self, database: Database, settings: IdentitySettings, logger: Logger + ) -> AsyncIterator[SessionDirectory]: + origin = PostgresSessionDirectory(database) + if settings.cache_url is None: + yield origin + return + client = Redis.from_url( + settings.cache_url.get_secret_value(), + socket_connect_timeout=settings.cache_timeout_seconds, + socket_timeout=settings.cache_timeout_seconds, + retry=Retry(NoBackoff(), 1), + ) + try: + yield CachedSessionDirectory( + origin, + client, + logger, + limit=timedelta(seconds=settings.session_cache_ttl_seconds), + cooldown=settings.cache_cooldown_seconds, + ) + finally: + await client.aclose() + + @provide(scope=Scope.APP) + def verify(self, users: UserDirectory, hasher: PasswordHasher) -> VerifyCredentials: + return VerifyCredentials(users, hasher) + + @provide(scope=Scope.APP) + def authenticate(self, sessions: SessionDirectory, clock: Clock) -> Authenticate: + return Authenticate(sessions, clock) + + @provide(scope=Scope.REQUEST) + def unit_of_work(self, database: Database) -> IdentityUnitOfWork: + return PostgresIdentityUnitOfWork(database) + + @provide(scope=Scope.REQUEST) + def current_user(self, users: UserDirectory) -> GetCurrentUser: + return GetCurrentUser(users) + + @provide(scope=Scope.REQUEST) + def command_bus( + self, + uow: IdentityUnitOfWork, + publisher: EventPublisher, + clock: Clock, + ids: IdGenerator, + hasher: PasswordHasher, + sessions: SessionDirectory, + settings: IdentitySettings, + ) -> IdentityCommandBus: + ttl = timedelta(seconds=settings.session_ttl_seconds) + handlers: dict[type[Command], CommandHandler] = { + RegisterUser: RegisterUserHandler(uow, clock, ids, hasher), + OpenSession: OpenSessionHandler(uow, clock, ttl), + CloseSession: CloseSessionHandler(uow, sessions), + } + return IdentityCommandBus(handlers, uow, publisher) diff --git a/src/messenger/identity/entrypoints/journal.py b/src/messenger/identity/entrypoints/journal.py new file mode 100644 index 00000000..9d51aeee --- /dev/null +++ b/src/messenger/identity/entrypoints/journal.py @@ -0,0 +1,20 @@ +from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered +from messenger.shared.application.ports import Logger + +LOG_FIELDS = frozenset({"actor_id"}) + + +class IdentityJournal: + __slots__ = ("_logger",) + + def __init__(self, logger: Logger) -> None: + self._logger = logger + + async def on_user_registered(self, event: UserRegistered) -> None: + self._logger.info("audit.user_registered", actor_id=str(event.user_id)) + + async def on_session_opened(self, event: SessionOpened) -> None: + self._logger.info("audit.session_opened", actor_id=str(event.user_id)) + + async def on_session_closed(self, event: SessionClosed) -> None: + self._logger.info("audit.session_closed", actor_id=str(event.user_id)) diff --git a/src/messenger/identity/entrypoints/schemas.py b/src/messenger/identity/entrypoints/schemas.py new file mode 100644 index 00000000..7560cfd2 --- /dev/null +++ b/src/messenger/identity/entrypoints/schemas.py @@ -0,0 +1,42 @@ +from datetime import datetime +from typing import Literal +from uuid import UUID + +from pydantic import BaseModel, ConfigDict + +from messenger.identity.domain.models import Session, User + + +class CreateUserRequest(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + username: str + display_name: str + password: str + + +class UserOut(BaseModel): + id: UUID + username: str + display_name: str + created_at: datetime + + @classmethod + def of(cls, user: User) -> UserOut: + return cls( + id=user.id, + username=user.username.value, + display_name=user.display_name.value, + created_at=user.created_at, + ) + + +class SessionOut(BaseModel): + token: str + token_type: Literal["Bearer"] = "Bearer" + expires_at: datetime + user: UserOut + + @classmethod + def of(cls, token: str, session: Session, user: User) -> SessionOut: + return cls(token=token, expires_at=session.expires_at, user=UserOut.of(user)) diff --git a/src/messenger/identity/infrastructure/__init__.py b/src/messenger/identity/infrastructure/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/identity/infrastructure/argon2.py b/src/messenger/identity/infrastructure/argon2.py new file mode 100644 index 00000000..159dba76 --- /dev/null +++ b/src/messenger/identity/infrastructure/argon2.py @@ -0,0 +1,35 @@ +import asyncio +import secrets + +from argon2 import PasswordHasher, Type +from argon2.exceptions import InvalidHashError, VerificationError + +TIME_COST = 2 +MEMORY_COST_KIB = 19_456 +PARALLELISM = 1 + + +class Argon2PasswordHasher: + __slots__ = ("_dummy", "_hasher", "_slots") + + def __init__(self, concurrency: int) -> None: + self._hasher = PasswordHasher( + time_cost=TIME_COST, + memory_cost=MEMORY_COST_KIB, + parallelism=PARALLELISM, + type=Type.ID, + ) + self._slots = asyncio.Semaphore(concurrency) + self._dummy = self._hasher.hash(secrets.token_urlsafe(16)) + + async def hash(self, password: str) -> str: + async with self._slots: + return await asyncio.to_thread(self._hasher.hash, password) + + async def verify(self, password_hash: str | None, password: str) -> bool: + async with self._slots: + try: + await asyncio.to_thread(self._hasher.verify, password_hash or self._dummy, password) + except VerificationError, InvalidHashError: + return False + return password_hash is not None diff --git a/src/messenger/identity/infrastructure/postgres.py b/src/messenger/identity/infrastructure/postgres.py new file mode 100644 index 00000000..ab8ddf3a --- /dev/null +++ b/src/messenger/identity/infrastructure/postgres.py @@ -0,0 +1,124 @@ +from datetime import datetime +from uuid import UUID + +from asyncpg import Record + +from messenger.identity.domain.errors import UsernameAlreadyTaken +from messenger.identity.domain.models import Session, User +from messenger.identity.domain.values import DisplayName, Username +from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork + +INSERT_USER = """ +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (username) DO NOTHING +RETURNING true +""" +USER_BY_ID = """ +SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1 +""" +USER_BY_USERNAME = """ +SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1 +""" +INSERT_SESSION = """ +WITH expired AS (DELETE FROM sessions WHERE user_id = $2 AND expires_at <= $3) +INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES ($1, $2, $3, $4) +""" +DELETE_SESSION = "DELETE FROM sessions WHERE token_hash = $1" +ACTIVE_SESSION = """ +SELECT token_hash, user_id, created_at, expires_at +FROM sessions +WHERE token_hash = $1 AND expires_at > $2 +""" + + +def user_of(row: Record | None) -> User | None: + if row is None: + return None + return User( + id=row["id"], + username=Username(row["username"]), + display_name=DisplayName(row["display_name"]), + created_at=row["created_at"], + password_hash=row["password_hash"], + ) + + +class PostgresUserRepository: + __slots__ = ("_connection",) + + def __init__(self, connection: Connection) -> None: + self._connection = connection + + async def add(self, user: User) -> None: + inserted = await self._connection.fetchval( + INSERT_USER, + user.id, + user.username.value, + user.display_name.value, + user.password_hash, + user.created_at, + ) + if inserted is None: + raise UsernameAlreadyTaken("username уже занят") + + +class PostgresSessionRepository: + __slots__ = ("_connection",) + + def __init__(self, connection: Connection) -> None: + self._connection = connection + + async def add(self, session: Session) -> None: + await self._connection.execute( + INSERT_SESSION, + session.token_hash, + session.user_id, + session.created_at, + session.expires_at, + ) + + async def remove(self, token_hash: bytes) -> None: + await self._connection.execute(DELETE_SESSION, token_hash) + + +class PostgresIdentityUnitOfWork(PostgresUnitOfWork): + __slots__ = () + + @property + def users(self) -> PostgresUserRepository: + return PostgresUserRepository(self.connection) + + @property + def sessions(self) -> PostgresSessionRepository: + return PostgresSessionRepository(self.connection) + + +class PostgresUserDirectory: + __slots__ = ("_database",) + + def __init__(self, database: Database) -> None: + self._database = database + + async def find(self, user_id: UUID) -> User | None: + async with self._database.connection() as connection: + return user_of(await connection.fetchrow(USER_BY_ID, user_id)) + + async def find_by_username(self, username: str) -> User | None: + async with self._database.connection() as connection: + return user_of(await connection.fetchrow(USER_BY_USERNAME, username)) + + +class PostgresSessionDirectory: + __slots__ = ("_database",) + + def __init__(self, database: Database) -> None: + self._database = database + + async def find(self, token_hash: bytes, now: datetime) -> Session | None: + async with self._database.connection() as connection: + row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now) + return None if row is None else Session(**dict(row)) + + async def invalidate(self, session: Session) -> None: + return None diff --git a/src/messenger/identity/infrastructure/valkey.py b/src/messenger/identity/infrastructure/valkey.py new file mode 100644 index 00000000..c3d80200 --- /dev/null +++ b/src/messenger/identity/infrastructure/valkey.py @@ -0,0 +1,102 @@ +import time +from collections.abc import Awaitable +from datetime import datetime, timedelta +from uuid import UUID + +from redis.asyncio import Redis +from redis.exceptions import RedisError + +from messenger.identity.application.ports import SessionDirectory +from messenger.identity.domain.models import Session +from messenger.shared.application.errors import Unavailable +from messenger.shared.application.ports import Logger + +REVOKED = "-" +FAILURES = (RedisError, OSError) + + +def key_of(token_hash: bytes) -> str: + return f"session:{token_hash.hex()}" + + +def milliseconds(moment: datetime) -> int: + return int(moment.timestamp() * 1000) + + +def encode(session: Session) -> str: + return f"{session.user_id} {session.created_at.isoformat()} {session.expires_at.isoformat()}" + + +def decode(token_hash: bytes, value: str) -> Session: + user_id, created_at, expires_at = value.split(" ") + return Session( + token_hash=token_hash, + user_id=UUID(user_id), + created_at=datetime.fromisoformat(created_at), + expires_at=datetime.fromisoformat(expires_at), + ) + + +class CachedSessionDirectory: + __slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at") + + def __init__( + self, + origin: SessionDirectory, + client: Redis, + logger: Logger, + *, + limit: timedelta, + cooldown: float, + ) -> None: + self._origin = origin + self._client = client + self._logger = logger + self._limit = limit + self._cooldown = cooldown + self._resume_at = 0.0 + + async def find(self, token_hash: bytes, now: datetime) -> Session | None: + key = key_of(token_hash) + cached = await self._read(key) + if cached == REVOKED: + return None + if cached is not None: + session = decode(token_hash, cached) + return session if session.expires_at > now else None + session = await self._origin.find(token_hash, now) + if session is not None and self._closed(): + until = milliseconds(min(session.expires_at, now + self._limit)) + await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True)) + return session + + async def invalidate(self, session: Session) -> None: + if not self._closed(): + raise Unavailable("кэш сессий недоступен") + try: + await self._client.set( + key_of(session.token_hash), REVOKED, pxat=milliseconds(session.expires_at) + ) + except FAILURES as error: + self._trip(error) + raise Unavailable("кэш сессий недоступен") from error + + async def _read(self, key: str) -> str | None: + if not self._closed(): + return None + value = await self._quietly(self._client.get(key)) + return value.decode() if isinstance(value, bytes) else value + + async def _quietly[ResultT](self, call: Awaitable[ResultT]) -> ResultT | None: + try: + return await call + except FAILURES as error: + self._trip(error) + return None + + def _closed(self) -> bool: + return time.monotonic() >= self._resume_at + + def _trip(self, error: Exception) -> None: + self._resume_at = time.monotonic() + self._cooldown + self._logger.warning("cache.bypassed", error=type(error).__name__, limit=self._cooldown) diff --git a/src/messenger/main.py b/src/messenger/main.py new file mode 100644 index 00000000..fd1a9922 --- /dev/null +++ b/src/messenger/main.py @@ -0,0 +1,104 @@ +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +from dishka import make_async_container +from dishka.integrations.fastapi import FastapiProvider, setup_dishka +from fastapi import FastAPI + +from messenger.identity.config import IdentitySettings +from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered +from messenger.identity.entrypoints.authentication import challenge_for, guard +from messenger.identity.entrypoints.errors import ERROR_CODES as IDENTITY_ERRORS +from messenger.identity.entrypoints.http import router as users_router +from messenger.identity.entrypoints.http import sessions_router +from messenger.identity.entrypoints.ioc import IdentityProvider +from messenger.identity.entrypoints.journal import LOG_FIELDS as IDENTITY_FIELDS +from messenger.identity.entrypoints.journal import IdentityJournal +from messenger.messaging.config import MessagingSettings +from messenger.messaging.domain.events import ChatCreated, MessagePosted +from messenger.messaging.entrypoints.errors import ERROR_CODES as MESSAGING_ERRORS +from messenger.messaging.entrypoints.http import chats_router, messages_router +from messenger.messaging.entrypoints.ioc import MessagingProvider +from messenger.messaging.entrypoints.journal import LOG_FIELDS as MESSAGING_FIELDS +from messenger.messaging.entrypoints.journal import MessagingJournal +from messenger.shared.application.messagebus import EventBus +from messenger.shared.application.ports import Logger +from messenger.shared.config import PlatformSettings +from messenger.shared.entrypoints import errors, health +from messenger.shared.entrypoints.config import TransportSettings +from messenger.shared.entrypoints.ioc import PlatformProvider +from messenger.shared.entrypoints.pipeline import RequestPipeline +from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger + +TRANSPORT_FIELDS = frozenset({"dropped_total", "queue", "instance"}) + +LOG_FIELDS = PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS +ERROR_CODES = {**IDENTITY_ERRORS, **MESSAGING_ERRORS} + + +def wire_events(bus: EventBus, logger: Logger) -> None: + identity = IdentityJournal(logger) + bus.subscribe(UserRegistered, identity.on_user_registered) + bus.subscribe(SessionOpened, identity.on_session_opened) + bus.subscribe(SessionClosed, identity.on_session_closed) + + messaging = MessagingJournal(logger) + bus.subscribe(ChatCreated, messaging.on_chat_created) + bus.subscribe(MessagePosted, messaging.on_message_posted) + + +def create_app( + platform: PlatformSettings | None = None, + transport: TransportSettings | None = None, + identity: IdentitySettings | None = None, + messaging: MessagingSettings | None = None, +) -> FastAPI: + platform = platform or PlatformSettings() + transport = transport or TransportSettings() + identity = identity or IdentitySettings() + messaging = messaging or MessagingSettings() + logger = StructlogLogger(level=platform.log_level, allowed_fields=LOG_FIELDS) + container = make_async_container( + PlatformProvider(platform, logger), + IdentityProvider(identity), + MessagingProvider(messaging), + FastapiProvider(), + ) + + @asynccontextmanager + async def lifespan(_app: FastAPI) -> AsyncIterator[None]: + bus = await container.get(EventBus) + wire_events(bus, logger) + bus.start() + logger.info("service.started") + try: + yield + finally: + await bus.stop() + await container.close() + logger.info("service.stopped") + + app = FastAPI( + title="MTUSI Messenger", + version="1.4.0", + lifespan=lifespan, + docs_url="/docs" if transport.docs else None, + redoc_url=None, + openapi_url="/openapi.json" if transport.docs else None, + ) + app.add_middleware( + RequestPipeline, + logger=logger, + max_bytes=transport.max_body_bytes, + timeout=transport.request_timeout_seconds, + guard=guard, + instance=platform.instance_id, + ) + errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id) + app.include_router(health.router) + app.include_router(users_router) + app.include_router(sessions_router) + app.include_router(chats_router) + app.include_router(messages_router) + setup_dishka(container, app) + return app diff --git a/src/messenger/messaging/__init__.py b/src/messenger/messaging/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/messaging/application/__init__.py b/src/messenger/messaging/application/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/messaging/application/bus.py b/src/messenger/messaging/application/bus.py new file mode 100644 index 00000000..26fb2e6e --- /dev/null +++ b/src/messenger/messaging/application/bus.py @@ -0,0 +1,5 @@ +from messenger.shared.application.messagebus import CommandBus + + +class MessagingCommandBus(CommandBus): + __slots__ = () diff --git a/src/messenger/messaging/application/commands.py b/src/messenger/messaging/application/commands.py new file mode 100644 index 00000000..33e0f7b9 --- /dev/null +++ b/src/messenger/messaging/application/commands.py @@ -0,0 +1,21 @@ +from collections.abc import Sequence +from dataclasses import dataclass +from uuid import UUID + +from messenger.shared.application.commands import Command + + +@dataclass(frozen=True, slots=True) +class CreateChat(Command): + creator_id: UUID + title: str + member_ids: Sequence[UUID] + + +@dataclass(frozen=True, slots=True) +class PostMessage(Command): + sender_id: UUID + chat_id: UUID + text: str + key: str + fingerprint: bytes diff --git a/src/messenger/messaging/application/handlers.py b/src/messenger/messaging/application/handlers.py new file mode 100644 index 00000000..c4b96fbb --- /dev/null +++ b/src/messenger/messaging/application/handlers.py @@ -0,0 +1,62 @@ +from datetime import timedelta + +from messenger.messaging.application.commands import CreateChat, PostMessage +from messenger.messaging.application.ports import MessagingUnitOfWork +from messenger.messaging.domain.errors import ChatNotFound +from messenger.messaging.domain.models import Chat, Message, Receipt +from messenger.shared.application.ports import Clock, IdGenerator + + +class CreateChatHandler: + __slots__ = ("_clock", "_ids", "_uow") + + def __init__(self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator) -> None: + self._uow = uow + self._clock = clock + self._ids = ids + + async def __call__(self, command: CreateChat) -> Chat: + chat = Chat.create( + chat_id=self._ids.new_id(), + title=command.title, + member_ids=command.member_ids, + creator_id=command.creator_id, + created_at=self._clock.now(), + ) + async with self._uow.transaction(): + await self._uow.chats.add(chat) + await self._uow.commit() + return chat + + +class PostMessageHandler: + __slots__ = ("_clock", "_ids", "_ttl", "_uow") + + def __init__( + self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator, ttl: timedelta + ) -> None: + self._uow = uow + self._clock = clock + self._ids = ids + self._ttl = ttl + + async def __call__(self, command: PostMessage) -> Message: + async with self._uow.transaction(): + chat = await self._uow.chats.get(command.chat_id) + if chat is None: + raise ChatNotFound("чат не найден") + now = self._clock.now() + message = chat.post( + message_id=self._ids.new_id(), + sender_id=command.sender_id, + text=command.text, + now=now, + ) + known = await self._uow.chats.receipt( + chat.id, command.sender_id, command.key, now - self._ttl + ) + if known is not None: + return known.replay(command.fingerprint) + await self._uow.chats.append(Receipt(command.key, command.fingerprint, message)) + await self._uow.commit() + return message diff --git a/src/messenger/messaging/application/ports.py b/src/messenger/messaging/application/ports.py new file mode 100644 index 00000000..adf82004 --- /dev/null +++ b/src/messenger/messaging/application/ports.py @@ -0,0 +1,46 @@ +from datetime import datetime +from typing import Protocol, runtime_checkable +from uuid import UUID + +from messenger.messaging.domain.keys import HistoryKey +from messenger.messaging.domain.models import Chat, Message, Receipt +from messenger.shared.application.ports import UnitOfWork + + +@runtime_checkable +class CursorCodec(Protocol): + def encode(self, scope: str, key: HistoryKey) -> str: ... + + def decode(self, scope: str, raw: str) -> HistoryKey: ... + + +@runtime_checkable +class ChatRepository(Protocol): + async def add(self, chat: Chat) -> None: ... + + async def get(self, chat_id: UUID) -> Chat | None: ... + + async def receipt( + self, chat_id: UUID, sender_id: UUID, key: str, since: datetime + ) -> Receipt | None: ... + + async def append(self, receipt: Receipt) -> None: ... + + +@runtime_checkable +class MessagingUnitOfWork(UnitOfWork, Protocol): + @property + def chats(self) -> ChatRepository: ... + + +@runtime_checkable +class ChatDirectory(Protocol): + async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None: ... + + async def chats_of( + self, user_id: UUID, *, after: HistoryKey | None, limit: int + ) -> tuple[list[Chat], bool]: ... + + async def history( + self, chat_id: UUID, *, after: HistoryKey | None, limit: int + ) -> tuple[list[Message], bool]: ... diff --git a/src/messenger/messaging/application/queries.py b/src/messenger/messaging/application/queries.py new file mode 100644 index 00000000..8e16e947 --- /dev/null +++ b/src/messenger/messaging/application/queries.py @@ -0,0 +1,73 @@ +from dataclasses import dataclass +from uuid import UUID + +from messenger.messaging.application.ports import ChatDirectory, CursorCodec +from messenger.messaging.domain.errors import ChatNotFound +from messenger.messaging.domain.keys import HistoryKey +from messenger.messaging.domain.models import Chat, Message + + +@dataclass(frozen=True, slots=True) +class Page[ItemT]: + items: list[ItemT] + next_cursor: str | None + + +def chats_scope(user_id: UUID) -> str: + return f"chats:{user_id}" + + +def messages_scope(chat_id: UUID) -> str: + return f"messages:{chat_id}" + + +class GetChat: + __slots__ = ("_chats",) + + def __init__(self, chats: ChatDirectory) -> None: + self._chats = chats + + async def __call__(self, chat_id: UUID, user_id: UUID) -> Chat: + chat = await self._chats.chat_for_member(chat_id, user_id) + if chat is None: + raise ChatNotFound("чат не найден") + return chat + + +class ListChats: + __slots__ = ("_chats", "_cursors") + + def __init__(self, chats: ChatDirectory, cursors: CursorCodec) -> None: + self._chats = chats + self._cursors = cursors + + async def __call__(self, user_id: UUID, *, limit: int, cursor: str | None) -> Page[Chat]: + scope = chats_scope(user_id) + after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None + items, has_more = await self._chats.chats_of(user_id, after=after, limit=limit) + next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None + return Page(items=items, next_cursor=next_cursor) + + +class ReadHistory: + __slots__ = ("_chats", "_cursors") + + def __init__(self, chats: ChatDirectory, cursors: CursorCodec) -> None: + self._chats = chats + self._cursors = cursors + + async def __call__( + self, + chat_id: UUID, + user_id: UUID, + *, + limit: int, + cursor: str | None, + ) -> Page[Message]: + if await self._chats.chat_for_member(chat_id, user_id) is None: + raise ChatNotFound("чат не найден") + scope = messages_scope(chat_id) + after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None + items, has_more = await self._chats.history(chat_id, after=after, limit=limit) + next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None + return Page(items=items, next_cursor=next_cursor) diff --git a/src/messenger/messaging/config.py b/src/messenger/messaging/config.py new file mode 100644 index 00000000..71cd0c2a --- /dev/null +++ b/src/messenger/messaging/config.py @@ -0,0 +1,8 @@ +from pydantic import Field, SecretStr + +from messenger.shared.config import Settings + + +class MessagingSettings(Settings): + cursor_secret: SecretStr = Field(min_length=16) + idempotency_ttl_seconds: int = Field(default=86_400, ge=1) diff --git a/src/messenger/messaging/domain/__init__.py b/src/messenger/messaging/domain/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/messaging/domain/errors.py b/src/messenger/messaging/domain/errors.py new file mode 100644 index 00000000..38c25b42 --- /dev/null +++ b/src/messenger/messaging/domain/errors.py @@ -0,0 +1,25 @@ +from messenger.shared.domain.errors import DomainError + + +class MessagingError(DomainError): + pass + + +class InvalidChatData(MessagingError): + pass + + +class InvalidMessageText(MessagingError): + pass + + +class InvalidPageRequest(MessagingError): + pass + + +class ChatNotFound(MessagingError): + pass + + +class IdempotencyConflict(MessagingError): + pass diff --git a/src/messenger/messaging/domain/events.py b/src/messenger/messaging/domain/events.py new file mode 100644 index 00000000..1b0709d3 --- /dev/null +++ b/src/messenger/messaging/domain/events.py @@ -0,0 +1,24 @@ +from dataclasses import dataclass, field +from datetime import datetime +from uuid import UUID + +from messenger.shared.domain.events import DomainEvent + + +@dataclass(frozen=True, slots=True) +class ChatCreated(DomainEvent): + chat_id: UUID + creator_id: UUID + member_count: int + created_at: datetime + name: str = field(init=False, default="chat.created") + + +@dataclass(frozen=True, slots=True) +class MessagePosted(DomainEvent): + message_id: UUID + chat_id: UUID + sender_id: UUID + text_length: int + created_at: datetime + name: str = field(init=False, default="message.posted") diff --git a/src/messenger/messaging/domain/keys.py b/src/messenger/messaging/domain/keys.py new file mode 100644 index 00000000..2e432477 --- /dev/null +++ b/src/messenger/messaging/domain/keys.py @@ -0,0 +1,3 @@ +from datetime import datetime + +type HistoryKey = tuple[datetime, int] diff --git a/src/messenger/messaging/domain/models.py b/src/messenger/messaging/domain/models.py new file mode 100644 index 00000000..dc1109cc --- /dev/null +++ b/src/messenger/messaging/domain/models.py @@ -0,0 +1,142 @@ +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta +from uuid import UUID + +from messenger.messaging.domain.errors import ChatNotFound, IdempotencyConflict, InvalidChatData +from messenger.messaging.domain.events import ChatCreated, MessagePosted +from messenger.messaging.domain.keys import HistoryKey +from messenger.messaging.domain.values import CHAT_MEMBERS_MAX, ChatTitle, MessageText +from messenger.shared.domain.events import DomainEvent + +TICK = timedelta(microseconds=1) + + +@dataclass(frozen=True, slots=True) +class Message: + id: UUID + chat_id: UUID + sender_id: UUID + text: MessageText + created_at: datetime + + @property + def key(self) -> HistoryKey: + return (self.created_at, self.id.int) + + +@dataclass(frozen=True, slots=True) +class Receipt: + key: str + fingerprint: bytes + message: Message + + def replay(self, fingerprint: bytes) -> Message: + if fingerprint != self.fingerprint: + raise IdempotencyConflict("ключ идемпотентности уже использован с другим телом") + return self.message + + +class Chat: + __slots__ = ( + "_events", + "_members", + "created_at", + "id", + "last_message_at", + "member_ids", + "title", + ) + + def __init__( + self, + *, + chat_id: UUID, + title: ChatTitle, + member_ids: Sequence[UUID], + created_at: datetime, + last_message_at: datetime | None = None, + ) -> None: + self.id = chat_id + self.title = title + self.member_ids: tuple[UUID, ...] = tuple(member_ids) + self.created_at = created_at + self.last_message_at = last_message_at + self._members: frozenset[UUID] = frozenset(member_ids) + self._events: list[DomainEvent] = [] + + @classmethod + def create( + cls, + *, + chat_id: UUID, + title: str, + member_ids: Sequence[UUID], + creator_id: UUID, + created_at: datetime, + ) -> Chat: + if not member_ids: + raise InvalidChatData("поле member_ids не может быть пустым") + if len(member_ids) > CHAT_MEMBERS_MAX: + raise InvalidChatData(f"поле member_ids содержит больше {CHAT_MEMBERS_MAX} участников") + unique = set(member_ids) + if len(unique) != len(member_ids): + raise InvalidChatData("поле member_ids содержит дубликаты") + if creator_id not in unique: + raise InvalidChatData("создатель чата обязан входить в список member_ids") + chat = cls( + chat_id=chat_id, + title=ChatTitle(title), + member_ids=member_ids, + created_at=created_at, + ) + chat.record( + ChatCreated( + chat_id=chat.id, + creator_id=creator_id, + member_count=len(unique), + created_at=created_at, + ) + ) + return chat + + @property + def key(self) -> HistoryKey: + return (self.created_at, self.id.int) + + def record(self, event: DomainEvent) -> None: + self._events.append(event) + + def is_member(self, user_id: UUID) -> bool: + return user_id in self._members + + def require_member(self, user_id: UUID) -> None: + if not self.is_member(user_id): + raise ChatNotFound("чат не найден") + + def post(self, *, message_id: UUID, sender_id: UUID, text: str, now: datetime) -> Message: + self.require_member(sender_id) + last = self.last_message_at + created_at = now if last is None or now > last else last + TICK + message = Message( + id=message_id, + chat_id=self.id, + sender_id=sender_id, + text=MessageText(text), + created_at=created_at, + ) + self.last_message_at = created_at + self.record( + MessagePosted( + message_id=message.id, + chat_id=self.id, + sender_id=sender_id, + text_length=len(message.text.value), + created_at=created_at, + ) + ) + return message + + def collect_events(self) -> list[DomainEvent]: + events, self._events = self._events, [] + return events diff --git a/src/messenger/messaging/domain/values.py b/src/messenger/messaging/domain/values.py new file mode 100644 index 00000000..82895255 --- /dev/null +++ b/src/messenger/messaging/domain/values.py @@ -0,0 +1,39 @@ +from dataclasses import dataclass + +from messenger.messaging.domain.errors import InvalidChatData, InvalidMessageText + +CHAT_TITLE_MAX = 100 +MESSAGE_TEXT_MAX = 4000 +CHAT_MEMBERS_MAX = 100 + + +@dataclass(frozen=True, slots=True) +class ChatTitle: + value: str + + def __post_init__(self) -> None: + if not isinstance(self.value, str): + raise InvalidChatData("поле title должно быть строкой") + if not self.value.strip(): + raise InvalidChatData("поле title не может быть пустым или состоять из пробелов") + if len(self.value) > CHAT_TITLE_MAX: + raise InvalidChatData(f"поле title длиннее {CHAT_TITLE_MAX} символов Unicode") + + def __str__(self) -> str: + return self.value + + +@dataclass(frozen=True, slots=True) +class MessageText: + value: str + + def __post_init__(self) -> None: + if not isinstance(self.value, str): + raise InvalidMessageText("поле text должно быть строкой") + if not self.value.strip(): + raise InvalidMessageText("поле text не может быть пустым или состоять из пробелов") + if len(self.value) > MESSAGE_TEXT_MAX: + raise InvalidMessageText(f"поле text длиннее {MESSAGE_TEXT_MAX} символов Unicode") + + def __str__(self) -> str: + return self.value diff --git a/src/messenger/messaging/entrypoints/__init__.py b/src/messenger/messaging/entrypoints/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/messaging/entrypoints/errors.py b/src/messenger/messaging/entrypoints/errors.py new file mode 100644 index 00000000..98690321 --- /dev/null +++ b/src/messenger/messaging/entrypoints/errors.py @@ -0,0 +1,16 @@ +from messenger.messaging.domain.errors import ( + ChatNotFound, + IdempotencyConflict, + InvalidChatData, + InvalidMessageText, + InvalidPageRequest, +) +from messenger.shared.domain.errors import DomainError + +ERROR_CODES: dict[type[DomainError], tuple[str, int]] = { + InvalidChatData: ("invalid_request", 400), + InvalidMessageText: ("invalid_request", 400), + InvalidPageRequest: ("invalid_request", 400), + ChatNotFound: ("not_found", 404), + IdempotencyConflict: ("conflict", 409), +} diff --git a/src/messenger/messaging/entrypoints/http.py b/src/messenger/messaging/entrypoints/http.py new file mode 100644 index 00000000..fe67b0bc --- /dev/null +++ b/src/messenger/messaging/entrypoints/http.py @@ -0,0 +1,89 @@ +from typing import Annotated +from uuid import UUID + +from dishka.integrations.fastapi import FromDishka, inject +from fastapi import APIRouter, Query, status + +from messenger.messaging.application.bus import MessagingCommandBus +from messenger.messaging.application.commands import CreateChat, PostMessage +from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory +from messenger.messaging.entrypoints.schemas import ( + ChatOut, + CreateChatRequest, + CreateMessageRequest, + IdempotencyKey, + MessageOut, + PageOut, + PageQuery, +) +from messenger.shared.entrypoints.actor import Actor + +chats_router = APIRouter(prefix="/api/v1/chats", tags=["chats"]) +messages_router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"]) + + +@chats_router.post("", status_code=status.HTTP_201_CREATED) +@inject +async def create_chat( + actor: Actor, + body: CreateChatRequest, + bus: FromDishka[MessagingCommandBus], +) -> ChatOut: + chat = await bus.execute( + CreateChat(creator_id=actor, title=body.title, member_ids=body.member_ids) + ) + return ChatOut.of(chat) + + +@chats_router.get("") +@inject +async def list_chats( + actor: Actor, + page: Annotated[PageQuery, Query()], + query: FromDishka[ListChats], +) -> PageOut[ChatOut]: + chats = await query(actor, limit=page.limit, cursor=page.cursor) + return PageOut[ChatOut].of(chats, ChatOut.of) + + +@chats_router.get("/{chat_id}") +@inject +async def read_chat( + chat_id: UUID, + actor: Actor, + query: FromDishka[GetChat], +) -> ChatOut: + return ChatOut.of(await query(chat_id, actor)) + + +@messages_router.post("", status_code=status.HTTP_201_CREATED) +@inject +async def post_message( + chat_id: UUID, + actor: Actor, + body: CreateMessageRequest, + key: IdempotencyKey, + bus: FromDishka[MessagingCommandBus], +) -> MessageOut: + message = await bus.execute( + PostMessage( + sender_id=actor, + chat_id=chat_id, + text=body.text, + key=key, + fingerprint=body.fingerprint(), + ) + ) + return MessageOut.of(message) + + +@messages_router.get("") +@inject +async def read_history( + chat_id: UUID, + actor: Actor, + page: Annotated[PageQuery, Query()], + query: FromDishka[ReadHistory], +) -> PageOut[MessageOut]: + messages = await query(chat_id, actor, limit=page.limit, cursor=page.cursor) + return PageOut[MessageOut].of(messages, MessageOut.of) diff --git a/src/messenger/messaging/entrypoints/ioc.py b/src/messenger/messaging/entrypoints/ioc.py new file mode 100644 index 00000000..88d5909d --- /dev/null +++ b/src/messenger/messaging/entrypoints/ioc.py @@ -0,0 +1,69 @@ +from datetime import timedelta + +from dishka import Provider, Scope, provide + +from messenger.messaging.application.bus import MessagingCommandBus +from messenger.messaging.application.commands import CreateChat, PostMessage +from messenger.messaging.application.handlers import CreateChatHandler, PostMessageHandler +from messenger.messaging.application.ports import ChatDirectory, CursorCodec, MessagingUnitOfWork +from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory +from messenger.messaging.config import MessagingSettings +from messenger.messaging.infrastructure.cursor import SignedCursorCodec +from messenger.messaging.infrastructure.postgres import ( + PostgresChatDirectory, + PostgresMessagingUnitOfWork, +) +from messenger.shared.application.commands import Command +from messenger.shared.application.messagebus import CommandHandler +from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator +from messenger.shared.infrastructure.postgres import Database + + +class MessagingProvider(Provider): + def __init__(self, settings: MessagingSettings) -> None: + super().__init__() + self._settings = settings + + @provide(scope=Scope.APP) + def settings(self) -> MessagingSettings: + return self._settings + + @provide(scope=Scope.APP) + def directory(self, database: Database) -> ChatDirectory: + return PostgresChatDirectory(database) + + @provide(scope=Scope.APP) + def cursors(self, settings: MessagingSettings) -> CursorCodec: + return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode()) + + @provide(scope=Scope.REQUEST) + def unit_of_work(self, database: Database) -> MessagingUnitOfWork: + return PostgresMessagingUnitOfWork(database) + + @provide(scope=Scope.REQUEST) + def chat(self, directory: ChatDirectory) -> GetChat: + return GetChat(directory) + + @provide(scope=Scope.REQUEST) + def chat_list(self, directory: ChatDirectory, cursors: CursorCodec) -> ListChats: + return ListChats(directory, cursors) + + @provide(scope=Scope.REQUEST) + def history(self, directory: ChatDirectory, cursors: CursorCodec) -> ReadHistory: + return ReadHistory(directory, cursors) + + @provide(scope=Scope.REQUEST) + def command_bus( + self, + uow: MessagingUnitOfWork, + publisher: EventPublisher, + clock: Clock, + ids: IdGenerator, + settings: MessagingSettings, + ) -> MessagingCommandBus: + ttl = timedelta(seconds=settings.idempotency_ttl_seconds) + handlers: dict[type[Command], CommandHandler] = { + CreateChat: CreateChatHandler(uow, clock, ids), + PostMessage: PostMessageHandler(uow, clock, ids, ttl), + } + return MessagingCommandBus(handlers, uow, publisher) diff --git a/src/messenger/messaging/entrypoints/journal.py b/src/messenger/messaging/entrypoints/journal.py new file mode 100644 index 00000000..17c7e675 --- /dev/null +++ b/src/messenger/messaging/entrypoints/journal.py @@ -0,0 +1,27 @@ +from messenger.messaging.domain.events import ChatCreated, MessagePosted +from messenger.shared.application.ports import Logger + +LOG_FIELDS = frozenset({"chat_id", "message_id", "count"}) + + +class MessagingJournal: + __slots__ = ("_logger",) + + def __init__(self, logger: Logger) -> None: + self._logger = logger + + async def on_chat_created(self, event: ChatCreated) -> None: + self._logger.info( + "audit.chat_created", + chat_id=str(event.chat_id), + actor_id=str(event.creator_id), + count=event.member_count, + ) + + async def on_message_posted(self, event: MessagePosted) -> None: + self._logger.info( + "audit.message_posted", + chat_id=str(event.chat_id), + actor_id=str(event.sender_id), + message_id=str(event.message_id), + ) diff --git a/src/messenger/messaging/entrypoints/schemas.py b/src/messenger/messaging/entrypoints/schemas.py new file mode 100644 index 00000000..bb5728fc --- /dev/null +++ b/src/messenger/messaging/entrypoints/schemas.py @@ -0,0 +1,82 @@ +from collections.abc import Callable +from datetime import datetime +from hashlib import sha256 +from typing import Annotated, Self +from uuid import UUID + +from fastapi import Header +from pydantic import BaseModel, ConfigDict, Field + +from messenger.messaging.application.queries import Page +from messenger.messaging.domain.models import Chat, Message + +STRICT = ConfigDict(extra="forbid", strict=True) + +type IdempotencyKey = Annotated[ + str, + Header(alias="Idempotency-Key", min_length=1, max_length=128, pattern=r"^[A-Za-z0-9._:-]+$"), +] + + +class CreateChatRequest(BaseModel): + model_config = STRICT + + title: str + member_ids: list[Annotated[UUID, Field(strict=False)]] + + +class CreateMessageRequest(BaseModel): + model_config = STRICT + + text: str + + def fingerprint(self) -> bytes: + return sha256(self.model_dump_json().encode()).digest() + + +class PageQuery(BaseModel): + limit: int = Field(default=50, ge=1, le=100) + cursor: str | None = None + + +class ChatOut(BaseModel): + id: UUID + title: str + member_ids: tuple[UUID, ...] + created_at: datetime + + @classmethod + def of(cls, chat: Chat) -> ChatOut: + return cls( + id=chat.id, + title=chat.title.value, + member_ids=chat.member_ids, + created_at=chat.created_at, + ) + + +class MessageOut(BaseModel): + id: UUID + chat_id: UUID + sender_id: UUID + text: str + created_at: datetime + + @classmethod + def of(cls, message: Message) -> MessageOut: + return cls( + id=message.id, + chat_id=message.chat_id, + sender_id=message.sender_id, + text=message.text.value, + created_at=message.created_at, + ) + + +class PageOut[ItemT](BaseModel): + items: list[ItemT] + next_cursor: str | None + + @classmethod + def of[SourceT](cls, page: Page[SourceT], view: Callable[[SourceT], ItemT]) -> Self: + return cls(items=[view(item) for item in page.items], next_cursor=page.next_cursor) diff --git a/src/messenger/messaging/infrastructure/__init__.py b/src/messenger/messaging/infrastructure/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/messaging/infrastructure/cursor.py b/src/messenger/messaging/infrastructure/cursor.py new file mode 100644 index 00000000..40044241 --- /dev/null +++ b/src/messenger/messaging/infrastructure/cursor.py @@ -0,0 +1,59 @@ +import hmac +from base64 import urlsafe_b64decode, urlsafe_b64encode +from datetime import UTC, datetime, timedelta +from hashlib import sha256 + +from messenger.messaging.domain.errors import InvalidPageRequest +from messenger.messaging.domain.keys import HistoryKey + +VERSION = "1" +SIGNATURE_BYTES = 12 +EPOCH = datetime(1970, 1, 1, tzinfo=UTC) +PARTS = 4 + + +def _encode_part(value: bytes) -> str: + return urlsafe_b64encode(value).decode("ascii").rstrip("=") + + +def _decode_part(value: str) -> bytes: + padding = "=" * (-len(value) % 4) + try: + return urlsafe_b64decode(value + padding) + except (ValueError, TypeError) as error: + raise InvalidPageRequest("параметр cursor повреждён") from error + + +class SignedCursorCodec: + __slots__ = ("_secret",) + + def __init__(self, secret: bytes) -> None: + self._secret = secret + + def encode(self, scope: str, key: HistoryKey) -> str: + moment, identifier = key + micros = (moment - EPOCH) // timedelta(microseconds=1) + body = f"{VERSION}.{micros}.{identifier:032x}" + return f"{body}.{_encode_part(self._sign(scope, body))}" + + def decode(self, scope: str, raw: str) -> HistoryKey: + parts = raw.split(".") + if len(parts) != PARTS or parts[0] != VERSION: + raise InvalidPageRequest("параметр cursor не распознан") + body = ".".join(parts[:3]) + if not hmac.compare_digest(self._sign(scope, body), _decode_part(parts[3])): + raise InvalidPageRequest("параметр cursor недействителен для этого запроса") + try: + micros = int(parts[1]) + identifier = int(parts[2], 16) + except ValueError as error: + raise InvalidPageRequest("параметр cursor повреждён") from error + try: + moment = EPOCH + timedelta(microseconds=micros) + except (OverflowError, ValueError) as error: + raise InvalidPageRequest("параметр cursor повреждён") from error + return (moment, identifier) + + def _sign(self, scope: str, body: str) -> bytes: + payload = f"{scope}|{body}".encode() + return hmac.new(self._secret, payload, sha256).digest()[:SIGNATURE_BYTES] diff --git a/src/messenger/messaging/infrastructure/postgres.py b/src/messenger/messaging/infrastructure/postgres.py new file mode 100644 index 00000000..7d23d27d --- /dev/null +++ b/src/messenger/messaging/infrastructure/postgres.py @@ -0,0 +1,201 @@ +from collections.abc import Sequence +from datetime import datetime +from uuid import UUID + +from asyncpg import ForeignKeyViolationError, Record + +from messenger.messaging.domain.errors import InvalidChatData +from messenger.messaging.domain.keys import HistoryKey +from messenger.messaging.domain.models import Chat, Message, Receipt +from messenger.messaging.domain.values import ChatTitle, MessageText +from messenger.shared.infrastructure.postgres import ( + Connection, + Database, + EventSource, + PostgresUnitOfWork, +) + +INSERT_CHAT = "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)" +INSERT_MEMBERS = """ +INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) +SELECT $1, member.user_id, member.position, $3 +FROM unnest($2::uuid[]) WITH ORDINALITY AS member (user_id, position) +""" +LOCK_CHAT = """ +SELECT c.id, c.title, c.created_at, c.last_message_at, + ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids +FROM chats c +WHERE c.id = $1 +FOR UPDATE +""" +RECEIPT = """ +SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at +FROM idempotency_keys k JOIN messages m ON m.id = k.message_id +WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4 +""" +APPEND_MESSAGE = """ +WITH message AS ( + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1, $2, $3, $4, $5) + RETURNING id, chat_id, sender_id, created_at +), receipt AS ( + INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at) + SELECT chat_id, sender_id, $6, $7, id, created_at FROM message + ON CONFLICT (chat_id, user_id, key) DO UPDATE + SET fingerprint = EXCLUDED.fingerprint, + message_id = EXCLUDED.message_id, + created_at = EXCLUDED.created_at +) +UPDATE chats SET last_message_at = message.created_at +FROM message +WHERE chats.id = message.chat_id +""" +CHAT_OF_MEMBER = """ +SELECT c.id, c.title, c.created_at, + ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids +FROM chat_members m JOIN chats c ON c.id = m.chat_id +WHERE m.chat_id = $1 AND m.user_id = $2 +""" +CHATS_FIRST = """ +SELECT c.id, c.title, c.created_at, + ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids +FROM chat_members m JOIN chats c ON c.id = m.chat_id +WHERE m.user_id = $1 +ORDER BY m.chat_created_at, m.chat_id +LIMIT $2 +""" +CHATS_AFTER = """ +SELECT c.id, c.title, c.created_at, + ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids +FROM chat_members m JOIN chats c ON c.id = m.chat_id +WHERE m.user_id = $1 AND (m.chat_created_at, m.chat_id) > ($2, $3) +ORDER BY m.chat_created_at, m.chat_id +LIMIT $4 +""" +HISTORY_FIRST = """ +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = $1 +ORDER BY created_at, id +LIMIT $2 +""" +HISTORY_AFTER = """ +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = $1 AND (created_at, id) > ($2, $3) +ORDER BY created_at, id +LIMIT $4 +""" + + +def chat_of(row: Record) -> Chat: + return Chat( + chat_id=row["id"], + title=ChatTitle(row["title"]), + member_ids=row["member_ids"], + created_at=row["created_at"], + last_message_at=row.get("last_message_at"), + ) + + +def message_of(row: Record) -> Message: + return Message( + id=row["id"], + chat_id=row["chat_id"], + sender_id=row["sender_id"], + text=MessageText(row["text"]), + created_at=row["created_at"], + ) + + +def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]: + return list(rows[:limit]), len(rows) > limit + + +class PostgresChatRepository: + __slots__ = ("_connection", "_seen") + + def __init__(self, connection: Connection, seen: list[EventSource]) -> None: + self._connection = connection + self._seen = seen + + async def add(self, chat: Chat) -> None: + await self._connection.execute(INSERT_CHAT, chat.id, chat.title.value, chat.created_at) + try: + await self._connection.execute( + INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at + ) + except ForeignKeyViolationError as error: + raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error + self._seen.append(chat) + + async def get(self, chat_id: UUID) -> Chat | None: + row = await self._connection.fetchrow(LOCK_CHAT, chat_id) + if row is None: + return None + chat = chat_of(row) + self._seen.append(chat) + return chat + + async def receipt( + self, chat_id: UUID, sender_id: UUID, key: str, since: datetime + ) -> Receipt | None: + row = await self._connection.fetchrow(RECEIPT, chat_id, sender_id, key, since) + return None if row is None else Receipt(key, row["fingerprint"], message_of(row)) + + async def append(self, receipt: Receipt) -> None: + message = receipt.message + await self._connection.execute( + APPEND_MESSAGE, + message.id, + message.chat_id, + message.sender_id, + message.text.value, + message.created_at, + receipt.key, + receipt.fingerprint, + ) + + +class PostgresMessagingUnitOfWork(PostgresUnitOfWork): + __slots__ = () + + @property + def chats(self) -> PostgresChatRepository: + return PostgresChatRepository(self.connection, self.seen) + + +class PostgresChatDirectory: + __slots__ = ("_database",) + + def __init__(self, database: Database) -> None: + self._database = database + + async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None: + async with self._database.connection() as connection: + row = await connection.fetchrow(CHAT_OF_MEMBER, chat_id, user_id) + return None if row is None else chat_of(row) + + async def chats_of( + self, user_id: UUID, *, after: HistoryKey | None, limit: int + ) -> tuple[list[Chat], bool]: + async with self._database.connection() as connection: + if after is None: + rows = await connection.fetch(CHATS_FIRST, user_id, limit + 1) + else: + rows = await connection.fetch( + CHATS_AFTER, user_id, after[0], UUID(int=after[1]), limit + 1 + ) + return page([chat_of(row) for row in rows], limit) + + async def history( + self, chat_id: UUID, *, after: HistoryKey | None, limit: int + ) -> tuple[list[Message], bool]: + async with self._database.connection() as connection: + if after is None: + rows = await connection.fetch(HISTORY_FIRST, chat_id, limit + 1) + else: + rows = await connection.fetch( + HISTORY_AFTER, chat_id, after[0], UUID(int=after[1]), limit + 1 + ) + return page([message_of(row) for row in rows], limit) diff --git a/src/messenger/migrate.py b/src/messenger/migrate.py new file mode 100644 index 00000000..27037f6d --- /dev/null +++ b/src/messenger/migrate.py @@ -0,0 +1,70 @@ +import asyncio +import hashlib +from importlib import resources + +import asyncpg + +from messenger.shared.config import PlatformSettings +from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger + +LOCK_KEY = 20_260_002 +JOURNAL = """ +CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + checksum text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT now() +) +""" + + +class MigrationChangedError(Exception): + pass + + +def migrations() -> list[tuple[str, str]]: + folder = resources.files("messenger") / "migrations" + found = (item for item in folder.iterdir() if item.name.endswith(".sql")) + return sorted((item.name.removesuffix(".sql"), item.read_text()) for item in found) + + +async def migrate(dsn: str) -> list[str]: + connection = await asyncpg.connect(dsn, timeout=10) + try: + await connection.execute("SELECT pg_advisory_lock($1)", LOCK_KEY) + await connection.execute(JOURNAL) + applied = dict(await connection.fetch("SELECT version, checksum FROM schema_migrations")) + done: list[str] = [] + for version, sql in migrations(): + checksum = hashlib.sha256(sql.encode()).hexdigest() + if version in applied: + if applied[version] != checksum: + raise MigrationChangedError(version) + continue + async with connection.transaction(): + await connection.execute(sql) + await connection.execute( + "INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)", + version, + checksum, + ) + done.append(version) + return done + finally: + await connection.close() + + +def main() -> None: + settings = PlatformSettings() + logger = StructlogLogger(level=settings.log_level, allowed_fields=PLATFORM_FIELDS | {"version"}) + try: + done = asyncio.run(migrate(settings.database_url.get_secret_value())) + except MigrationChangedError as error: + logger.error("migration.changed", version=str(error)) + raise SystemExit(1) from None + for version in done: + logger.info("migration.applied", version=version) + logger.info("migration.completed", reason="up to date" if not done else "applied") + + +if __name__ == "__main__": + main() diff --git a/src/messenger/migrations/0001_init.sql b/src/messenger/migrations/0001_init.sql new file mode 100644 index 00000000..d8ccac01 --- /dev/null +++ b/src/messenger/migrations/0001_init.sql @@ -0,0 +1,46 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL CONSTRAINT users_username_key UNIQUE + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%'), + created_at timestamptz NOT NULL +); + +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32), + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + CHECK (expires_at > created_at) +); + +CREATE INDEX sessions_user_idx ON sessions (user_id); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL, + last_message_at timestamptz +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + position smallint NOT NULL CHECK (position BETWEEN 1 AND 100), + chat_created_at timestamptz NOT NULL, + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_created_at, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL, + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id) +); + +CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); diff --git a/src/messenger/migrations/0002_idempotency_keys.sql b/src/messenger/migrations/0002_idempotency_keys.sql new file mode 100644 index 00000000..a556f0fd --- /dev/null +++ b/src/messenger/migrations/0002_idempotency_keys.sql @@ -0,0 +1,10 @@ +CREATE TABLE idempotency_keys ( + chat_id uuid NOT NULL, + user_id uuid NOT NULL, + key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32), + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL, + PRIMARY KEY (chat_id, user_id, key), + FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id) +); diff --git a/src/messenger/shared/__init__.py b/src/messenger/shared/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/shared/application/__init__.py b/src/messenger/shared/application/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/shared/application/commands.py b/src/messenger/shared/application/commands.py new file mode 100644 index 00000000..9eaa1e2e --- /dev/null +++ b/src/messenger/shared/application/commands.py @@ -0,0 +1,2 @@ +class Command: + pass diff --git a/src/messenger/shared/application/errors.py b/src/messenger/shared/application/errors.py new file mode 100644 index 00000000..dee87401 --- /dev/null +++ b/src/messenger/shared/application/errors.py @@ -0,0 +1,2 @@ +class Unavailable(Exception): + pass diff --git a/src/messenger/shared/application/messagebus.py b/src/messenger/shared/application/messagebus.py new file mode 100644 index 00000000..0ef69a42 --- /dev/null +++ b/src/messenger/shared/application/messagebus.py @@ -0,0 +1,123 @@ +import asyncio +from collections.abc import Awaitable, Callable, Mapping, Sequence +from contextlib import suppress +from typing import Any + +from messenger.shared.application.commands import Command +from messenger.shared.application.ports import EventPublisher, Logger, UnitOfWork +from messenger.shared.domain.events import DomainEvent + +type CommandHandler = Callable[[Any], Awaitable[Any]] +type EventHandler[EventT: DomainEvent] = Callable[[EventT], Awaitable[None]] + + +class CommandBus: + __slots__ = ("_handlers", "_publisher", "_uow") + + def __init__( + self, + handlers: Mapping[type[Command], CommandHandler], + uow: UnitOfWork, + publisher: EventPublisher, + ) -> None: + self._handlers = handlers + self._uow = uow + self._publisher = publisher + + async def execute(self, command: Command) -> Any: + handler = self._handlers.get(type(command)) + if handler is None: + raise LookupError(f"нет обработчика для команды {type(command).__name__}") + result = await handler(command) + events = self._uow.collect_new_events() + if events: + await self._publisher.publish(events) + return result + + +class EventBus: + __slots__ = ("_deferred", "_dropped", "_logger", "_projections", "_queue", "_worker") + + def __init__(self, logger: Logger, *, max_queue: int = 10_000) -> None: + self._logger = logger + self._queue: asyncio.Queue[DomainEvent] = asyncio.Queue(maxsize=max_queue) + self._projections: dict[type[DomainEvent], list[Any]] = {} + self._deferred: dict[type[DomainEvent], list[Any]] = {} + self._worker: asyncio.Task[None] | None = None + self._dropped = 0 + + def project[EventT: DomainEvent]( + self, event_type: type[EventT], handler: EventHandler[EventT] + ) -> None: + self._projections.setdefault(event_type, []).append(handler) + + def subscribe[EventT: DomainEvent]( + self, event_type: type[EventT], handler: EventHandler[EventT] + ) -> None: + self._deferred.setdefault(event_type, []).append(handler) + + async def emit(self, event: DomainEvent) -> bool: + await self._run(self._projections.get(type(event), []), event, "projection") + if not self._deferred.get(type(event)): + return True + try: + self._queue.put_nowait(event) + except asyncio.QueueFull: + self._dropped += 1 + self._logger.warning( + "event.dropped", event_name=event.name, dropped_total=self._dropped + ) + return False + return True + + @property + def dropped(self) -> int: + return self._dropped + + @property + def pending(self) -> int: + return self._queue.qsize() + + def start(self) -> None: + if self._worker is None: + self._worker = asyncio.create_task(self._drain()) + + async def stop(self) -> None: + if self._worker is None: + return + await self._queue.join() + self._worker.cancel() + with suppress(asyncio.CancelledError): + await self._worker + self._worker = None + + async def _drain(self) -> None: + while True: + event = await self._queue.get() + try: + await self._run(self._deferred.get(type(event), []), event, "subscriber") + finally: + self._queue.task_done() + + async def _run(self, handlers: Sequence[Any], event: DomainEvent, kind: str) -> None: + for handler in handlers: + try: + await handler(event) + except Exception as error: + self._logger.error( + "event.handler_failed", + event_name=event.name, + reason=kind, + error=type(error).__name__, + ) + + +class InMemoryEventPublisher: + __slots__ = ("_bus",) + + def __init__(self, bus: EventBus) -> None: + self._bus = bus + + async def publish(self, events: Sequence[DomainEvent]) -> None: + for event in events: + await self._bus.emit(event) diff --git a/src/messenger/shared/application/ports.py b/src/messenger/shared/application/ports.py new file mode 100644 index 00000000..16586867 --- /dev/null +++ b/src/messenger/shared/application/ports.py @@ -0,0 +1,42 @@ +from collections.abc import Sequence +from contextlib import AbstractAsyncContextManager +from datetime import datetime +from typing import Any, Protocol, runtime_checkable +from uuid import UUID + +from messenger.shared.domain.events import DomainEvent + + +@runtime_checkable +class Clock(Protocol): + def now(self) -> datetime: ... + + +@runtime_checkable +class IdGenerator(Protocol): + def new_id(self) -> UUID: ... + + +@runtime_checkable +class Logger(Protocol): + def info(self, event: str, /, **fields: Any) -> None: ... + + def warning(self, event: str, /, **fields: Any) -> None: ... + + def error(self, event: str, /, **fields: Any) -> None: ... + + +@runtime_checkable +class UnitOfWork(Protocol): + def transaction(self) -> AbstractAsyncContextManager[None]: ... + + async def commit(self) -> None: ... + + def record(self, event: DomainEvent) -> None: ... + + def collect_new_events(self) -> list[DomainEvent]: ... + + +@runtime_checkable +class EventPublisher(Protocol): + async def publish(self, events: Sequence[DomainEvent]) -> None: ... diff --git a/src/messenger/shared/config.py b/src/messenger/shared/config.py new file mode 100644 index 00000000..8eff8736 --- /dev/null +++ b/src/messenger/shared/config.py @@ -0,0 +1,49 @@ +import os +import socket +from pathlib import Path +from typing import Any + +from pydantic import Field, SecretStr +from pydantic.fields import FieldInfo +from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict + +CONFIG = SettingsConfigDict(extra="ignore", frozen=True) + + +class FileVariables(PydanticBaseSettingsSource): + def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]: + path = os.environ.get(f"{field_name.upper()}_FILE") + return (Path(path).read_text().strip() if path else None), field_name, False + + def __call__(self) -> dict[str, Any]: + found = { + name: self.get_field_value(field, name)[0] + for name, field in self.settings_cls.model_fields.items() + } + return {name: value for name, value in found.items() if value is not None} + + +class Settings(BaseSettings): + model_config = CONFIG + + @classmethod + def settings_customise_sources( + cls, + settings_cls: type[BaseSettings], + init_settings: PydanticBaseSettingsSource, + env_settings: PydanticBaseSettingsSource, + dotenv_settings: PydanticBaseSettingsSource, + file_secret_settings: PydanticBaseSettingsSource, + ) -> tuple[PydanticBaseSettingsSource, ...]: + return init_settings, env_settings, FileVariables(settings_cls) + + +class PlatformSettings(Settings): + log_level: str = "INFO" + instance_id: str = Field(default_factory=socket.gethostname, min_length=1) + event_queue_max: int = Field(default=10_000, ge=16) + database_url: SecretStr + db_pool_max_size: int = Field(default=8, ge=1, le=50) + db_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30) + db_acquire_timeout_seconds: float = Field(default=1.0, gt=0, le=30) + db_command_timeout_seconds: float = Field(default=2.0, gt=0, le=60) diff --git a/src/messenger/shared/domain/__init__.py b/src/messenger/shared/domain/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/shared/domain/errors.py b/src/messenger/shared/domain/errors.py new file mode 100644 index 00000000..f7d33023 --- /dev/null +++ b/src/messenger/shared/domain/errors.py @@ -0,0 +1,4 @@ +class DomainError(Exception): + def __init__(self, detail: str) -> None: + super().__init__(detail) + self.detail = detail diff --git a/src/messenger/shared/domain/events.py b/src/messenger/shared/domain/events.py new file mode 100644 index 00000000..a295e356 --- /dev/null +++ b/src/messenger/shared/domain/events.py @@ -0,0 +1,6 @@ +from dataclasses import dataclass, field + + +@dataclass(frozen=True, slots=True) +class DomainEvent: + name: str = field(init=False, default="domain.event") diff --git a/src/messenger/shared/entrypoints/__init__.py b/src/messenger/shared/entrypoints/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/shared/entrypoints/actor.py b/src/messenger/shared/entrypoints/actor.py new file mode 100644 index 00000000..0a81d11b --- /dev/null +++ b/src/messenger/shared/entrypoints/actor.py @@ -0,0 +1,16 @@ +from typing import Annotated +from uuid import UUID + +from fastapi import Depends, Request + +from messenger.shared.entrypoints.errors import Unauthenticated + + +async def current_actor(request: Request) -> UUID: + actor = getattr(request.state, "actor", None) + if not isinstance(actor, UUID): + raise Unauthenticated("заголовок идентификации обязателен и должен быть действительным") + return actor + + +type Actor = Annotated[UUID, Depends(current_actor)] diff --git a/src/messenger/shared/entrypoints/config.py b/src/messenger/shared/entrypoints/config.py new file mode 100644 index 00000000..c3e77663 --- /dev/null +++ b/src/messenger/shared/entrypoints/config.py @@ -0,0 +1,10 @@ +from pydantic import Field + +from messenger.shared.config import Settings + + +class TransportSettings(Settings): + docs: bool = False + max_body_bytes: int = Field(default=1_048_576, ge=4_096) + request_timeout_seconds: float = Field(default=8.0, gt=0, le=300) + shutdown_timeout_seconds: int = Field(default=5, ge=1, le=10) diff --git a/src/messenger/shared/entrypoints/errors.py b/src/messenger/shared/entrypoints/errors.py new file mode 100644 index 00000000..e32c6e72 --- /dev/null +++ b/src/messenger/shared/entrypoints/errors.py @@ -0,0 +1,136 @@ +from collections.abc import Callable, Mapping + +from fastapi import FastAPI, Request, Response, status +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException + +from messenger.shared.application.errors import Unavailable +from messenger.shared.application.ports import Logger +from messenger.shared.domain.errors import DomainError +from messenger.shared.entrypoints.schemas import ErrorEnvelope + +REQUEST_ID_HEADER = "X-Request-Id" +INSTANCE_ID_HEADER = "X-Instance-Id" + +type ErrorCodes = Mapping[type[DomainError], tuple[str, int]] +type Challenge = Callable[[str], str] + +MESSAGES = { + "invalid_request": "Запрос не соответствует контракту", + "unauthorized": "Аутентификация не предоставлена или недействительна", + "not_found": "Объект не найден", + "conflict": "Конфликт состояния", + "payload_too_large": "Тело запроса больше допустимого", + "unsupported_media_type": "Неподдерживаемый тип содержимого", + "rate_limited": "Слишком много запросов", + "unavailable": "Сервис временно недоступен", + "internal_error": "Внутренняя ошибка", +} + +STATUS_CODES = { + status.HTTP_400_BAD_REQUEST: "invalid_request", + status.HTTP_401_UNAUTHORIZED: "unauthorized", + status.HTTP_404_NOT_FOUND: "not_found", + status.HTTP_409_CONFLICT: "conflict", + status.HTTP_413_CONTENT_TOO_LARGE: "payload_too_large", + status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: "unsupported_media_type", + status.HTTP_422_UNPROCESSABLE_CONTENT: "invalid_request", + status.HTTP_429_TOO_MANY_REQUESTS: "rate_limited", + status.HTTP_503_SERVICE_UNAVAILABLE: "unavailable", +} + + +class Unauthenticated(Exception): + pass + + +def classify(error: DomainError, codes: ErrorCodes) -> tuple[str, int]: + for kind in type(error).__mro__: + known = codes.get(kind) # type: ignore[arg-type] + if known is not None: + return known + return "internal_error", status.HTTP_500_INTERNAL_SERVER_ERROR + + +def route_of(request: Request) -> str: + route = request.scope.get("route") + return getattr(route, "path", request.url.path) + + +def install( + app: FastAPI, logger: Logger, codes: ErrorCodes, challenge: Challenge, instance: str +) -> None: + def error_response(request: Request, code: str, detail: str, http_status: int) -> Response: + request_id = getattr(request.state, "request_id", "") or "unknown" + headers = {REQUEST_ID_HEADER: request_id, INSTANCE_ID_HEADER: instance} + if http_status == status.HTTP_401_UNAUTHORIZED: + headers["WWW-Authenticate"] = challenge(request.url.path) + return Response( + status_code=http_status, + content=ErrorEnvelope.of(code, detail, request_id).model_dump_json(), + media_type="application/json", + headers=headers, + ) + + @app.exception_handler(DomainError) + async def _domain(request: Request, exc: DomainError) -> Response: + code, http_status = classify(exc, codes) + return error_response(request, code, exc.detail, http_status) + + @app.exception_handler(Unavailable) + async def _unavailable(request: Request, exc: Unavailable) -> Response: + logger.warning( + "dependency.unavailable", + route=route_of(request), + error=type(exc.__cause__ or exc).__name__, + request_id=getattr(request.state, "request_id", None), + ) + return error_response( + request, + "unavailable", + MESSAGES["unavailable"], + status.HTTP_503_SERVICE_UNAVAILABLE, + ) + + @app.exception_handler(Unauthenticated) + async def _unauthenticated(request: Request, _exc: Unauthenticated) -> Response: + return error_response( + request, + "unauthorized", + MESSAGES["unauthorized"], + status.HTTP_401_UNAUTHORIZED, + ) + + @app.exception_handler(RequestValidationError) + async def _validation(request: Request, _exc: RequestValidationError) -> Response: + return error_response( + request, + "invalid_request", + MESSAGES["invalid_request"], + status.HTTP_400_BAD_REQUEST, + ) + + @app.exception_handler(HTTPException) + async def _http(request: Request, exc: HTTPException) -> Response: + http_status = exc.status_code + if http_status == status.HTTP_405_METHOD_NOT_ALLOWED: + http_status = status.HTTP_404_NOT_FOUND + code = STATUS_CODES.get(http_status, "internal_error") + return error_response( + request, code, MESSAGES.get(code, MESSAGES["internal_error"]), http_status + ) + + @app.exception_handler(Exception) + async def _unexpected(request: Request, exc: Exception) -> Response: + logger.error( + "request.failed", + route=route_of(request), + error=type(exc).__name__, + request_id=getattr(request.state, "request_id", None), + ) + return error_response( + request, + "internal_error", + MESSAGES["internal_error"], + status.HTTP_500_INTERNAL_SERVER_ERROR, + ) diff --git a/src/messenger/shared/entrypoints/health.py b/src/messenger/shared/entrypoints/health.py new file mode 100644 index 00000000..b2da72c9 --- /dev/null +++ b/src/messenger/shared/entrypoints/health.py @@ -0,0 +1,25 @@ +from threading import Event + +from dishka.integrations.fastapi import FromDishka, inject +from fastapi import APIRouter + +from messenger.shared.application.errors import Unavailable +from messenger.shared.entrypoints.schemas import HealthOut +from messenger.shared.infrastructure.postgres import Database + +router = APIRouter(tags=["health"]) +DRAINING = Event() + + +@router.get("/health/live") +async def live() -> HealthOut: + return HealthOut() + + +@router.get("/health/ready") +@inject +async def ready(database: FromDishka[Database]) -> HealthOut: + if DRAINING.is_set(): + raise Unavailable("Реплика выходит из ротации") + await database.ping() + return HealthOut() diff --git a/src/messenger/shared/entrypoints/ioc.py b/src/messenger/shared/entrypoints/ioc.py new file mode 100644 index 00000000..2c99ab1b --- /dev/null +++ b/src/messenger/shared/entrypoints/ioc.py @@ -0,0 +1,54 @@ +from collections.abc import AsyncIterator + +from dishka import Provider, Scope, provide + +from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher +from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger +from messenger.shared.config import PlatformSettings +from messenger.shared.infrastructure.clock import MonotonicUtcClock +from messenger.shared.infrastructure.ids import Uuid7Generator +from messenger.shared.infrastructure.postgres import Database + + +class PlatformProvider(Provider): + def __init__(self, settings: PlatformSettings, logger: Logger) -> None: + super().__init__() + self._settings = settings + self._logger = logger + + @provide(scope=Scope.APP) + def settings(self) -> PlatformSettings: + return self._settings + + @provide(scope=Scope.APP) + def logger(self) -> Logger: + return self._logger + + @provide(scope=Scope.APP) + def clock(self) -> Clock: + return MonotonicUtcClock() + + @provide(scope=Scope.APP) + def ids(self) -> IdGenerator: + return Uuid7Generator() + + @provide(scope=Scope.APP) + async def database(self, settings: PlatformSettings) -> AsyncIterator[Database]: + database = Database( + settings.database_url.get_secret_value(), + max_size=settings.db_pool_max_size, + connect_timeout=settings.db_connect_timeout_seconds, + acquire_timeout=settings.db_acquire_timeout_seconds, + command_timeout=settings.db_command_timeout_seconds, + ) + await database.open() + yield database + await database.close() + + @provide(scope=Scope.APP) + def event_bus(self, logger: Logger, settings: PlatformSettings) -> EventBus: + return EventBus(logger, max_queue=settings.event_queue_max) + + @provide(scope=Scope.APP) + def publisher(self, bus: EventBus) -> EventPublisher: + return InMemoryEventPublisher(bus) diff --git a/src/messenger/shared/entrypoints/pipeline.py b/src/messenger/shared/entrypoints/pipeline.py new file mode 100644 index 00000000..e88c995d --- /dev/null +++ b/src/messenger/shared/entrypoints/pipeline.py @@ -0,0 +1,165 @@ +import asyncio +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from uuid import uuid4 + +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +from messenger.shared.application.errors import Unavailable +from messenger.shared.application.ports import Logger +from messenger.shared.entrypoints.errors import INSTANCE_ID_HEADER, MESSAGES, REQUEST_ID_HEADER +from messenger.shared.entrypoints.schemas import ErrorEnvelope + +type Headers = tuple[tuple[str, str], ...] + + +@dataclass(frozen=True, slots=True) +class Rejection: + status: int + code: str + headers: Headers = () + + +type Guard = Callable[[Scope], Awaitable[Rejection | None]] + +HEADER_BYTES = REQUEST_ID_HEADER.lower().encode() +INSTANCE_BYTES = INSTANCE_ID_HEADER.lower().encode() +STAMPED = frozenset({HEADER_BYTES, INSTANCE_BYTES}) +MAX_REQUEST_ID = 200 + + +def header(scope: Scope, name: bytes) -> str: + for key, value in scope["headers"]: + if key == name: + return value.decode("latin-1").strip() + return "" + + +async def send_error( + send: Send, status: int, code: str, request_id: str, headers: Headers = () +) -> None: + body = ErrorEnvelope.of(code, MESSAGES[code], request_id).model_dump_json().encode() + await send( + { + "type": "http.response.start", + "status": status, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode()), + (HEADER_BYTES, request_id.encode("latin-1", "replace")), + *((name.encode(), value.encode("latin-1")) for name, value in headers), + ], + } + ) + await send({"type": "http.response.body", "body": body}) + + +class RequestPipeline: + __slots__ = ("_app", "_guard", "_instance", "_logger", "_max_bytes", "_timeout") + + def __init__( + self, + app: ASGIApp, + logger: Logger, + max_bytes: int, + timeout: float, + guard: Guard, + instance: str, + ) -> None: + self._app = app + self._logger = logger + self._max_bytes = max_bytes + self._timeout = timeout + self._guard = guard + self._instance = instance.encode() + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self._app(scope, receive, send) + return + + incoming = header(scope, HEADER_BYTES) + request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex + state = scope.setdefault("state", {}) + state["request_id"] = request_id + state["actor"] = None + started = time.perf_counter() + status_holder = [500] + answered = [False] + + async def wrapped_send(message: Message) -> None: + if message["type"] == "http.response.start": + status_holder[0] = message["status"] + answered[0] = True + headers = [ + (key, value) + for key, value in message.get("headers", []) + if key.lower() not in STAMPED + ] + headers.append((HEADER_BYTES, request_id.encode("latin-1", "replace"))) + headers.append((INSTANCE_BYTES, self._instance)) + message = {**message, "headers": headers} + await send(message) + + declared = header(scope, b"content-length") + if declared.isdigit() and int(declared) > self._max_bytes: + await send_error(wrapped_send, 413, "payload_too_large", request_id) + self._log(scope, status_holder[0], request_id, started) + return + + rejection: Rejection | None = None + try: + async with asyncio.timeout(self._timeout): + rejection = await self._guard(scope) + if rejection is None: + await self._app(scope, receive, wrapped_send) + except Unavailable as error: + self._logger.warning( + "dependency.unavailable", + route=self._route(scope), + error=type(error.__cause__ or error).__name__, + request_id=request_id, + ) + rejection = Rejection(503, "unavailable") + except TimeoutError: + self._logger.warning( + "request.timeout", + method=scope["method"], + route=self._route(scope), + request_id=request_id, + limit=self._timeout, + duration_ms=round((time.perf_counter() - started) * 1000, 3), + ) + if not answered[0]: + await send_error(wrapped_send, 503, "unavailable", request_id) + self._log(scope, status_holder[0], request_id, started) + return + except Exception: + self._logger.error( + "request.unhandled", + method=scope["method"], + route=self._route(scope), + request_id=request_id, + duration_ms=round((time.perf_counter() - started) * 1000, 3), + ) + raise + if rejection is not None and not answered[0]: + await send_error( + wrapped_send, rejection.status, rejection.code, request_id, rejection.headers + ) + self._log(scope, status_holder[0], request_id, started) + + def _route(self, scope: Scope) -> str: + route = scope.get("route") + return getattr(route, "path", scope["path"]) + + def _log(self, scope: Scope, status: int, request_id: str, started: float) -> None: + self._logger.info( + "request.handled", + method=scope["method"], + route=self._route(scope), + status=status, + request_id=request_id, + duration_ms=round((time.perf_counter() - started) * 1000, 3), + ) diff --git a/src/messenger/shared/entrypoints/schemas.py b/src/messenger/shared/entrypoints/schemas.py new file mode 100644 index 00000000..f27d12b5 --- /dev/null +++ b/src/messenger/shared/entrypoints/schemas.py @@ -0,0 +1,21 @@ +from typing import Literal + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + code: str + message: str + request_id: str + + +class ErrorEnvelope(BaseModel): + error: ErrorDetail + + @classmethod + def of(cls, code: str, message: str, request_id: str) -> ErrorEnvelope: + return cls(error=ErrorDetail(code=code, message=message, request_id=request_id)) + + +class HealthOut(BaseModel): + status: Literal["ok"] = "ok" diff --git a/src/messenger/shared/infrastructure/__init__.py b/src/messenger/shared/infrastructure/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/messenger/shared/infrastructure/clock.py b/src/messenger/shared/infrastructure/clock.py new file mode 100644 index 00000000..808a3bf7 --- /dev/null +++ b/src/messenger/shared/infrastructure/clock.py @@ -0,0 +1,17 @@ +from datetime import UTC, datetime, timedelta + +TICK = timedelta(microseconds=1) + + +class MonotonicUtcClock: + __slots__ = ("_last",) + + def __init__(self) -> None: + self._last: datetime | None = None + + def now(self) -> datetime: + current = datetime.now(UTC) + if self._last is not None and current <= self._last: + current = self._last + TICK + self._last = current + return current diff --git a/src/messenger/shared/infrastructure/ids.py b/src/messenger/shared/infrastructure/ids.py new file mode 100644 index 00000000..95998244 --- /dev/null +++ b/src/messenger/shared/infrastructure/ids.py @@ -0,0 +1,8 @@ +from uuid import UUID, uuid7 + + +class Uuid7Generator: + __slots__ = () + + def new_id(self) -> UUID: + return uuid7() diff --git a/src/messenger/shared/infrastructure/logging.py b/src/messenger/shared/infrastructure/logging.py new file mode 100644 index 00000000..a3936546 --- /dev/null +++ b/src/messenger/shared/infrastructure/logging.py @@ -0,0 +1,113 @@ +import logging +import sys +from typing import Any + +import orjson +import structlog +from structlog.typing import EventDict, Processor, WrappedLogger + +PLATFORM_FIELDS = frozenset( + { + "method", + "route", + "status", + "duration_ms", + "request_id", + "event_name", + "error", + "reason", + "limit", + } +) + + +def render(obj: object, **_kwargs: object) -> str: + return orjson.dumps(obj).decode() + + +RESERVED = frozenset({"event", "level", "ts", "logger"}) + +FOREIGN_LOGGERS = ( + "uvicorn", + "uvicorn.error", + "gunicorn", + "gunicorn.error", + "asyncio", +) + +SILENCED_LOGGERS = ("uvicorn.access", "gunicorn.access") + + +def field_filter(allowed: frozenset[str]) -> Processor: + def drop_unlisted_fields( + _logger: WrappedLogger, _method: str, event_dict: EventDict + ) -> EventDict: + return { + key: value + for key, value in event_dict.items() + if (key in RESERVED or key in allowed) and value is not None + } + + return drop_unlisted_fields + + +def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIELDS) -> None: + shared = [ + structlog.contextvars.merge_contextvars, + structlog.processors.add_log_level, + structlog.processors.TimeStamper(fmt="iso", utc=True, key="ts"), + ] + structlog.configure( + processors=[*shared, structlog.stdlib.ProcessorFormatter.wrap_for_formatter], + logger_factory=structlog.stdlib.LoggerFactory(), + wrapper_class=structlog.stdlib.BoundLogger, + cache_logger_on_first_use=False, + ) + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter( + structlog.stdlib.ProcessorFormatter( + foreign_pre_chain=shared, + processors=[ + structlog.stdlib.ProcessorFormatter.remove_processors_meta, + field_filter(allowed_fields), + structlog.processors.JSONRenderer(serializer=render), + ], + ) + ) + root = logging.getLogger() + for existing in list(root.handlers): + root.removeHandler(existing) + root.addHandler(handler) + root.setLevel(level.upper()) + for name in FOREIGN_LOGGERS: + foreign = logging.getLogger(name) + for existing in list(foreign.handlers): + foreign.removeHandler(existing) + foreign.propagate = True + for name in SILENCED_LOGGERS: + silenced = logging.getLogger(name) + for existing in list(silenced.handlers): + silenced.removeHandler(existing) + silenced.propagate = False + + +class StructlogLogger: + __slots__ = ("_logger",) + + def __init__( + self, + name: str = "messenger", + level: str = "INFO", + allowed_fields: frozenset[str] = PLATFORM_FIELDS, + ) -> None: + configure(level, allowed_fields) + self._logger = structlog.get_logger(name) + + def info(self, event: str, /, **fields: Any) -> None: + self._logger.info(event, **fields) + + def warning(self, event: str, /, **fields: Any) -> None: + self._logger.warning(event, **fields) + + def error(self, event: str, /, **fields: Any) -> None: + self._logger.error(event, **fields) diff --git a/src/messenger/shared/infrastructure/postgres.py b/src/messenger/shared/infrastructure/postgres.py new file mode 100644 index 00000000..4cfebcfb --- /dev/null +++ b/src/messenger/shared/infrastructure/postgres.py @@ -0,0 +1,118 @@ +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any, Protocol + +import asyncpg + +from messenger.shared.application.errors import Unavailable +from messenger.shared.domain.events import DomainEvent + +FAILURES = ( + OSError, + asyncpg.InterfaceError, + asyncpg.PostgresConnectionError, + asyncpg.exceptions.OperatorInterventionError, + asyncpg.exceptions.InsufficientResourcesError, + asyncpg.exceptions.LockNotAvailableError, +) + +PING_TIMEOUT_SECONDS = 0.4 + +type Connection = asyncpg.Connection + + +class EventSource(Protocol): + def collect_events(self) -> list[DomainEvent]: ... + + +class Database: + __slots__ = ("_acquire_timeout", "_pool") + + def __init__( + self, + dsn: str, + *, + max_size: int, + connect_timeout: float, + acquire_timeout: float, + command_timeout: float, + ) -> None: + self._acquire_timeout = acquire_timeout + self._pool = asyncpg.create_pool( + dsn, + min_size=0, + max_size=max_size, + timeout=connect_timeout, + command_timeout=command_timeout, + max_inactive_connection_lifetime=60, + server_settings={ + "statement_timeout": str(int(command_timeout * 1000)), + "lock_timeout": str(int(command_timeout * 1000)), + "idle_in_transaction_session_timeout": "10000", + }, + ) + + async def open(self) -> None: + await self._pool + + async def close(self) -> None: + await self._pool.close() + + @asynccontextmanager + async def connection(self, wait: float | None = None) -> AsyncIterator[Connection]: + try: + async with self._pool.acquire(timeout=wait or self._acquire_timeout) as connection: + yield connection + except FAILURES as error: + raise Unavailable("PostgreSQL недоступен") from error + + async def ping(self) -> None: + async with self.connection(PING_TIMEOUT_SECONDS) as connection: + await connection.fetchval("SELECT 1", timeout=PING_TIMEOUT_SECONDS) + + +class PostgresUnitOfWork: + __slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen") + + def __init__(self, database: Database) -> None: + self._database = database + self._connection: Connection | None = None + self._transaction: Any = None + self._committed = False + self._events: list[DomainEvent] = [] + self.seen: list[EventSource] = [] + + @property + def connection(self) -> Connection: + if self._connection is None: + raise RuntimeError("репозиторий используется вне транзакции") + return self._connection + + @asynccontextmanager + async def transaction(self) -> AsyncIterator[None]: + async with self._database.connection() as connection: + self._connection = connection + self._transaction = connection.transaction() + await self._transaction.start() + self._committed = False + try: + yield + finally: + if not self._committed: + self._events.clear() + await self._transaction.rollback() + self.seen.clear() + self._connection = None + + async def commit(self) -> None: + await self._transaction.commit() + self._committed = True + for source in self.seen: + self._events.extend(source.collect_events()) + + def record(self, event: DomainEvent) -> None: + self._events.append(event) + + def collect_new_events(self) -> list[DomainEvent]: + events, self._events = self._events, [] + return events diff --git a/student-tests/api/test_access.py b/student-tests/api/test_access.py new file mode 100644 index 00000000..8a623623 --- /dev/null +++ b/student-tests/api/test_access.py @@ -0,0 +1,84 @@ +from uuid import uuid4 + +from httpx import AsyncClient + +from conftest import actor, keyed, make_chat, register + + +async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + eve = await register(client, "eve") + chat = await make_chat(client, alice, bob) + response = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve)) + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" + + +async def test_unknown_chat_is_indistinguishable_from_foreign(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + foreign = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve)) + missing = await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(eve)) + assert foreign.status_code == missing.status_code == 404 + assert foreign.json()["error"]["code"] == missing.json()["error"]["code"] + assert foreign.json()["error"]["message"] == missing.json()["error"]["message"] + + +async def test_outsider_cannot_write(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "чужое"}, + headers=keyed(eve), + ) + assert response.status_code == 404 + history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice)) + assert history.json()["items"] == [] + + +async def test_outsider_cannot_read_history(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve)) + assert response.status_code == 404 + + +async def test_access_checked_before_body(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": ""}, + headers=keyed(eve), + ) + assert response.status_code == 404 + + +async def test_chat_list_hides_foreign_chats(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + eve = await register(client, "eve") + chat = await make_chat(client, alice, bob) + for member in (alice, bob): + listed = await client.get("/api/v1/chats?limit=100", headers=actor(member)) + assert any(item["id"] == chat["id"] for item in listed.json()["items"]) + hidden = await client.get("/api/v1/chats?limit=100", headers=actor(eve)) + assert hidden.json()["items"] == [] + + +async def test_403_is_never_used(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + paths = [ + f"/api/v1/chats/{chat['id']}", + f"/api/v1/chats/{chat['id']}/messages", + ] + for path in paths: + assert (await client.get(path, headers=actor(eve))).status_code != 403 diff --git a/student-tests/api/test_bounded_contexts.py b/student-tests/api/test_bounded_contexts.py new file mode 100644 index 00000000..63d4bed2 --- /dev/null +++ b/student-tests/api/test_bounded_contexts.py @@ -0,0 +1,242 @@ +import ast +import re +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[2] / "src" / "messenger" +IDENTITY = "messenger.identity" +MESSAGING = "messenger.messaging" + + +def imports_of(path: Path) -> list[str]: + tree = ast.parse(path.read_text(), filename=str(path)) + found: list[str] = [] + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module: + found.append(node.module) + elif isinstance(node, ast.Import): + found.extend(alias.name for alias in node.names) + return found + + +def modules_under(*parts: str) -> list[Path]: + root = SOURCE.joinpath(*parts) + return [path for path in root.rglob("*.py") if path.name != "__init__.py"] + + +def test_identity_does_not_know_about_messaging() -> None: + offenders = { + str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(MESSAGING)] + for path in modules_under("identity") + } + assert not {k: v for k, v in offenders.items() if v} + + +def test_messaging_touches_identity_only_through_events() -> None: + allowed = f"{IDENTITY}.domain.events" + offenders: dict[str, list[str]] = {} + for path in modules_under("messaging"): + borrowed = [ + module + for module in imports_of(path) + if module.startswith(IDENTITY) and module != allowed + ] + if borrowed: + offenders[str(path.relative_to(SOURCE))] = borrowed + assert not offenders + + +def test_domains_do_not_import_infrastructure() -> None: + offenders: dict[str, list[str]] = {} + for zone in ("identity", "messaging", "shared"): + for layer in ("domain", "application"): + for path in modules_under(zone, layer): + borrowed = [m for m in imports_of(path) if ".infrastructure" in m] + if borrowed: + offenders[str(path.relative_to(SOURCE))] = borrowed + assert not offenders + + +def test_core_layers_do_not_import_pydantic() -> None: + offenders: dict[str, list[str]] = {} + for zone in ("identity", "messaging", "shared"): + for layer in ("domain", "application"): + for path in modules_under(zone, layer): + borrowed = [m for m in imports_of(path) if m.split(".")[0] == "pydantic"] + if borrowed: + offenders[str(path.relative_to(SOURCE))] = borrowed + assert not offenders, "схемы pydantic живут на границе: в entrypoints/ и config.py" + + +def test_shared_knows_nothing_about_zones() -> None: + offenders: dict[str, list[str]] = {} + for path in modules_under("shared"): + borrowed = [ + module + for module in imports_of(path) + if module.startswith(IDENTITY) or module.startswith(MESSAGING) + ] + if borrowed: + offenders[str(path.relative_to(SOURCE))] = borrowed + assert not offenders + + +TRANSPORT = ("fastapi", "starlette", "uvicorn", "gunicorn") + + +def test_shared_core_is_free_of_transport() -> None: + offenders: dict[str, list[str]] = {} + for layer in ("domain", "application", "infrastructure"): + for path in modules_under("shared", layer): + borrowed = [module for module in imports_of(path) if module.split(".")[0] in TRANSPORT] + if borrowed: + offenders[str(path.relative_to(SOURCE))] = borrowed + assert not offenders, "ядро shared обязано жить без веб-фреймворка" + + +def test_shared_core_holds_only_platform() -> None: + names = { + path.name + for layer in ("domain", "application", "infrastructure") + for path in modules_under("shared", layer) + } + assert names == { + "errors.py", + "events.py", + "commands.py", + "messagebus.py", + "ports.py", + "clock.py", + "ids.py", + "logging.py", + "postgres.py", + } + + +def test_shared_entrypoints_hold_only_transport() -> None: + names = {path.name for path in modules_under("shared", "entrypoints")} + assert names == { + "actor.py", + "config.py", + "errors.py", + "health.py", + "ioc.py", + "pipeline.py", + "schemas.py", + } + + +def test_every_zone_owns_its_errors_events_and_commands() -> None: + for zone in ("identity", "messaging"): + assert (SOURCE / zone / "domain" / "errors.py").is_file() + assert (SOURCE / zone / "domain" / "events.py").is_file() + assert (SOURCE / zone / "application" / "commands.py").is_file() + + +def test_every_zone_owns_its_http_layer() -> None: + for zone in ("identity", "messaging"): + for part in ("http.py", "ioc.py", "errors.py", "journal.py"): + assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}" + + +def test_only_main_knows_both_zones() -> None: + offenders: dict[str, list[str]] = {} + for path in SOURCE.rglob("*.py"): + relative = path.relative_to(SOURCE) + if path.name in {"__init__.py", "main.py"} or relative.parts[0] in { + "identity", + "messaging", + }: + continue + borrowed = [ + module + for module in imports_of(path) + if module.startswith(IDENTITY) or module.startswith(MESSAGING) + ] + if borrowed: + offenders[str(relative)] = borrowed + assert not offenders + + +def test_application_has_no_separate_entrypoints_root() -> None: + assert not (SOURCE / "entrypoints").exists() + assert (SOURCE / "main.py").is_file() + + +ZONE_WORDS = ( + "username", + "display_name", + "chat", + "member", + "history", + "cursor", + "sender", + "message_id", + "message_text", +) + + +def test_shared_source_mentions_no_domain_vocabulary() -> None: + offenders: dict[str, list[str]] = {} + for path in modules_under("shared"): + source = path.read_text().lower() + hits = sorted({word for word in ZONE_WORDS if word in source}) + if hits: + offenders[str(path.relative_to(SOURCE))] = hits + assert not offenders + + +def test_shared_declares_no_concrete_commands_or_events() -> None: + for path in modules_under("shared"): + tree = ast.parse(path.read_text(), filename=str(path)) + declared = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)] + concrete = [ + name + for name in declared + if name not in {"Command", "DomainEvent", "DomainError"} + and (name.endswith("Event") or name in {"RegisterUser", "CreateChat", "PostMessage"}) + ] + assert not concrete, f"{path.name}: {concrete}" + + +def test_shared_has_no_test_doubles() -> None: + for path in modules_under("shared"): + source = path.read_text() + for marker in ("Frozen", "Fake", "Stub", "Null", "Dummy"): + assert marker not in source, f"{path.name} содержит подделку {marker}" + + +def test_zone_errors_do_not_leak_transport_codes() -> None: + for zone in ("identity", "messaging", "shared"): + source = (SOURCE / zone / "domain" / "errors.py").read_text() + assert "http_status" not in source + assert "invalid_request" not in source + assert "404" not in source + + +IDENTITY_TABLES = ("users", "sessions") +MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys") + + +def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]: + words: set[str] = set() + for path in modules_under(zone): + tree = ast.parse(path.read_text(), filename=str(path)) + for node in ast.walk(tree): + if isinstance(node, ast.Constant) and isinstance(node.value, str): + words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value)) + return words & set(tables) + + +def test_sql_of_each_zone_reads_only_its_tables() -> None: + assert sql_tables("messaging", IDENTITY_TABLES) == set() + assert sql_tables("identity", MESSAGING_TABLES) == set() + assert sql_tables("messaging", MESSAGING_TABLES) == set(MESSAGING_TABLES) + assert sql_tables("identity", IDENTITY_TABLES) == set(IDENTITY_TABLES) + + +def test_messaging_does_not_import_identity_at_all() -> None: + borrowed = { + str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(IDENTITY)] + for path in modules_under("messaging") + } + assert not {key: value for key, value in borrowed.items() if value} diff --git a/student-tests/api/test_cache.py b/student-tests/api/test_cache.py new file mode 100644 index 00000000..63f845d1 --- /dev/null +++ b/student-tests/api/test_cache.py @@ -0,0 +1,118 @@ +import asyncio +import time +from datetime import datetime +from hashlib import sha256 + +from redis.asyncio import Redis + +from conftest import actor, bearer, register, resolve, running_app, scalar +from messenger.identity.application.ports import SessionDirectory +from messenger.identity.domain.models import Session +from messenger.identity.infrastructure.valkey import CachedSessionDirectory + +BEARER = 'Bearer realm="messenger"' + + +def key_of(token: str) -> str: + return f"session:{sha256(token.encode()).hexdigest()}" + + +def token_of(user: dict) -> str: + return actor(user)["Authorization"].split()[1] + + +async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None: + cache = Redis.from_url(valkey["url"]) + async with running_app(cache_url=valkey["url"]) as http: + alice = await register(http, "alice") + assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200 + hits = (await cache.info("stats"))["keyspace_hits"] + assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200 + assert (await cache.info("stats"))["keyspace_hits"] == hits + 1 + key = key_of(token_of(alice)) + stored = str(await cache.get(key)) + sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid" + expires_at: datetime = await scalar(sql, alice["id"]) + assert alice["id"] in stored and token_of(alice) not in stored + assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000) + await cache.aclose() + + +async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -> None: + cache = Redis.from_url(valkey["url"]) + async with running_app(cache_url=valkey["url"]) as http: + alice = await register(http, "alice") + assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200 + assert ( + await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)) + ).status_code == 204 + assert await cache.get(key_of(token_of(alice))) == b"-" + response = await http.get("/api/v1/users/me", headers=actor(alice)) + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == BEARER + await cache.aclose() + + +async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None: + async with running_app(cache_url=valkey["url"]) as http: + alice = await register(http, "alice") + directory = await resolve(http, SessionDirectory) + assert isinstance(directory, CachedSessionDirectory) + origin = directory._origin + stale: list[Session | None] = [] + entered, released = asyncio.Event(), asyncio.Event() + + class SlowOrigin: + async def find(self, token_hash: bytes, now: datetime) -> Session | None: + stale.append(await origin.find(token_hash, now)) + entered.set() + await released.wait() + return stale[-1] + + async def invalidate(self, session: Session) -> None: + await origin.invalidate(session) + + directory._origin = SlowOrigin() + reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice))) + await entered.wait() + directory._origin = origin + assert ( + await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)) + ).status_code == 204 + released.set() + assert (await reader).status_code == 200 + assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401 + + +async def test_flushall_loses_nothing(valkey: dict[str, str]) -> None: + cache = Redis.from_url(valkey["url"]) + async with running_app(cache_url=valkey["url"]) as http: + alice = await register(http, "alice") + bob = await register(http, "bob") + assert ( + await http.delete("/api/v1/auth/sessions/current", headers=actor(bob)) + ).status_code == 204 + await cache.flushall() + assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200 + assert (await http.get("/api/v1/users/me", headers=actor(bob))).status_code == 401 + await cache.aclose() + + +async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None: + async with running_app(cache_url="redis://127.0.0.1:1/0") as http: + alice = await register(http, "alice") + started = time.perf_counter() + me = await http.get("/api/v1/users/me", headers=actor(alice)) + stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43)) + elapsed = time.perf_counter() - started + ready = await http.get("/health/ready") + logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)) + still = await http.get("/api/v1/users/me", headers=actor(alice)) + assert me.json() == alice + assert stranger.status_code == 401 + assert stranger.headers["WWW-Authenticate"] == BEARER + assert elapsed < 1 + assert ready.status_code == 200 + assert logout.status_code == 503 + assert logout.json()["error"]["code"] == "unavailable" + assert still.status_code == 200 diff --git a/student-tests/api/test_concurrency.py b/student-tests/api/test_concurrency.py new file mode 100644 index 00000000..aeeeb4e5 --- /dev/null +++ b/student-tests/api/test_concurrency.py @@ -0,0 +1,88 @@ +import asyncio +from urllib.parse import quote +from uuid import uuid4 + +from httpx import AsyncClient + +from conftest import PASSWORD, actor, keyed, make_chat, register + +CLIENTS = 10 +PER_CLIENT = 10 +TOTAL = CLIENTS * PER_CLIENT + + +async def drain(client: AsyncClient, chat: dict, reader: dict) -> list[dict]: + collected: list[dict] = [] + cursor: str | None = None + while True: + query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "") + page = ( + await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)) + ).json() + collected.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return collected + + +async def flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]: + async def writer(worker: int) -> list[int]: + codes = [] + for index in range(PER_CLIENT): + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": f"нагрузка-{worker}-{index}"}, + headers=keyed(sender), + ) + codes.append(response.status_code) + return codes + + batches = await asyncio.gather(*(writer(worker) for worker in range(CLIENTS))) + return [code for batch in batches for code in batch] + + +async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + + codes = await flood(client, chat, alice) + assert codes.count(201) == TOTAL, f"неуспешные ответы: {set(codes) - {201}}" + + history = await drain(client, chat, bob) + assert len(history) == TOTAL + assert len({item["id"] for item in history}) == TOTAL + assert len({item["text"] for item in history}) == TOTAL + + keys = [(item["created_at"], item["id"]) for item in history] + assert keys == sorted(keys), "история не упорядочена по (created_at, id)" + stamps = [item["created_at"] for item in history] + assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать" + + +async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None: + body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD} + responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20))) + codes = [response.status_code for response in responses] + assert codes.count(201) == 1 + assert codes.count(409) == len(codes) - 1 + + +async def test_parallel_chat_creation_is_atomic(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + responses = await asyncio.gather( + *( + client.post( + "/api/v1/chats", + json={"title": f"Чат {index}", "member_ids": [alice["id"], bob["id"]]}, + headers=actor(alice), + ) + for index in range(20) + ) + ) + assert all(response.status_code == 201 for response in responses) + listed = (await client.get("/api/v1/chats?limit=100", headers=actor(bob))).json() + assert len(listed["items"]) == 20 + keys = [(item["created_at"], item["id"]) for item in listed["items"]] + assert keys == sorted(keys) diff --git a/student-tests/api/test_consistency.py b/student-tests/api/test_consistency.py new file mode 100644 index 00000000..5a616a2a --- /dev/null +++ b/student-tests/api/test_consistency.py @@ -0,0 +1,188 @@ +import asyncio +from urllib.parse import quote +from uuid import uuid4 + +from httpx import AsyncClient + +from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar + +REGISTRATIONS = 25 + + +async def drain_history(client: AsyncClient, chat: dict, reader: dict) -> list[dict]: + collected: list[dict] = [] + cursor: str | None = None + while True: + query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "") + page = ( + await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)) + ).json() + collected.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return collected + + +async def test_registration_is_visible_to_chats_immediately() -> None: + async with running_app() as client: + for _ in range(REGISTRATIONS): + user = await register(client, "race") + response = await client.post( + "/api/v1/chats", + json={"title": "Сразу после регистрации", "member_ids": [user["id"]]}, + headers=actor(user), + ) + assert response.status_code == 201, response.text + + +async def test_parallel_registrations_are_all_usable_as_members() -> None: + async with running_app() as client: + alice = await register(client, "alice") + bodies = [new_user(f"par{index}") for index in range(REGISTRATIONS)] + responses = await asyncio.gather( + *(client.post("/api/v1/users", json=body) for body in bodies) + ) + assert all(response.status_code == 201 for response in responses) + created = [response.json()["id"] for response in responses] + chat = await client.post( + "/api/v1/chats", + json={"title": "Все параллельные", "member_ids": [alice["id"], *created]}, + headers=actor(alice), + ) + assert chat.status_code == 201, chat.text + assert len(chat.json()["member_ids"]) == REGISTRATIONS + 1 + + +async def test_rejected_registration_leaves_no_trace() -> None: + async with running_app() as client: + alice = await register(client, "alice") + duplicate = await client.post( + "/api/v1/users", + json={"username": alice["username"], "display_name": "Двойник", "password": PASSWORD}, + ) + assert duplicate.status_code == 409 + invalid = await client.post( + "/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD} + ) + assert invalid.status_code == 400 + sql = "SELECT count(*) FROM users WHERE username = $1" + assert await scalar(sql, alice["username"]) == 1 + + +async def test_failed_chat_creation_rolls_back_both_tables() -> None: + title = f"Откат {uuid4().hex}" + async with running_app() as client: + alice = await register(client, "alice") + before = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json() + rejected = await client.post( + "/api/v1/chats", + json={"title": title, "member_ids": [alice["id"], str(uuid4())]}, + headers=actor(alice), + ) + assert rejected.status_code == 400 + assert rejected.json()["error"]["code"] == "invalid_request" + after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json() + assert after["items"] == before["items"] + assert await scalar("SELECT count(*) FROM chats WHERE title = $1", title) == 0 + members = "SELECT count(*) FROM chat_members WHERE user_id = $1::uuid" + assert await scalar(members, alice["id"]) == 0 + + +async def test_rejected_message_does_not_enter_history() -> None: + async with running_app() as client: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + + assert ( + await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": " "}, + headers=keyed(alice), + ) + ).status_code == 400 + assert ( + await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "чужое"}, + headers=keyed(eve), + ) + ).status_code == 404 + + assert await drain_history(client, chat, alice) == [] + + +async def test_confirmed_write_is_visible_to_next_read() -> None: + async with running_app() as client: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + + for index in range(30): + posted = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": f"подтверждение {index}"}, + headers=keyed(alice), + ) + assert posted.status_code == 201 + history = await drain_history(client, chat, bob) + assert history[-1]["id"] == posted.json()["id"] + assert len(history) == index + 1 + + +async def test_parallel_writes_across_zones_keep_counts_consistent() -> None: + async with running_app() as client: + alice = await register(client, "alice") + chats = [await make_chat(client, alice) for _ in range(4)] + + async def writer(chat: dict, worker: int) -> None: + for index in range(10): + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": f"поток-{worker}-{index}"}, + headers=keyed(alice), + ) + assert response.status_code == 201 + + async def registrar(index: int) -> str: + return (await register(client, f"parallel{index}"))["id"] + + results = await asyncio.gather( + *(writer(chat, number) for number, chat in enumerate(chats)), + *(registrar(index) for index in range(10)), + ) + + registered = [item for item in results if isinstance(item, str)] + assert len(set(registered)) == 10 + for chat in chats: + history = await drain_history(client, chat, alice) + assert len(history) == 10 + assert len({item["id"] for item in history}) == 10 + keys = [(item["created_at"], item["id"]) for item in history] + assert keys == sorted(keys) + + +async def test_chat_membership_survives_parallel_reads_and_writes() -> None: + async with running_app() as client: + alice = await register(client, "alice") + bob = await register(client, "bob") + eve = await register(client, "eve") + chat = await make_chat(client, alice, bob) + + async def write(index: int) -> None: + await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": f"параллельно {index}"}, + headers=keyed(alice), + ) + + async def intruder() -> int: + response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve)) + return response.status_code + + results = await asyncio.gather( + *(write(index) for index in range(20)), + *(intruder() for _ in range(20)), + ) + assert {code for code in results if isinstance(code, int)} == {404} + assert len(await drain_history(client, chat, bob)) == 20 diff --git a/student-tests/api/test_drain.py b/student-tests/api/test_drain.py new file mode 100644 index 00000000..5b400ece --- /dev/null +++ b/student-tests/api/test_drain.py @@ -0,0 +1,108 @@ +import json +import os +import signal +import socket +import subprocess +import sys +import time + +import httpx + +from conftest import DATABASE, new_user +from messenger.shared.entrypoints.health import DRAINING + +DRAIN = 1.5 +SHUTDOWN = 4 +GUNICORN = ( + "-m", + "gunicorn", + "--config", + "python:messenger.gunicorn_conf", + "messenger.main:create_app()", +) + + +async def test_draining_replica_is_not_ready_but_alive(client: httpx.AsyncClient) -> None: + DRAINING.set() + try: + ready = await client.get("/health/ready") + live = await client.get("/health/live") + finally: + DRAINING.clear() + assert ready.status_code == 503 + assert ready.json()["error"]["code"] == "unavailable" + assert ready.headers["X-Instance-Id"] + assert live.status_code == 200 + assert (await client.get("/health/ready")).status_code == 200 + + +def free_port() -> int: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def status(port: int, path: str) -> int: + try: + return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1).status_code + except httpx.TransportError: + return 0 + + +def begin_registration(port: int) -> tuple[socket.socket, bytes]: + body = json.dumps(new_user("drain")).encode() + head = ( + "POST /api/v1/users HTTP/1.1\r\nHost: replica\r\nContent-Type: application/json\r\n" + f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n" + ) + connection = socket.create_connection(("127.0.0.1", port), timeout=5) + connection.sendall(head.encode() + body[:8]) + return connection, body[8:] + + +def test_sigterm_leaves_rotation_then_closes_and_exits() -> None: + port = free_port() + settings = { + "HOST": "127.0.0.1", + "PORT": str(port), + "WEB_CONCURRENCY": "2", + "DATABASE_URL": DATABASE["url"], + "CURSOR_SECRET": "test-secret-for-cursors", + "LOG_LEVEL": "WARNING", + "DRAIN_SECONDS": str(DRAIN), + "SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN), + } + server = subprocess.Popen( + [sys.executable, *GUNICORN], + env={**os.environ, **settings}, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + deadline = time.monotonic() + 30 + while status(port, "/health/ready") != 200: + assert time.monotonic() < deadline, "gunicorn не стал готов" + time.sleep(0.2) + pending, rest = begin_registration(port) + sent = time.monotonic() + server.send_signal(signal.SIGTERM) + time.sleep(0.3) + during = status(port, "/health/ready"), status(port, "/health/live") + while status(port, "/health/live") == 200: + time.sleep(0.05) + closed = time.monotonic() - sent + pending.sendall(rest) + answer = pending.recv(64).split(b"\r\n")[0].decode() + pending.close() + code = server.wait(timeout=SHUTDOWN + 2) + exited = time.monotonic() - sent + finally: + if server.poll() is None: + server.kill() + print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с") + print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}") + assert during == (503, 200) + assert answer == "HTTP/1.1 201 Created" + assert DRAIN - 0.2 <= closed < SHUTDOWN + assert exited < SHUTDOWN + assert code == 0 diff --git a/student-tests/api/test_events.py b/student-tests/api/test_events.py new file mode 100644 index 00000000..a6975565 --- /dev/null +++ b/student-tests/api/test_events.py @@ -0,0 +1,124 @@ +import asyncio +from dataclasses import fields +from datetime import UTC, datetime +from uuid import uuid4 + +from httpx import ASGITransport, AsyncClient + +from conftest import keyed, make_chat, register, split_settings +from fakes import NullLogger +from messenger.identity.domain.events import UserRegistered +from messenger.main import create_app +from messenger.messaging.domain.events import MessagePosted +from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher + + +def posted() -> MessagePosted: + return MessagePosted( + message_id=uuid4(), + chat_id=uuid4(), + sender_id=uuid4(), + text_length=5, + created_at=datetime.now(UTC), + ) + + +async def test_event_has_no_message_text() -> None: + names = {field.name for field in fields(posted())} + assert names == {"name", "message_id", "chat_id", "sender_id", "text_length", "created_at"} + + +async def test_every_subscriber_receives_event() -> None: + bus = EventBus(NullLogger()) + seen: list[str] = [] + + async def first(_event: MessagePosted) -> None: + seen.append("first") + + async def second(_event: MessagePosted) -> None: + seen.append("second") + + bus.subscribe(MessagePosted, first) + bus.subscribe(MessagePosted, second) + bus.start() + await InMemoryEventPublisher(bus).publish([posted()]) + await bus.stop() + assert sorted(seen) == ["first", "second"] + + +async def test_failing_subscriber_does_not_block_others() -> None: + bus = EventBus(NullLogger()) + survived: list[str] = [] + + async def broken(_event: MessagePosted) -> None: + raise RuntimeError("обработчик упал") + + async def healthy(_event: MessagePosted) -> None: + survived.append("ok") + + bus.subscribe(MessagePosted, broken) + bus.subscribe(MessagePosted, healthy) + bus.start() + await InMemoryEventPublisher(bus).publish([posted()]) + await bus.stop() + assert survived == ["ok"] + + +async def test_queue_overflow_drops_events_without_raising() -> None: + bus = EventBus(NullLogger(), max_queue=16) + + async def never_called(_event: MessagePosted) -> None: + raise AssertionError("обработчик не должен вызываться без запущенной шины") + + bus.subscribe(MessagePosted, never_called) + publisher = InMemoryEventPublisher(bus) + await publisher.publish([posted() for _ in range(64)]) + assert bus.dropped > 0 + assert bus.pending <= 16 + + +async def test_projection_runs_before_publish_returns() -> None: + bus = EventBus(NullLogger()) + seen: list[str] = [] + + async def projection(_event: MessagePosted) -> None: + seen.append("projected") + + bus.project(MessagePosted, projection) + await InMemoryEventPublisher(bus).publish([posted()]) + assert seen == ["projected"] + + +async def test_publication_does_not_delay_response() -> None: + app = create_app(**split_settings(log_level="CRITICAL")) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http, + ): + alice = await register(http, "alice") + chat = await make_chat(http, alice) + bus = await app.state.dishka_container.get(EventBus) + slow = asyncio.Event() + + async def blocker(_event: MessagePosted) -> None: + await slow.wait() + + bus.subscribe(MessagePosted, blocker) + response = await asyncio.wait_for( + http.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "не ждём обработчик"}, + headers=keyed(alice), + ), + timeout=2, + ) + assert response.status_code == 201 + slow.set() + + +async def test_null_logger_hides_everything() -> None: + logger = NullLogger() + logger.info("x", route="/") + logger.warning("x") + logger.error("x") + assert isinstance(UserRegistered, type) diff --git a/student-tests/api/test_idempotency.py b/student-tests/api/test_idempotency.py new file mode 100644 index 00000000..02f94a90 --- /dev/null +++ b/student-tests/api/test_idempotency.py @@ -0,0 +1,145 @@ +import asyncio +from typing import Any +from uuid import uuid4 + +import pytest +from httpx import AsyncClient, Response + +from conftest import actor, keyed, make_chat, register, running_app, scalar + +INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"] + + +async def send(http: AsyncClient, chat: dict, user: dict, text: str, key: str) -> Response: + return await http.post( + f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(user, key) + ) + + +async def history(http: AsyncClient, chat: dict, user: dict) -> list[dict[str, Any]]: + response = await http.get(f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=actor(user)) + return response.json()["items"] + + +async def test_replay_returns_the_same_message(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + first = await send(client, chat, alice, "один раз", "replay-1") + again = await send(client, chat, alice, "один раз", "replay-1") + assert first.status_code == again.status_code == 201 + assert again.json() == first.json() + assert [item["id"] for item in await history(client, chat, alice)] == [first.json()["id"]] + + +async def test_same_json_in_other_layout_is_a_replay(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + first = await send(client, chat, alice, "форма", "layout-1") + again = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + content='{ "text" : "форма" }'.encode(), + headers={**keyed(alice, "layout-1"), "Content-Type": "application/json"}, + ) + assert again.status_code == 201 + assert again.json() == first.json() + + +async def test_other_body_with_same_key_conflicts(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + await send(client, chat, alice, "первое", "conflict-1") + response = await send(client, chat, alice, "другое", "conflict-1") + assert response.status_code == 409 + assert response.json()["error"]["code"] == "conflict" + assert len(await history(client, chat, alice)) == 1 + + +async def test_missing_key_is_rejected(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", json={"text": "без ключа"}, headers=actor(alice) + ) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + assert await history(client, chat, alice) == [] + + +@pytest.mark.parametrize("key", INVALID_KEYS, ids=range(len(INVALID_KEYS))) +async def test_malformed_key_is_rejected(client: AsyncClient, key: str) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + headers = {**actor(alice), "Idempotency-Key": key} + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "ключ плохой"}, + headers={name.encode(): value.encode() for name, value in headers.items()}, + ) + assert response.status_code == 400 + assert await history(client, chat, alice) == [] + + +async def test_rejected_attempt_does_not_take_the_key(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + assert (await send(client, chat, alice, "", "spare-1")).status_code == 400 + assert (await send(client, chat, eve, "чужое", "spare-1")).status_code == 404 + assert (await send(client, chat, alice, "теперь можно", "spare-1")).status_code == 201 + + +async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + other = await make_chat(client, alice) + ids = { + (await send(client, chat, alice, "алиса", "shared-1")).json()["id"], + (await send(client, chat, bob, "боб", "shared-1")).json()["id"], + (await send(client, other, alice, "другой чат", "shared-1")).json()["id"], + } + assert len(ids) == 3 + + +async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + chat = await make_chat(client, alice) + assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 201 + assert (await send(client, chat, eve, "до выхода", "recheck-1")).status_code == 404 + logout = await client.delete("/api/v1/auth/sessions/current", headers=actor(alice)) + assert logout.status_code == 204 + assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 401 + + +async def test_expired_key_starts_over() -> None: + async with running_app(idempotency_ttl_seconds=1) as http: + alice = await register(http, "alice") + chat = await make_chat(http, alice) + first = await send(http, chat, alice, "давно", "expire-1") + await asyncio.sleep(1.1) + later = await send(http, chat, alice, "заново", "expire-1") + assert later.status_code == 201 + assert later.json()["id"] != first.json()["id"] + assert len(await history(http, chat, alice)) == 2 + + +async def test_concurrent_retries_through_two_replicas_store_one_message() -> None: + async with ( + running_app(instance_id="replica-a") as first, + running_app(instance_id="replica-b") as second, + ): + alice = await register(first, "alice") + chat = await make_chat(first, alice) + key, text = uuid4().hex, "гонка ключа" + responses = await asyncio.gather( + *(send(http, chat, alice, text, key) for http in (first, second) * 4) + ) + assert {response.status_code for response in responses} == {201} + assert {response.headers["X-Instance-Id"] for response in responses} == { + "replica-a", + "replica-b", + } + assert all(response.json() == responses[0].json() for response in responses) + assert [item["text"] for item in await history(second, chat, alice)] == [text] + assert await scalar("SELECT count(*) FROM idempotency_keys WHERE key = $1", key) == 1 diff --git a/student-tests/api/test_instance.py b/student-tests/api/test_instance.py new file mode 100644 index 00000000..b76fe4fb --- /dev/null +++ b/student-tests/api/test_instance.py @@ -0,0 +1,64 @@ +import socket +from uuid import uuid4 + +from httpx import ASGITransport, AsyncClient, Response + +from conftest import actor, register, running_app, split_settings +from messenger.main import create_app +from messenger.shared.config import PlatformSettings + +REPLICA = "replica-7f3a" + + +def stamped(response: Response) -> bool: + return bool(response.headers.get("X-Request-Id")) and ( + response.headers.get("X-Instance-Id") == REPLICA + ) + + +async def test_every_response_names_the_replica() -> None: + async with running_app(instance_id=REPLICA) as http: + alice = await register(http, "alice") + probes = [ + await http.get("/health/live"), + await http.get("/health/ready"), + await http.get("/api/v1/users/me", headers=actor(alice)), + await http.get("/api/v1/users/me"), + await http.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)), + await http.get("/nothing-here"), + await http.delete("/health/live"), + await http.post("/api/v1/users", json={"username": "x"}), + await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)), + ] + assert [probe.status_code for probe in probes] == [200, 200, 200, 401, 404, 404, 404, 400, 204] + assert all(stamped(probe) for probe in probes) + + +async def test_rejected_body_names_the_replica() -> None: + async with running_app(instance_id=REPLICA, max_body_bytes=4096) as http: + response = await http.post("/api/v1/users", content=b"x" * 5000) + assert response.status_code == 413 + assert stamped(response) + + +async def test_unhandled_error_names_the_replica() -> None: + app = create_app(**split_settings(instance_id=REPLICA)) + + async def boom() -> None: + raise RuntimeError("сбой") + + app.add_api_route("/health/boom", boom) + transport = ASGITransport(app=app, raise_app_exceptions=False) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=transport, base_url="http://testserver") as http, + ): + response = await http.get("/health/boom") + assert response.status_code == 500 + assert response.json()["error"]["code"] == "internal_error" + assert stamped(response) + + +def test_replica_defaults_to_container_hostname() -> None: + settings = PlatformSettings.model_validate({"database_url": "postgresql://u@h/d"}) + assert settings.instance_id == socket.gethostname() diff --git a/student-tests/api/test_migrations.py b/student-tests/api/test_migrations.py new file mode 100644 index 00000000..12d9a351 --- /dev/null +++ b/student-tests/api/test_migrations.py @@ -0,0 +1,77 @@ +import asyncpg +import pytest + +from conftest import DATABASE, scalar +from messenger.migrate import MigrationChangedError, migrate, migrations + +COUNTS = """ +SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions), + (SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members), + (SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys) +""" + + +async def counts() -> list[int]: + connection = await asyncpg.connect(DATABASE["url"]) + try: + return list(await connection.fetchrow(COUNTS)) + finally: + await connection.close() + + +async def test_migrations_are_ordered_and_versioned() -> None: + versions = [version for version, _ in migrations()] + assert versions == sorted(versions) + assert versions[:2] == ["0001_init", "0002_idempotency_keys"] + applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations") + assert applied == versions + + +async def test_rerun_changes_nothing() -> None: + before = await counts() + assert await migrate(DATABASE["url"]) == [] + assert await counts() == before + + +async def test_changed_migration_is_refused() -> None: + connection = await asyncpg.connect(DATABASE["url"]) + try: + original = await connection.fetchval( + "SELECT checksum FROM schema_migrations WHERE version = '0001_init'" + ) + await connection.execute( + "UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'" + ) + with pytest.raises(MigrationChangedError): + await migrate(DATABASE["url"]) + await connection.execute( + "UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original + ) + finally: + await connection.close() + + +async def test_sender_must_be_member_even_bypassing_api() -> None: + connection = await asyncpg.connect(DATABASE["url"]) + try: + with pytest.raises(asyncpg.ForeignKeyViolationError): + await connection.execute( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at) " + "VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())" + ) + finally: + await connection.close() + + +async def test_key_needs_a_member_and_a_message() -> None: + connection = await asyncpg.connect(DATABASE["url"]) + try: + with pytest.raises(asyncpg.ForeignKeyViolationError): + await connection.execute( + "INSERT INTO idempotency_keys " + "(chat_id, user_id, key, fingerprint, message_id, created_at) " + "VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', " + "sha256('x'), gen_random_uuid(), now())" + ) + finally: + await connection.close() diff --git a/student-tests/api/test_negative.py b/student-tests/api/test_negative.py new file mode 100644 index 00000000..a1dc7ccf --- /dev/null +++ b/student-tests/api/test_negative.py @@ -0,0 +1,196 @@ +from uuid import uuid4 + +import pytest +from httpx import AsyncClient + +from conftest import PASSWORD, actor, keyed, make_chat, register + +ERROR_CODES = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", +} + + +def assert_error(response, expected_status: int) -> None: + assert response.status_code == expected_status, response.text + assert response.headers.get("content-type", "").startswith("application/json") + body = response.json() + assert set(body) == {"error"} + assert set(body["error"]) == {"code", "message", "request_id"} + assert body["error"]["code"] == ERROR_CODES[expected_status] + assert body["error"]["message"] + assert body["error"]["request_id"] == response.headers["X-Request-Id"] + + +async def test_malformed_json(client: AsyncClient) -> None: + response = await client.post( + "/api/v1/users", + content=b'{"username": ', + headers={"Content-Type": "application/json"}, + ) + assert_error(response, 400) + + +async def test_unexpected_field(client: AsyncClient) -> None: + response = await client.post( + "/api/v1/users", + json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"}, + ) + assert_error(response, 400) + + +async def test_wrong_types(client: AsyncClient) -> None: + response = await client.post( + "/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234} + ) + assert_error(response, 400) + + +@pytest.mark.parametrize( + "body", + [ + {"username": "Alice", "display_name": "X", "password": PASSWORD}, + {"username": "ab", "display_name": "X", "password": PASSWORD}, + {"username": "alice_01\n", "display_name": "X", "password": PASSWORD}, + {"username": "abc_def", "display_name": "", "password": PASSWORD}, + {"username": "abc_def", "display_name": " ", "password": PASSWORD}, + {"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD}, + {"username": "abc_def", "display_name": "X", "password": "short"}, + {"username": "abc_def", "display_name": "X", "password": "x" * 129}, + {"username": "abc_def", "display_name": "X", "password": " " * 20}, + {"username": "abc_def", "display_name": "X"}, + {"username": "abc_def", "password": PASSWORD}, + ], +) +async def test_invalid_registration(client: AsyncClient, body: dict) -> None: + assert_error(await client.post("/api/v1/users", json=body), 400) + + +async def test_duplicate_username(client: AsyncClient) -> None: + alice = await register(client, "alice") + repeat = await client.post( + "/api/v1/users", + json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD}, + ) + assert_error(repeat, 409) + + +async def test_missing_identity(client: AsyncClient) -> None: + assert_error(await client.get("/api/v1/users/me"), 401) + + +BAD_AUTHORIZATIONS = [ + "", + "Bearer", + "Bearer ", + "Bearer not a token", + "Bearer " + "x" * 43, + "Token abcdef", + "11111111-1111-4111-8111-111111111111", +] + + +@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS) +async def test_invalid_bearer(client: AsyncClient, raw: str) -> None: + response = await client.get("/api/v1/users/me", headers={"Authorization": raw}) + assert_error(response, 401) + assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"' + + +async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None: + alice = await register(client, "alice") + response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}) + assert_error(response, 401) + + +async def test_identity_checked_before_body(client: AsyncClient) -> None: + response = await client.post( + "/api/v1/chats", + content=b"{broken", + headers={"Content-Type": "application/json"}, + ) + assert_error(response, 401) + + +async def test_empty_message_rejected(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + for text in ("", " ", "\n\t"): + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": text}, + headers=keyed(alice), + ) + assert_error(response, 400) + + +async def test_long_message_rejected(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "я" * 4001}, + headers=keyed(alice), + ) + assert_error(response, 400) + + +async def test_sender_id_not_accepted(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "подмена", "sender_id": bob["id"]}, + headers=keyed(alice), + ) + assert_error(response, 400) + + +@pytest.mark.parametrize( + "body", + [ + {"title": "Чат", "member_ids": []}, + {"title": "", "member_ids": None}, + {"title": " ", "member_ids": None}, + {"title": "Чат", "member_ids": ["не-uuid"]}, + {"title": "Чат", "member_ids": [1]}, + {"title": "Чат", "member_ids": "не-список"}, + ], +) +async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None: + alice = await register(client, "alice") + payload = dict(body) + if payload["member_ids"] is None: + payload["member_ids"] = [alice["id"]] + response = await client.post("/api/v1/chats", json=payload, headers=actor(alice)) + assert_error(response, 400) + + +async def test_creator_must_be_member(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + response = await client.post( + "/api/v1/chats", + json={"title": "Чат", "member_ids": [bob["id"]]}, + headers=actor(alice), + ) + assert_error(response, 400) + + +async def test_unknown_member_rejected(client: AsyncClient) -> None: + alice = await register(client, "alice") + response = await client.post( + "/api/v1/chats", + json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]}, + headers=actor(alice), + ) + assert_error(response, 400) + + +async def test_bad_chat_id_in_path(client: AsyncClient) -> None: + alice = await register(client, "alice") + assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400) diff --git a/student-tests/api/test_operability.py b/student-tests/api/test_operability.py new file mode 100644 index 00000000..91adaeb4 --- /dev/null +++ b/student-tests/api/test_operability.py @@ -0,0 +1,144 @@ +import json +import time +from uuid import uuid4 + +from httpx import ASGITransport, AsyncClient + +from conftest import PASSWORD, actor, keyed, make_chat, register, running_app, split_settings +from messenger.main import create_app + +MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a" + + +async def test_health_needs_no_identity(client: AsyncClient) -> None: + for path in ("/health/live", "/health/ready"): + response = await client.get(path) + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + assert response.headers["X-Request-Id"] + + +async def test_every_response_carries_request_id(client: AsyncClient) -> None: + alice = await register(client, "alice") + probes = [ + await client.get("/health/live"), + await client.get("/api/v1/users/me", headers=actor(alice)), + await client.get("/api/v1/users/me"), + await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)), + await client.get("/api/v1/unknown-path"), + ] + assert all(probe.headers.get("X-Request-Id") for probe in probes) + + +async def test_client_request_id_is_preserved(client: AsyncClient) -> None: + response = await client.get("/health/live", headers={"X-Request-Id": "trace-42"}) + assert response.headers["X-Request-Id"] == "trace-42" + + +async def test_unknown_public_route_is_404(client: AsyncClient) -> None: + response = await client.get("/nothing-here") + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" + + +async def test_unknown_protected_route_needs_identity(client: AsyncClient) -> None: + anonymous = await client.get("/api/v1/unknown-path") + assert anonymous.status_code == 401 + assert set(anonymous.json()["error"]) == {"code", "message", "request_id"} + alice = await register(client, "alice") + identified = await client.get("/api/v1/unknown-path", headers=actor(alice)) + assert identified.status_code == 404 + + +async def test_method_not_allowed_is_hidden(client: AsyncClient) -> None: + response = await client.delete("/health/live") + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" + + +async def test_logs_do_not_contain_message_text(capsys) -> None: + app = create_app(**split_settings(log_level="INFO")) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http, + ): + alice = await register(http, "alice") + chat = await make_chat(http, alice) + response = await http.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": MARKER_TEXT}, + headers=keyed(alice), + ) + assert response.status_code == 201 + captured = capsys.readouterr() + assert MARKER_TEXT not in captured.out + assert MARKER_TEXT not in captured.err + assert alice["display_name"] not in captured.out + assert any("request.handled" in line for line in captured.out.splitlines()) + + +async def test_log_lines_are_json(capsys) -> None: + app = create_app(**split_settings(log_level="INFO")) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http, + ): + await http.get("/health/live") + for line in capsys.readouterr().out.splitlines(): + record = json.loads(line) + assert {"ts", "level", "event"} <= set(record) + + +async def test_body_limit_returns_413() -> None: + app = create_app(**split_settings(max_body_bytes=4096)) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http, + ): + response = await http.post("/api/v1/users", content=b"x" * 5000) + assert response.status_code == 413 + assert response.json()["error"]["code"] == "payload_too_large" + + +async def test_ready_turns_unavailable_without_database() -> None: + async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http: + started = time.perf_counter() + ready = await http.get("/health/ready") + live = await http.get("/health/live") + elapsed = time.perf_counter() - started + assert ready.status_code == 503 + assert ready.json()["error"]["code"] == "unavailable" + assert live.status_code == 200 + assert elapsed < 2 + + +async def test_protected_request_is_503_not_401_without_database() -> None: + async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http: + response = await http.get( + "/api/v1/users/me", headers={"Authorization": "Bearer " + "x" * 43} + ) + assert response.status_code == 503 + assert response.json()["error"]["code"] == "unavailable" + assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"] + + +async def test_state_survives_new_process() -> None: + async with running_app() as http: + alice = await register(http, "alice") + chat = await make_chat(http, alice) + async with running_app() as http: + me = await http.get("/api/v1/users/me", headers=actor(alice)) + listed = await http.get("/api/v1/chats?limit=100", headers=actor(alice)) + assert me.json() == alice + assert [item["id"] for item in listed.json()["items"]] == [chat["id"]] + + +async def test_logs_do_not_contain_credentials(capsys) -> None: + async with running_app(log_level="INFO") as http: + alice = await register(http, "secret") + assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200 + output = capsys.readouterr() + captured = output.out + output.err + assert PASSWORD not in captured + assert actor(alice)["Authorization"].split()[1] not in captured + assert "audit.session_opened" in captured diff --git a/student-tests/api/test_pagination.py b/student-tests/api/test_pagination.py new file mode 100644 index 00000000..980aa559 --- /dev/null +++ b/student-tests/api/test_pagination.py @@ -0,0 +1,155 @@ +from urllib.parse import quote + +import pytest +from httpx import AsyncClient + +from conftest import actor, keyed, make_chat, register + +TOTAL = 12 + + +async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]: + texts = [] + for index in range(count): + text = f"сообщение {index:02d}" + response = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": text}, + headers=keyed(sender), + ) + assert response.status_code == 201, response.text + texts.append(text) + return texts + + +async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]: + collected: list[str] = [] + cursor: str | None = None + step = 0 + while True: + limit = limits[min(step, len(limits) - 1)] + query = f"?limit={limit}" + if cursor: + query += f"&cursor={quote(cursor, safe='')}" + response = await client.get( + f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader) + ) + assert response.status_code == 200, response.text + page = response.json() + assert len(page["items"]) <= limit + collected.extend(item["text"] for item in page["items"]) + cursor = page["next_cursor"] + step += 1 + if cursor is None: + return collected + + +async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + expected = await fill(client, chat, alice, TOTAL) + assert await walk(client, chat, bob, [5]) == expected + + +async def test_limit_may_change_between_pages(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + expected = await fill(client, chat, alice, TOTAL) + assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected + + +async def test_last_page_closes_history(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + await fill(client, chat, alice, 2) + first = ( + await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice)) + ).json() + assert len(first["items"]) == 2 + assert first["next_cursor"] is None + + +async def test_cursor_is_shared_between_members(client: AsyncClient) -> None: + alice = await register(client, "alice") + bob = await register(client, "bob") + chat = await make_chat(client, alice, bob) + await fill(client, chat, alice, 3) + page = ( + await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice)) + ).json() + cursor = quote(page["next_cursor"], safe="") + response = await client.get( + f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob) + ) + assert response.status_code == 200 + + +async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None: + alice = await register(client, "alice") + first = await make_chat(client, alice) + second = await make_chat(client, alice) + await fill(client, first, alice, 3) + await fill(client, second, alice, 3) + page = ( + await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice)) + ).json() + cursor = quote(page["next_cursor"], safe="") + response = await client.get( + f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice) + ) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20"]) +async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + response = await client.get( + f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", headers=actor(alice) + ) + assert response.status_code == 400 + + +@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""]) +async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"): + response = await client.get(f"{path}?limit={limit}", headers=actor(alice)) + assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}" + + +async def test_default_limit_is_50(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + await fill(client, chat, alice, 51) + page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json() + assert len(page["items"]) == 50 + assert page["next_cursor"] is not None + + +async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + await fill(client, chat, alice, 2) + for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"): + response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice)) + assert response.status_code == 200, response.text + assert len(response.json()["items"]) == 1 + + +async def test_chat_list_pagination(client: AsyncClient) -> None: + alice = await register(client, "alice") + created = [(await make_chat(client, alice))["id"] for _ in range(5)] + collected: list[str] = [] + cursor: str | None = None + while True: + query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "") + page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json() + collected.extend(item["id"] for item in page["items"]) + cursor = page["next_cursor"] + if cursor is None: + break + assert collected == created diff --git a/student-tests/api/test_pool.py b/student-tests/api/test_pool.py new file mode 100644 index 00000000..e27586f6 --- /dev/null +++ b/student-tests/api/test_pool.py @@ -0,0 +1,27 @@ +import time + +from conftest import actor, register, resolve, running_app +from messenger.shared.infrastructure.postgres import Database + + +async def test_exhausted_pool_answers_503_in_bounded_time() -> None: + async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http: + alice = await register(http, "alice") + database = await resolve(http, Database) + async with database.connection(): + started = time.perf_counter() + starved = await http.get("/api/v1/users/me", headers=actor(alice)) + elapsed = time.perf_counter() - started + recovered = await http.get("/api/v1/users/me", headers=actor(alice)) + assert starved.status_code == 503 + assert starved.json()["error"]["code"] == "unavailable" + assert 0.25 < elapsed < 1 + assert recovered.json() == alice + + +async def test_statement_timeout_is_set_on_connections() -> None: + async with running_app(db_command_timeout_seconds=1.5) as http: + database = await resolve(http, Database) + async with database.connection() as connection: + assert await connection.fetchval("SHOW statement_timeout") == "1500ms" + assert await connection.fetchval("SHOW lock_timeout") == "1500ms" diff --git a/student-tests/api/test_sessions.py b/student-tests/api/test_sessions.py new file mode 100644 index 00000000..6397ad1f --- /dev/null +++ b/student-tests/api/test_sessions.py @@ -0,0 +1,172 @@ +import asyncio +from datetime import datetime, timedelta + +import pytest +from httpx import AsyncClient + +from conftest import ( + PASSWORD, + actor, + basic, + bearer, + login, + make_chat, + new_user, + register, + running_app, + scalar, +) + +BASIC = 'Basic realm="messenger", charset="UTF-8"' +BEARER = 'Bearer realm="messenger"' + + +def challenged(response, challenge: str) -> None: + assert response.status_code == 401, response.text + assert response.headers["WWW-Authenticate"] == challenge + assert response.json()["error"]["code"] == "unauthorized" + assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"] + + +async def test_login_returns_session_for_registered_user(client: AsyncClient) -> None: + body = new_user("alice") + user = (await client.post("/api/v1/users", json=body)).json() + session = await login(client, body["username"]) + assert set(session) == {"token", "token_type", "expires_at", "user"} + assert session["token_type"] == "Bearer" + assert session["user"] == user + assert len(session["token"]) >= 43 + assert body["username"] not in session["token"] and user["id"] not in session["token"] + assert session["expires_at"].endswith("Z") + expires = datetime.fromisoformat(session["expires_at"]) + created = datetime.fromisoformat(user["created_at"]) + assert timedelta(seconds=3500) < expires - created < timedelta(seconds=3700) + + +async def test_registration_response_hides_password(client: AsyncClient) -> None: + body = new_user("alice") + response = await client.post("/api/v1/users", json=body) + assert set(response.json()) == {"id", "username", "display_name", "created_at"} + assert PASSWORD not in response.text + + +async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None: + alice = await register(client, "alice") + stored = await scalar("SELECT password_hash FROM users WHERE id = $1::uuid", alice["id"]) + assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$") + assert PASSWORD not in stored + + +async def test_session_stores_only_token_digest(client: AsyncClient) -> None: + alice = await register(client, "alice") + token = actor(alice)["Authorization"].split()[1] + sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))" + assert await scalar(sql, token) == 1 + raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1" + assert await scalar(raw, token) == 0 + + +async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None: + alice = await register(client, "alice") + wrong = await client.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20)) + unknown = await client.post("/api/v1/auth/sessions", headers=basic("u_ghost_000", PASSWORD)) + challenged(wrong, BASIC) + challenged(unknown, BASIC) + assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"] + + +@pytest.mark.parametrize( + "headers", + [{}, {"Authorization": "Basic !!!"}, {"Authorization": "Bearer abc"}, {"X-User-Id": "x"}], +) +async def test_login_without_valid_basic(client: AsyncClient, headers: dict) -> None: + challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC) + + +async def test_password_with_colon_logs_in(client: AsyncClient) -> None: + body = new_user("colon", password="пароль:с:двоеточием") + assert (await client.post("/api/v1/users", json=body)).status_code == 201 + assert (await login(client, body["username"], body["password"]))["token"] + + +async def test_login_with_body_is_rejected(client: AsyncClient) -> None: + body = new_user("body") + await client.post("/api/v1/users", json=body) + response = await client.post( + "/api/v1/auth/sessions", headers=basic(body["username"], PASSWORD), json={"x": 1} + ) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +async def test_basic_on_business_endpoint_gets_bearer_challenge(client: AsyncClient) -> None: + body = new_user("alice") + await client.post("/api/v1/users", json=body) + challenged( + await client.get("/api/v1/users/me", headers=basic(body["username"], PASSWORD)), BEARER + ) + + +async def test_user_id_header_does_not_override_owner(client: AsyncClient) -> None: + alice = await register(client, "alice") + eve = await register(client, "eve") + response = await client.get( + "/api/v1/users/me", headers={**actor(alice), "X-User-Id": eve["id"]} + ) + assert response.json() == alice + + +async def test_authentication_precedes_validation(client: AsyncClient) -> None: + response = await client.post( + "/api/v1/chats/not-a-uuid/messages", + content=b"{broken", + headers={"Content-Type": "application/json"}, + ) + challenged(response, BEARER) + + +async def test_logout_revokes_only_current_session(client: AsyncClient) -> None: + body = new_user("alice") + await client.post("/api/v1/users", json=body) + first = (await login(client, body["username"]))["token"] + second = (await login(client, body["username"]))["token"] + logout = await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)) + assert logout.status_code == 204 + assert logout.content == b"" + assert logout.headers["X-Request-Id"] + challenged(await client.get("/api/v1/users/me", headers=bearer(first)), BEARER) + challenged(await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)), BEARER) + assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200 + + +async def test_short_ttl_session_expires() -> None: + async with running_app(session_ttl_seconds=1) as client: + alice = await register(client, "alice") + assert (await client.get("/api/v1/users/me", headers=actor(alice))).status_code == 200 + await asyncio.sleep(1.2) + challenged(await client.get("/api/v1/users/me", headers=actor(alice)), BEARER) + + +async def test_expired_sessions_are_purged_on_next_login() -> None: + async with running_app(session_ttl_seconds=1) as client: + body = new_user("purge") + user = (await client.post("/api/v1/users", json=body)).json() + await login(client, body["username"]) + await asyncio.sleep(1.2) + await login(client, body["username"]) + sql = "SELECT count(*) FROM sessions WHERE user_id = $1::uuid" + assert await scalar(sql, user["id"]) == 1 + + +async def test_chat_routes_require_bearer(client: AsyncClient) -> None: + alice = await register(client, "alice") + chat = await make_chat(client, alice) + for method, path in [ + ("GET", "/api/v1/chats"), + ("POST", "/api/v1/chats"), + ("GET", f"/api/v1/chats/{chat['id']}"), + ("GET", f"/api/v1/chats/{chat['id']}/messages"), + ("POST", f"/api/v1/chats/{chat['id']}/messages"), + ("DELETE", "/api/v1/auth/sessions/current"), + ]: + challenged(await client.request(method, path, headers={"X-User-Id": alice["id"]}), BEARER) diff --git a/student-tests/api/test_timeout.py b/student-tests/api/test_timeout.py new file mode 100644 index 00000000..9118d660 --- /dev/null +++ b/student-tests/api/test_timeout.py @@ -0,0 +1,97 @@ +import asyncio +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager + +from httpx import AsyncClient + +from conftest import keyed, make_chat, register, resolve, running_app +from messenger.messaging.application import handlers +from messenger.messaging.domain.events import MessagePosted +from messenger.shared.application.messagebus import EventBus + +MARKER = "текст-который-не-должен-утечь-при-таймауте" + + +@asynccontextmanager +async def slow_post(delay: float) -> AsyncIterator[None]: + original: Callable = handlers.PostMessageHandler.__call__ + + async def stalled(self, command): + await asyncio.sleep(delay) + return await original(self, command) + + handlers.PostMessageHandler.__call__ = stalled + try: + yield + finally: + handlers.PostMessageHandler.__call__ = original + + +async def post(client: AsyncClient, chat: dict, sender: dict, text: str): + return await client.post( + f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(sender) + ) + + +async def prepared(client: AsyncClient) -> tuple[dict, dict]: + alice = await register(client, "alice") + return alice, await make_chat(client, alice) + + +async def test_timeout_returns_unavailable_error_body() -> None: + async with running_app(request_timeout_seconds=0.15) as client: + alice, chat = await prepared(client) + async with slow_post(1.0): + response = await post(client, chat, alice, "медленная запись") + assert response.status_code == 503 + body = response.json() + assert body["error"]["code"] == "unavailable" + assert body["error"]["request_id"] == response.headers["X-Request-Id"] + + +async def test_timeout_does_not_break_following_requests() -> None: + async with running_app(request_timeout_seconds=0.15) as client: + alice, chat = await prepared(client) + async with slow_post(1.0): + assert (await post(client, chat, alice, "зависшая запись")).status_code == 503 + assert (await post(client, chat, alice, "нормальная запись")).status_code == 201 + assert (await client.get("/health/ready")).status_code == 200 + + +async def test_timeout_is_logged_without_message_text(capsys) -> None: + async with running_app(request_timeout_seconds=0.15, log_level="INFO") as client: + alice, chat = await prepared(client) + async with slow_post(1.0): + assert (await post(client, chat, alice, MARKER)).status_code == 503 + captured = capsys.readouterr() + assert "request.timeout" in captured.out + assert MARKER not in captured.out + assert MARKER not in captured.err + + +async def test_normal_request_is_not_affected_by_timeout() -> None: + async with running_app(request_timeout_seconds=5.0) as client: + alice, chat = await prepared(client) + assert (await post(client, chat, alice, "обычная запись")).status_code == 201 + + +async def test_slow_event_handler_does_not_trigger_timeout() -> None: + async with running_app(request_timeout_seconds=0.3) as client: + alice, chat = await prepared(client) + blocked = asyncio.Event() + bus = await resolve(client, EventBus) + + async def stall(_event: MessagePosted) -> None: + await blocked.wait() + + bus.subscribe(MessagePosted, stall) + response = await post(client, chat, alice, "ответ не ждёт обработчик") + blocked.set() + assert response.status_code == 201 + + +async def test_healthcheck_stays_fast(client: AsyncClient) -> None: + loop = asyncio.get_running_loop() + started = loop.time() + assert (await client.get("/health/live")).status_code == 200 + assert loop.time() - started < 1.0 diff --git a/student-tests/api/test_wire_format.py b/student-tests/api/test_wire_format.py new file mode 100644 index 00000000..6f1f2983 --- /dev/null +++ b/student-tests/api/test_wire_format.py @@ -0,0 +1,68 @@ +import json +import re +from datetime import UTC, datetime +from typing import Any + +import pytest +from httpx import Response + +from conftest import bearer, login, new_user, running_app +from messenger.shared.infrastructure.clock import MonotonicUtcClock + +RFC3339_UTC = re.compile(r"\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z\Z") +MOMENTS = [ + datetime(2026, 10, 12, 8, 49, 2, tzinfo=UTC), + datetime(2026, 10, 12, 8, 49, 2, 120, tzinfo=UTC), +] + + +def assert_wire(response: Response, expected: dict[str, Any]) -> None: + assert ( + response.content == json.dumps(expected, ensure_ascii=False, separators=(",", ":")).encode() + ) + + +@pytest.mark.parametrize("moment", MOMENTS, ids=["whole-second", "microseconds"]) +async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment: datetime) -> None: + monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self: moment) + stamp = moment.isoformat().replace("+00:00", "Z") + assert RFC3339_UTC.match(stamp) + async with running_app() as http: + body = new_user("wire") + response = await http.post("/api/v1/users", json=body) + user_id = response.json()["id"] + user = { + "id": user_id, + "username": body["username"], + "display_name": body["display_name"], + "created_at": stamp, + } + assert_wire(response, user) + session = await login(http, body["username"]) + headers = bearer(session["token"]) + assert session["user"] == user + assert_wire(await http.get("/api/v1/users/me", headers=headers), user) + + response = await http.post( + "/api/v1/chats", json={"title": "Чат", "member_ids": [user_id]}, headers=headers + ) + chat_id = response.json()["id"] + chat = {"id": chat_id, "title": "Чат", "member_ids": [user_id], "created_at": stamp} + assert_wire(response, chat) + assert_wire(await http.get(f"/api/v1/chats/{chat_id}", headers=headers), chat) + listed = await http.get("/api/v1/chats", headers=headers) + assert_wire(listed, {"items": [chat], "next_cursor": None}) + + path = f"/api/v1/chats/{chat_id}/messages" + sent = {**headers, "Idempotency-Key": "wire-1"} + response = await http.post(path, json={"text": "привет"}, headers=sent) + message = { + "id": response.json()["id"], + "chat_id": chat_id, + "sender_id": user_id, + "text": "привет", + "created_at": stamp, + } + assert_wire(response, message) + history = await http.get(path, headers=headers) + assert_wire(history, {"items": [message], "next_cursor": None}) diff --git a/student-tests/conftest.py b/student-tests/conftest.py new file mode 100644 index 00000000..a109998a --- /dev/null +++ b/student-tests/conftest.py @@ -0,0 +1,208 @@ +import asyncio +import re +import subprocess +import time +from base64 import b64encode +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import asyncpg +import pytest +from fastapi import FastAPI +from httpx import ASGITransport, AsyncClient + +from messenger.identity.config import IdentitySettings +from messenger.main import create_app +from messenger.messaging.config import MessagingSettings +from messenger.migrate import migrate +from messenger.shared.config import PlatformSettings +from messenger.shared.entrypoints.config import TransportSettings + +ROOT = Path(__file__).resolve().parents[1] +POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)") +VALKEY_IMAGE = re.compile(r"image: (valkey/valkey:\S+)") +STARTUP_SECONDS = 60 +PASSWORD = "Пароль-для-тестов-01" +APPS: dict[int, FastAPI] = {} +TOKENS: dict[str, str] = {} +DATABASE: dict[str, str] = {} + + +def docker(*args: str) -> str: + done = subprocess.run(["docker", *args], check=True, capture_output=True, text=True) + return done.stdout.strip() + + +async def migrated(dsn: str) -> None: + deadline = time.monotonic() + STARTUP_SECONDS + while True: + try: + await migrate(dsn) + return + except OSError, asyncpg.PostgresError, asyncpg.InterfaceError: + if time.monotonic() > deadline: + raise + await asyncio.sleep(0.5) + + +@pytest.fixture(autouse=True) +def database_for_api(request: pytest.FixtureRequest) -> None: + if "api" in request.node.path.parts: + request.getfixturevalue("database") + + +def image(pattern: re.Pattern[str]) -> str: + found = pattern.search((ROOT / "compose.yaml").read_text()) + assert found is not None + return found[1] + + +def published(name: str, port: int) -> int: + return int(docker("port", name, f"{port}/tcp").splitlines()[0].rsplit(":", 1)[1]) + + +def container(name: str, *args: str) -> None: + docker("run", "-d", "--rm", "--name", name, *args) + + +def answering(name: str, *probe: str) -> bool: + done = subprocess.run(["docker", "exec", name, *probe], capture_output=True, check=False) + return done.returncode == 0 and b"PONG" in done.stdout + + +@pytest.fixture(scope="session") +def valkey() -> Iterator[dict[str, str]]: + name = f"mtusi-lab4-test-valkey-{uuid4().hex[:8]}" + container(name, "-p", "127.0.0.1::6379", image(VALKEY_IMAGE)) + try: + deadline = time.monotonic() + STARTUP_SECONDS + while not answering(name, "valkey-cli", "ping"): + assert time.monotonic() < deadline + time.sleep(0.2) + yield {"name": name, "url": f"redis://127.0.0.1:{published(name, 6379)}/0"} + finally: + subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False) + + +@pytest.fixture(scope="session") +def database() -> Iterator[str]: + name = f"mtusi-lab4-test-{uuid4().hex[:8]}" + tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"] + environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"] + container(name, *environment, "-p", "127.0.0.1::5432", image(POSTGRES_IMAGE), *tuning) + try: + dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger" + asyncio.run(migrated(dsn)) + DATABASE["url"] = dsn + yield dsn + finally: + subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False) + + +def split_settings(**overrides: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "log_level": "CRITICAL", + "cursor_secret": "test-secret-for-cursors", + "database_url": DATABASE.get("url", "postgresql://unused@127.0.0.1:1/unused"), + } + base.update(overrides) + groups = { + "platform": PlatformSettings, + "transport": TransportSettings, + "identity": IdentitySettings, + "messaging": MessagingSettings, + } + return { + name: kind.model_validate( + {key: value for key, value in base.items() if key in kind.model_fields} + ) + for name, kind in groups.items() + } + + +@asynccontextmanager +async def running_app(**overrides: Any) -> AsyncIterator[AsyncClient]: + app = create_app(**split_settings(**overrides)) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http, + ): + APPS[id(http)] = app + try: + yield http + finally: + APPS.pop(id(http), None) + + +async def resolve[DependencyT](http: AsyncClient, dependency: type[DependencyT]) -> DependencyT: + return await APPS[id(http)].state.dishka_container.get(dependency) + + +@pytest.fixture +async def client() -> AsyncIterator[AsyncClient]: + async with running_app() as http: + yield http + + +async def scalar(sql: str, *args: Any) -> Any: + connection = await asyncpg.connect(DATABASE["url"]) + try: + return await connection.fetchval(sql, *args) + finally: + await connection.close() + + +def basic(username: str, password: str) -> dict[str, str]: + encoded = b64encode(f"{username}:{password}".encode()).decode() + return {"Authorization": f"Basic {encoded}"} + + +def bearer(token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {token}"} + + +def new_user(label: str, password: str = PASSWORD) -> dict[str, str]: + return { + "username": f"u_{label}_{uuid4().hex[:12]}", + "display_name": f"Студент {label}", + "password": password, + } + + +async def login(http: AsyncClient, username: str, password: str = PASSWORD) -> dict[str, Any]: + response = await http.post("/api/v1/auth/sessions", headers=basic(username, password)) + assert response.status_code == 201, response.text + return response.json() + + +async def register(http: AsyncClient, label: str, password: str = PASSWORD) -> dict[str, Any]: + body = new_user(label, password) + response = await http.post("/api/v1/users", json=body) + assert response.status_code == 201, response.text + user = response.json() + TOKENS[user["id"]] = (await login(http, body["username"], password))["token"] + return user + + +async def make_chat( + http: AsyncClient, owner: dict[str, Any], *members: dict[str, Any] +) -> dict[str, Any]: + member_ids = [owner["id"], *[member["id"] for member in members]] + response = await http.post( + "/api/v1/chats", + json={"title": "Тестовый чат", "member_ids": member_ids}, + headers=actor(owner), + ) + assert response.status_code == 201, response.text + return response.json() + + +def actor(user: dict[str, Any]) -> dict[str, str]: + return bearer(TOKENS[user["id"]]) + + +def keyed(user: dict[str, Any], key: str | None = None) -> dict[str, str]: + return {**actor(user), "Idempotency-Key": key or uuid4().hex} diff --git a/student-tests/fakes.py b/student-tests/fakes.py new file mode 100644 index 00000000..3043b0af --- /dev/null +++ b/student-tests/fakes.py @@ -0,0 +1,23 @@ +from datetime import datetime, timedelta +from typing import Any + + +class NullLogger: + __slots__ = () + + def info(self, event: str, /, **fields: Any) -> None: ... + + def warning(self, event: str, /, **fields: Any) -> None: ... + + def error(self, event: str, /, **fields: Any) -> None: ... + + +class FrozenClock: + __slots__ = ("_current",) + + def __init__(self, start: datetime) -> None: + self._current = start + + def now(self) -> datetime: + self._current += timedelta(microseconds=1) + return self._current diff --git a/student-tests/stack/test_faults.py b/student-tests/stack/test_faults.py new file mode 100644 index 00000000..6e78de49 --- /dev/null +++ b/student-tests/stack/test_faults.py @@ -0,0 +1,229 @@ +import asyncio +from collections.abc import AsyncIterator +from uuid import uuid4 + +import pytest +from httpx import AsyncClient + +from stand import ( + BASE_URL, + BASIC, + BEARER, + basic, + bearer, + compose, + enroll, + inside_replica, + lb_up, + new_user, + psql, + report, + started_at, + timed, + valkey, + wait_ready, + waited, +) + +pytestmark = pytest.mark.stack +RACERS = 50 + + +@pytest.fixture +async def http() -> AsyncIterator[AsyncClient]: + async with AsyncClient(base_url=BASE_URL, timeout=10, trust_env=False) as client: + yield client + + +async def test_registration_race_yields_exactly_one_user(http: AsyncClient) -> None: + body = new_user("race") + responses = await asyncio.gather( + *(http.post("/api/v1/users", json=body) for _ in range(RACERS)) + ) + codes = sorted(response.status_code for response in responses) + print(f"гонка {RACERS} регистраций: 201×{codes.count(201)}, 409×{codes.count(409)}") + assert codes.count(201) == 1 + assert codes.count(409) == RACERS - 1 + assert psql("SELECT count(*) FROM users WHERE username = :'name'", name=body["username"]) == "1" + + +async def test_chat_creation_rolls_back_on_unknown_member(http: AsyncClient) -> None: + alice, token = await enroll(http, "alice") + title = f"Откат {uuid4().hex}" + response = await http.post( + "/api/v1/chats", + json={"title": title, "member_ids": [alice["id"], str(uuid4())]}, + headers=bearer(token), + ) + print(f"чат с несуществующим участником: {response.status_code}") + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + assert psql("SELECT count(*) FROM chats WHERE title = :'title'", title=title) == "0" + members = "SELECT count(*) FROM chat_members WHERE user_id = :'id'::uuid" + assert psql(members, id=alice["id"]) == "0" + + +async def test_wrong_password_and_unknown_user_get_same_basic_challenge(http: AsyncClient) -> None: + alice, _ = await enroll(http, "alice") + wrong, wrong_time = await timed( + http.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20)) + ) + unknown, unknown_time = await timed( + http.post("/api/v1/auth/sessions", headers=basic(f"u_ghost_{uuid4().hex[:8]}")) + ) + report("неверный пароль", wrong, wrong_time) + report("неизвестный пользователь", unknown, unknown_time) + for response in (wrong, unknown): + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == BASIC + assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"] + + +async def test_logout_then_token_is_dead(http: AsyncClient) -> None: + _, token = await enroll(http, "alice") + assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 200 + logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token)) + after = await http.get("/api/v1/users/me", headers=bearer(token)) + again = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token)) + print(f"logout: {logout.status_code}, затем {after.status_code}, повтор {again.status_code}") + assert (logout.status_code, logout.content) == (204, b"") + assert after.status_code == again.status_code == 401 + assert again.headers["WWW-Authenticate"] == BEARER + + +async def test_valkey_serves_repeated_checks(http: AsyncClient) -> None: + _, token = await enroll(http, "cache") + await http.get("/api/v1/users/me", headers=bearer(token)) + before = int(valkey("info stats").split("keyspace_hits:")[1].split()[0]) + for _ in range(5): + assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 200 + after = int(valkey("info stats").split("keyspace_hits:")[1].split()[0]) + print(f"5 проверок токена: keyspace_hits {before} → {after}") + assert after - before >= 5 + + +async def test_valkey_stopped_is_bypassed_but_logout_waits(http: AsyncClient) -> None: + user, token = await enroll(http, "nocache") + try: + compose("stop", "valkey") + me, me_time = await timed(http.get("/api/v1/users/me", headers=bearer(token))) + stranger, stranger_time = await timed( + http.get("/api/v1/users/me", headers=bearer("x" * 43)) + ) + ready = await http.get("/health/ready") + login = await http.post("/api/v1/auth/sessions", headers=basic(user["username"])) + logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token)) + report("valkey остановлен, действующий токен", me, me_time) + report("valkey остановлен, неизвестный токен", stranger, stranger_time) + codes = (ready.status_code, login.status_code, logout.status_code) + print("valkey остановлен: ready {}, вход {}, выход {}".format(*codes)) + assert me.json() == user and me_time < 1 + assert stranger.status_code == 401 and stranger.headers["WWW-Authenticate"] == BEARER + assert ready.status_code == 200 + assert login.status_code == 201 + assert logout.status_code == 503 and logout.json()["error"]["code"] == "unavailable" + finally: + compose("start", "valkey") + compose("up", "-d", "--wait", "valkey") + await asyncio.sleep(1.2) + retried = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token)) + print(f"valkey снова запущен: повторный выход {retried.status_code}") + assert retried.status_code == 204 + assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 401 + + +async def test_valkey_restart_keeps_cache_and_revocations(http: AsyncClient) -> None: + _, alive = await enroll(http, "alive") + _, revoked = await enroll(http, "revoked") + assert (await http.get("/api/v1/users/me", headers=bearer(alive))).status_code == 200 + assert (await http.get("/api/v1/users/me", headers=bearer(revoked))).status_code == 200 + assert ( + await http.delete("/api/v1/auth/sessions/current", headers=bearer(revoked)) + ).status_code == 204 + keys_before = valkey("dbsize") + compose("restart", "valkey") + compose("up", "-d", "--wait", "valkey") + keys_after = valkey("dbsize") + await asyncio.sleep(1.2) + still = await http.get("/api/v1/users/me", headers=bearer(alive)) + dead = await http.get("/api/v1/users/me", headers=bearer(revoked)) + print(f"рестарт valkey: ключей {keys_before} → {keys_after}") + print(f"рестарт valkey: живой {still.status_code}, отозванный {dead.status_code}") + assert keys_after == keys_before + assert still.status_code == 200 + assert dead.status_code == 401 + + +async def test_valkey_flushall_loses_nothing(http: AsyncClient) -> None: + _, alive = await enroll(http, "alive") + _, revoked = await enroll(http, "revoked") + assert ( + await http.delete("/api/v1/auth/sessions/current", headers=bearer(revoked)) + ).status_code == 204 + valkey("flushall") + still = await http.get("/api/v1/users/me", headers=bearer(alive)) + dead = await http.get("/api/v1/users/me", headers=bearer(revoked)) + print(f"FLUSHALL: живой {still.status_code}, отозванный {dead.status_code}") + assert still.status_code == 200 + assert dead.status_code == 401 + + +async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient) -> None: + user, token = await enroll(http, "nodb") + assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 200 + api_started = started_at("api") + try: + compose("stop", "postgres") + checks = { + "ready": await timed(http.get("/health/ready")), + "me": await timed(http.get("/api/v1/users/me", headers=bearer(token))), + "stranger": await timed(http.get("/api/v1/users/me", headers=bearer("x" * 43))), + "login": await timed( + http.post("/api/v1/auth/sessions", headers=basic(user["username"])) + ), + "register": await timed(http.post("/api/v1/users", json=new_user("nodb"))), + } + live_inside = inside_replica("/health/live") + excluded = await waited(lambda: lb_up() == 0, 5) + through_lb = await http.get("/health/live") + for name, (response, elapsed) in checks.items(): + report(f"postgres остановлен, {name}", response, elapsed) + assert elapsed < 2 + assert response.status_code == 503 + assert response.json()["error"]["code"] == "unavailable" + print( + f"live внутри реплики {live_inside}; LB исключил все реплики ещё через {excluded:.2f} с" + ) + report("live через LB без реплик", through_lb, 0) + assert live_inside == 200 + assert lb_up() == 0 + assert excluded < 2 + assert through_lb.status_code == 503 + assert through_lb.json()["error"]["request_id"] == through_lb.headers["X-Request-Id"] + assert "X-Instance-Id" not in through_lb.headers + finally: + compose("start", "postgres") + recovered = await wait_ready(http) + await waited(lambda: lb_up() == len(compose("ps", "-q", "api").split())) + me = await http.get("/api/v1/users/me", headers=bearer(token)) + print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}") + assert me.json() == user + assert started_at("api") == api_started + + +async def test_api_restart_keeps_session_without_extending_it(http: AsyncClient) -> None: + body = new_user("restart") + assert (await http.post("/api/v1/users", json=body)).status_code == 201 + session = (await http.post("/api/v1/auth/sessions", headers=basic(body["username"]))).json() + compose("restart", "api") + recovered = await wait_ready(http) + me = await http.get("/api/v1/users/me", headers=bearer(session["token"])) + stored = psql( + "SELECT to_char(expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') " + "FROM sessions s JOIN users u ON u.id = s.user_id WHERE u.username = :'name'", + name=body["username"], + ) + print(f"рестарт api: готовность через {recovered:.1f} с, токен {me.status_code}") + print(f"expires_at при входе {session['expires_at']}, в БД после рестарта {stored}") + assert me.status_code == 200 + assert stored.rstrip("Z").rstrip("0") == session["expires_at"].rstrip("Z").rstrip("0") diff --git a/student-tests/stand.py b/student-tests/stand.py new file mode 100644 index 00000000..7264b1d2 --- /dev/null +++ b/student-tests/stand.py @@ -0,0 +1,132 @@ +import asyncio +import csv +import os +import subprocess +import time +from base64 import b64encode +from collections.abc import Awaitable, Callable +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import httpx +from httpx import AsyncClient, Response, TransportError + +ROOT = Path(__file__).resolve().parents[1] +BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080") +PASSWORD = "Пароль-для-стенда-01" +BASIC = 'Basic realm="messenger", charset="UTF-8"' +BEARER = 'Bearer realm="messenger"' +VALKEY_AUTH = 'REDISCLI_AUTH="$(sed -n "s/^requirepass //p" /run/secrets/valkey.conf)"' + + +def compose(*args: str, stdin: str | None = None) -> str: + done = subprocess.run( + ["docker", "compose", *args], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + input=stdin, + ) + return done.stdout.strip() + + +def psql(sql: str, **variables: str) -> str: + assigned = [item for name, value in variables.items() for item in ("-v", f"{name}={value}")] + command = ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tA"] + return compose(*command, *assigned, stdin=sql) + + +def valkey(command: str) -> str: + return compose("exec", "-T", "valkey", "sh", "-c", f"{VALKEY_AUTH} valkey-cli {command}") + + +def started_at(service: str) -> str: + return subprocess.run( + [ + "docker", + "inspect", + "--format", + "{{.State.StartedAt}}", + *compose("ps", "-q", service).split(), + ], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + +def inside_replica(path: str) -> int: + replica = compose("ps", "-q", "api").split()[0] + probe = f"import urllib.request as u;print(u.urlopen('http://127.0.0.1:8080{path}').status)" + done = subprocess.run( + ["docker", "exec", replica, "python", "-c", probe], + capture_output=True, + text=True, + check=False, + ) + return int(done.stdout.strip() or 0) + + +def lb_up() -> int: + stats = httpx.get(f"http://{compose('port', 'lb', '8404')}/stats;csv", timeout=2).text + rows = csv.DictReader(stats.lstrip("# ").splitlines()) + servers = (r for r in rows if r["pxname"] == "api" and r["svname"] != "BACKEND") + return sum(1 for r in servers if r["status"].startswith("UP")) + + +def basic(username: str, password: str = PASSWORD) -> dict[str, str]: + return {"Authorization": "Basic " + b64encode(f"{username}:{password}".encode()).decode()} + + +def bearer(token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {token}"} + + +def new_user(label: str) -> dict[str, str]: + return { + "username": f"u_{label}_{uuid4().hex[:12]}", + "display_name": f"Стенд {label}", + "password": PASSWORD, + } + + +async def enroll(http: AsyncClient, label: str) -> tuple[dict[str, Any], str]: + body = new_user(label) + created = await http.post("/api/v1/users", json=body) + assert created.status_code == 201, created.text + session = await http.post("/api/v1/auth/sessions", headers=basic(body["username"])) + assert session.status_code == 201, session.text + return created.json(), session.json()["token"] + + +async def timed(call: Awaitable[Response]) -> tuple[Response, float]: + started = time.perf_counter() + response = await call + return response, time.perf_counter() - started + + +async def wait_ready(http: AsyncClient, seconds: float = 60) -> float: + started = time.perf_counter() + while time.perf_counter() - started < seconds: + try: + if (await http.get("/health/ready")).status_code == 200: + return time.perf_counter() - started + except TransportError: + pass + await asyncio.sleep(0.25) + raise AssertionError("стенд не вернулся в готовность") + + +async def waited(condition: Callable[[], bool], seconds: float = 30) -> float: + started = time.perf_counter() + while time.perf_counter() - started < seconds: + if condition(): + return time.perf_counter() - started + await asyncio.sleep(0.05) + raise AssertionError("условие не выполнилось за отведённое время") + + +def report(event: str, response: Response, elapsed: float) -> None: + print(f"{event}: {response.status_code} за {elapsed:.3f} с") diff --git a/student-tests/unit/test_authentication.py b/student-tests/unit/test_authentication.py new file mode 100644 index 00000000..6837b434 --- /dev/null +++ b/student-tests/unit/test_authentication.py @@ -0,0 +1,64 @@ +from base64 import b64encode + +import pytest + +from messenger.identity.entrypoints.authentication import ( + basic_credentials, + bearer_token, + challenge_for, +) + + +def encoded(raw: bytes) -> str: + return "Basic " + b64encode(raw).decode() + + +def test_basic_splits_on_first_colon() -> None: + assert basic_credentials(encoded(b"alice:pa:ss:word")) == ("alice", "pa:ss:word") + + +def test_basic_decodes_utf8_password() -> None: + assert basic_credentials(encoded("alice:пароль👋".encode())) == ("alice", "пароль👋") + + +def test_basic_scheme_is_case_insensitive() -> None: + assert basic_credentials("bAsIc " + b64encode(b"alice:secret").decode()) == ("alice", "secret") + + +@pytest.mark.parametrize( + "raw", + [ + "", + "Basic", + "Basic ", + "Basic !!!not-base64!!!", + "Basic YWxpY2U", + encoded(b"no-colon-here"), + encoded("алиса:пароль".encode()), + encoded(b"alice:\xff\xfe"), + "Bearer " + b64encode(b"alice:secret").decode(), + ], +) +def test_basic_rejects_malformed(raw: str) -> None: + assert basic_credentials(raw) is None + + +def test_bearer_accepts_token68() -> None: + assert bearer_token("Bearer abc-DEF_123.~+/==") == "abc-DEF_123.~+/==" + assert bearer_token("bearer token") == "token" + + +@pytest.mark.parametrize("raw", ["", "Bearer", "Bearer ", "Bearer a b", "Basic abc", "x" * 40]) +def test_bearer_rejects_malformed(raw: str) -> None: + assert bearer_token(raw) is None + + +def test_bearer_rejects_oversized_token() -> None: + assert bearer_token("Bearer " + "x" * 513) is None + + +def test_challenge_depends_only_on_path() -> None: + assert challenge_for("/api/v1/auth/sessions") == 'Basic realm="messenger", charset="UTF-8"' + assert challenge_for("/api/v1/auth/sessions/") == 'Basic realm="messenger", charset="UTF-8"' + assert challenge_for("/api/v1/auth/sessions/current") == 'Bearer realm="messenger"' + assert challenge_for("/api/v1/users/me") == 'Bearer realm="messenger"' diff --git a/student-tests/unit/test_cursor.py b/student-tests/unit/test_cursor.py new file mode 100644 index 00000000..5458b9ee --- /dev/null +++ b/student-tests/unit/test_cursor.py @@ -0,0 +1,56 @@ +from datetime import UTC, datetime +from uuid import uuid4 + +import pytest + +from messenger.messaging.domain.errors import InvalidPageRequest +from messenger.messaging.infrastructure.cursor import SignedCursorCodec + +KEY = (datetime(2026, 5, 17, 12, 30, 45, 123456, tzinfo=UTC), uuid4().int) + + +def codec(secret: bytes = b"secret-for-tests") -> SignedCursorCodec: + return SignedCursorCodec(secret) + + +def test_roundtrip_preserves_key() -> None: + subject = codec() + assert subject.decode("messages:a", subject.encode("messages:a", KEY)) == KEY + + +def test_cursor_is_opaque() -> None: + encoded = codec().encode("messages:a", KEY) + assert "2026" not in encoded + assert str(KEY[1]) not in encoded + + +def test_cursor_from_another_scope_is_rejected() -> None: + subject = codec() + encoded = subject.encode("messages:chat-one", KEY) + with pytest.raises(InvalidPageRequest): + subject.decode("messages:chat-two", encoded) + + +def test_forged_cursor_is_rejected() -> None: + encoded = codec(b"one-secret").encode("messages:a", KEY) + with pytest.raises(InvalidPageRequest): + codec(b"another-secret").decode("messages:a", encoded) + + +@pytest.mark.parametrize( + "raw", + ["", "garbage", "1.2.3", "2.1.2.3", "1.notanumber.ff.AAAA", "1.1.zz.AAAA"], +) +def test_broken_cursor_is_rejected(raw: str) -> None: + with pytest.raises(InvalidPageRequest): + codec().decode("messages:a", raw) + + +def test_tampered_payload_is_rejected() -> None: + subject = codec() + encoded = subject.encode("messages:a", KEY) + head, _, signature = encoded.rpartition(".") + version, micros, identifier = head.split(".") + tampered = f"{version}.{int(micros) + 1}.{identifier}.{signature}" + with pytest.raises(InvalidPageRequest): + subject.decode("messages:a", tampered) diff --git a/student-tests/unit/test_domain.py b/student-tests/unit/test_domain.py new file mode 100644 index 00000000..c0706583 --- /dev/null +++ b/student-tests/unit/test_domain.py @@ -0,0 +1,197 @@ +from dataclasses import fields +from datetime import UTC, datetime, timedelta +from itertools import pairwise +from uuid import uuid4 + +import pytest + +from messenger.identity.domain.errors import InvalidUserData +from messenger.identity.domain.models import Session, User, token_digest +from messenger.identity.domain.values import DisplayName, Password, Username +from messenger.messaging.domain.errors import ( + ChatNotFound, + IdempotencyConflict, + InvalidChatData, + InvalidMessageText, +) +from messenger.messaging.domain.models import Chat, Receipt +from messenger.messaging.domain.values import MessageText +from messenger.shared.infrastructure.clock import MonotonicUtcClock + +MOMENT = datetime(2026, 1, 1, tzinfo=UTC) + + +@pytest.mark.parametrize( + "raw", ["ab", "a" * 33, "Alice", "alice-01", "алиса", "", "a b", "alice\n", "alice\r\n"] +) +def test_username_rejects_invalid(raw: str) -> None: + with pytest.raises(InvalidUserData): + Username(raw) + + +@pytest.mark.parametrize("raw", ["abc", "a_b_9", "a" * 32]) +def test_username_accepts_valid(raw: str) -> None: + assert Username(raw).value == raw + + +@pytest.mark.parametrize("raw", ["", " ", "\t\n", "x" * 101]) +def test_display_name_rejects_invalid(raw: str) -> None: + with pytest.raises(InvalidUserData): + DisplayName(raw) + + +@pytest.mark.parametrize("raw", ["", " " * 20, "x" * 11, "x" * 129, "\t" * 12]) +def test_password_rejects_invalid(raw: str) -> None: + with pytest.raises(InvalidUserData): + Password(raw) + + +@pytest.mark.parametrize("raw", ["x" * 12, "п" * 128, "пароль:с:двоеточием", "👋" * 12]) +def test_password_counts_code_points(raw: str) -> None: + assert Password(raw).value == raw + + +def test_password_is_not_printed() -> None: + assert "секретный-пароль" not in repr(Password("секретный-пароль")) + + +def test_session_token_is_opaque_and_stored_as_digest() -> None: + user_id = uuid4() + token, session = Session.issue(user_id=user_id, issued_at=MOMENT, ttl=timedelta(hours=1)) + assert len(token) >= 43 + assert str(user_id) not in token + assert session.token_hash == token_digest(token) + assert len(session.token_hash) == 32 + assert session.expires_at == MOMENT + timedelta(hours=1) + assert token not in repr(session) + + +def test_session_tokens_are_unique() -> None: + tokens = { + Session.issue(user_id=uuid4(), issued_at=MOMENT, ttl=timedelta(seconds=1))[0] + for _ in range(1000) + } + assert len(tokens) == 1000 + + +def test_message_text_counts_code_points_not_bytes() -> None: + emoji = "👋" * 4000 + assert len(MessageText(emoji).value) == 4000 + with pytest.raises(InvalidMessageText): + MessageText("👋" * 4001) + + +def test_message_text_rejects_blank() -> None: + for raw in ("", " ", "\n\t "): + with pytest.raises(InvalidMessageText): + MessageText(raw) + + +def make_chat(*members: object) -> Chat: + ids = [uuid4() for _ in members] if members else [uuid4()] + return Chat.create( + chat_id=uuid4(), + title="Чат", + member_ids=ids, + creator_id=ids[0], + created_at=MOMENT, + ) + + +def test_chat_requires_creator_in_members() -> None: + members = [uuid4(), uuid4()] + with pytest.raises(InvalidChatData): + Chat.create( + chat_id=uuid4(), + title="Чат", + member_ids=members, + creator_id=uuid4(), + created_at=MOMENT, + ) + + +def test_chat_rejects_duplicate_members() -> None: + same = uuid4() + with pytest.raises(InvalidChatData): + Chat.create( + chat_id=uuid4(), + title="Чат", + member_ids=[same, same], + creator_id=same, + created_at=MOMENT, + ) + + +def test_chat_rejects_more_than_hundred_members() -> None: + members = [uuid4() for _ in range(101)] + with pytest.raises(InvalidChatData): + Chat.create( + chat_id=uuid4(), + title="Чат", + member_ids=members, + creator_id=members[0], + created_at=MOMENT, + ) + + +def test_outsider_cannot_post() -> None: + chat = make_chat(1) + with pytest.raises(ChatNotFound): + chat.post(message_id=uuid4(), sender_id=uuid4(), text="привет", now=MOMENT) + + +def test_post_never_moves_history_back() -> None: + chat = make_chat(1) + sender = chat.member_ids[0] + first = chat.post( + message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT + timedelta(seconds=1) + ) + second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=MOMENT) + assert second.created_at == first.created_at + timedelta(microseconds=1) + assert chat.last_message_at == second.created_at + + +def test_post_keeps_clock_when_it_is_ahead() -> None: + chat = make_chat(1) + sender = chat.member_ids[0] + first = chat.post(message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT) + later = MOMENT + timedelta(seconds=5) + second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=later) + assert first.created_at == MOMENT + assert second.created_at == later + + +def test_post_validates_membership_before_text() -> None: + chat = make_chat(1) + with pytest.raises(ChatNotFound): + chat.post(message_id=uuid4(), sender_id=uuid4(), text="", now=MOMENT) + + +def test_receipt_replays_only_the_same_request() -> None: + chat = make_chat(1) + message = chat.post(message_id=uuid4(), sender_id=chat.member_ids[0], text="раз", now=MOMENT) + receipt = Receipt("key-1", b"a" * 32, message) + assert receipt.replay(b"a" * 32) is message + with pytest.raises(IdempotencyConflict): + receipt.replay(b"b" * 32) + + +def test_user_registration_emits_event() -> None: + user, event = User.register( + user_id=uuid4(), + username=Username("alice_01"), + display_name=DisplayName("Алиса"), + password_hash="$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA", + registered_at=MOMENT, + ) + assert event.name == "user.registered" + assert {field.name for field in fields(event)} == {"name", "user_id", "registered_at"} + assert user.created_at == MOMENT + assert "argon2id" not in repr(user) + + +def test_clock_is_strictly_increasing() -> None: + clock = MonotonicUtcClock() + stamps = [clock.now() for _ in range(1000)] + assert all(later > earlier for earlier, later in pairwise(stamps)) + assert all(stamp.tzinfo is UTC for stamp in stamps) diff --git a/student-tests/unit/test_timeouts.py b/student-tests/unit/test_timeouts.py new file mode 100644 index 00000000..4050372a --- /dev/null +++ b/student-tests/unit/test_timeouts.py @@ -0,0 +1,60 @@ +import re +from pathlib import Path +from typing import Any + +import yaml + +from messenger.shared.infrastructure.postgres import PING_TIMEOUT_SECONDS + +ROOT = Path(__file__).resolve().parents[2] +DEFAULT = re.compile(r"\$\{\w+:?-([^}]*)\}") +UNITS = {"ms": 0.001, "s": 1.0, "": 1.0} + + +def seconds(value: object) -> float: + found = re.fullmatch(r"([\d.]+)(ms|s|)", str(value)) + assert found is not None, value + return float(found[1]) * UNITS[found[2]] + + +def services() -> dict[str, Any]: + return yaml.safe_load(DEFAULT.sub(r"\1", (ROOT / "compose.yaml").read_text()))["services"] + + +def balancer() -> dict[str, float]: + text = (ROOT / "infra/haproxy/haproxy.cfg").read_text() + found = { + f"timeout {name}": seconds(value) + for name, value in re.findall(r"timeout ([\w-]+) (\S+)\n", text) + } + found["hard-stop-after"] = seconds(re.findall(r"hard-stop-after (\S+)", text)[0]) + check = re.findall(r"default-server .*", text)[0] + for key in ("inter", "fastinter", "fall", "rise"): + found[key] = seconds(re.findall(rf"\b{key} (\S+)", check)[0]) + return found + + +def test_timeouts_shrink_inwards_and_shutdown_fits_the_stop_budget() -> None: + lb, stand = balancer(), services() + api = {k: seconds(v) for k, v in stand["api"]["environment"].items() if k.endswith("SECONDS")} + hook = seconds( + re.findall(r"STOP_TIMEOUT:-(\d+)", (ROOT / "scripts/stop-one.sh").read_text())[0] + ) + grace = seconds(stand["api"]["stop_grace_period"]) + detection = lb["inter"] + (lb["fall"] - 1) * lb["fastinter"] + hung = detection + lb["fall"] * lb["timeout check"] + database = api["DB_ACQUIRE_TIMEOUT_SECONDS"] + api["DB_COMMAND_TIMEOUT_SECONDS"] + drain, shutdown = api["DRAIN_SECONDS"], api["SHUTDOWN_TIMEOUT_SECONDS"] + print( + f"обнаружение {detection} с (зависание {hung} с), окно {drain} с, остановка {shutdown} с," + f" хук {hook} с, stop_grace_period {grace} с; LB server {lb['timeout server']} с >" + f" запрос {api['REQUEST_TIMEOUT_SECONDS']} с > БД {database} с;" + f" readiness {2 * PING_TIMEOUT_SECONDS} с < check {lb['timeout check']} с" + ) + assert lb["timeout server"] > api["REQUEST_TIMEOUT_SECONDS"] > database + assert lb["timeout check"] > 2 * PING_TIMEOUT_SECONDS + assert drain > detection + assert shutdown - drain >= database + assert shutdown < hook < grace < 10 + assert lb["hard-stop-after"] < seconds(stand["lb"]["stop_grace_period"]) + assert (detection, hung) == (1.5, 3.5) diff --git a/uv.lock b/uv.lock new file mode 100644 index 00000000..aa04401d --- /dev/null +++ b/uv.lock @@ -0,0 +1,763 @@ +version = 1 +revision = 5 +requires-python = "==3.14.*" + +[[package]] +name = "annotated-doc" +version = "0.0.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/8e/38aa427ed5402449e226975b649c5dc73ccadfefeb95e6aecb8f8ea4b6b6/annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb", size = 10758, upload-time = "2026-07-28T13:50:58.129Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302, upload-time = "2026-07-28T13:50:57.239Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "anyio" +version = "4.15.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, +] + +[[package]] +name = "argon2-cffi" +version = "25.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "argon2-cffi-bindings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" }, +] + +[[package]] +name = "argon2-cffi-bindings" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0b/43/bb8b6e8708d49a5ab36781333af092d9f483b198a2710d01281204640055/argon2_cffi_bindings-26.1.0.tar.gz", hash = "sha256:63505c71542a44b68b1e38060450fb006404170da375feb31af153e7f9c6205d", size = 1790807, upload-time = "2026-08-20T07:44:22.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/d2/0ae991f1b2181e5be49007c574710a800ad36c2978683addb3e67c474e55/argon2_cffi_bindings-26.1.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:21ca0396fe5ec995dd54431c32698189666f9224810acfa752e50d2bd94d9df2", size = 25521, upload-time = "2026-08-20T07:32:43.019Z" }, + { url = "https://files.pythonhosted.org/packages/7e/e4/ad91d8297638aa2258aad4501c306aca99480dfe76ccd638173fa3702db9/argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:78de2d65e0b9ea7ce9d1b1c3e87297b2d7305a02c266ee2a2d6910daddd7ee69", size = 27177, upload-time = "2026-08-20T07:32:44.158Z" }, + { url = "https://files.pythonhosted.org/packages/6f/86/5363df11b86d02cf3662208e7406496327649cc90eb365bf6f4e8a54a41f/argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:27f1821903e2ceadcb88ec2b45ef190897b7682449c772f4d9b53e42c520cf29", size = 26597, upload-time = "2026-08-20T07:32:45.172Z" }, + { url = "https://files.pythonhosted.org/packages/f4/b5/a14dcc592652347dad23ee93b278a4da5d2a25c9ed3ebd10d68eea823a4f/argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d88e5f7e60f28ae0b0cc6b2f16c43e87cd642a196a86f85e0d8bb6fe016fc16d", size = 27403, upload-time = "2026-08-20T07:32:46.13Z" }, + { url = "https://files.pythonhosted.org/packages/b3/81/b4a20d4902af7f796390bf9245ff83c5217dfa7367efa1d14986956c482b/argon2_cffi_bindings-26.1.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:34b7d9c24a4165a2c61cc8ae11d44d48c9ce2830fb536cb7914e11fdd9962728", size = 27132, upload-time = "2026-08-20T07:32:47.13Z" }, + { url = "https://files.pythonhosted.org/packages/7e/1b/c8de358af07b1c490e0fcb863ef98e46ddb486e45567aca5a60bd68d9daa/argon2_cffi_bindings-26.1.0-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:224865cbbcb7a2bd1356741dff12b0134df726b6d44bb7b500df8e303cbd9e81", size = 27588, upload-time = "2026-08-20T07:32:48.087Z" }, + { url = "https://files.pythonhosted.org/packages/48/2f/7ee62a6e79f9309f9d9982d301b22a00010adb580c05c8109b94d7b33de0/argon2_cffi_bindings-26.1.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ffff613aaa9ce6236766e2fc6dc560bb5abde7a2e2416e3db1f9ae395a2b4dd4", size = 26785, upload-time = "2026-08-20T07:32:48.977Z" }, + { url = "https://files.pythonhosted.org/packages/e9/10/960d0ee93d4897741bcaf4799c697dae2d81499f66fd1ed042a7dd54c1f4/argon2_cffi_bindings-26.1.0-cp310-abi3-win32.whl", hash = "sha256:a86c069c91a747a2c4e5c51473590aeb48172fff9b2130d23729a42d98665ecb", size = 23898, upload-time = "2026-08-20T07:32:50.114Z" }, + { url = "https://files.pythonhosted.org/packages/6d/3a/0cc14a05810e6add9bce5e87693334baa2222de5f647fa31781885b6573f/argon2_cffi_bindings-26.1.0-cp310-abi3-win_amd64.whl", hash = "sha256:2c36ff87b5dfaa477d0bd51e9d7f6abdae7c8955d2983c97419085d842154b3e", size = 25730, upload-time = "2026-08-20T07:32:51.091Z" }, + { url = "https://files.pythonhosted.org/packages/4e/db/d83cf2af140547f0b9cdaece05b2dc2dcbf991be4667331d073eff771435/argon2_cffi_bindings-26.1.0-cp310-abi3-win_arm64.whl", hash = "sha256:f9c4420a7a864fe1b86ce35befc95b8e39fb852493b81cf798671ddc265de638", size = 24478, upload-time = "2026-08-20T07:32:52.111Z" }, + { url = "https://files.pythonhosted.org/packages/76/38/de696045960f5b846d428c0fb6c130ed3da87aac2af209b05c193815404c/argon2_cffi_bindings-26.1.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:db0fcd827ca61622a01b220aadfbece01939acf53888f2cb98cd93e9b1e2c97e", size = 15449, upload-time = "2026-08-20T07:32:54.075Z" }, + { url = "https://files.pythonhosted.org/packages/91/0a/c25af768f6b75a5a71e31207f87c540656b2808c015260444a22763221ad/argon2_cffi_bindings-26.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:28524438cd3e723f25412f63d4fd516ff5bae9ae5aa56acbe2a1404398a0cf31", size = 25683, upload-time = "2026-08-20T07:32:55.05Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7e/be212c751ab0bcea7f646615f933bf262e8e50b3f7bef32f861d0a2d066b/argon2_cffi_bindings-26.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ac82fc756a446b6ccd7139ce70efa9d8bbe541e7ad579a12dcb52764b7175c5f", size = 27311, upload-time = "2026-08-20T07:32:56.166Z" }, + { url = "https://files.pythonhosted.org/packages/a6/ee/f84b28e4afd13d3cac36c1d8fa8c239d2dc2c51cd978d02ee5d5ad98d9bb/argon2_cffi_bindings-26.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a4e68eed961a8de6928d1c17ff3dc2a547e0e923c17f8f1cd79fb7bc9502f98", size = 26771, upload-time = "2026-08-20T07:32:57.206Z" }, + { url = "https://files.pythonhosted.org/packages/21/c3/95c07a023691ecd529da9cb6a8f0779e13ebc1bdfaa86d145fdc1c6e7e79/argon2_cffi_bindings-26.1.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:151dfaad9de753f4af2a7854e707e4784f2acc434340ade64239c5b104b2d605", size = 27568, upload-time = "2026-08-20T07:32:58.361Z" }, + { url = "https://files.pythonhosted.org/packages/e6/31/3a18e31406d8694b4d6a31573c3e572fff6bed318bb744453eb653766d22/argon2_cffi_bindings-26.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:061a6919145bbf282ebf1f9c59d3135d4833c25313c8595c0d68cf7712ddfce2", size = 27280, upload-time = "2026-08-20T07:32:59.343Z" }, + { url = "https://files.pythonhosted.org/packages/0b/39/d4be4577e178b2397aa5b5575c8a309bf0da2afe05fe0c72c8f398662d63/argon2_cffi_bindings-26.1.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:62ff20cd130c956c7c9144d5fe35228f98b51c579b2439e988b27ef93e16c02a", size = 27776, upload-time = "2026-08-20T07:33:00.325Z" }, + { url = "https://files.pythonhosted.org/packages/71/47/78f4dd96f7411339f723b96fe24039c1bd5835102b8a5ba71ac4ec712ac7/argon2_cffi_bindings-26.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:19423e5d7ac1cc354baab59eaabf18db2ec04ef6593b5abe5a34f323c4a8f87a", size = 26932, upload-time = "2026-08-20T07:33:01.272Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/96bfd37434cc0a848a9066c291d84b28846c4c9ea289ed9866b1164d622b/argon2_cffi_bindings-26.1.0-cp314-cp314t-win32.whl", hash = "sha256:4f84cdd868978d7b7350a566c254042d44216d9e37f241f3a6d3b1dfebeede35", size = 24878, upload-time = "2026-08-20T07:33:02.189Z" }, + { url = "https://files.pythonhosted.org/packages/f1/42/d8b6810abd9b1bd2f47ebbccf460da59c9f32e94888bea4f7b137d998797/argon2_cffi_bindings-26.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:2b741888c93147444fdfc851abd81cc207f37f7f7da42062a00deb3888e57da8", size = 26656, upload-time = "2026-08-20T07:33:03.222Z" }, + { url = "https://files.pythonhosted.org/packages/a9/d1/095d95eaf2ed1d9f77268cf3291bde148c6cd56121f8db2c74c1ba618a0e/argon2_cffi_bindings-26.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6ab674f668d5962a3a4136ae0812519b0f1586874263723a32181d60d64137e1", size = 25378, upload-time = "2026-08-20T07:33:04.332Z" }, +] + +[[package]] +name = "asyncpg" +version = "0.32.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/80/4e/59dc964f962f09e3ed472e5d2d3ba670a41a2be25080dc62ab3db507ff5e/asyncpg-0.32.0.tar.gz", hash = "sha256:45e64e56714d888330b884aad1dfb363d0bf43fb343e3d1a8968525f3bade478", size = 1075156, upload-time = "2026-10-06T20:32:40.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/25/25/a30ca6417f9142c6a63a7caf5f33717902b2d0ca8a8ff8fc72c6cc2fa77d/asyncpg-0.32.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:5ac18d9ee7a8ca70aed276f79b249d9f37e4d55e3525db1002b5f0b62ddec4f5", size = 691699, upload-time = "2026-10-06T20:31:24.168Z" }, + { url = "https://files.pythonhosted.org/packages/c1/b5/59f10f2381a073c199cd868fce0d8f7aa448b08412de4dc4dbe4118bcee9/asyncpg-0.32.0-cp314-cp314-macosx_11_0_x86_64.whl", hash = "sha256:e1120ef2ae3a5e514c9ea9fce83519ba692710ea5f38434eadbbf12789073dfe", size = 715194, upload-time = "2026-10-06T20:31:25.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/59/79a5aebd58250bedefa6dcd43b22b037d9cf0054ceb4c718c53ebf04e63f/asyncpg-0.32.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4fa68acb42f22436597016e5d7feef7b0b5c49b4c56aece3fdb3ba0da2326cb2", size = 3729978, upload-time = "2026-10-06T20:31:27.541Z" }, + { url = "https://files.pythonhosted.org/packages/68/db/fc91b503b3ec66cf242d83c799388285ea5f0ee238435d53dd9c1a8648a9/asyncpg-0.32.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:63417b8f7369c54f6754c1fbd5a2968fbe632ff55bfbedd56a0177b6a96bd251", size = 3794539, upload-time = "2026-10-06T20:31:29.617Z" }, + { url = "https://files.pythonhosted.org/packages/40/bd/7359320499fdb2733206191b8fd15b7ec602656cbc1444bff7a8c66a365c/asyncpg-0.32.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2c6366841a792d0a4d16991de240a8053b7c4772a18a5f27fa6fad09c0e359fb", size = 3632884, upload-time = "2026-10-06T20:31:31.298Z" }, + { url = "https://files.pythonhosted.org/packages/18/75/dd3c3dd99f1db55b9736d23a44da29501f07f852bf4df91507f37b156fb1/asyncpg-0.32.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c3ef1dfd11919280e011ffd1c873323c5088a94fd2c3f77946a5250cf306e2eb", size = 3764931, upload-time = "2026-10-06T20:31:32.916Z" }, + { url = "https://files.pythonhosted.org/packages/38/4f/161b275759725a774d170a383c1208996865ebad50d6891e60d35461a3e6/asyncpg-0.32.0-cp314-cp314-win32.whl", hash = "sha256:77cf9d7023f063ae6f9e443077b55af0dc1807dd9afff1ae656b93ee0cddedc9", size = 557690, upload-time = "2026-10-06T20:31:34.856Z" }, + { url = "https://files.pythonhosted.org/packages/b5/03/880d0db1faedf8b740a57a7ba50e115651a0f05c5905140195813879b086/asyncpg-0.32.0-cp314-cp314-win_amd64.whl", hash = "sha256:2f87452025b47ce80dcc3a0be2b5d1f8aab5deec2516d266f1643d4e53cc40d5", size = 634859, upload-time = "2026-10-06T20:31:36.512Z" }, + { url = "https://files.pythonhosted.org/packages/79/bb/2e86b462a2a2a795eaa7838266db019876b8e7a12c465b903517a4e87fd0/asyncpg-0.32.0-cp314-cp314-win_arm64.whl", hash = "sha256:d0e4508a3d62b0f42d7a99c030c364050b11e75f61c9dd4861e5fdda7cb60636", size = 594013, upload-time = "2026-10-06T20:31:37.91Z" }, + { url = "https://files.pythonhosted.org/packages/20/1d/5369c4438496e654121cbda75be2e8043d1fcae3552b856d44011a19b723/asyncpg-0.32.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:afec11e0b9c001e69966becacd2f948cc8949b4916ec4c0f4dc9b52e47de4528", size = 743832, upload-time = "2026-10-06T20:31:39.261Z" }, + { url = "https://files.pythonhosted.org/packages/60/b0/4b92582c2339a164275a6418ccaeeb0453b72f2e0d7003702379cb50e852/asyncpg-0.32.0-cp314-cp314t-macosx_11_0_x86_64.whl", hash = "sha256:418d266a553e932bf961bb43bfd610ee6c5425fb1b9a599a5828fd12bae8f5c4", size = 769568, upload-time = "2026-10-06T20:31:40.691Z" }, + { url = "https://files.pythonhosted.org/packages/3d/88/919d9ff7ca3c3b96aa404b88b6a53e142b4422623c5ee5a69c4b733240ce/asyncpg-0.32.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b1666e1b747ebbc75c87cb31972704ae8a3ca15b950f94456e97d26781c67d10", size = 3948962, upload-time = "2026-10-06T20:31:42.456Z" }, + { url = "https://files.pythonhosted.org/packages/27/8b/e9f412ae9a3e3f0eb23415249e8d5933e7aeb01068b4083fc86714043d1f/asyncpg-0.32.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83510bb25d38f0415e155aa3a7af78621369891f5ecd8730d012d9cb26143ffc", size = 3874815, upload-time = "2026-10-06T20:31:44.094Z" }, + { url = "https://files.pythonhosted.org/packages/08/71/24364e9ff7bb9860548452513f295306b12f5b24e8fb0b78f1605c443946/asyncpg-0.32.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:87957755d11639cf248c6aaa094eee9d150f07065866d1710c9427e02dfc0790", size = 3762465, upload-time = "2026-10-06T20:31:45.908Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e1/33cb7e805ec6806b196473e2c7a2ba9d5af3ad2928930aa06359c8eeef87/asyncpg-0.32.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:764227423bf30a3001d3da6df90e82d30a2a097d762e4ee5fa074236eda262f4", size = 3797285, upload-time = "2026-10-06T20:31:47.53Z" }, + { url = "https://files.pythonhosted.org/packages/be/e7/85eb86d6040725f5c191fd6af9f10769c60ed971634b47f4b4bcab293d44/asyncpg-0.32.0-cp314-cp314t-win32.whl", hash = "sha256:f2342b1f3e87b2096320a77edcbb830fbd23b1d4d4842c57567764430b95e4fc", size = 594006, upload-time = "2026-10-06T20:31:49.197Z" }, + { url = "https://files.pythonhosted.org/packages/f9/aa/ea75defe55718457bcf41cde42248db5bbee65fce8c6f0a0e43d9eca1723/asyncpg-0.32.0-cp314-cp314t-win_amd64.whl", hash = "sha256:5c3a48908cb0a02393e5bdab7fa92aefd700f2a93212bf91f04aa9657b4f554d", size = 674647, upload-time = "2026-10-06T20:31:50.547Z" }, + { url = "https://files.pythonhosted.org/packages/0d/0b/078d362872c6c72dd5d11c214dde8dac65b1c87ece96fd2fc2f786a8f66c/asyncpg-0.32.0-cp314-cp314t-win_arm64.whl", hash = "sha256:f8eadd207c26850a2e15f3c2a1096b5d051ea6758a26f2f3e65ce16f84297ed8", size = 624589, upload-time = "2026-10-06T20:31:52.291Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, +] + +[[package]] +name = "click" +version = "8.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "dishka" +version = "1.10.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/97/da/b75b5fe665d16725e1d46e291c8dd4b0ed1731c7964f41087fda92f03d40/dishka-1.10.1.tar.gz", hash = "sha256:51fb624b9acc948b90f57128460061d1f3a1780121fe1c7d14c565e8bbff2083", size = 282008, upload-time = "2026-04-25T12:07:57.587Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/08/dd3259a319ba45c48d975caf237c830c7873a203288cb4ab186cc5bef585/dishka-1.10.1-py3-none-any.whl", hash = "sha256:84f40c1115eb391ce3fb558fd7946c5bcaf6361c35b77b7a185b7697a5720ec7", size = 120062, upload-time = "2026-04-25T12:07:59.153Z" }, +] + +[[package]] +name = "fastapi" +version = "0.141.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8a/02/91e3416a8fdd715abb903a952a6bec7cdd8d14eed55d415fc8595524c319/fastapi-0.141.1.tar.gz", hash = "sha256:e8822fc40db1e1858054d7a949a888695bc9bdce70139178e33bd2871a453ca1", size = 425799, upload-time = "2026-07-29T17:18:05.568Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/03/10388a42375ee7e4ac9b94eb2c5c569c8b5795e377e701c9ac3ad63de890/fastapi-0.141.1-py3-none-any.whl", hash = "sha256:bfb91aa2d334c61cb35ba9a116fc123b3d3df31640b801cf57a7a78ec3f603b3", size = 131954, upload-time = "2026-07-29T17:18:04.364Z" }, +] + +[[package]] +name = "gunicorn" +version = "26.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/8a/e4ef6ee11701b6cd64702848415ffb69eeff85cb388a3c6c7fe86f22f3f8/gunicorn-26.2.0.tar.gz", hash = "sha256:62b864895d9ebff0b2f9867ba04fe811c93121596540830c9c916d0769668447", size = 787921, upload-time = "2026-08-24T15:05:59.3Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/85/7522a52e5e2f42faf1a129113ab63e548c42e103e9af395b7bfe65e403e2/gunicorn-26.2.0-py3-none-any.whl", hash = "sha256:bd249d0b3f7972f7432f0a6b6ff3b3ee2d129f70cd1ff6c09a9dd9e29a2b88e3", size = 228389, upload-time = "2026-08-24T15:05:57.67Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httptools" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/e5/d471fcb0e14523fe1c3f4ba58ca52480e7bd70ad7109a3846bc75892f7fb/httptools-0.8.0.tar.gz", hash = "sha256:6b2a32f18d97e16e90827d7a819ffa8dbd8cc245fc4e1fa9d1095b54ef4bd999", size = 271342, upload-time = "2026-05-25T22:17:48.841Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/12/fa3fbf5f9517b273edea2dc982aa82a8c634091e67c590792b729017bc6f/httptools-0.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:de242a49b5d18e0a8776e654e9f6bf6d89f3875a5c35b425a0e7ce940feb3fd6", size = 206183, upload-time = "2026-05-25T22:17:24.004Z" }, + { url = "https://files.pythonhosted.org/packages/30/fc/5e7c4cb443370f2090a3aba0453a07384d29ff66b7435bb90e77e1037599/httptools-0.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:159e9ab5f701ccd42e555a12f1ad8ff69702910fc1c996cf2bb66e5fcb7a231b", size = 112079, upload-time = "2026-05-25T22:17:25.216Z" }, + { url = "https://files.pythonhosted.org/packages/ba/53/771bd891eb0f236f32145d6a1775777ec85745f3cc983a1f23d1a3b8ddfe/httptools-0.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c4a9f1707e4823d54dfec6c33fa3697d302aed536ed352a7ebb5a061ddb869d0", size = 481596, upload-time = "2026-05-25T22:17:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/62/42/94e15bc68ce3d423243c45d7f1b0c7561f13844f97dc52ae23182fb65628/httptools-0.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d76ad7b951387e3632c8716a9bb03ac5b45c5f16119aa409db0459520887944e", size = 480865, upload-time = "2026-05-25T22:17:27.542Z" }, + { url = "https://files.pythonhosted.org/packages/1c/7c/fe2980fc03723272e30f135b62360b075f513dfe7cc73aef36c7f04012bd/httptools-0.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a3b7387147361c3fd47a0bde763c5c91b5b4cd4dc9989b8ece84ff436c99843b", size = 463189, upload-time = "2026-05-25T22:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/15/1b/47fc5fff68acd1bfa20b4734059c9a06cadb88119dcd5258b5b0d21d91c8/httptools-0.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f256d6ce930c52ca1cb2a960b7da03548c454e7d28b06059ad41bfe789036ce0", size = 466610, upload-time = "2026-05-25T22:17:29.816Z" }, + { url = "https://files.pythonhosted.org/packages/60/bd/07b13c93ffd9bec9546e0d43f8e19378dd696dbd278511406bc07371ef1f/httptools-0.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:19d1ee275bb59ba2643ba9a3a1e51cc0c788caf2b8df506368e03f56fdd08527", size = 92705, upload-time = "2026-05-25T22:17:31.133Z" }, + { url = "https://files.pythonhosted.org/packages/fd/c4/121648f68ce066d7bd762d6b6d97e620847642d38d54f3d90ff11d947629/httptools-0.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:de1ed58a974e75d56560acc7e7fed01a454994429456f65209789992e41f2568", size = 215023, upload-time = "2026-05-25T22:17:32.401Z" }, + { url = "https://files.pythonhosted.org/packages/b9/b0/312a062ae741ae3e8baa8c8bf20be81b2e67337b259ab4349bebc7b6142e/httptools-0.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e93c227b595c6926c1acee96891dd9da4be338cfbe82e5cd3bb9d8dd7dc4ac0b", size = 117405, upload-time = "2026-05-25T22:17:33.742Z" }, + { url = "https://files.pythonhosted.org/packages/fc/37/fccd705f795386bb05bf413012fecff2a33e5aa8c2f069096de3e9fd8702/httptools-0.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2a021c3a8e65cc125390d72f59b968afca3bdcaff25bd67965e0a055a14946ca", size = 558497, upload-time = "2026-05-25T22:17:34.732Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/f172e8003576de35f5ba77ff417cf0e34429d35dc014deef15afa337a72c/httptools-0.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48774d39cbb70e2b1f71f88852a3087ae1d3a1eb80482bb48c13067ab080c14f", size = 571585, upload-time = "2026-05-25T22:17:35.813Z" }, + { url = "https://files.pythonhosted.org/packages/3e/b9/f5564760af99f3dbbf3f9104dc00e5da27e96cf433c6bdcf77617f70bf3f/httptools-0.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:88eead8ec8680a9f146c655bc88445a325bd7921cfd8194c7337e9467282427d", size = 543297, upload-time = "2026-05-25T22:17:37.08Z" }, + { url = "https://files.pythonhosted.org/packages/99/67/8d9f2c313618e161b82f3873188e7196126da1d6e29688df40eb3997c77a/httptools-0.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2c032fa028f46871ec7e1fc59fc15e8023eab3e6bbe6ece786a1611719a5d081", size = 539535, upload-time = "2026-05-25T22:17:38.032Z" }, + { url = "https://files.pythonhosted.org/packages/48/63/b906c01e53f50d432c0defe43ce52764a111dc1bdd028bafbeb54dcfd008/httptools-0.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:384c17174464c8e873398b7af24f0b1f44d992c820328413951a625323155d77", size = 108209, upload-time = "2026-05-25T22:17:39.473Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "mtusi-messenger" +version = "1.4.0" +source = { editable = "." } +dependencies = [ + { name = "argon2-cffi" }, + { name = "asyncpg" }, + { name = "dishka" }, + { name = "fastapi" }, + { name = "gunicorn" }, + { name = "orjson" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "redis" }, + { name = "structlog" }, + { name = "uvicorn", extra = ["standard"] }, + { name = "uvicorn-worker" }, +] + +[package.dev-dependencies] +dev = [ + { name = "httpx" }, + { name = "pytest" }, + { name = "pytest-asyncio" }, + { name = "ruff" }, + { name = "ty" }, +] + +[package.metadata] +requires-dist = [ + { name = "argon2-cffi", specifier = ">=25.1.0" }, + { name = "asyncpg", specifier = ">=0.32.0" }, + { name = "dishka", specifier = ">=1.7.0" }, + { name = "fastapi", specifier = ">=0.118.0" }, + { name = "gunicorn", specifier = ">=26.2.0" }, + { name = "orjson", specifier = ">=3.12.0" }, + { name = "pydantic", specifier = ">=2.11.0" }, + { name = "pydantic-settings", specifier = ">=2.11.0" }, + { name = "redis", specifier = ">=8.1.0" }, + { name = "structlog", specifier = ">=26.1.0" }, + { name = "uvicorn", extras = ["standard"], specifier = ">=0.37.0" }, + { name = "uvicorn-worker", specifier = ">=0.4.0" }, +] + +[package.metadata.requires-dev] +dev = [ + { name = "httpx", specifier = ">=0.28.0" }, + { name = "pytest", specifier = ">=8.4.0" }, + { name = "pytest-asyncio", specifier = ">=1.2.0" }, + { name = "ruff", specifier = ">=0.14.0" }, + { name = "ty", specifier = ">=0.0.1a21" }, +] + +[[package]] +name = "orjson" +version = "3.12.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/f3/742fb1f62b825f2c010697eaf4e828004bc2a81e7e806666989c132c7c42/orjson-3.12.0.tar.gz", hash = "sha256:d14203fb1aae2ad9b3d52f8a0e82aeb10197ef1c9bc61da7f358bd70b00123d5", size = 4142915, upload-time = "2026-08-14T16:13:30.607Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/9d/3931253e6f3148abf2cbe14830367042a4806b362ea520df2303db188fb9/orjson-3.12.0-cp314-cp314-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:9e6fee342a48760e854d743e7a81534d8e2925a6f46e09f750cf56b50fd1de5d", size = 223391, upload-time = "2026-08-14T16:12:59.184Z" }, + { url = "https://files.pythonhosted.org/packages/8a/0e/b4a4f1e305367245877b967a0bad70fcf001d77c54ac4339a120b66fdae4/orjson-3.12.0-cp314-cp314-macosx_15_0_arm64.whl", hash = "sha256:8c3bb86dd10f39b3fbf434b7d5dc7cac77d6fc8ac572ae30a10731ede2c4b647", size = 123659, upload-time = "2026-08-14T16:13:00.548Z" }, + { url = "https://files.pythonhosted.org/packages/96/f3/6782c6fa85e2702bc66be183c3b421486167dcf266ee4dc1403fe3824870/orjson-3.12.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:2bb3ce43203936072dd8b4917b01d3aecfc02329bfb42510cb7cfb24708adc9c", size = 113337, upload-time = "2026-08-14T16:13:02.009Z" }, + { url = "https://files.pythonhosted.org/packages/bf/79/b32ab64bacda9d0fa4942ef483bd03cabf0eaf2be819ca9fb7ff610c559d/orjson-3.12.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:6a2a79c89984dc719817d388c8709e0efc2a2795a934eaa746b4882eb6045adc", size = 130112, upload-time = "2026-08-14T16:13:03.404Z" }, + { url = "https://files.pythonhosted.org/packages/ee/49/6e6142999ca01509219be5e5a9c338a3e5ea011f63e91ff473fbbf3734ed/orjson-3.12.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f06dd838d1e07d9b1de0932ec0485ec92c4d5f5d1ad4817a656268c3e88be1e1", size = 130520, upload-time = "2026-08-14T16:13:04.798Z" }, + { url = "https://files.pythonhosted.org/packages/49/d0/3745af0a4cc9867784f29722929cec4d10bd1c877cd754b01ba6d96eb21a/orjson-3.12.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c6b11be792c3d2c6a4be2af4ebf97a68d0bf5f580aca6e86a418a354f6cc846a", size = 131053, upload-time = "2026-08-14T16:13:06.14Z" }, + { url = "https://files.pythonhosted.org/packages/c3/f4/6fe5a22fa478fffb190e65c338c84df5c311ef597b363150a17cc57063c0/orjson-3.12.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:477ecaf6b9f88f873341b91fcc736119ca81b5e002a9f7f308ff5b4f2ce2a70e", size = 135321, upload-time = "2026-08-14T16:13:07.544Z" }, + { url = "https://files.pythonhosted.org/packages/ff/41/b1b0ec30289646a81a76e2dbaae2686b96fcccb7cb0323dc1dd78cbc7875/orjson-3.12.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f3c0683136acdc29afdf88a5bc2f7d3d0e34087788d1d63c0144b805a87a196f", size = 127485, upload-time = "2026-08-14T16:13:08.88Z" }, + { url = "https://files.pythonhosted.org/packages/bf/2b/277404bdcc21c93b112b963655b76443ebfe828f8a3ff1de7d90f8850eb3/orjson-3.12.0-cp314-cp314-win32.whl", hash = "sha256:d39f3f5c3927e2dc0913fe5bbc1a2f6b1b9d1bba1de6358340d0ad0d0c00ca92", size = 128048, upload-time = "2026-08-14T16:13:10.305Z" }, + { url = "https://files.pythonhosted.org/packages/41/2b/395b36fa2b4ce7af70b651d715e88f80d884b2c2b14a6b53e84d554fb5f0/orjson-3.12.0-cp314-cp314-win_amd64.whl", hash = "sha256:0b1ac5bf6609b2716c7954011c5fef6254922df029f45d032ee4ebf5d363cbed", size = 121858, upload-time = "2026-08-14T16:13:11.634Z" }, + { url = "https://files.pythonhosted.org/packages/ea/a3/833e895ff452859eebe75093d26691fe9108f1a7a6a08435d7a5780ea652/orjson-3.12.0-cp314-cp314-win_arm64.whl", hash = "sha256:50fae885cb073eac7556353ff3df93312b0d5137b0a5056b2bb63f97ed9a93c7", size = 126749, upload-time = "2026-08-14T16:13:13.117Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "pycparser" +version = "3.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/27/eeb9f307bf07060f3d9f9aa0fb8c15b01bdfded0a941e4b2719c7f94cacd/pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6", size = 158785, upload-time = "2026-10-22T13:40:03.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/ae/315bbeee126a769cbde43cf4908acb4b40408d8bf8bbf334dd7368d8dadf/pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e", size = 62600, upload-time = "2026-10-22T13:40:02.021Z" }, +] + +[[package]] +name = "pydantic" +version = "2.13.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/53/ef/fc4f868f4e2cee79f863883abffceff107875f569b848507319842d2a681/pydantic-2.13.5.tar.gz", hash = "sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08", size = 845750, upload-time = "2026-08-28T14:04:00.916Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/eb/47/c95ffc2009878c7aac0c5e08528022dcb885933252a88b5f170058014464/pydantic-2.13.5-py3-none-any.whl", hash = "sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73", size = 472589, upload-time = "2026-08-28T14:03:59.136Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.46.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/af/f9/8a06bea35ef8daf588f707784c973a7046e0034c8d8cfb08828eeffb8b75/pydantic_core-2.46.5.tar.gz", hash = "sha256:10416c15b8839ecc4ef4d0885da76da6fd0f67333a0eb8aff6d93c4b8f2910fc", size = 472262, upload-time = "2026-08-28T10:01:31.677Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8e/8a/14596f2a8367da50cf7cbac48169ee5d9c8e11d486a3b527082384630c72/pydantic_core-2.46.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c1c43ad4339643d70ebb8124e1305a7dab423001eff58bb41a0f731adbc98355", size = 2074081, upload-time = "2026-08-28T09:59:16.141Z" }, + { url = "https://files.pythonhosted.org/packages/ae/d5/d8a4eb6d6c7f66b91dd37c576d76e9e60fba900caf5372c17bcf949febc2/pydantic_core-2.46.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a353f84de772f423b5ffb11d7ae352fbbef0f446f3c0b0af0f8236d7233606e", size = 1920497, upload-time = "2026-08-28T09:59:18.065Z" }, + { url = "https://files.pythonhosted.org/packages/8e/26/092079428f86e927e030b2c0ced87df69dbb1c875cdeaa67bf42ea2be746/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5086029a57366b8cf81b130a43908738095c270c21a8d7f0e8bdfdb89718e2f3", size = 1952130, upload-time = "2026-08-28T09:59:20.476Z" }, + { url = "https://files.pythonhosted.org/packages/08/c3/8ec0e290a9ebaebd64047bf5fda94be835c6b1551b02437e4b76778fbcd7/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:46c25dda9d092a06c08db76ffe0a197107904d0dfac653f7d5306bbcd6d6119c", size = 2026371, upload-time = "2026-08-28T09:59:22.227Z" }, + { url = "https://files.pythonhosted.org/packages/01/72/4fd20ad520fb8da0157f95b27a7eb05a72790ef08138e7701ac972c342ea/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:37ea7b83c935e5b0d68c9449b82651accf78a10828b2c02b2f2d9e9496446c21", size = 2202822, upload-time = "2026-08-28T09:59:24.277Z" }, + { url = "https://files.pythonhosted.org/packages/31/b0/d16e0771206b29314f0d52198b720be21e8a99ab2bf11e3bc0d7c9cebdff/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e64e88d5585bea9ce95861079de72006c7fa6d3df4e3a3b65ba31eb979c15c9f", size = 2262756, upload-time = "2026-08-28T09:59:26.608Z" }, + { url = "https://files.pythonhosted.org/packages/2c/9b/59634b7ac631c63b2a37760eb6943af3e29573d6b59a4abc5e7f019d4cee/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:54d510bac3ee52247af28ed4bb18a1e799f040ac60fd2bf5ccd4c92f1fbe786f", size = 2068352, upload-time = "2026-08-28T09:59:29.044Z" }, + { url = "https://files.pythonhosted.org/packages/08/7c/570abb1ad2155348dc754ea91be22e5aaa18eb6d69a6068f7c6f2679a6ed/pydantic_core-2.46.5-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:a2a5e1d0ff29adddc9f6d6821a66302e4493f8ca898b715b6b1182c2c201ea0a", size = 2104777, upload-time = "2026-08-28T09:59:30.95Z" }, + { url = "https://files.pythonhosted.org/packages/8e/25/5bf74adc65a1ac5b7be3f6cb0bcb5433615c1598a801c19d830d84c98ded/pydantic_core-2.46.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:03b9666e41e35d8909852ba191a0607520f81b74eaf12ccf8737005dbb313821", size = 2156312, upload-time = "2026-08-28T09:59:32.604Z" }, + { url = "https://files.pythonhosted.org/packages/90/6a/2ef38830675e050121040618135564ed56b860b45433b02d9b4ebece46f3/pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:a91c17edf6eea2402cb5457b4c89e99bc5ed1004aa34c4adf1d4258c1a5c22c2", size = 2150067, upload-time = "2026-08-28T09:59:34.453Z" }, + { url = "https://files.pythonhosted.org/packages/90/ef/a7dbb03a14a64c2a4621f989c615ed9a892535a6cad938fc27079f919d80/pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:b49924c73a235e969511bf2aabdff3beebf9820931f646c80274d5d780010c47", size = 2304516, upload-time = "2026-08-28T09:59:36.194Z" }, + { url = "https://files.pythonhosted.org/packages/68/f8/6bb4c4b80e8a6fde1904c64a51c62a1d04fcdfa3ea521a66b2ddefa1d885/pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:2cbd9a5eff05e51c447c34dfa4632145b26b09120cf04bd0c871e44c1a5e1c9a", size = 2335223, upload-time = "2026-08-28T09:59:37.931Z" }, + { url = "https://files.pythonhosted.org/packages/2a/80/f46b8c681195190b2c1f1c7c0a81abce60663e987613e09ef64d433dd96b/pydantic_core-2.46.5-cp314-cp314-win32.whl", hash = "sha256:2d5d76654becf5efd62c9e51c3756c67b49498b0c9a40884934c40807adbd074", size = 1934827, upload-time = "2026-08-28T09:59:39.836Z" }, + { url = "https://files.pythonhosted.org/packages/f7/3c/60674207246bc0a4009d2391b7c7251c7159f279c8d2ab8aae8ef46f3dee/pydantic_core-2.46.5-cp314-cp314-win_amd64.whl", hash = "sha256:fa10ef4112775900e7a0661068635eb67b2ab824fbde764de6e0e21982a93db0", size = 2042648, upload-time = "2026-08-28T09:59:41.792Z" }, + { url = "https://files.pythonhosted.org/packages/69/0c/117c562c7c1babdf44576b72a5e496906506c93690387ecfbca7c729ae2e/pydantic_core-2.46.5-cp314-cp314-win_arm64.whl", hash = "sha256:045ab3b6d308439e32b81cc173bba5b9018bc6ed896afd0c65b3b009b1699af5", size = 1989652, upload-time = "2026-08-28T09:59:43.702Z" }, + { url = "https://files.pythonhosted.org/packages/e8/66/9336ae58f9eb68c41d121894e52c4c89eccb07eb8f602a04ee9c3f37736a/pydantic_core-2.46.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8816f3d218beb4b787de5c9759c259b8fa61f9dec42dc7811f320a33771778b7", size = 2065829, upload-time = "2026-08-28T09:59:45.364Z" }, + { url = "https://files.pythonhosted.org/packages/c5/02/bc19b47a96c2d3109760711acf22369e56bd7e405ca52f7ade164d2ead57/pydantic_core-2.46.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:bce57638e08ac148e5778cce7feb968307a727d66f8e2274a543d0cf0c9ad6a3", size = 1905716, upload-time = "2026-08-28T09:59:47.18Z" }, + { url = "https://files.pythonhosted.org/packages/52/a4/70b47c0509923dd98ccfed04fb3e32ea3849c82a0ff2205bb41009b43c00/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:976e1128455aa595ea04c79ccfedff1aaeab96ee013fcc916bed120c4f0ad94f", size = 1934216, upload-time = "2026-08-28T09:59:49.241Z" }, + { url = "https://files.pythonhosted.org/packages/52/ab/aa03b65f7bb198585edf806b906c3223ecf1795543e39e23aec4cce27ad2/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e7b891faeedeafba41b2983e5001a81b6a915b69544c7e7570d1989ce1c36ac7", size = 2010635, upload-time = "2026-08-28T09:59:51.692Z" }, + { url = "https://files.pythonhosted.org/packages/3c/8b/0da06343f30b84ec549aafd309c6456223d5dc8bd36af504c573faad561d/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f194189415698233dd1114a093a9b56e61e2c57e11b469be3b0506f46f0771c", size = 2209369, upload-time = "2026-08-28T09:59:53.582Z" }, + { url = "https://files.pythonhosted.org/packages/d6/5b/844c4defaa34a3df66eb9257087d121d70c201298b96abdf9f492fc2f1bf/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:82a36973cf8a2ef5406f4fe2edbf8ed0c99629535d959e0b100c76a32535a111", size = 2253238, upload-time = "2026-08-28T09:59:55.484Z" }, + { url = "https://files.pythonhosted.org/packages/f4/64/a4e536cb16d7f61a7fd3120b46c577fc7fa7325992f69c4f52bc786d77d8/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdbb78909f52b981d3b2d56b97328d71eb0b974c36bd77c920123a7ebb192829", size = 2065740, upload-time = "2026-08-28T09:59:58.038Z" }, + { url = "https://files.pythonhosted.org/packages/5f/75/aaa38c6bc2d085f6605b34eabdc6a8a4e0b2e61fc9c8e6e52b28e97b3125/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:52e24eacdb536cade636aa90fb851835222becff8484b7001fdc78cb0290f2aa", size = 2087425, upload-time = "2026-08-28T09:59:59.898Z" }, + { url = "https://files.pythonhosted.org/packages/55/ae/fcab4cfc39aba3689e1d20c8b5250ad280957022c09af2ed9cd585602a5e/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:37ae34309d7bd8c0d61ab839668058f2a7962ea1fc51d105d2db228fe0618034", size = 2139306, upload-time = "2026-08-28T10:00:03.057Z" }, + { url = "https://files.pythonhosted.org/packages/2d/f4/f1d03a4bc9d9acbc62f4d742b8a319af52f71885079868b2ff8e48a651ee/pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:0cdbada856a1c69a7624a64d3d9aefe79300bd6ef827b43a4f265010b9b55184", size = 2144589, upload-time = "2026-08-28T10:00:05.645Z" }, + { url = "https://files.pythonhosted.org/packages/83/f3/7a53bb1356de514a4cd295f25b6ac39237895620c0462d2592b76c16e114/pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:545f26c504b27c3758439a5e6d9349931f0a04f855668d5fe323c89e82300a38", size = 2288882, upload-time = "2026-08-28T10:00:07.931Z" }, + { url = "https://files.pythonhosted.org/packages/cd/94/5a81583660c175c59d49ffb09f4b3a44debeaf86a19fca664ae1cdd9ee32/pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9", size = 2335210, upload-time = "2026-08-28T10:00:10.177Z" }, + { url = "https://files.pythonhosted.org/packages/5a/9f/5d685c2693b972d1a59c998586e8823712b66603aeff47ee60a4bdaafd37/pydantic_core-2.46.5-cp314-cp314t-win32.whl", hash = "sha256:97cf3eb53a8cccacf9d46686a0926186c9bfb5574f2ed66d3639d5fe117cd3a9", size = 1921180, upload-time = "2026-08-28T10:00:12.35Z" }, + { url = "https://files.pythonhosted.org/packages/70/12/5c94ee16d65a37a15f9e869f5e6256df111154491173801a4c5e800ab548/pydantic_core-2.46.5-cp314-cp314t-win_amd64.whl", hash = "sha256:d2f9fc07a8042a8f95925b35c4f04f469707c981fc33245b6ca187cf5d2dd290", size = 2020515, upload-time = "2026-08-28T10:00:14.774Z" }, + { url = "https://files.pythonhosted.org/packages/63/19/67830dda664e6bdf9285ee2e40f355d0d7d6b92aa0c42e8d217bb8d33d36/pydantic_core-2.46.5-cp314-cp314t-win_arm64.whl", hash = "sha256:acf8a67ba51f4ca9ddbd0e6b3000a65ac51ab734661778b3e7ba64d99a710f2f", size = 1989276, upload-time = "2026-08-28T10:00:16.984Z" }, +] + +[[package]] +name = "pydantic-settings" +version = "2.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/68/ca/31c57507b13119d7d3cfa1576dad2911a4861e3be07b579395f4e9d393f9/pydantic_settings-2.15.0.tar.gz", hash = "sha256:694b793e84f766ba76a90ebdefc01d0a9a045dab0382bee70393da93712ad117", size = 261253, upload-time = "2026-08-07T09:24:57.419Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/30/a4/2bffa9f8e804325a09867f0e9d30795c80ea9f8d62560bd1b6ad6220eb2f/pydantic_settings-2.15.0-py3-none-any.whl", hash = "sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42", size = 69413, upload-time = "2026-08-07T09:24:55.839Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "pytest-asyncio" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, +] + +[[package]] +name = "python-dotenv" +version = "1.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/53/ed9d74092561d4b01a2ef1349d52cdbc135e526c245f366b089cfca6de49/python_dotenv-1.2.3.tar.gz", hash = "sha256:a20a594dabeaa385725aa239d5244871c143ecb356add8a20fcf23773a6c3a35", size = 58945, upload-time = "2026-08-16T16:54:54.067Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0d/17/c5c6b53ddc18f297992099b3d9ec16c855c0ccc83263a21fe4d1c625ec6c/python_dotenv-1.2.3-py3-none-any.whl", hash = "sha256:904552145e8bfed22162c09dab1c2b9b54fefa7b23ba780f4f26ca0316b0f0d9", size = 22780, upload-time = "2026-08-16T16:54:52.473Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[package]] +name = "redis" +version = "8.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a8/99/604f0b666d4c616d891cf77ebb9db6bb21601344c051aebf1b72b9ff915f/redis-8.1.0.tar.gz", hash = "sha256:6e1a19beef9225c83efd689c7e6b7da2d5215b1f42cd13b7fc3714d0a09c7b25", size = 5254356, upload-time = "2026-07-30T08:51:00.269Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/66/9d/c5731f6e3608663d4d3656fd8d3aecee8b509c3082818f5a13eae925baea/redis-8.1.0-py3-none-any.whl", hash = "sha256:a4fe1aac3d3b3cc791d4b3d5931c5a956045dc951ee74d1c913ee3ac4d2ee9fb", size = 560618, upload-time = "2026-07-30T08:50:58.497Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/96/bf/c935ca98e73fe8ce65b87ef08a280c0c1e85295d569228c15e87d8fdfaf1/ruff-0.16.9.tar.gz", hash = "sha256:12b625c6cfba78d285d9f48eda5f053374f1e53cb10ef17342a383750db99161", size = 4948764, upload-time = "2026-09-24T20:37:49.416Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0d/26/df51322b52ee1ada7eff2d071ea09d11d5c2d1dcc9f02594f5785c4d1635/ruff-0.16.9-py3-none-linux_armv6l.whl", hash = "sha256:95e6f022090368ab3b824c36276839c53b2adf1a3f4c09fefc33dfc400f6da96", size = 10082922, upload-time = "2026-09-24T20:37:13.045Z" }, + { url = "https://files.pythonhosted.org/packages/a5/27/7bf51f5a7aa375e9f339280a303aab44ca75dc1525f1cdc5991761685b0f/ruff-0.16.9-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a5f27be168556594a86d2f415db0cf43f5291917849318f873c7e2791f7a8c67", size = 10236360, upload-time = "2026-09-24T20:37:16.049Z" }, + { url = "https://files.pythonhosted.org/packages/b6/63/09659283f92f02dff45809da194a70da2f688d87c55d8875c4fae3536072/ruff-0.16.9-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1632eb1d6197f33bd00b1acbc5b71009e89a8895c158e2d2b03a834fac964ab6", size = 9892940, upload-time = "2026-09-24T20:37:17.957Z" }, + { url = "https://files.pythonhosted.org/packages/24/58/98de1b72ec172f5f8f1731236fe21585b3998bf7dfe9fcc44ae9ba626012/ruff-0.16.9-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f951b14d865d5952c89d40a5ca07e87abe24fa5453299878411e127748fb1c", size = 10032114, upload-time = "2026-09-24T20:37:19.942Z" }, + { url = "https://files.pythonhosted.org/packages/c8/7d/f1e17c54ab59d4bad1dce8ee3e22a7a1d0ef4745240decacdcf3832b5bb2/ruff-0.16.9-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:447fc07e1573afff7cb02803462b12b6c8ece7cf10e2cd78565fa6d7a1c0bf8d", size = 9910227, upload-time = "2026-09-24T20:37:21.872Z" }, + { url = "https://files.pythonhosted.org/packages/34/19/436f647a65075bbd3bab2668b3bdaa5120559b294694018cdcefabbbf30b/ruff-0.16.9-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8a3e039a6a40ed976c491722b60e0ae4a4aa1a86057f540ee7a37a5d19ae9120", size = 10547484, upload-time = "2026-09-24T20:37:24.229Z" }, + { url = "https://files.pythonhosted.org/packages/03/59/38430a6bc2f6d8095447ac39625cf8b6e9344a47e6c26225c8ba1bff3ffb/ruff-0.16.9-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4684dded7db60aa57cb118fa158630f5feade4af5782903b6053484bdf9bd129", size = 11412367, upload-time = "2026-09-24T20:37:26.307Z" }, + { url = "https://files.pythonhosted.org/packages/c8/bd/bbb6d7fc7f208c8b8c50dd5dc8206e4cfdb1e7a8fb852606a3adf370c880/ruff-0.16.9-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d29c934357e45642fda2f34c0b1f4025b4a6c01e15e4bf0016879d60078a142c", size = 10869787, upload-time = "2026-09-24T20:37:28.35Z" }, + { url = "https://files.pythonhosted.org/packages/bc/b8/9c543074918061abbefc3bd139bee22de35abedb00dde0f2d27288838962/ruff-0.16.9-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a21713e629d3e5bdb2f5c2def1cc7f04f47fa8e1a7eb0571b4a28e1da64bc728", size = 10406494, upload-time = "2026-09-24T20:37:30.624Z" }, + { url = "https://files.pythonhosted.org/packages/35/7a/5a8851bd146e7ccf8fd4b003f6c75c11f8fbdb0e60673b45097986b6bf41/ruff-0.16.9-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:7baa24ef5fc8e77aa93879e1d3f43754a01ae488e869f1ae30cf431afd4d2452", size = 10590083, upload-time = "2026-09-24T20:37:32.439Z" }, + { url = "https://files.pythonhosted.org/packages/87/f0/4c3467188f23f806960b46fa76575a7cd0514c9ba90562650b71efc96980/ruff-0.16.9-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:a41aac6230aadfaa133bdfa1614488531ffa3e0837567ae04c0da2058a9c0f9e", size = 10119151, upload-time = "2026-09-24T20:37:34.581Z" }, + { url = "https://files.pythonhosted.org/packages/15/34/5a4def5adea572ce6aea0bb64f21f928ee317b80e0db747d7979b01d7261/ruff-0.16.9-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:c2529fb5896d49115b0e9aa8f887490b34bbe76baf879ec2264ac59406869ce7", size = 9911544, upload-time = "2026-09-24T20:37:36.796Z" }, + { url = "https://files.pythonhosted.org/packages/62/5d/d15ebea7499eef9373318c0ee6ca127832927c6529731f6d48e18dce7ca9/ruff-0.16.9-py3-none-musllinux_1_2_i686.whl", hash = "sha256:41e3870277694177429b56406d65dfbdb2c2802c52b715edaf6a0b829c69d4ee", size = 10269884, upload-time = "2026-09-24T20:37:38.857Z" }, + { url = "https://files.pythonhosted.org/packages/d1/56/c5d3cd119ded7a3c7aba0e961b69cb3df701c91662c98ad694467d060ce1/ruff-0.16.9-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:8adbe4e58af167f767d7b2ba5e83c42e878350796cf78c2f5e14ab9903a92588", size = 10749366, upload-time = "2026-09-24T20:37:41.042Z" }, + { url = "https://files.pythonhosted.org/packages/ac/fe/734ec7527029ac757ecf821f143c9f3fcf69149c21f53a044a899b430f5a/ruff-0.16.9-py3-none-win32.whl", hash = "sha256:0e1dbc2073624dee6618d41d0098690a7244654af746704b64759e12b6b6b385", size = 10152355, upload-time = "2026-09-24T20:37:43.025Z" }, + { url = "https://files.pythonhosted.org/packages/14/21/26e4643629b3ebb44f0a06f9c9a53058d63d989415f63a9a3c28e2ee7f22/ruff-0.16.9-py3-none-win_amd64.whl", hash = "sha256:6bd40fec8cd4c8a3d4dd589bd8ad4e6320c13c29234159bfd959a40d529d597b", size = 10592965, upload-time = "2026-09-24T20:37:44.944Z" }, + { url = "https://files.pythonhosted.org/packages/51/60/5fb1a39dbb5ae314d5f59bc7348a63c1d5c20f3cd83914c4b5cb0be31d2d/ruff-0.16.9-py3-none-win_arm64.whl", hash = "sha256:ed1a252039200f57a59eebc063b54beabea67bfbaaca0eeaa7f54b5fbcda2284", size = 10458649, upload-time = "2026-09-24T20:37:46.882Z" }, +] + +[[package]] +name = "starlette" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size = 2736246, upload-time = "2026-09-23T07:30:26.35Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/d6/1ec1b290f9e0fb067899b61e1d37a30c923068bad260b216dbe37a7d2967/starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e", size = 78980, upload-time = "2026-09-23T07:30:24.567Z" }, +] + +[[package]] +name = "structlog" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5e/89/b4a0bcfdf4f71a3dea31379f095929613d7e4528a0996bca6aa964cd0dca/structlog-26.1.0.tar.gz", hash = "sha256:f63a716cbd1b1291cf7661de7794b455acfa4c43c5bcf1630e6ad5ddc1adb3b7", size = 1459881, upload-time = "2026-06-06T07:33:39.348Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/18/489c97b834dfff9cf2fc2507cede4bcd4b11e67f84bc462acd1992496f86/structlog-26.1.0-py3-none-any.whl", hash = "sha256:e081a26d6c373e6d201eca24eede26d8ffab07f88f477822e679183428d3d91e", size = 73764, upload-time = "2026-06-06T07:33:38.046Z" }, +] + +[[package]] +name = "ty" +version = "0.0.84" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/f6/34f8869c45ea87fe6a931ffa824b1fe4428167173543d92988d631add355/ty-0.0.84.tar.gz", hash = "sha256:0cefdb0cd5d399418dbe83c349ba605047b7dff815ae6f460c80e8522b40be67", size = 7409537, upload-time = "2026-09-24T13:16:24.367Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/0c/600648778e1c79133ce6b6a5c4c2531ae16b90c9b30f5041b38b574f61b8/ty-0.0.84-py3-none-linux_armv6l.whl", hash = "sha256:868438e2b9abfc835dd5b5b07ed693db95d8348ac40e3228252511d63ae87695", size = 13935333, upload-time = "2026-09-24T13:15:31.167Z" }, + { url = "https://files.pythonhosted.org/packages/c5/3b/27f06f49945c36170765fad82076898039ae3873338e9865f876dd62f12c/ty-0.0.84-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b00f39b521f0b559cde0f6abf8dd47213b513b04f33d58efeb9b98486a16bb17", size = 13511328, upload-time = "2026-09-24T13:15:34.446Z" }, + { url = "https://files.pythonhosted.org/packages/fc/b6/b12dd130e7f30141f0645614f454c925991cd389b1cc6c8284fd6bf32326/ty-0.0.84-py3-none-macosx_11_0_arm64.whl", hash = "sha256:8f78c2915567f2ee62ce0c24d86091bc76f81577677755e242d09951db588b9a", size = 13445445, upload-time = "2026-09-24T13:15:37.476Z" }, + { url = "https://files.pythonhosted.org/packages/44/96/f012de4b3c1d9a4773326621380d768b4d48c47e620dc012775c5e01c7d7/ty-0.0.84-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:61155cad0921e890d86d1d911a40b3a0e924ef4bdc3b4f3865a6c89c7e3012dc", size = 13471235, upload-time = "2026-09-24T13:15:40.64Z" }, + { url = "https://files.pythonhosted.org/packages/05/32/dca630f5f5353fa7bf67eebccf1549df99b16656d21071d0df6677c826a5/ty-0.0.84-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:417c3bf14947ed16b0b92976ab333c27915590354e96d4f581709068d3811355", size = 13680704, upload-time = "2026-09-24T13:15:43.817Z" }, + { url = "https://files.pythonhosted.org/packages/44/8d/33702c8f62f05ad45b33644fb914d483de6a0a7bc8e51884e9b8773e6d69/ty-0.0.84-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e06ef117759f654f5379efe9ae79bda8a186016c016f1023d05c34f8e15c1546", size = 14518923, upload-time = "2026-09-24T13:15:46.802Z" }, + { url = "https://files.pythonhosted.org/packages/c8/a1/da3246e6ef2ae0e842bca4058b25c54bee55ab058ffff4ee54e72517ec01/ty-0.0.84-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a05d1d53db8b64410ab38c6e32c5898510584869d1d5dd9c0605db81c9aef7df", size = 15027731, upload-time = "2026-09-24T13:15:49.755Z" }, + { url = "https://files.pythonhosted.org/packages/20/17/b0099098a560aeb4f9fde6c912f9a81622c3e44e6555e1fbe322b368ec31/ty-0.0.84-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b92400494ab855cfb1204ac1101e3f53b2d09a8e21d171758b2cf9acdab1809e", size = 14748260, upload-time = "2026-09-24T13:15:52.713Z" }, + { url = "https://files.pythonhosted.org/packages/60/d5/32cd67aedb271f006e716ad093806c96c5d7e2af86be8255469dbd3d76c8/ty-0.0.84-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af17eb391ae3027fed9be1780bea555c2b8a25ba68e184c627b4981b2c9eaab7", size = 14205858, upload-time = "2026-09-24T13:15:55.677Z" }, + { url = "https://files.pythonhosted.org/packages/43/c4/638ac62ca2e8eca1b92e3e16273085744fada728b993500819b5c258ca15/ty-0.0.84-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:44cf06af0e7ec78ea6d8ff33a3450fc19627756a4fba681f7410d4e3ef63047a", size = 14573196, upload-time = "2026-09-24T13:15:59.165Z" }, + { url = "https://files.pythonhosted.org/packages/a6/f6/9ee81c5d8921e5fd5f10889ae563c95cd3272b31df2ada528919ca1cef6b/ty-0.0.84-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:c6e56b443ff9ba462e34bfbc1e582004c2719ed35f8f93a433744b0ba0afb2d9", size = 13480760, upload-time = "2026-09-24T13:16:02.313Z" }, + { url = "https://files.pythonhosted.org/packages/f6/83/fbe5d1177667ae16d84c3242846b143809c9cc09568b333e5a9b4d5908f6/ty-0.0.84-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8b6562fcc48820c1030e2a4509ef2c14ef93043ca4860280074314ac3a825b95", size = 13696346, upload-time = "2026-09-24T13:16:05.391Z" }, + { url = "https://files.pythonhosted.org/packages/86/9a/1b4ac9ddc34cc0ab4624bc219825d66af52f1ad87f4778ad08ad03fa06d5/ty-0.0.84-py3-none-musllinux_1_2_i686.whl", hash = "sha256:dee7421451efcbd70f03e95a8f2c8d9e5ec3d35edcd27b4095ee00ee062abfc4", size = 13959410, upload-time = "2026-09-24T13:16:08.661Z" }, + { url = "https://files.pythonhosted.org/packages/c9/04/70e289437a67dfd686056ab4fd91880261a8233033a6a95d29393741fb97/ty-0.0.84-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:31e96307cf621babe969307dd657783d672e2d8bdbd06493710da635bf63fa07", size = 14350294, upload-time = "2026-09-24T13:16:11.865Z" }, + { url = "https://files.pythonhosted.org/packages/9c/f4/ae7dbd118425c850981d23efb850f0d9d7f6b8d2b852bde2767434f668b4/ty-0.0.84-py3-none-win32.whl", hash = "sha256:4bdc85f91cbaae35825f2b17bb4ac5de0563367875cb0f42b2bf07a1bf7ff2ba", size = 13176439, upload-time = "2026-09-24T13:16:15.049Z" }, + { url = "https://files.pythonhosted.org/packages/29/ec/994d87252f065dda5a500bc8afc726d18f6582d81d6f4ff1feb8a267c800/ty-0.0.84-py3-none-win_amd64.whl", hash = "sha256:71cc9aa7a7c89d4e12c6a814e9c0c3310ad5bee44efedbd6f5a42d91e9ac0f0d", size = 13962879, upload-time = "2026-09-24T13:16:18.191Z" }, + { url = "https://files.pythonhosted.org/packages/6d/1c/e6e91852b72566b1ab9aca504712857dfb89324c12092a5bd61d42d34427/ty-0.0.84-py3-none-win_arm64.whl", hash = "sha256:6c9d3718c4a0d318bc9c92af9b2aa85c3294e7dff54cf1d69ad79568f56516da", size = 13656453, upload-time = "2026-09-24T13:16:21.51Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.54.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, +] + +[package.optional-dependencies] +standard = [ + { name = "httptools" }, + { name = "python-dotenv" }, + { name = "pyyaml" }, + { name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'" }, + { name = "watchfiles" }, + { name = "websockets" }, +] + +[[package]] +name = "uvicorn-worker" +version = "0.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gunicorn" }, + { name = "uvicorn" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/80/59/9101b9c0680fd80e9d26c07deb822a5d18a324339fcf9cd017885ee808ad/uvicorn_worker-0.4.0.tar.gz", hash = "sha256:8ee5306070d8f38dce124adce488c3c0b50f20cf0c0222b12c66188da7214493", size = 9361, upload-time = "2025-09-20T10:47:01.218Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/25/09cd7a90c8bb7fb693be0d6704fccd5f9778d5513214b7a01cc4a94ff314/uvicorn_worker-0.4.0-py3-none-any.whl", hash = "sha256:e2ed952cef976f5e9e429d7269640bbcafbd36c80aa80f1003c8c77a6797abde", size = 5364, upload-time = "2025-09-20T10:46:59.776Z" }, +] + +[[package]] +name = "uvloop" +version = "0.22.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/06/f0/18d39dbd1971d6d62c4629cc7fa67f74821b0dc1f5a77af43719de7936a7/uvloop-0.22.1.tar.gz", hash = "sha256:6c84bae345b9147082b17371e3dd5d42775bddce91f885499017f4607fdaf39f", size = 2443250, upload-time = "2025-10-16T22:17:19.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/cd/b62bdeaa429758aee8de8b00ac0dd26593a9de93d302bff3d21439e9791d/uvloop-0.22.1-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3879b88423ec7e97cd4eba2a443aa26ed4e59b45e6b76aabf13fe2f27023a142", size = 1362067, upload-time = "2025-10-16T22:16:44.503Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f8/a132124dfda0777e489ca86732e85e69afcd1ff7686647000050ba670689/uvloop-0.22.1-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:4baa86acedf1d62115c1dc6ad1e17134476688f08c6efd8a2ab076e815665c74", size = 752423, upload-time = "2025-10-16T22:16:45.968Z" }, + { url = "https://files.pythonhosted.org/packages/a3/94/94af78c156f88da4b3a733773ad5ba0b164393e357cc4bd0ab2e2677a7d6/uvloop-0.22.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:297c27d8003520596236bdb2335e6b3f649480bd09e00d1e3a99144b691d2a35", size = 4272437, upload-time = "2025-10-16T22:16:47.451Z" }, + { url = "https://files.pythonhosted.org/packages/b5/35/60249e9fd07b32c665192cec7af29e06c7cd96fa1d08b84f012a56a0b38e/uvloop-0.22.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c1955d5a1dd43198244d47664a5858082a3239766a839b2102a269aaff7a4e25", size = 4292101, upload-time = "2025-10-16T22:16:49.318Z" }, + { url = "https://files.pythonhosted.org/packages/02/62/67d382dfcb25d0a98ce73c11ed1a6fba5037a1a1d533dcbb7cab033a2636/uvloop-0.22.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b31dc2fccbd42adc73bc4e7cdbae4fc5086cf378979e53ca5d0301838c5682c6", size = 4114158, upload-time = "2025-10-16T22:16:50.517Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/f1171b4a882a5d13c8b7576f348acfe6074d72eaf52cccef752f748d4a9f/uvloop-0.22.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:93f617675b2d03af4e72a5333ef89450dfaa5321303ede6e67ba9c9d26878079", size = 4177360, upload-time = "2025-10-16T22:16:52.646Z" }, + { url = "https://files.pythonhosted.org/packages/79/7b/b01414f31546caf0919da80ad57cbfe24c56b151d12af68cee1b04922ca8/uvloop-0.22.1-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:37554f70528f60cad66945b885eb01f1bb514f132d92b6eeed1c90fd54ed6289", size = 1454790, upload-time = "2025-10-16T22:16:54.355Z" }, + { url = "https://files.pythonhosted.org/packages/d4/31/0bb232318dd838cad3fa8fb0c68c8b40e1145b32025581975e18b11fab40/uvloop-0.22.1-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:b76324e2dc033a0b2f435f33eb88ff9913c156ef78e153fb210e03c13da746b3", size = 796783, upload-time = "2025-10-16T22:16:55.906Z" }, + { url = "https://files.pythonhosted.org/packages/42/38/c9b09f3271a7a723a5de69f8e237ab8e7803183131bc57c890db0b6bb872/uvloop-0.22.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:badb4d8e58ee08dad957002027830d5c3b06aea446a6a3744483c2b3b745345c", size = 4647548, upload-time = "2025-10-16T22:16:57.008Z" }, + { url = "https://files.pythonhosted.org/packages/c1/37/945b4ca0ac27e3dc4952642d4c900edd030b3da6c9634875af6e13ae80e5/uvloop-0.22.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b91328c72635f6f9e0282e4a57da7470c7350ab1c9f48546c0f2866205349d21", size = 4467065, upload-time = "2025-10-16T22:16:58.206Z" }, + { url = "https://files.pythonhosted.org/packages/97/cc/48d232f33d60e2e2e0b42f4e73455b146b76ebe216487e862700457fbf3c/uvloop-0.22.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:daf620c2995d193449393d6c62131b3fbd40a63bf7b307a1527856ace637fe88", size = 4328384, upload-time = "2025-10-16T22:16:59.36Z" }, + { url = "https://files.pythonhosted.org/packages/e4/16/c1fd27e9549f3c4baf1dc9c20c456cd2f822dbf8de9f463824b0c0357e06/uvloop-0.22.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6cde23eeda1a25c75b2e07d39970f3374105d5eafbaab2a4482be82f272d5a5e", size = 4296730, upload-time = "2025-10-16T22:17:00.744Z" }, +] + +[[package]] +name = "watchfiles" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/68/e6aa0b77d217b31f8f486ec0cdfe5e00e6e38dc0be657e7d85819b9faf0a/watchfiles-1.3.0.tar.gz", hash = "sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207", size = 108119, upload-time = "2026-09-21T09:08:55.664Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/68/fa/c0b840d5d8bafe640925408ce11095948c8945bb61be1e67d0ab629b872a/watchfiles-1.3.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441", size = 399703, upload-time = "2026-09-21T09:08:13.518Z" }, + { url = "https://files.pythonhosted.org/packages/c7/8a/894799b485fe9473ad10422a0d9668e53fb78e3a2b5cc6061159572844ad/watchfiles-1.3.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c", size = 397647, upload-time = "2026-09-21T09:08:15.16Z" }, + { url = "https://files.pythonhosted.org/packages/5a/61/f277cd5ead05f5d37b98b41fbdd0c943ee0c04d49738f62e902cb291cf43/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5", size = 454994, upload-time = "2026-09-21T09:08:16.587Z" }, + { url = "https://files.pythonhosted.org/packages/46/66/ea4c01382975e53b1ac1b0a0ea1b353416b8127fb6e04f5c1c313119aab6/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca", size = 460105, upload-time = "2026-09-21T09:08:17.961Z" }, + { url = "https://files.pythonhosted.org/packages/31/c3/1a501b597817096c9831c255f6270c124ce0e2faeb74124be24dcc93b86d/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30", size = 493761, upload-time = "2026-09-21T09:08:19.327Z" }, + { url = "https://files.pythonhosted.org/packages/5a/16/77352d05e152c7786a016e9f1decdb4507e8aa5bcf3343c72142a0413d14/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95", size = 577500, upload-time = "2026-09-21T09:08:20.723Z" }, + { url = "https://files.pythonhosted.org/packages/95/fe/81001c55b24466fe9911135e50269fd3a29f43e446627a92adfab54553b6/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29", size = 469209, upload-time = "2026-09-21T09:08:22.346Z" }, + { url = "https://files.pythonhosted.org/packages/8a/cf/e3ad894ed5909a7c44b0707e89bc25d19a3d78b3a7aec846119443b6ae56/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1", size = 458353, upload-time = "2026-09-21T09:08:23.7Z" }, + { url = "https://files.pythonhosted.org/packages/7f/f5/2f106829e6e2bc91ad74614730f6df484202b9a4d20d927dbf2f08d37d44/watchfiles-1.3.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935", size = 468707, upload-time = "2026-09-21T09:08:25.167Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/2741ab776b978669c1f3bba1e573f1a184f727ab8b4d3a6d9c61090800ed/watchfiles-1.3.0-cp310-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3", size = 632510, upload-time = "2026-09-21T09:08:26.532Z" }, + { url = "https://files.pythonhosted.org/packages/48/64/db4a4684275fe9b696ee5118c194705c1423b3d42181c3f8ee70194d5c73/watchfiles-1.3.0-cp310-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509", size = 661723, upload-time = "2026-09-21T09:08:28.004Z" }, + { url = "https://files.pythonhosted.org/packages/52/80/95ddb24f6a2f595c031c24432ab7b8aa7d6d1ada0c6d63a552166e06e8d1/watchfiles-1.3.0-cp310-abi3-win32.whl", hash = "sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661", size = 277761, upload-time = "2026-09-21T09:08:29.335Z" }, + { url = "https://files.pythonhosted.org/packages/48/a1/1c4a1b3c8030cd03206232612be8a6e8799093490c220b0fcb935d02b75a/watchfiles-1.3.0-cp310-abi3-win_amd64.whl", hash = "sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61", size = 290643, upload-time = "2026-09-21T09:08:30.45Z" }, + { url = "https://files.pythonhosted.org/packages/82/e0/d2db577c632d26d08078c4390dd870b8555c4e558df25d22270f0166c71f/watchfiles-1.3.0-cp310-abi3-win_arm64.whl", hash = "sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc", size = 285510, upload-time = "2026-09-21T09:08:31.561Z" }, + { url = "https://files.pythonhosted.org/packages/4f/55/a122743607939429ab6a7272672f49303aa02bbd34c3f06676765a3861de/watchfiles-1.3.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:e0204f90677b7fb8d3a824279a71a01166bea9f6e53923b8056592d87b33b0b6", size = 395978, upload-time = "2026-09-21T09:08:32.747Z" }, + { url = "https://files.pythonhosted.org/packages/3e/9d/0ee1b0ea42acfe72afa2484f0222e2386dd09992e9034a81e63cc3cdab0a/watchfiles-1.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7c1125e99f84934a92996ae343501285617373acd66f16b59fd5654b27ad8d80", size = 387997, upload-time = "2026-09-21T09:08:33.953Z" }, + { url = "https://files.pythonhosted.org/packages/b7/f2/4319c6b683e8bd28465dfc53c750617a2a07f072eb2e3ab0182ccf812229/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a85e243c87109d9f48a2e0d10d6abdee8768cc114848b32281ec83d7f81d86ef", size = 448067, upload-time = "2026-09-21T09:08:35.104Z" }, + { url = "https://files.pythonhosted.org/packages/b7/71/9f37ac192a51a24de3a2d7fe9aac1e99b2b2668300674ff7a9f85d95beb1/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:dd538c71766c59c732e2c5cedc39323c99c11897b99f93eac773438e54af206a", size = 452881, upload-time = "2026-09-21T09:08:36.238Z" }, + { url = "https://files.pythonhosted.org/packages/34/07/1224667c32a4a96876ddd642da69733cbfe6a15897db0865aec5a882cebc/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:da213822ec9082b62cadf3008e07a8c690ec7a3c89f6dc5e55a8cf07b56a1b26", size = 484802, upload-time = "2026-09-21T09:08:37.717Z" }, + { url = "https://files.pythonhosted.org/packages/bd/4d/7f29cd87e1f826df86fc0418d0b8f370ca0311c29c618406dc492aad9951/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d4593392e87669836670f87d62fc754059eaeb0e6157af44060a46558cebe5a3", size = 567522, upload-time = "2026-09-21T09:08:38.94Z" }, + { url = "https://files.pythonhosted.org/packages/e3/ac/3aa1f84abd4dbbfbae99a817dd931f77b439261c911189cad4c30fdfd470/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:26b81bc515a0f03f66a69a6fea86eea54c8eca4173c46dd7222569f79dd2f977", size = 461997, upload-time = "2026-09-21T09:08:40.142Z" }, + { url = "https://files.pythonhosted.org/packages/82/1c/27c66764d5b0dbb70a36770a32eca217eba739c28b24e8583a035087a3d7/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca39661934749df580d89f3dde266f2af7c6968f4c21c72ce2dc387d299e6aa7", size = 451856, upload-time = "2026-09-21T09:08:41.305Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b3/a45827084d953c1d0dd3d75abf85dcac26a0f5d115ad2fe0b7e9e931573b/watchfiles-1.3.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:04c5500faa725d69a99b0f63750e80795e455bb951849e9c98a811b4324997c4", size = 459889, upload-time = "2026-09-21T09:08:42.58Z" }, + { url = "https://files.pythonhosted.org/packages/7a/3d/07740d23ce2bb23419bb24055c435a9abe5fe03efdaea1ba0720b831aab6/watchfiles-1.3.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:ec3cd4bb181a7b6329134204c2277c7144ab5f62cce9c5335d6f901ee7ce8d6a", size = 624482, upload-time = "2026-09-21T09:08:44.064Z" }, + { url = "https://files.pythonhosted.org/packages/91/46/9540f8123eaec86df989f26d7704cad0448d9fb7271763a4f8f9fe23617d/watchfiles-1.3.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:e5871d4a7f788a9f64fb06f5793389d29d171e5c32d37c3ebfd520b017cc7694", size = 653724, upload-time = "2026-09-21T09:08:45.257Z" }, + { url = "https://files.pythonhosted.org/packages/25/9d/b9deb52f1e4528ffe44338c5ebab95c32ed79203082da661de50288e130a/watchfiles-1.3.0-cp314-cp314t-win32.whl", hash = "sha256:81c989d7267bfb7b676cd32c83bec97914e396870983cbf493e29415037bff5e", size = 270863, upload-time = "2026-09-21T09:08:46.518Z" }, + { url = "https://files.pythonhosted.org/packages/59/59/8b1881afccbafda06248be4185e28034dd73c80c85e4da24f2cb0c1321eb/watchfiles-1.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d754e049006e81a9be49dc78ba7802081cee426e968cbc63ee19e164fa2d0e39", size = 286879, upload-time = "2026-09-21T09:08:47.874Z" }, + { url = "https://files.pythonhosted.org/packages/46/dd/41c12ae9745d5d72f709333287679d71cbba68ad7678fed872207bba94f4/watchfiles-1.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:a5b631db08fd3032db57ec6a92d1777cd60f88803287e4e941a4858c53aab1e0", size = 276924, upload-time = "2026-09-21T09:08:48.976Z" }, +] + +[[package]] +name = "websockets" +version = "17.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/72/fba934cb3dff7a85d811820efffcd141ddd52b5a2a01637f64551373ff4d/websockets-17.1.tar.gz", hash = "sha256:acfea4c20bf54384883ea33b1240fc1db4f52e190823a4e2b334bc3e8bfca96a", size = 187520, upload-time = "2026-08-26T17:25:33.063Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/0d/500cf5daea09d4669dff3a7d67159094a0bd6c4ef130381404f6edd3eb5f/websockets-17.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0c9982938980e086da59f70d05f9418cd143401a601a0faac10fa48f7bb1cd3e", size = 217048, upload-time = "2026-08-26T14:56:36.03Z" }, + { url = "https://files.pythonhosted.org/packages/97/12/5b12c6168aa269cffbfd24d177cd492b130120403a418c7e89462e27b4ac/websockets-17.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:57b39dc8541cf7ed3f639da82bf7451060483967f9e733da1f8173e4095f0642", size = 214737, upload-time = "2026-08-26T14:56:37.43Z" }, + { url = "https://files.pythonhosted.org/packages/0c/36/e453e5106e4e2416f008ac222837c2f1637a063b08008afcd1088889b631/websockets-17.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:96abdecbaae746851b87c3a36cb4a661df93ca3d92f114270f79228bf1d00de6", size = 214955, upload-time = "2026-08-26T14:56:38.71Z" }, + { url = "https://files.pythonhosted.org/packages/dd/30/0204bb86176db02cdfc678ce65ed808a66fab87d250ce61a8790800a60b0/websockets-17.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:d9fc873e239c5abeb150bc24dbd1a7af23a9254526383ce0a077f5e20adbeb19", size = 224331, upload-time = "2026-08-26T14:56:39.924Z" }, + { url = "https://files.pythonhosted.org/packages/46/c8/d8372256e00c4e3cab1115c45075d1eeedb642a3f2b42bd70c4deae03f06/websockets-17.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6f42912fa9eb4cb7c7ec9fde9b3332ba339eb8a8811981043d4029599f3d950b", size = 224685, upload-time = "2026-08-26T14:56:41.169Z" }, + { url = "https://files.pythonhosted.org/packages/12/7d/650355b8f67f908ff99603351d4458d1a0b787d627950a47c38db7e25308/websockets-17.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f98bf378d7a5be047a044a1a27c987a8f355e10e3b5754617dbe756248cbc5ce", size = 225927, upload-time = "2026-08-26T14:56:42.359Z" }, + { url = "https://files.pythonhosted.org/packages/34/6c/a9ffa5b903579eed76017870f055d75ecc73988d9d0c9b65a92ba0bf2a27/websockets-17.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d334d11398086bb5559606cb42d51c013ea7c061c7db701521392373d3c087f5", size = 227300, upload-time = "2026-08-26T14:56:43.538Z" }, + { url = "https://files.pythonhosted.org/packages/9b/5d/4551c2269066af7481ee44605a0813770961615b5b5da3e87a8f5cb859ea/websockets-17.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5c27336b1a0ac56569493e858497870347854372395f50483725f8cdacc5a45c", size = 226533, upload-time = "2026-08-26T14:56:44.669Z" }, + { url = "https://files.pythonhosted.org/packages/3c/43/237a99233e5c445759a613831b3a92e91905afc064dc3bd0ad33c35fd1e2/websockets-17.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:67258b00302a5aaf0b267771c7014b13429abd7ea17eebc4c55bd935ff101555", size = 225280, upload-time = "2026-08-26T14:56:45.83Z" }, + { url = "https://files.pythonhosted.org/packages/d3/b5/e9407a91613d1d1cd932414143a1012096b26674a782fc55a0bd23217ee4/websockets-17.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:455ffeea0879d313205df1e745e5883e1feb7f31ecd26be882f5f0babd3db04f", size = 222540, upload-time = "2026-08-26T14:56:47.053Z" }, + { url = "https://files.pythonhosted.org/packages/db/d2/db76628db0577b783205d9779f64d8e373416b04c62d1546be4b75dc8540/websockets-17.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f7233eaf441a345a5943a929fd4b5ea3278f11aed35a9ed0f3106b8cb3ca846a", size = 225354, upload-time = "2026-08-26T14:56:48.32Z" }, + { url = "https://files.pythonhosted.org/packages/a9/4c/2174181c067b89a74ae18e2650c2ac29959f4b796afe876ab3f4d30d642c/websockets-17.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:c65da239a5ad553619804c1f9d65c1a0b3005381c6158ee14da2c7444cbd0c78", size = 223867, upload-time = "2026-08-26T14:56:49.579Z" }, + { url = "https://files.pythonhosted.org/packages/df/75/274decb9a8253561b5be3261e02a6676fc8ecdf31e95b722e53d5bfb8fd2/websockets-17.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:9fa1ffa08c81a4f809cdab6129f8e55bee4650b9d6d3461019dda73aacd146b6", size = 224652, upload-time = "2026-08-26T14:56:50.885Z" }, + { url = "https://files.pythonhosted.org/packages/9f/e6/49824f1fb4db7656d2f7492b1d8be16147b759d909490e32f4776843ee64/websockets-17.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:406b8107943a43ef4649b1e0cb0cdc052bbf08fe1c8905a623c4af9586e5cebb", size = 225822, upload-time = "2026-08-26T14:56:52.356Z" }, + { url = "https://files.pythonhosted.org/packages/b8/6a/5dc43838c0b02a95f42c47a0de33c5ddd7767a9feeb4d0d8777ac1cfefe4/websockets-17.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:4e8ffcb486c8490a34a4cef5e4409d8da5a1cb1681e5bf7d786ce5e84aa8540d", size = 223379, upload-time = "2026-08-26T14:56:53.699Z" }, + { url = "https://files.pythonhosted.org/packages/c2/62/585637cf06d6b321232f79c55dc14d65518d12cf87c94c44f5864068810e/websockets-17.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:fb88076df585b69c5761c387c0081aa87d7b9eb1b205a6535ca4777e25650d81", size = 224330, upload-time = "2026-08-26T14:56:55.184Z" }, + { url = "https://files.pythonhosted.org/packages/de/68/c3b234a6a1366b6ab5bbfaa4434a1b946e1dc4e8ddd6824bfd93a8835b7f/websockets-17.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5d4724255fb8398acd9e583b97eb2279cec20e0bd0f9a94bf75f6056ef9f13da", size = 224622, upload-time = "2026-08-26T14:56:56.393Z" }, + { url = "https://files.pythonhosted.org/packages/6a/d4/84cf3d1376f5d8207f55f43c1c818babd6b89447f5dcd01f18a6d5526796/websockets-17.1-cp314-cp314-win32.whl", hash = "sha256:be3f0129c5654517b2abf07dcb75bb1d9479759a4ccfb569e8293579e9fc029a", size = 217036, upload-time = "2026-08-26T14:56:57.652Z" }, + { url = "https://files.pythonhosted.org/packages/d0/0f/9e7ac63c5d7cb642952200814f584318e65146df008b7d375d5d9c6b2c97/websockets-17.1-cp314-cp314-win_amd64.whl", hash = "sha256:2a4dc6ef83f4559e0d05f313a375cb38f63c986096a9da99fe94fdd779d313e5", size = 217382, upload-time = "2026-08-26T14:56:59.065Z" }, + { url = "https://files.pythonhosted.org/packages/54/bb/1ae6b91f7f3ac05f5c9f14a72dc2181c115ff370bcd8a7f10f02c174adfd/websockets-17.1-cp314-cp314-win_arm64.whl", hash = "sha256:46c0331c9eaaf73a559f3a9e388466be0df96eb83d40f06f1ca6ab6613b35c82", size = 217268, upload-time = "2026-08-26T14:57:00.654Z" }, + { url = "https://files.pythonhosted.org/packages/b3/f0/f65644d0e0b2b90918a8c41503841cc4072a58f2bf76c09bc36e751fc0dd/websockets-17.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:d411ea5ca18ac1b12c0c94be88b60c18ca641ac43bcdfdf1c9f79d46cdbe1603", size = 217379, upload-time = "2026-08-26T14:57:02.181Z" }, + { url = "https://files.pythonhosted.org/packages/ff/35/4c46d1f620ac1a30f92b6eae78ee40a772a93f568647ca7ccdc5ea283cf8/websockets-17.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:07fa3e7c30e2c577928d359b56bf872a3e0cbcc15553eaa0907c1ee86344b56f", size = 214911, upload-time = "2026-08-26T14:57:03.478Z" }, + { url = "https://files.pythonhosted.org/packages/04/6e/4587e8406d7c1188e97b9cf466c081e93399380d447f885bfce81626cd37/websockets-17.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6de9acef07e3a78e9567fcd26c29011a4da8f050b13004bbf880a0fd82a6eea5", size = 215115, upload-time = "2026-08-26T14:57:04.692Z" }, + { url = "https://files.pythonhosted.org/packages/ec/06/1381c8fff525041025909eb80ace32489194a00ba22a0a8d428030afcc84/websockets-17.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:ea0ed9373b880115911d9d39634bccc95b8ce590c9c42e8589f5cacc3ef3cee2", size = 224696, upload-time = "2026-08-26T14:57:05.899Z" }, + { url = "https://files.pythonhosted.org/packages/36/9d/9034e867dc85340be058619751742b895f722326e83100d110063461ca07/websockets-17.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:50903d335bfda026c2fa11dd9aed09d8cbee0c451e3a85122a9acb041b7dc69b", size = 224975, upload-time = "2026-08-26T14:57:07.262Z" }, + { url = "https://files.pythonhosted.org/packages/40/eb/ed03aa3cae748ebf6397e5d44028f433f746bad09dc568ff754fda3a3c9b/websockets-17.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5a74531ce81af587f906ab42f194032388fcff8fc7938402e5917c9147a39441", size = 226151, upload-time = "2026-08-26T14:57:08.524Z" }, + { url = "https://files.pythonhosted.org/packages/b1/c9/cc1964a096d16f3b73cb1ee5f14f277f5a3bcac07c6e8f9a1dcded99f4c8/websockets-17.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8fbf28e639544503b7d1c96452a5e5e043e4108d89b1f3fa02910603622d19db", size = 228292, upload-time = "2026-08-26T14:57:09.846Z" }, + { url = "https://files.pythonhosted.org/packages/1a/26/46da6dd0363c2db2e4876fd59a40fd40c1943a82d7018d0a33afbce47d52/websockets-17.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f612dc57f00c07cf4aa2673f7cbceabd654ad2457b7e639f061b794d6e11f9fd", size = 226722, upload-time = "2026-08-26T14:57:11.118Z" }, + { url = "https://files.pythonhosted.org/packages/78/98/ecd8f5e1c5d0e54c08ebc5c66852271112166db68107cb0e17ca1bf25009/websockets-17.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1c7ac77401227212dc6e849182feee50d57cf456ec6329ffd6979c94bb136c5c", size = 225451, upload-time = "2026-08-26T14:57:12.601Z" }, + { url = "https://files.pythonhosted.org/packages/65/4d/da8d2760db53e17aae763738b6ba834b1fcf16813d3632f3edb6951e1ec8/websockets-17.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:32a2a68d989d6e5b74a9d5095415c51189ebae29fceb7cf2b64a1c0318a81256", size = 223003, upload-time = "2026-08-26T14:57:13.875Z" }, + { url = "https://files.pythonhosted.org/packages/a4/40/ea401c141a79c5b1d0021a0dab9d0df2051c108f1620fbb39a6e7c714c3b/websockets-17.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:aec00f018d34c67500ff0438dc314b40277be4a1b983cbacbf53ccf7db63e257", size = 225704, upload-time = "2026-08-26T14:57:15.091Z" }, + { url = "https://files.pythonhosted.org/packages/e1/8e/07ab3f44215d89840d5385fdcaaab1fed8caeffa67c6899e15062957c12c/websockets-17.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:0014eaff8ad5b3b43feda2279f9d34bf2eaae040720b9fbbb55944b10f40b14d", size = 224192, upload-time = "2026-08-26T14:57:16.3Z" }, + { url = "https://files.pythonhosted.org/packages/58/93/ccf1af0a23e5748d4e22292a377d78d15cf294d7e707bbb11a8990ae6bd5/websockets-17.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:db9d7ee47f3ba531e278be539af39e2c7c7d28fb94897b6cd1120d63b0ef5922", size = 225082, upload-time = "2026-08-26T14:57:17.531Z" }, + { url = "https://files.pythonhosted.org/packages/e2/db/e32200f99ce282e728d2929f2c429db353cf3282db7d0eba99eb32c9fec1/websockets-17.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:ff3e2ba7a9f0a110b0555452e9b5a03a34e11662544e01beea15f144b48ba7b7", size = 226101, upload-time = "2026-08-26T14:57:18.802Z" }, + { url = "https://files.pythonhosted.org/packages/28/3d/e7a6e9777b29433620167c98f3caaff0d6b08b1239a273ef7f7fd1393349/websockets-17.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:6da17fc94bd270f5987b10bee113461ac36a36a98b0481ddcc98056e5a90001a", size = 223794, upload-time = "2026-08-26T14:57:20.313Z" }, + { url = "https://files.pythonhosted.org/packages/48/05/ac569090726dedd6656f3ee28b0c02dfb1ba76e898dceaccc2987a237cef/websockets-17.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:e8dc3fa6d6b7ead3f9de57895f41b116a28787548e066365d9d90f7356bcaad2", size = 224567, upload-time = "2026-08-26T14:57:21.634Z" }, + { url = "https://files.pythonhosted.org/packages/14/50/4ef62941111db6b31193f4fabbb65f845a5177579040cb8fe0d774d25034/websockets-17.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b65d5fe48219dc2d5e158de9e6514e75600f379cc7e37108d35f31764c155566", size = 224993, upload-time = "2026-08-26T14:57:22.86Z" }, + { url = "https://files.pythonhosted.org/packages/28/42/2b95ada4ea19bf3a2072b68669ce4f4afb212690b727d31640576287fd68/websockets-17.1-cp314-cp314t-win32.whl", hash = "sha256:2cce251f3e2469b99b6802b55435bcdd07123b41870f54c87b336183af9d7e68", size = 217168, upload-time = "2026-08-26T14:57:24.466Z" }, + { url = "https://files.pythonhosted.org/packages/32/0a/67d5ee08dd8060a37d612fd40a625b5376ad19ae48fe1c8ad428c278b817/websockets-17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:8f6c38cdcaf98a911d7acc25577f2f9e710f3a2fc2bde1563556784320196b51", size = 217508, upload-time = "2026-08-26T14:57:25.983Z" }, + { url = "https://files.pythonhosted.org/packages/76/a3/822005d0c674451d2411027b878cdc128a2b7ea5a30d337d9e279da22eba/websockets-17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:d1e2f5fa2b6d01f0d85b4f223fea7ed1d504be282a02a81bd2be4817ef7a2f03", size = 217425, upload-time = "2026-08-26T14:57:27.324Z" }, + { url = "https://files.pythonhosted.org/packages/41/63/23572870e01836a98346075b9e17a8bc24a6ddd9800a3204ceee58677f3c/websockets-17.1-py3-none-any.whl", hash = "sha256:f221081107b8c48184d99f7019604486376e7ef826037e70aad6b02540732c23", size = 211134, upload-time = "2026-08-26T17:25:31.397Z" }, +]