From a6c74c9bb0ec78ee8c917f04278bccdc90dfaf6f Mon Sep 17 00:00:00 2001 From: Enterxx2 Date: Sun, 4 Oct 2026 15:30:59 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D0=BE=D0=BD=D0=B0=D0=BB=20=D0=BF=D0=B5=D1=80=D0=B2=D0=BE=D0=B9?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D1=8B=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 13 + .env.example | 2 + .gitignore | 1 + Dockerfile | 20 + Makefile | 52 +- docker-compose-local.yaml | 9 + poetry.lock | 547 ++++++++++++++++++ pyproject.toml | 26 + scripts/sigterm_check.py | 127 ++++ src/application/__init__.py | 4 + src/application/api/__init__.py | 10 + src/application/api/dependencies/__init__.py | 4 + src/application/api/dependencies/auth.py | 15 + src/application/api/dependencies/security.py | 10 + src/application/api/handlers/__init__.py | 3 + src/application/api/handlers/exceptions.py | 57 ++ src/application/api/health/__init__.py | 3 + src/application/api/health/endpoints.py | 28 + src/application/api/middlewares/__init__.py | 3 + .../api/middlewares/request_context.py | 55 ++ src/application/api/routers/__init__.py | 13 + src/application/api/routers/chats/__init__.py | 3 + .../api/routers/chats/endpoints.py | 58 ++ .../api/routers/messages/__init__.py | 3 + .../api/routers/messages/endpoints.py | 48 ++ src/application/api/routers/users/__init__.py | 3 + .../api/routers/users/endpoints.py | 33 ++ src/application/api/utils/__init__.py | 3 + src/application/api/utils/errors.py | 32 + src/config/__init__.py | 17 + src/config/log_config.py | 12 + src/config/settings.py | 17 + src/domain/__init__.py | 19 + src/domain/chats/__init__.py | 10 + src/domain/chats/constants.py | 3 + src/domain/chats/schemas.py | 46 ++ src/domain/errors/__init__.py | 22 + src/domain/errors/codes.py | 15 + src/domain/errors/exceptions.py | 55 ++ src/domain/errors/schemas.py | 21 + src/domain/health/__init__.py | 3 + src/domain/health/schemas.py | 9 + src/domain/messages/__init__.py | 9 + src/domain/messages/constants.py | 1 + src/domain/messages/schemas.py | 39 ++ src/domain/pagination/__init__.py | 6 + src/domain/pagination/schemas.py | 26 + src/domain/users/__init__.py | 9 + src/domain/users/constants.py | 3 + src/domain/users/schemas.py | 33 ++ src/domain/utils/__init__.py | 3 + src/domain/utils/types.py | 25 + src/gateway.py | 51 ++ src/healthcheck.py | 20 + src/infrastructure/__init__.py | 3 + src/infrastructure/dependencies/__init__.py | 4 + .../dependencies/service_creator.py | 51 ++ src/infrastructure/dependencies/storage.py | 9 + src/infrastructure/repositories/__init__.py | 9 + .../repositories/chat_repository/__init__.py | 3 + .../repositories/chat_repository/in_memory.py | 36 ++ .../message_repository/__init__.py | 3 + .../message_repository/in_memory.py | 29 + .../repositories/user_repository/__init__.py | 3 + .../repositories/user_repository/in_memory.py | 32 + src/infrastructure/services/__init__.py | 5 + .../services/chat_service/__init__.py | 3 + .../services/chat_service/chat_service.py | 47 ++ .../services/message_service/__init__.py | 3 + .../message_service/message_service.py | 42 ++ .../services/user_service/__init__.py | 3 + .../services/user_service/user_service.py | 34 ++ src/infrastructure/storage/__init__.py | 3 + src/infrastructure/storage/in_memory.py | 23 + src/infrastructure/utils/__init__.py | 17 + src/infrastructure/utils/clock.py | 22 + src/infrastructure/utils/pagination.py | 53 ++ src/interfaces/__init__.py | 5 + src/interfaces/chat_repository.py | 25 + src/interfaces/message_repository.py | 20 + src/interfaces/user_repository.py | 23 + student-tests/conftest.py | 63 ++ student-tests/helpers.py | 43 ++ student-tests/test_concurrency.py | 77 +++ student-tests/test_foreign_chat.py | 49 ++ student-tests/test_health.py | 15 + student-tests/test_invalid_json.py | 94 +++ student-tests/test_messages.py | 59 ++ student-tests/test_pagination.py | 138 +++++ student-tests/test_users.py | 40 ++ 90 files changed, 2746 insertions(+), 1 deletion(-) create mode 100644 Dockerfile create mode 100644 docker-compose-local.yaml create mode 100644 poetry.lock create mode 100644 pyproject.toml create mode 100644 scripts/sigterm_check.py create mode 100644 src/application/__init__.py create mode 100644 src/application/api/__init__.py create mode 100644 src/application/api/dependencies/__init__.py create mode 100644 src/application/api/dependencies/auth.py create mode 100644 src/application/api/dependencies/security.py create mode 100644 src/application/api/handlers/__init__.py create mode 100644 src/application/api/handlers/exceptions.py create mode 100644 src/application/api/health/__init__.py create mode 100644 src/application/api/health/endpoints.py create mode 100644 src/application/api/middlewares/__init__.py create mode 100644 src/application/api/middlewares/request_context.py create mode 100644 src/application/api/routers/__init__.py create mode 100644 src/application/api/routers/chats/__init__.py create mode 100644 src/application/api/routers/chats/endpoints.py create mode 100644 src/application/api/routers/messages/__init__.py create mode 100644 src/application/api/routers/messages/endpoints.py create mode 100644 src/application/api/routers/users/__init__.py create mode 100644 src/application/api/routers/users/endpoints.py create mode 100644 src/application/api/utils/__init__.py create mode 100644 src/application/api/utils/errors.py create mode 100644 src/config/__init__.py create mode 100644 src/config/log_config.py create mode 100644 src/config/settings.py create mode 100644 src/domain/__init__.py create mode 100644 src/domain/chats/__init__.py create mode 100644 src/domain/chats/constants.py create mode 100644 src/domain/chats/schemas.py create mode 100644 src/domain/errors/__init__.py create mode 100644 src/domain/errors/codes.py create mode 100644 src/domain/errors/exceptions.py create mode 100644 src/domain/errors/schemas.py create mode 100644 src/domain/health/__init__.py create mode 100644 src/domain/health/schemas.py create mode 100644 src/domain/messages/__init__.py create mode 100644 src/domain/messages/constants.py create mode 100644 src/domain/messages/schemas.py create mode 100644 src/domain/pagination/__init__.py create mode 100644 src/domain/pagination/schemas.py create mode 100644 src/domain/users/__init__.py create mode 100644 src/domain/users/constants.py create mode 100644 src/domain/users/schemas.py create mode 100644 src/domain/utils/__init__.py create mode 100644 src/domain/utils/types.py create mode 100644 src/gateway.py create mode 100644 src/healthcheck.py create mode 100644 src/infrastructure/__init__.py create mode 100644 src/infrastructure/dependencies/__init__.py create mode 100644 src/infrastructure/dependencies/service_creator.py create mode 100644 src/infrastructure/dependencies/storage.py create mode 100644 src/infrastructure/repositories/__init__.py create mode 100644 src/infrastructure/repositories/chat_repository/__init__.py create mode 100644 src/infrastructure/repositories/chat_repository/in_memory.py create mode 100644 src/infrastructure/repositories/message_repository/__init__.py create mode 100644 src/infrastructure/repositories/message_repository/in_memory.py create mode 100644 src/infrastructure/repositories/user_repository/__init__.py create mode 100644 src/infrastructure/repositories/user_repository/in_memory.py create mode 100644 src/infrastructure/services/__init__.py create mode 100644 src/infrastructure/services/chat_service/__init__.py create mode 100644 src/infrastructure/services/chat_service/chat_service.py create mode 100644 src/infrastructure/services/message_service/__init__.py create mode 100644 src/infrastructure/services/message_service/message_service.py create mode 100644 src/infrastructure/services/user_service/__init__.py create mode 100644 src/infrastructure/services/user_service/user_service.py create mode 100644 src/infrastructure/storage/__init__.py create mode 100644 src/infrastructure/storage/in_memory.py create mode 100644 src/infrastructure/utils/__init__.py create mode 100644 src/infrastructure/utils/clock.py create mode 100644 src/infrastructure/utils/pagination.py create mode 100644 src/interfaces/__init__.py create mode 100644 src/interfaces/chat_repository.py create mode 100644 src/interfaces/message_repository.py create mode 100644 src/interfaces/user_repository.py create mode 100644 student-tests/conftest.py create mode 100644 student-tests/helpers.py create mode 100644 student-tests/test_concurrency.py create mode 100644 student-tests/test_foreign_chat.py create mode 100644 student-tests/test_health.py create mode 100644 student-tests/test_invalid_json.py create mode 100644 student-tests/test_messages.py create mode 100644 student-tests/test_pagination.py create mode 100644 student-tests/test_users.py diff --git a/.dockerignore b/.dockerignore index bc16e55..7c41595 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,16 @@ __pycache__ node_modules evidence .DS_Store +.pytest_cache +*.py[cod] +tests +student-tests +contracts +scripts +examples +docs +*.md +Makefile +Dockerfile* +requirements-dev.txt +lab.json diff --git a/.env.example b/.env.example index 714c807..074c931 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,8 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +LOG_LEVEL=INFO +SHUTDOWN_TIMEOUT_SEC=5 SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url diff --git a/.gitignore b/.gitignore index b5a7189..ed8abe8 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,4 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +.pytest_cache/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4cf1cea --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +FROM python:3.12.12-slim-bookworm + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + POETRY_VIRTUALENVS_CREATE=false + +WORKDIR /app +COPY poetry.lock pyproject.toml ./ +RUN pip install --no-cache-dir "poetry==2.2.1" \ + && poetry install --only main --no-root --no-interaction +COPY src ./src + +# Процесс работает не от root +RUN useradd --system --uid 10001 --no-create-home app +USER app + +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD ["python", "src/healthcheck.py"] +CMD ["python", "src/gateway.py"] diff --git a/Makefile b/Makefile index 9ecb223..0bf045e 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,19 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +ENV_FILE ?= .env +-include $(ENV_FILE) +IMAGE ?= mtusi-messenger:lab2 +CONTAINER ?= mtusi-messenger-lab2 +PUBLISH ?= 127.0.0.1:$(APP_PORT):$(APP_PORT) +READY_TIMEOUT_SEC ?= 30 +POETRY ?= poetry + +.PHONY: help check validate test load test-persistence install build run wait-ready stop restart logs student-test concurrency-test sigterm-check up_local down_local help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "install: dev venv; build/run/stop/restart/logs: container; up_local/down_local: docker compose; student-test: own tests; concurrency-test, sigterm-check: evidence" check: $(PYTHON) scripts/check_contract.py @@ -24,3 +33,44 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +install: + $(POETRY) install --no-root + +build: + docker build -t $(IMAGE) . + +run: + docker run --rm -d --name $(CONTAINER) -p $(PUBLISH) --env-file $(ENV_FILE) $(IMAGE) + @$(MAKE) --no-print-directory wait-ready + +wait-ready: + @for i in $$(seq 1 $(READY_TIMEOUT_SEC)); do \ + curl -fsS "$(BASE_URL)/health/ready" >/dev/null 2>&1 && echo "ready: $(BASE_URL)" && exit 0; \ + sleep 1; \ + done; echo "API is not ready after $(READY_TIMEOUT_SEC)s"; exit 1 + +stop: + docker stop $(CONTAINER) + +restart: + docker restart $(CONTAINER) + @$(MAKE) --no-print-directory wait-ready + +logs: + docker logs -f $(CONTAINER) + +student-test: + BASE_URL="$(BASE_URL)" $(POETRY) run pytest + +concurrency-test: + BASE_URL="$(BASE_URL)" $(POETRY) run pytest student-tests/test_concurrency.py -s + +sigterm-check: + CONTAINER="$(CONTAINER)" $(PYTHON) scripts/sigterm_check.py --base-url "$(BASE_URL)" + +up_local: + docker compose -f docker-compose-local.yaml up --build -d + +down_local: + docker compose -f docker-compose-local.yaml down diff --git a/docker-compose-local.yaml b/docker-compose-local.yaml new file mode 100644 index 0000000..51620a2 --- /dev/null +++ b/docker-compose-local.yaml @@ -0,0 +1,9 @@ +services: + messenger: + build: . + image: mtusi-messenger:lab2 + container_name: mtusi-messenger-lab2 + env_file: + - .env + ports: + - "127.0.0.1:${APP_PORT}:${APP_PORT}" diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..c58ac8e --- /dev/null +++ b/poetry.lock @@ -0,0 +1,547 @@ +# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand. + +[[package]] +name = "annotated-doc" +version = "0.0.5" +description = "Document parameters, class attributes, return types, and variables inline, with Annotated." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101"}, + {file = "annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb"}, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +description = "Reusable constraint types to use with typing.Annotated" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0"}, + {file = "annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7"}, +] + +[[package]] +name = "anyio" +version = "4.15.1" +description = "High-level concurrency and networking framework on top of asyncio or Trio" +optional = false +python-versions = ">=3.10" +groups = ["main", "dev"] +files = [ + {file = "anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101"}, + {file = "anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94"}, +] + +[package.dependencies] +idna = ">=2.8" +typing_extensions = {version = ">=4.16.0", markers = "python_version < \"3.15\""} + +[package.extras] +trio = ["trio (>=0.32.0)"] + +[[package]] +name = "certifi" +version = "2026.7.22" +description = "Python package for providing Mozilla's CA Bundle." +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775"}, + {file = "certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55"}, +] + +[[package]] +name = "click" +version = "8.5.0" +description = "Composable command line interface toolkit" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360"}, + {file = "click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34"}, +] + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["main", "dev"] +markers = "sys_platform == \"win32\"" +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] + +[[package]] +name = "envparse" +version = "0.2.0" +description = "Simple environment variable parsing" +optional = false +python-versions = "*" +groups = ["main"] +files = [ + {file = "envparse-0.2.0.tar.gz", hash = "sha256:4f3b9a27bb55d27f124eb4adf006fec05e4588891c9a054a183a112645056eb7"}, +] + +[package.extras] +testing = ["pytest"] + +[[package]] +name = "fastapi" +version = "0.142.2" +description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "fastapi-0.142.2-py3-none-any.whl", hash = "sha256:bd5f4d81f1e93a88bcd77caf4dfe3c2dbffc3805407a0007e9a114c18b3a670b"}, + {file = "fastapi-0.142.2.tar.gz", hash = "sha256:06366626f2e70576367714d9ab2fe8472e6c8456dba69b399f9f797ab5e92570"}, +] + +[package.dependencies] +annotated-doc = ">=0.0.2" +opentelemetry-api = ">=1.44.0" +pydantic = ">=2.9.0" +starlette = ">=0.46.0" +typing-extensions = ">=4.8.0" +typing-inspection = ">=0.4.2" + +[package.extras] +all = ["email-validator (>=2.0.0)", "fastapi-cli[standard] (>=0.0.32)", "httpx (>=0.23.0,<1.0.0)", "itsdangerous (>=1.1.0)", "jinja2 (>=3.1.5)", "opentelemetry-exporter-otlp-proto-http (>=1.44.0)", "opentelemetry-sdk (>=1.44.0)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.18)", "pyyaml (>=5.3.1)", "uvicorn[standard] (>=0.12.0)"] +opentelemetry = ["opentelemetry-exporter-otlp-proto-http (>=1.44.0)", "opentelemetry-sdk (>=1.44.0)"] +standard = ["email-validator (>=2.0.0)", "fastapi-cli[standard] (>=0.0.32)", "fastar (>=0.9.0)", "httpx (>=0.23.0,<1.0.0)", "jinja2 (>=3.1.5)", "opentelemetry-exporter-otlp-proto-http (>=1.44.0)", "opentelemetry-sdk (>=1.44.0)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.18)", "uvicorn[standard] (>=0.12.0)"] +standard-no-fastapi-cloud-cli = ["email-validator (>=2.0.0)", "fastapi-cli[standard-no-fastapi-cloud-cli] (>=0.0.32)", "httpx (>=0.23.0,<1.0.0)", "jinja2 (>=3.1.5)", "opentelemetry-exporter-otlp-proto-http (>=1.44.0)", "opentelemetry-sdk (>=1.44.0)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.18)", "uvicorn[standard] (>=0.12.0)"] + +[[package]] +name = "h11" +version = "0.16.0" +description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1" +optional = false +python-versions = ">=3.8" +groups = ["main", "dev"] +files = [ + {file = "h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86"}, + {file = "h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1"}, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +description = "A minimal low-level HTTP client." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55"}, + {file = "httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8"}, +] + +[package.dependencies] +certifi = "*" +h11 = ">=0.16" + +[package.extras] +asyncio = ["anyio (>=4.0,<5.0)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] +trio = ["trio (>=0.22.0,<1.0)"] + +[[package]] +name = "httpx" +version = "0.28.1" +description = "The next generation HTTP client." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad"}, + {file = "httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc"}, +] + +[package.dependencies] +anyio = "*" +certifi = "*" +httpcore = "==1.*" +idna = "*" + +[package.extras] +brotli = ["brotli ; platform_python_implementation == \"CPython\"", "brotlicffi ; platform_python_implementation != \"CPython\""] +cli = ["click (==8.*)", "pygments (==2.*)", "rich (>=10,<14)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] +zstd = ["zstandard (>=0.18.0)"] + +[[package]] +name = "idna" +version = "3.20" +description = "Internationalized Domain Names in Applications (IDNA)" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c"}, + {file = "idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44"}, +] + +[package.extras] +all = ["coverage (>=7.10.0)", "hypothesis (>=6.141.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.16.0)", "ty (>=0.0.37)"] + +[[package]] +name = "iniconfig" +version = "2.3.0" +description = "brain-dead simple config-ini parsing" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12"}, + {file = "iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730"}, +] + +[[package]] +name = "loguru" +version = "0.7.3" +description = "Python logging made (stupidly) simple" +optional = false +python-versions = "<4.0,>=3.5" +groups = ["main"] +files = [ + {file = "loguru-0.7.3-py3-none-any.whl", hash = "sha256:31a33c10c8e1e10422bfd431aeb5d351c7cf7fa671e3c4df004162264b28220c"}, + {file = "loguru-0.7.3.tar.gz", hash = "sha256:19480589e77d47b8d85b2c827ad95d49bf31b0dcde16593892eb51dd18706eb6"}, +] + +[package.dependencies] +colorama = {version = ">=0.3.4", markers = "sys_platform == \"win32\""} +win32-setctime = {version = ">=1.0.0", markers = "sys_platform == \"win32\""} + +[package.extras] +dev = ["Sphinx (==8.1.3) ; python_version >= \"3.11\"", "build (==1.2.2) ; python_version >= \"3.11\"", "colorama (==0.4.5) ; python_version < \"3.8\"", "colorama (==0.4.6) ; python_version >= \"3.8\"", "exceptiongroup (==1.1.3) ; python_version >= \"3.7\" and python_version < \"3.11\"", "freezegun (==1.1.0) ; python_version < \"3.8\"", "freezegun (==1.5.0) ; python_version >= \"3.8\"", "mypy (==v0.910) ; python_version < \"3.6\"", "mypy (==v0.971) ; python_version == \"3.6\"", "mypy (==v1.13.0) ; python_version >= \"3.8\"", "mypy (==v1.4.1) ; python_version == \"3.7\"", "myst-parser (==4.0.0) ; python_version >= \"3.11\"", "pre-commit (==4.0.1) ; python_version >= \"3.9\"", "pytest (==6.1.2) ; python_version < \"3.8\"", "pytest (==8.3.2) ; python_version >= \"3.8\"", "pytest-cov (==2.12.1) ; python_version < \"3.8\"", "pytest-cov (==5.0.0) ; python_version == \"3.8\"", "pytest-cov (==6.0.0) ; python_version >= \"3.9\"", "pytest-mypy-plugins (==1.9.3) ; python_version >= \"3.6\" and python_version < \"3.8\"", "pytest-mypy-plugins (==3.1.0) ; python_version >= \"3.8\"", "sphinx-rtd-theme (==3.0.2) ; python_version >= \"3.11\"", "tox (==3.27.1) ; python_version < \"3.8\"", "tox (==4.23.2) ; python_version >= \"3.8\"", "twine (==6.0.1) ; python_version >= \"3.11\""] + +[[package]] +name = "opentelemetry-api" +version = "1.45.0" +description = "OpenTelemetry Python API" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_api-1.45.0-py3-none-any.whl", hash = "sha256:80e068aba7cd56c8b58512d6a36f8d25cb1dfaa0c0a4cc1c938ccf9f362d9cb3"}, + {file = "opentelemetry_api-1.45.0.tar.gz", hash = "sha256:711ede81773c8025c2c03dac0450bc89f3d30aea6eabcc815c570d4e35a963f7"}, +] + +[package.dependencies] +typing-extensions = ">=4.5.0" + +[[package]] +name = "packaging" +version = "26.3" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"}, + {file = "packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79"}, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +description = "plugin and hook calling mechanisms for python" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746"}, + {file = "pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3"}, +] + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["coverage", "pytest", "pytest-benchmark"] + +[[package]] +name = "pydantic" +version = "2.13.5" +description = "Data validation using Python type hints" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "pydantic-2.13.5-py3-none-any.whl", hash = "sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73"}, + {file = "pydantic-2.13.5.tar.gz", hash = "sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08"}, +] + +[package.dependencies] +annotated-types = ">=0.6.0" +pydantic-core = "2.46.5" +typing-extensions = ">=4.14.1" +typing-inspection = ">=0.4.2" + +[package.extras] +email = ["email-validator (>=2.0.0)"] +timezone = ["tzdata ; python_version >= \"3.9\" and platform_system == \"Windows\""] + +[[package]] +name = "pydantic-core" +version = "2.46.5" +description = "Core functionality for Pydantic validation and serialization" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "pydantic_core-2.46.5-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:657b40d6240c0a7b6a64b30f22d1e3aa631c7e846c621b0c0f6d1d75e2e15ea6"}, + {file = "pydantic_core-2.46.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ecb42011e12ee19cafbc312887cbf3546959fe02fbad44f272d4be5baa997615"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4dedce55295becb61921e386b99d4f2706045306e7fa52249a33004c837379fb"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:9f47b8a949e60f027f0aa0a6f6c7b7e9c55cbf4380d10b344e282fa4e7ab1e1b"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:200aa3dc9f8d54f0754f43247c0bad0999fdcfbfd2488384dd44f37279271fe6"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6d30e1a4f138b8951063e9a394752a9179b51da288ffa507b1e659222f4c1793"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:850a08d167dde16db8702c274f320c7be9d7da6f6dff2b58b18f9e815bd94f5b"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_31_riscv64.whl", hash = "sha256:c3471e5c4a949c26ec00a77f01df59096aa9495877de76fd60a980f8ee6be461"}, + {file = "pydantic_core-2.46.5-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3a3e26b6a8274211bddee2d0e4d0d42778f17a34510f49d2ec44b58abfc41736"}, + {file = "pydantic_core-2.46.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:fc5d783bd4a2387e97b8a2d5ec781cfb92b3d893bf82370548e99db5915935d3"}, + {file = "pydantic_core-2.46.5-cp310-cp310-musllinux_1_1_armv7l.whl", hash = "sha256:356c8368cbc321050b169595683a2e1d63413b1e0e2868b330af9fc14c616d3f"}, + {file = "pydantic_core-2.46.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:eb7d8d0e5886a89a55d2eef490e272fa965a9d57c6b29a5b5088a7997ec2cad1"}, + {file = "pydantic_core-2.46.5-cp310-cp310-win32.whl", hash = "sha256:4d44cf99ddebf875f9b68cc267aa684c99b7b44fe63ee1cac4ec163807290069"}, + {file = "pydantic_core-2.46.5-cp310-cp310-win_amd64.whl", hash = "sha256:1e5aad1220a1192c42341c8fd4a8686657e73ab2a920c970bdc4de334fe3193d"}, + {file = "pydantic_core-2.46.5-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:a1dee1b804ff4d11c663636cf15d2ea47e9f79cd56c033fb1cbf08924842a48f"}, + {file = "pydantic_core-2.46.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d625a186a65201c23a9e3b8ed9c47e90a026e03256608cc91851c6709096844f"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4f8507560a9284e1370bb048ed4282012fbef4e8d109875b95e884d228552061"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5f93c5fe914d75fbec9a49209b00da5f08e9e467d69da2b1510c81940cfd10be"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c767f552b21b10f774aeac128e828eafb796adfa1b666a18bf6321453c3a"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:701b2e04b560eeb4bddf7a25ab8ca476176e34fdbd9a0e18196f0d12d4685f0b"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49776eab08766a08dfff7012f8b422dcd7e25e43b316eedf0477c24fcfa84b7c"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:a2468d93d181667a7abd66e1b64bb9f76f361b0fef8faddf687456453576f5ee"}, + {file = "pydantic_core-2.46.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:53feb344243bb9510a9dec7bf3cf1b64d88a98af5dc7872a5160465f8b198c8e"}, + {file = "pydantic_core-2.46.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:cd5214352ae68f3b5e9af7768bdc5253695ee069675db3480518420b3be881f2"}, + {file = "pydantic_core-2.46.5-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:9432f3598db432cb51c5b37fdbf29a60fcccc79e30d37a05022776a6bc4ab689"}, + {file = "pydantic_core-2.46.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8feeac04b5794e513e710af2f9c87d49f31a6dc47967bb264a1fed61a8989bec"}, + {file = "pydantic_core-2.46.5-cp311-cp311-win32.whl", hash = "sha256:892a881d5f68c2b9ea304b7a6c2c60d9343df578a311b0f86b94bc8f1ffe8129"}, + {file = "pydantic_core-2.46.5-cp311-cp311-win_amd64.whl", hash = "sha256:40375c2d05acec10323e45dfe2077ac44bc74659008614af5069034e2cfc781c"}, + {file = "pydantic_core-2.46.5-cp311-cp311-win_arm64.whl", hash = "sha256:28a6a556cd3b6066bea827857f9d9cce027c96f776e512f544a581f9e42161f8"}, + {file = "pydantic_core-2.46.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:b9fe6fb92520e3fd61f2e49000b6911b188824f089b75973ea06d6267f0b476d"}, + {file = "pydantic_core-2.46.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a39ac25a9a2fa4072efdb429833c4a4c8009a51ff9eea3eeae131713cd27991e"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4fdc8b93a41521988916eeaa271173fcca7fa0803d62f87675aac8dcec1c8e29"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b98134087d9de723658d17a42c7d0da8d6e2ef08015dee7dc93889047315f5e4"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e652ab17569c94bff5475520f907b7148b8c24036a8ebbe5cf7cf7493d28579a"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d925f3d9afd05a8c0fb3a1031463a8d59ebe5e2afad297e29c78be19e13b4e62"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0fc5be0abd4a407e200d844b404e33639a554e7bd0d448e7b9ae181be4789ac2"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:816ff0a6550ffc06c098ccd2e0698600f9aa7da192a79eaa6f9af504a35db869"}, + {file = "pydantic_core-2.46.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c7ea57fc63aa7da93a1bd2d644e6577befae10c52c4e36377635eea1056a74f5"}, + {file = "pydantic_core-2.46.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:efd62a42486f1bda5d24cb4f63d15a3c7768375fe83d36f9417b4ad7a2fb20b3"}, + {file = "pydantic_core-2.46.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:2bc9419666990c06d7397831f2126a1ecc3594aaa3ff7de5bf2d066802f4e07b"}, + {file = "pydantic_core-2.46.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:18a09e1e1011b462f2e32774f25859ef1223d5c2b0546a633cf56654710721e0"}, + {file = "pydantic_core-2.46.5-cp312-cp312-win32.whl", hash = "sha256:5cb482e9e84c851f4e623fe4acc1ced89168cf1fe18f7089db4548c8f5bbb65b"}, + {file = "pydantic_core-2.46.5-cp312-cp312-win_amd64.whl", hash = "sha256:5e81740c09e310f5aa5cbd3e434a01c154d4bef93241c7877b39f211d2b78ba8"}, + {file = "pydantic_core-2.46.5-cp312-cp312-win_arm64.whl", hash = "sha256:f7b0ec93a2893de856652154d73b7ba622f26fa97726487dcac373de5f4c6084"}, + {file = "pydantic_core-2.46.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:b7ca9034437b6022f941f4857459562ee00a560b97e7cce8a0ec5a74fc6766e0"}, + {file = "pydantic_core-2.46.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f332f0e72a5a0400141f830744e141bf9f97917878dbe968669e8a7fefea78ff"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:193375f3548919d3f0b60936ca113ada3e38f264f91b9b8e0508efaad57be931"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:79bdfa52f843137045b2d081cc05c120ba6665d29b7559c2c47690906f39279f"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:24922243639cbdac66c75fcb6fd6495a9cb52b213d62f9a0d16f0310b1ff8038"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c76fe65e607be28c7fd4d56fc3c42b1583aa058ce3408b7ad0fd540171d31f9f"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6f7b393a8b3da82f5c1fc0751e6d01ac6c55b93c18226a60bdfba4a724efafd1"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:7ac031912d54f3d83ef3b3eb98dfabc1608802e2202263d25957eeed40b94761"}, + {file = "pydantic_core-2.46.5-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:837b396ca3d7b74091ca623f6cbd8351bd42d670a79c2683e79fb089f06a2de5"}, + {file = "pydantic_core-2.46.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:5ee239d575f80b08eca11f6e20f90c4c695de7825c67eefe6091fbf20dda648e"}, + {file = "pydantic_core-2.46.5-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:e80675d75ae2cd14372cb65cad5400d9347a3d3f6c13000183f22dfd027283ed"}, + {file = "pydantic_core-2.46.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:9c4b71f10dd532fb7a5cbc8f58707779e64f03a258c2bf8bfbaecfcd9970b519"}, + {file = "pydantic_core-2.46.5-cp313-cp313-win32.whl", hash = "sha256:97bf8de4d541598c94a59344eeb988a94c08ff76b5723c41f6567ec18c7892ea"}, + {file = "pydantic_core-2.46.5-cp313-cp313-win_amd64.whl", hash = "sha256:15f4a94963c95accac15b7b657bb177d3ad82bb90b0d0526d9a9b85079925db5"}, + {file = "pydantic_core-2.46.5-cp313-cp313-win_arm64.whl", hash = "sha256:d22a945598fb91236b4dd793a6e42e4f3dd7740bb5aace5ebd7d4c08d13bb575"}, + {file = "pydantic_core-2.46.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c1c43ad4339643d70ebb8124e1305a7dab423001eff58bb41a0f731adbc98355"}, + {file = "pydantic_core-2.46.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a353f84de772f423b5ffb11d7ae352fbbef0f446f3c0b0af0f8236d7233606e"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5086029a57366b8cf81b130a43908738095c270c21a8d7f0e8bdfdb89718e2f3"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:46c25dda9d092a06c08db76ffe0a197107904d0dfac653f7d5306bbcd6d6119c"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:37ea7b83c935e5b0d68c9449b82651accf78a10828b2c02b2f2d9e9496446c21"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e64e88d5585bea9ce95861079de72006c7fa6d3df4e3a3b65ba31eb979c15c9f"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:54d510bac3ee52247af28ed4bb18a1e799f040ac60fd2bf5ccd4c92f1fbe786f"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:a2a5e1d0ff29adddc9f6d6821a66302e4493f8ca898b715b6b1182c2c201ea0a"}, + {file = "pydantic_core-2.46.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:03b9666e41e35d8909852ba191a0607520f81b74eaf12ccf8737005dbb313821"}, + {file = "pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:a91c17edf6eea2402cb5457b4c89e99bc5ed1004aa34c4adf1d4258c1a5c22c2"}, + {file = "pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:b49924c73a235e969511bf2aabdff3beebf9820931f646c80274d5d780010c47"}, + {file = "pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:2cbd9a5eff05e51c447c34dfa4632145b26b09120cf04bd0c871e44c1a5e1c9a"}, + {file = "pydantic_core-2.46.5-cp314-cp314-win32.whl", hash = "sha256:2d5d76654becf5efd62c9e51c3756c67b49498b0c9a40884934c40807adbd074"}, + {file = "pydantic_core-2.46.5-cp314-cp314-win_amd64.whl", hash = "sha256:fa10ef4112775900e7a0661068635eb67b2ab824fbde764de6e0e21982a93db0"}, + {file = "pydantic_core-2.46.5-cp314-cp314-win_arm64.whl", hash = "sha256:045ab3b6d308439e32b81cc173bba5b9018bc6ed896afd0c65b3b009b1699af5"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8816f3d218beb4b787de5c9759c259b8fa61f9dec42dc7811f320a33771778b7"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:bce57638e08ac148e5778cce7feb968307a727d66f8e2274a543d0cf0c9ad6a3"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:976e1128455aa595ea04c79ccfedff1aaeab96ee013fcc916bed120c4f0ad94f"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e7b891faeedeafba41b2983e5001a81b6a915b69544c7e7570d1989ce1c36ac7"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f194189415698233dd1114a093a9b56e61e2c57e11b469be3b0506f46f0771c"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:82a36973cf8a2ef5406f4fe2edbf8ed0c99629535d959e0b100c76a32535a111"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdbb78909f52b981d3b2d56b97328d71eb0b974c36bd77c920123a7ebb192829"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:52e24eacdb536cade636aa90fb851835222becff8484b7001fdc78cb0290f2aa"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:37ae34309d7bd8c0d61ab839668058f2a7962ea1fc51d105d2db228fe0618034"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:0cdbada856a1c69a7624a64d3d9aefe79300bd6ef827b43a4f265010b9b55184"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:545f26c504b27c3758439a5e6d9349931f0a04f855668d5fe323c89e82300a38"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-win32.whl", hash = "sha256:97cf3eb53a8cccacf9d46686a0926186c9bfb5574f2ed66d3639d5fe117cd3a9"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-win_amd64.whl", hash = "sha256:d2f9fc07a8042a8f95925b35c4f04f469707c981fc33245b6ca187cf5d2dd290"}, + {file = "pydantic_core-2.46.5-cp314-cp314t-win_arm64.whl", hash = "sha256:acf8a67ba51f4ca9ddbd0e6b3000a65ac51ab734661778b3e7ba64d99a710f2f"}, + {file = "pydantic_core-2.46.5-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:c583b927a8838dab890706a6fa7573fbb8b70e24000ef9f7238e2d6f6435a5ed"}, + {file = "pydantic_core-2.46.5-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:cdc8b74ecc48c0cb1e9607a05ec4e9e88db60a19ffcc9a1d5f9088ede40c8dc0"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b10e3e8fd7ddc2bd915848a2768e44c15b22936f1cc54c462ad1164deb02655"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f077d0b97ab11fa7dcc633fca53515f290bca8a8a633e966d5b6d1879d9ed01a"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7b0fc826b16c55e561e5d2a0c5c77b051ba1d92808118c4e4b5390f5e0cf191d"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ef3fbbf161dc9351a2fe0422e51b129f9e97e42385bd0320b309c15f7d287dd8"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:978e7b97d4824b5be09c69fb70507cbde3b0323fc147332ca40a94d9a6a0ebbf"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_31_riscv64.whl", hash = "sha256:9b68938dd5b0c783d88ff8e2dcc69451b5eb936fe212d516b21b9d5567f6d464"}, + {file = "pydantic_core-2.46.5-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:771cf63ae0b1b50dd22e5f3e3549fab5f3f4ff1635d352a9e1a97fe01c7b2e64"}, + {file = "pydantic_core-2.46.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:7c6be839a5a8312626b32029a415644a0846b420bc8b52b95b28cd92da162168"}, + {file = "pydantic_core-2.46.5-cp39-cp39-musllinux_1_1_armv7l.whl", hash = "sha256:895395f8918627b04efb1ad2a4cf605387143300ba03304cd1dfa6d03f5e095e"}, + {file = "pydantic_core-2.46.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13"}, + {file = "pydantic_core-2.46.5-cp39-cp39-win32.whl", hash = "sha256:3d2652072b2d774947ba5cf78a9e59644ac62ee572daf6dd2e1dfe905e15b2b7"}, + {file = "pydantic_core-2.46.5-cp39-cp39-win_amd64.whl", hash = "sha256:3aa166e99c4f2985407fb8714aebede877ecb5455cf321b606adca926d30d5a0"}, + {file = "pydantic_core-2.46.5-graalpy311-graalpy242_311_native-macosx_10_12_x86_64.whl", hash = "sha256:c14ad3bdc85ee7f318742c457ca3968a92126d144b15721c759033bfb06296c2"}, + {file = "pydantic_core-2.46.5-graalpy311-graalpy242_311_native-macosx_11_0_arm64.whl", hash = "sha256:0bddb4020d8f04175865ccd17eff3040874fc11fb593f424edb452653b4b947c"}, + {file = "pydantic_core-2.46.5-graalpy311-graalpy242_311_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2471fd51c61c610e1dcf7de44d7299283661654d11264ab4802b303368d69c47"}, + {file = "pydantic_core-2.46.5-graalpy311-graalpy242_311_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b10ec717381bdbfafef34607824db4c91de69ff085e4fca3b2af91b4fa17e68a"}, + {file = "pydantic_core-2.46.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:013d6f3483d81e02e7c328831808f336c8596ee33b4bd4026b9ffb1e960b8942"}, + {file = "pydantic_core-2.46.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:e9c134bb666dd54b778b9fc0d2b50cbb7f979b9e3716f26a88c9ab3b6fc1dd0f"}, + {file = "pydantic_core-2.46.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:347ec774390c87326a2e4929d58d3f7e8763a104d5d35f4cd595a4c952366433"}, + {file = "pydantic_core-2.46.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e24d8f05fa2d28513d94e877e9c75ad66175376209b3977f916e240e623193c"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:ab4b66edffb32d9e951efb3814bd104b8367a7501b81b955cacb5726d897389f"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:337639ba62a11acde6ef3aeb08c8ea755f8ef1fe5e513356c0f36a2b0d7568b0"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:413a717a410d0c817ef5b786a059415550b3794e1d0c2abffd9efb93a3d9f7b4"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1e449def1945a462c464331254e5a44fca7c3b4f9aedf59ec2f50f8066dd8e25"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:a445486499897b88a7d6c310c88ed64dd37b1b59bfd7ae9107490bbb362f47d6"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:2d330aaba8621b1edcec8ae2c4050f63b84ccf6d98723a8f212e9684713abf0e"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:b6acfb46a814762367fb7ba0828b0a17d441b92ce249a0e007474c9072662dda"}, + {file = "pydantic_core-2.46.5-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:d0a24b40877af2de4950252be9d21eaf7fb07660f3c2cae1f56c6b599ada5266"}, + {file = "pydantic_core-2.46.5.tar.gz", hash = "sha256:10416c15b8839ecc4ef4d0885da76da6fd0f67333a0eb8aff6d93c4b8f2910fc"}, +] + +[package.dependencies] +typing-extensions = ">=4.14.1" + +[[package]] +name = "pygments" +version = "2.21.0" +description = "Pygments is a syntax highlighting package written in Python." +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9"}, + {file = "pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c"}, +] + +[package.extras] +windows-terminal = ["colorama (>=0.4.6)"] + +[[package]] +name = "pytest" +version = "9.1.1" +description = "pytest: simple powerful testing with Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c"}, + {file = "pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313"}, +] + +[package.dependencies] +colorama = {version = ">=0.4", markers = "sys_platform == \"win32\""} +iniconfig = ">=1.0.1" +packaging = ">=22" +pluggy = ">=1.5,<2" +pygments = ">=2.7.2" + +[package.extras] +dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "requests", "setuptools", "xmlschema"] + +[[package]] +name = "starlette" +version = "1.7.0" +description = "The little ASGI library that shines." +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e"}, + {file = "starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d"}, +] + +[package.dependencies] +anyio = ">=4.0.0,<5" +typing-extensions = {version = ">=4.10.0", markers = "python_version < \"3.13\""} + +[package.extras] +full = ["httpx (>=0.27.0,<0.29.0)", "httpx2 (>=2.0.0)", "itsdangerous", "jinja2", "opentelemetry-api", "python-multipart (>=0.0.18)", "pyyaml"] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +description = "Backported and Experimental Type Hints for Python 3.9+" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8"}, + {file = "typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5"}, +] + +[[package]] +name = "typing-inspection" +version = "0.4.4" +description = "Runtime typing introspection tools" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147"}, + {file = "typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47"}, +] + +[package.dependencies] +typing-extensions = ">=4.15.0" + +[[package]] +name = "uvicorn" +version = "0.54.0" +description = "The lightning-fast ASGI server." +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf"}, + {file = "uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620"}, +] + +[package.dependencies] +click = ">=7.0" +h11 = ">=0.8" + +[package.extras] +standard = ["httptools (>=0.8.0)", "python-dotenv (>=0.13)", "pyyaml (>=5.1)", "uvloop (>=0.15.1) ; sys_platform != \"win32\" and sys_platform != \"cygwin\" and platform_python_implementation != \"PyPy\"", "watchfiles (>=0.20)", "websockets (>=13.0)"] + +[[package]] +name = "win32-setctime" +version = "1.2.0" +description = "A small Python utility to set file creation time on Windows" +optional = false +python-versions = ">=3.5" +groups = ["main"] +markers = "sys_platform == \"win32\"" +files = [ + {file = "win32_setctime-1.2.0-py3-none-any.whl", hash = "sha256:95d644c4e708aba81dc3704a116d8cbc974d70b3bdb8be1d150e36be6e9d1390"}, + {file = "win32_setctime-1.2.0.tar.gz", hash = "sha256:ae1fdf948f5640aae05c511ade119313fb6a30d7eabe25fef9764dca5873c4c0"}, +] + +[package.extras] +dev = ["black (>=19.3b0) ; python_version >= \"3.6\"", "pytest (>=4.6.2)"] + +[metadata] +lock-version = "2.1" +python-versions = ">=3.12,<3.13" +content-hash = "0fa9cbd0321b256afe0bfead469acfb6ff52bb827c224b2ce16a16beb07b9b22" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..01dc8a1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,26 @@ +[tool.poetry] +name = "max2" +version = "1.2.0" +description = "In-memory мессенджер, лабораторная 2" +authors = ["Саватеев Артём"] +package-mode = false + +[tool.poetry.dependencies] +python = ">=3.12,<3.13" +fastapi = "0.142.2" +uvicorn = "0.54.0" +pydantic = "2.13.5" +envparse = "0.2.0" +loguru = "0.7.3" + +[tool.poetry.group.dev.dependencies] +pytest = "9.1.1" +httpx = "0.28.1" + +[build-system] +requires = ["poetry-core>=2.0.0,<3.0.0"] +build-backend = "poetry.core.masonry.api" + +[tool.pytest.ini_options] +testpaths = ["student-tests"] +addopts = "-v" diff --git a/scripts/sigterm_check.py b/scripts/sigterm_check.py new file mode 100644 index 0000000..8a055b5 --- /dev/null +++ b/scripts/sigterm_check.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""SIGTERM: процесс перестаёт принимать запросы и завершается не дольше чем за 10 секунд. + +Во время проверки фоновый клиент непрерывно шлёт GET /health/live: до сигнала +ответы 200, после — отказ в соединении; ответов 5xx быть не должно. +""" + +import argparse +import json +import os +import subprocess +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"] + +SHUTDOWN_LIMIT_SEC = 10 +PROBE_INTERVAL_SEC = 0.02 + + +class Prober(threading.Thread): + """Фоновый клиент: каждое обращение — новое соединение""" + + def __init__(self, url: str) -> None: + super().__init__(daemon=True) + self.url = url + self.stop = threading.Event() + self.ok: list[float] = [] + self.refused: list[float] = [] + self.server_errors = 0 + + def run(self) -> None: + while not self.stop.is_set(): + try: + with urllib.request.urlopen(self.url, timeout=2) as response: + if response.status == 200: + self.ok.append(time.monotonic()) + except urllib.error.HTTPError as error: + if error.code >= 500: + self.server_errors += 1 + except OSError: + self.refused.append(time.monotonic()) + time.sleep(PROBE_INTERVAL_SEC) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--base-url", default=os.environ.get("BASE_URL") or DEFAULT_BASE_URL + ) + parser.add_argument( + "--container", default=os.environ.get("CONTAINER", "mtusi-messenger-lab2") + ) + args = parser.parse_args() + + logs = subprocess.Popen( + ["docker", "logs", "--follow", "--since", "0s", args.container], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + waiter = subprocess.Popen( + ["docker", "wait", args.container], stdout=subprocess.PIPE, text=True + ) + prober = Prober(args.base_url.rstrip("/") + "/health/live") + prober.start() + time.sleep(1) + if not prober.ok: + raise SystemExit("FAIL: API не отвечает до отправки SIGTERM") + + sent_at = time.monotonic() + subprocess.run( + ["docker", "kill", "--signal", "SIGTERM", args.container], + check=True, + capture_output=True, + ) + exit_code = int(waiter.communicate(timeout=SHUTDOWN_LIMIT_SEC + 5)[0].strip()) + exited_at = time.monotonic() + time.sleep(0.5) + prober.stop.set() + prober.join() + shutdown_log = logs.communicate(timeout=5)[0] + + shutdown_sec = exited_at - sent_at + ok_after = [t for t in prober.ok if t > sent_at] + first_refused = min((t for t in prober.refused if t > sent_at), default=None) + print("Логи контейнера после SIGTERM:") + print( + "\n".join(line for line in shutdown_log.splitlines() if "/health/" not in line) + ) + print( + json.dumps( + { + "container": args.container, + "exit_code": exit_code, + "shutdown_seconds": round(shutdown_sec, 3), + "limit_seconds": SHUTDOWN_LIMIT_SEC, + "probes_ok_before_sigterm": len(prober.ok) - len(ok_after), + "probes_ok_after_sigterm": len(ok_after), + "first_refused_after_sigterm_seconds": None + if first_refused is None + else round(first_refused - sent_at, 3), + "probes_refused_after_sigterm": len(prober.refused), + "server_errors_5xx": prober.server_errors, + }, + indent=2, + ) + ) + if ( + exit_code != 0 + or shutdown_sec > SHUTDOWN_LIMIT_SEC + or prober.server_errors + or first_refused is None + ): + raise SystemExit("FAIL: завершение по SIGTERM не соответствует требованиям") + print( + "PASS: SIGTERM завершил процесс за %.2f с, новые соединения отклоняются" + % shutdown_sec + ) + + +if __name__ == "__main__": + main() diff --git a/src/application/__init__.py b/src/application/__init__.py new file mode 100644 index 0000000..7514376 --- /dev/null +++ b/src/application/__init__.py @@ -0,0 +1,4 @@ +from .api import app as api_endpoints +from .api import health_router as health_endpoints + +__all__ = ["api_endpoints", "health_endpoints"] diff --git a/src/application/api/__init__.py b/src/application/api/__init__.py new file mode 100644 index 0000000..48c9b63 --- /dev/null +++ b/src/application/api/__init__.py @@ -0,0 +1,10 @@ +from fastapi import APIRouter + +from .health import health_router +from .routers import app as v1_endpoints + +app = APIRouter(prefix="/api") + +app.include_router(v1_endpoints) + +__all__ = ["app", "health_router"] diff --git a/src/application/api/dependencies/__init__.py b/src/application/api/dependencies/__init__.py new file mode 100644 index 0000000..c71b267 --- /dev/null +++ b/src/application/api/dependencies/__init__.py @@ -0,0 +1,4 @@ +from .auth import get_current_user +from .security import USER_ID_HEADER, user_id_header + +__all__ = ["get_current_user", "user_id_header", "USER_ID_HEADER"] diff --git a/src/application/api/dependencies/auth.py b/src/application/api/dependencies/auth.py new file mode 100644 index 0000000..585b9f4 --- /dev/null +++ b/src/application/api/dependencies/auth.py @@ -0,0 +1,15 @@ +from fastapi import Depends + +from domain import UserSchema +from infrastructure.dependencies import ServiceCreator +from infrastructure.services import UserService + +from .security import user_id_header + + +async def get_current_user( + raw_user_id: str | None = Depends(user_id_header), + service: UserService = Depends(ServiceCreator.get_user_service), +) -> UserSchema: + """Текущий пользователь из X-User-Id; иначе 401""" + return await service.authenticate(raw_user_id) diff --git a/src/application/api/dependencies/security.py b/src/application/api/dependencies/security.py new file mode 100644 index 0000000..edf6b3a --- /dev/null +++ b/src/application/api/dependencies/security.py @@ -0,0 +1,10 @@ +from fastapi.security import APIKeyHeader + +USER_ID_HEADER = "X-User-Id" + +user_id_header = APIKeyHeader( + name=USER_ID_HEADER, + scheme_name="devUser", + description="uuid существующего пользователя", + auto_error=False, +) diff --git a/src/application/api/handlers/__init__.py b/src/application/api/handlers/__init__.py new file mode 100644 index 0000000..59f2c3f --- /dev/null +++ b/src/application/api/handlers/__init__.py @@ -0,0 +1,3 @@ +from .exceptions import register_exception_handlers + +__all__ = ["register_exception_handlers"] diff --git a/src/application/api/handlers/exceptions.py b/src/application/api/handlers/exceptions.py new file mode 100644 index 0000000..441d384 --- /dev/null +++ b/src/application/api/handlers/exceptions.py @@ -0,0 +1,57 @@ +from http import HTTPStatus + +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +from application.api.utils import error_response, get_request_id +from domain.errors import AppError, ErrorCode, InvalidRequestError, NotFoundError + + +async def app_error_handler(request: Request, error: Exception) -> JSONResponse: + """Доменные ошибки сервисов и репозиториев""" + assert isinstance(error, AppError) + return error_response( + get_request_id(request), error.status_code, error.code, error.message + ) + + +async def validation_error_handler(request: Request, error: Exception) -> JSONResponse: + """Malformed JSON, лишние поля, неверные типы, uuid и limit — 400""" + assert isinstance(error, RequestValidationError) + return error_response( + get_request_id(request), + InvalidRequestError.status_code, + InvalidRequestError.code, + _describe_validation_error(error), + ) + + +async def http_error_handler(request: Request, error: Exception) -> JSONResponse: + """Ошибки маршрутизации неизвестный путь, неподдерживаемый метод""" + assert isinstance(error, StarletteHTTPException) + if error.status_code == HTTPStatus.NOT_FOUND: + code, message = NotFoundError.code, NotFoundError.default_message + elif error.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR: + code, message = AppError.code, AppError.default_message + else: + code, message = ErrorCode.INVALID_REQUEST, HTTPStatus(error.status_code).phrase + return error_response( + get_request_id(request), error.status_code, code, message, error.headers + ) + + +def _describe_validation_error(error: RequestValidationError) -> str: + """Безопасное описание: только тип и путь поля, без присланного значения""" + first = error.errors()[0] + if first.get("type") == "json_invalid": + return "Некорректный JSON в теле запроса" + location = ".".join(str(part) for part in first.get("loc", ())) + return f"Некорректное значение: {location}" + + +def register_exception_handlers(app: FastAPI) -> None: + app.add_exception_handler(AppError, app_error_handler) + app.add_exception_handler(RequestValidationError, validation_error_handler) + app.add_exception_handler(StarletteHTTPException, http_error_handler) diff --git a/src/application/api/health/__init__.py b/src/application/api/health/__init__.py new file mode 100644 index 0000000..400c3b1 --- /dev/null +++ b/src/application/api/health/__init__.py @@ -0,0 +1,3 @@ +from .endpoints import health_router + +__all__ = ["health_router"] diff --git a/src/application/api/health/endpoints.py b/src/application/api/health/endpoints.py new file mode 100644 index 0000000..ce6738d --- /dev/null +++ b/src/application/api/health/endpoints.py @@ -0,0 +1,28 @@ +from fastapi import APIRouter, Request, status + +from domain import HealthSchema +from domain.errors import UnavailableError + +health_router = APIRouter(prefix="/health", tags=["Health"]) + + +@health_router.get( + "/live", + status_code=status.HTTP_200_OK, + response_model=HealthSchema, +) +async def liveness() -> HealthSchema: + """Процесс жив и обрабатывает хттп""" + return HealthSchema() + + +@health_router.get( + "/ready", + status_code=status.HTTP_200_OK, + response_model=HealthSchema, +) +async def readiness(request: Request) -> HealthSchema: + """Хранилище создано и приложение не завершается""" + if not getattr(request.app.state, "is_ready", False): + raise UnavailableError() + return HealthSchema() diff --git a/src/application/api/middlewares/__init__.py b/src/application/api/middlewares/__init__.py new file mode 100644 index 0000000..6005e31 --- /dev/null +++ b/src/application/api/middlewares/__init__.py @@ -0,0 +1,3 @@ +from .request_context import RequestContextMiddleware + +__all__ = ["RequestContextMiddleware"] diff --git a/src/application/api/middlewares/request_context.py b/src/application/api/middlewares/request_context.py new file mode 100644 index 0000000..4ae099c --- /dev/null +++ b/src/application/api/middlewares/request_context.py @@ -0,0 +1,55 @@ +import time +import uuid + +from fastapi import Request, Response +from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint + +from application.api.utils import REQUEST_ID_HEADER, error_response +from config import LOGGER +from domain.errors import AppError + +HEALTH_PATH_PREFIX = "/health/" + + +class RequestContextMiddleware(BaseHTTPMiddleware): + """ + X-Request-Id в каждом ответе, журнал запросов и защита от необработанных ошибок. + + В лог попадают метод, путь, статус и длительность — без тел запросов, + query-параметров и текста сообщений. + """ + + async def dispatch( + self, request: Request, call_next: RequestResponseEndpoint + ) -> Response: + request_id = uuid.uuid4().hex + request.state.request_id = request_id + started = time.perf_counter() + try: + response = await call_next(request) + except Exception: + LOGGER.exception(f"Необработанная ошибка | request_id={request_id}") + error = AppError() + response = error_response( + request_id, error.status_code, error.code, error.message + ) + response.headers[REQUEST_ID_HEADER] = request_id + self._log_request(request, response, request_id, started) + return response + + @staticmethod + def _log_request( + request: Request, response: Response, request_id: str, started: float + ) -> None: + duration_ms = (time.perf_counter() - started) * 1000 + if response.status_code >= 500: + level = "ERROR" + elif request.url.path.startswith(HEALTH_PATH_PREFIX): + level = "DEBUG" + else: + level = "INFO" + LOGGER.log( + level, + f"{request.method} {request.url.path} -> {response.status_code} " + f"| {duration_ms:.1f} ms | request_id={request_id}", + ) diff --git a/src/application/api/routers/__init__.py b/src/application/api/routers/__init__.py new file mode 100644 index 0000000..49c8681 --- /dev/null +++ b/src/application/api/routers/__init__.py @@ -0,0 +1,13 @@ +from fastapi import APIRouter + +from .chats import chats_router +from .messages import messages_router +from .users import users_router + +app = APIRouter(prefix="/v1") + +app.include_router(users_router) +app.include_router(chats_router) +app.include_router(messages_router) + +__all__ = ["app"] diff --git a/src/application/api/routers/chats/__init__.py b/src/application/api/routers/chats/__init__.py new file mode 100644 index 0000000..7364c40 --- /dev/null +++ b/src/application/api/routers/chats/__init__.py @@ -0,0 +1,3 @@ +from .endpoints import chats_router + +__all__ = ["chats_router"] diff --git a/src/application/api/routers/chats/endpoints.py b/src/application/api/routers/chats/endpoints.py new file mode 100644 index 0000000..4556db5 --- /dev/null +++ b/src/application/api/routers/chats/endpoints.py @@ -0,0 +1,58 @@ +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Body, Depends, Query, status + +from application.api.dependencies import get_current_user +from domain import ( + ChatPageSchema, + ChatSchema, + CreateChatSchema, + UserSchema, +) +from infrastructure.dependencies import ServiceCreator +from infrastructure.services import ChatService + +chats_router = APIRouter(prefix="/chats", tags=["Chats"]) + + +@chats_router.post( + "", + status_code=status.HTTP_201_CREATED, + response_model=ChatSchema, +) +async def create_chat( + body: Annotated[CreateChatSchema, Body(...)], + current_user: UserSchema = Depends(get_current_user), + service: ChatService = Depends(ServiceCreator.get_chat_service), +) -> ChatSchema: + """Вызывающий должен входить в member_ids""" + return await service.create_chat(current_user, body) + + +@chats_router.get( + "", + status_code=status.HTTP_200_OK, + response_model=ChatPageSchema, +) +async def list_chats( + limit: Annotated[int, Query(ge=1, le=100)] = 50, + cursor: Annotated[str | None, Query(min_length=1)] = None, + current_user: UserSchema = Depends(get_current_user), + service: ChatService = Depends(ServiceCreator.get_chat_service), +) -> ChatPageSchema: + """Чаты текущего пользователя по (created_at, id) по возрастанию""" + return await service.list_chats(current_user, limit, cursor) + + +@chats_router.get( + "/{chat_id}", + status_code=status.HTTP_200_OK, + response_model=ChatSchema, +) +async def get_chat( + chat_id: UUID, + current_user: UserSchema = Depends(get_current_user), + service: ChatService = Depends(ServiceCreator.get_chat_service), +) -> ChatSchema: + return await service.get_chat(current_user, chat_id) diff --git a/src/application/api/routers/messages/__init__.py b/src/application/api/routers/messages/__init__.py new file mode 100644 index 0000000..8573c3b --- /dev/null +++ b/src/application/api/routers/messages/__init__.py @@ -0,0 +1,3 @@ +from .endpoints import messages_router + +__all__ = ["messages_router"] diff --git a/src/application/api/routers/messages/endpoints.py b/src/application/api/routers/messages/endpoints.py new file mode 100644 index 0000000..0353fd9 --- /dev/null +++ b/src/application/api/routers/messages/endpoints.py @@ -0,0 +1,48 @@ +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Body, Depends, Query, status + +from application.api.dependencies import get_current_user +from domain import ( + CreateMessageSchema, + MessagePageSchema, + MessageSchema, + UserSchema, +) +from infrastructure.dependencies import ServiceCreator +from infrastructure.services import MessageService + +messages_router = APIRouter( + prefix="/chats/{chat_id}/messages", tags=["Messages"] +) + + +@messages_router.post( + "", + status_code=status.HTTP_201_CREATED, + response_model=MessageSchema, +) +async def send_message( + chat_id: UUID, + body: Annotated[CreateMessageSchema, Body(...)], + current_user: UserSchema = Depends(get_current_user), + service: MessageService = Depends(ServiceCreator.get_message_service), +) -> MessageSchema: + return await service.send_message(current_user, chat_id, body) + + +@messages_router.get( + "", + status_code=status.HTTP_200_OK, + response_model=MessagePageSchema, +) +async def list_messages( + chat_id: UUID, + limit: Annotated[int, Query(ge=1, le=100)] = 50, + cursor: Annotated[str | None, Query(min_length=1)] = None, + current_user: UserSchema = Depends(get_current_user), + service: MessageService = Depends(ServiceCreator.get_message_service), +) -> MessagePageSchema: + """История чата: keyset cursor по (created_at, id) по возрастанию""" + return await service.list_messages(current_user, chat_id, limit, cursor) diff --git a/src/application/api/routers/users/__init__.py b/src/application/api/routers/users/__init__.py new file mode 100644 index 0000000..ca28ba5 --- /dev/null +++ b/src/application/api/routers/users/__init__.py @@ -0,0 +1,3 @@ +from .endpoints import users_router + +__all__ = ["users_router"] diff --git a/src/application/api/routers/users/endpoints.py b/src/application/api/routers/users/endpoints.py new file mode 100644 index 0000000..f91c950 --- /dev/null +++ b/src/application/api/routers/users/endpoints.py @@ -0,0 +1,33 @@ +from typing import Annotated + +from fastapi import APIRouter, Body, Depends, status + +from application.api.dependencies import get_current_user +from domain import CreateUserSchema, UserSchema +from infrastructure.dependencies import ServiceCreator +from infrastructure.services import UserService + +users_router = APIRouter(prefix="/users", tags=["Users"]) + + +@users_router.post( + "", + status_code=status.HTTP_201_CREATED, + response_model=UserSchema, + openapi_extra={"security": []}, +) +async def register_user( + body: Annotated[CreateUserSchema, Body(...)], + service: UserService = Depends(ServiceCreator.get_user_service), +) -> UserSchema: + """Публичная регистрация; username уникален""" + return await service.register(body) + + +@users_router.get( + "/me", + status_code=status.HTTP_200_OK, + response_model=UserSchema, +) +async def get_me(current_user: UserSchema = Depends(get_current_user)) -> UserSchema: + return current_user diff --git a/src/application/api/utils/__init__.py b/src/application/api/utils/__init__.py new file mode 100644 index 0000000..0e10f35 --- /dev/null +++ b/src/application/api/utils/__init__.py @@ -0,0 +1,3 @@ +from .errors import REQUEST_ID_HEADER, error_response, get_request_id + +__all__ = ["REQUEST_ID_HEADER", "error_response", "get_request_id"] diff --git a/src/application/api/utils/errors.py b/src/application/api/utils/errors.py new file mode 100644 index 0000000..5c2fc3c --- /dev/null +++ b/src/application/api/utils/errors.py @@ -0,0 +1,32 @@ +from collections.abc import Mapping + +from fastapi import Request +from fastapi.responses import JSONResponse + +from domain.errors import ErrorBodySchema, ErrorCode, ErrorSchema + +REQUEST_ID_HEADER = "X-Request-Id" + + +def get_request_id(request: Request) -> str: + """ID запроса, назначенный RequestContextMiddleware""" + request_id: str = request.state.request_id + return request_id + + +def error_response( + request_id: str, + status_code: int, + code: ErrorCode, + message: str, + headers: Mapping[str, str] | None = None, +) -> JSONResponse: + """Ответ в едином формате ошибки контракта""" + body = ErrorSchema( + error=ErrorBodySchema(code=code, message=message, request_id=request_id) + ) + return JSONResponse( + status_code=status_code, + content=body.model_dump(mode="json"), + headers={**(headers or {}), REQUEST_ID_HEADER: request_id}, + ) diff --git a/src/config/__init__.py b/src/config/__init__.py new file mode 100644 index 0000000..b748db0 --- /dev/null +++ b/src/config/__init__.py @@ -0,0 +1,17 @@ +from .log_config import LOGGER +from .settings import ( + APP_ENV, + APP_HOST, + APP_PORT, + LOG_LEVEL, + SHUTDOWN_TIMEOUT_SEC, +) + +__all__ = [ + "LOGGER", + "APP_HOST", + "APP_PORT", + "APP_ENV", + "LOG_LEVEL", + "SHUTDOWN_TIMEOUT_SEC", +] diff --git a/src/config/log_config.py b/src/config/log_config.py new file mode 100644 index 0000000..cce05f1 --- /dev/null +++ b/src/config/log_config.py @@ -0,0 +1,12 @@ +"""Сборщик логов""" + +import sys + +from loguru import logger + +from .settings import LOG_LEVEL + +LOGGER = logger + +LOGGER.remove() +LOGGER.add(sys.stdout, level=LOG_LEVEL, diagnose=False) diff --git a/src/config/settings.py b/src/config/settings.py new file mode 100644 index 0000000..4b3d10a --- /dev/null +++ b/src/config/settings.py @@ -0,0 +1,17 @@ +import os +from pathlib import Path + +from envparse import Env + +env = Env() + +ENV_FILE = Path(os.getenv("ENV_FILE", ".env")) +if ENV_FILE.is_file(): + env.read_envfile(path=str(ENV_FILE)) + +APP_HOST = env.str("APP_HOST") +APP_PORT = env.int("APP_PORT") +APP_ENV = env.str("APP_ENV") + +LOG_LEVEL = env.str("LOG_LEVEL") +SHUTDOWN_TIMEOUT_SEC = env.int("SHUTDOWN_TIMEOUT_SEC") diff --git a/src/domain/__init__.py b/src/domain/__init__.py new file mode 100644 index 0000000..cdfbf7e --- /dev/null +++ b/src/domain/__init__.py @@ -0,0 +1,19 @@ +from .chats import ChatPageSchema, ChatSchema, CreateChatSchema +from .health import HealthSchema +from .messages import CreateMessageSchema, MessagePageSchema, MessageSchema +from .pagination import PageCursorSchema, PageKey +from .users import CreateUserSchema, UserSchema + +__all__ = [ + "CreateUserSchema", + "UserSchema", + "CreateChatSchema", + "ChatSchema", + "ChatPageSchema", + "CreateMessageSchema", + "MessageSchema", + "MessagePageSchema", + "HealthSchema", + "PageKey", + "PageCursorSchema", +] diff --git a/src/domain/chats/__init__.py b/src/domain/chats/__init__.py new file mode 100644 index 0000000..f7b5958 --- /dev/null +++ b/src/domain/chats/__init__.py @@ -0,0 +1,10 @@ +from .constants import CHAT_MEMBERS_MAX_COUNT, CHAT_TITLE_MAX_LENGTH +from .schemas import ChatPageSchema, ChatSchema, CreateChatSchema + +__all__ = [ + "CreateChatSchema", + "ChatSchema", + "ChatPageSchema", + "CHAT_TITLE_MAX_LENGTH", + "CHAT_MEMBERS_MAX_COUNT", +] diff --git a/src/domain/chats/constants.py b/src/domain/chats/constants.py new file mode 100644 index 0000000..2f6dd33 --- /dev/null +++ b/src/domain/chats/constants.py @@ -0,0 +1,3 @@ +CHAT_TITLE_MAX_LENGTH = 100 + +CHAT_MEMBERS_MAX_COUNT = 100 diff --git a/src/domain/chats/schemas.py b/src/domain/chats/schemas.py new file mode 100644 index 0000000..980780b --- /dev/null +++ b/src/domain/chats/schemas.py @@ -0,0 +1,46 @@ +from typing import Annotated +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from domain.utils import NotBlankStr, UtcDateTime + +from .constants import CHAT_MEMBERS_MAX_COUNT, CHAT_TITLE_MAX_LENGTH + +ChatTitle = Annotated[ + NotBlankStr, Field(min_length=1, max_length=CHAT_TITLE_MAX_LENGTH) +] + + +class CreateChatSchema(BaseModel): + """Запрос создания чата: участники задаются явно, включая вызывающего""" + + model_config = ConfigDict(extra="forbid") + + title: ChatTitle + member_ids: list[UUID] = Field(min_length=1, max_length=CHAT_MEMBERS_MAX_COUNT) + + @field_validator("member_ids") + @classmethod + def validate_unique_members(cls, value: list[UUID]) -> list[UUID]: + if len(set(value)) != len(value): + raise ValueError("member_ids не должен содержать дубликаты") + return value + + +class ChatSchema(BaseModel): + """Чат""" + + model_config = ConfigDict(frozen=True) + + id: UUID + title: str + member_ids: list[UUID] + created_at: UtcDateTime + + +class ChatPageSchema(BaseModel): + """Страница чатов текущего пользователя""" + + items: list[ChatSchema] + next_cursor: str | None diff --git a/src/domain/errors/__init__.py b/src/domain/errors/__init__.py new file mode 100644 index 0000000..62c0ac5 --- /dev/null +++ b/src/domain/errors/__init__.py @@ -0,0 +1,22 @@ +from .codes import ErrorCode +from .exceptions import ( + AppError, + ConflictError, + InvalidRequestError, + NotFoundError, + UnauthorizedError, + UnavailableError, +) +from .schemas import ErrorBodySchema, ErrorSchema + +__all__ = [ + "ErrorCode", + "AppError", + "InvalidRequestError", + "UnauthorizedError", + "NotFoundError", + "ConflictError", + "UnavailableError", + "ErrorBodySchema", + "ErrorSchema", +] diff --git a/src/domain/errors/codes.py b/src/domain/errors/codes.py new file mode 100644 index 0000000..f17eebe --- /dev/null +++ b/src/domain/errors/codes.py @@ -0,0 +1,15 @@ +from enum import StrEnum + + +class ErrorCode(StrEnum): + """коды ошибок""" + + INVALID_REQUEST = "invalid_request" + UNAUTHORIZED = "unauthorized" + NOT_FOUND = "not_found" + CONFLICT = "conflict" + PAYLOAD_TOO_LARGE = "payload_too_large" + UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type" + RATE_LIMITED = "rate_limited" + UNAVAILABLE = "unavailable" + INTERNAL_ERROR = "internal_error" diff --git a/src/domain/errors/exceptions.py b/src/domain/errors/exceptions.py new file mode 100644 index 0000000..0045802 --- /dev/null +++ b/src/domain/errors/exceptions.py @@ -0,0 +1,55 @@ +from http import HTTPStatus + +from .codes import ErrorCode + + +class AppError(Exception): + """Базовая ошибка приложения: статус, машинный код и безопасное сообщение""" + + status_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR + code: ErrorCode = ErrorCode.INTERNAL_ERROR + default_message: str = "Внутренняя ошибка сервера" + + def __init__(self, message: str | None = None) -> None: + self.message = message or self.default_message + super().__init__(self.message) + + +class InvalidRequestError(AppError): + """Неверные поля, UUID, cursor или limit""" + + status_code = HTTPStatus.BAD_REQUEST + code = ErrorCode.INVALID_REQUEST + default_message = "Некорректный запрос" + + +class UnauthorizedError(AppError): + """Нет действительной идентификации пользователя""" + + status_code = HTTPStatus.UNAUTHORIZED + code = ErrorCode.UNAUTHORIZED + default_message = "Требуется заголовок X-User-Id существующего пользователя" + + +class NotFoundError(AppError): + """Объекта нет или он чужой: существование чужого объекта не раскрывается""" + + status_code = HTTPStatus.NOT_FOUND + code = ErrorCode.NOT_FOUND + default_message = "Объект не найден" + + +class ConflictError(AppError): + """Конфликт состояния, например занятый username""" + + status_code = HTTPStatus.CONFLICT + code = ErrorCode.CONFLICT + default_message = "Конфликт состояния" + + +class UnavailableError(AppError): + """Приложение не готово обслуживать запросы""" + + status_code = HTTPStatus.SERVICE_UNAVAILABLE + code = ErrorCode.UNAVAILABLE + default_message = "Сервис временно недоступен" diff --git a/src/domain/errors/schemas.py b/src/domain/errors/schemas.py new file mode 100644 index 0000000..29fcc61 --- /dev/null +++ b/src/domain/errors/schemas.py @@ -0,0 +1,21 @@ +from pydantic import BaseModel, ConfigDict + +from .codes import ErrorCode + + +class ErrorBodySchema(BaseModel): + """Тело ошибки""" + + model_config = ConfigDict(extra="forbid") + + code: ErrorCode + message: str + request_id: str + + +class ErrorSchema(BaseModel): + """Единый формат ошибки: {"error": {...}}""" + + model_config = ConfigDict(extra="forbid") + + error: ErrorBodySchema diff --git a/src/domain/health/__init__.py b/src/domain/health/__init__.py new file mode 100644 index 0000000..d9f144b --- /dev/null +++ b/src/domain/health/__init__.py @@ -0,0 +1,3 @@ +from .schemas import HealthSchema + +__all__ = ["HealthSchema"] diff --git a/src/domain/health/schemas.py b/src/domain/health/schemas.py new file mode 100644 index 0000000..8199321 --- /dev/null +++ b/src/domain/health/schemas.py @@ -0,0 +1,9 @@ +from typing import Literal + +from pydantic import BaseModel + + +class HealthSchema(BaseModel): + """Ответ health-проверок""" + + status: Literal["ok"] = "ok" diff --git a/src/domain/messages/__init__.py b/src/domain/messages/__init__.py new file mode 100644 index 0000000..2cdf109 --- /dev/null +++ b/src/domain/messages/__init__.py @@ -0,0 +1,9 @@ +from .constants import MESSAGE_TEXT_MAX_LENGTH +from .schemas import CreateMessageSchema, MessagePageSchema, MessageSchema + +__all__ = [ + "CreateMessageSchema", + "MessageSchema", + "MessagePageSchema", + "MESSAGE_TEXT_MAX_LENGTH", +] diff --git a/src/domain/messages/constants.py b/src/domain/messages/constants.py new file mode 100644 index 0000000..dd584fa --- /dev/null +++ b/src/domain/messages/constants.py @@ -0,0 +1 @@ +MESSAGE_TEXT_MAX_LENGTH = 4000 diff --git a/src/domain/messages/schemas.py b/src/domain/messages/schemas.py new file mode 100644 index 0000000..6bb768a --- /dev/null +++ b/src/domain/messages/schemas.py @@ -0,0 +1,39 @@ +from typing import Annotated +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field + +from domain.utils import NotBlankStr, UtcDateTime + +from .constants import MESSAGE_TEXT_MAX_LENGTH + +MessageText = Annotated[ + NotBlankStr, Field(min_length=1, max_length=MESSAGE_TEXT_MAX_LENGTH) +] + + +class CreateMessageSchema(BaseModel): + """Запрос отправки сообщения: отправитель берётся из X-User-Id""" + + model_config = ConfigDict(extra="forbid") + + text: MessageText + + +class MessageSchema(BaseModel): + """Сообщение""" + + model_config = ConfigDict(frozen=True) + + id: UUID + chat_id: UUID + sender_id: UUID + text: str + created_at: UtcDateTime + + +class MessagePageSchema(BaseModel): + """Страница истории чата""" + + items: list[MessageSchema] + next_cursor: str | None diff --git a/src/domain/pagination/__init__.py b/src/domain/pagination/__init__.py new file mode 100644 index 0000000..cb7ef9c --- /dev/null +++ b/src/domain/pagination/__init__.py @@ -0,0 +1,6 @@ +from .schemas import PageCursorSchema, PageKey + +__all__ = [ + "PageKey", + "PageCursorSchema", +] diff --git a/src/domain/pagination/schemas.py b/src/domain/pagination/schemas.py new file mode 100644 index 0000000..f5be98b --- /dev/null +++ b/src/domain/pagination/schemas.py @@ -0,0 +1,26 @@ +from datetime import datetime +from typing import NamedTuple +from uuid import UUID + +from pydantic import BaseModel, ConfigDict + + +class PageKey(NamedTuple): + """Ключ keyset-пагинации: порядок (created_at, id) по возрастанию""" + + created_at: datetime + id: UUID + + +class PageCursorSchema(BaseModel): + """Содержимое непрозрачного cursor: ключ последнего элемента и его ресурс""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + scope: str + created_at: datetime + id: UUID + + @property + def key(self) -> PageKey: + return PageKey(self.created_at, self.id) diff --git a/src/domain/users/__init__.py b/src/domain/users/__init__.py new file mode 100644 index 0000000..2f90fd0 --- /dev/null +++ b/src/domain/users/__init__.py @@ -0,0 +1,9 @@ +from .constants import DISPLAY_NAME_MAX_LENGTH, USERNAME_PATTERN +from .schemas import CreateUserSchema, UserSchema + +__all__ = [ + "CreateUserSchema", + "UserSchema", + "USERNAME_PATTERN", + "DISPLAY_NAME_MAX_LENGTH", +] diff --git a/src/domain/users/constants.py b/src/domain/users/constants.py new file mode 100644 index 0000000..9852e57 --- /dev/null +++ b/src/domain/users/constants.py @@ -0,0 +1,3 @@ +USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$" + +DISPLAY_NAME_MAX_LENGTH = 100 diff --git a/src/domain/users/schemas.py b/src/domain/users/schemas.py new file mode 100644 index 0000000..43de887 --- /dev/null +++ b/src/domain/users/schemas.py @@ -0,0 +1,33 @@ +from typing import Annotated +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, StrictStr + +from domain.utils import NotBlankStr, UtcDateTime + +from .constants import DISPLAY_NAME_MAX_LENGTH, USERNAME_PATTERN + +Username = Annotated[StrictStr, Field(pattern=USERNAME_PATTERN)] +DisplayName = Annotated[ + NotBlankStr, Field(min_length=1, max_length=DISPLAY_NAME_MAX_LENGTH) +] + + +class CreateUserSchema(BaseModel): + """Запрос регистрации пользователя""" + + model_config = ConfigDict(extra="forbid") + + username: Username + display_name: DisplayName + + +class UserSchema(BaseModel): + """Пользователь""" + + model_config = ConfigDict(frozen=True) + + id: UUID + username: str + display_name: str + created_at: UtcDateTime diff --git a/src/domain/utils/__init__.py b/src/domain/utils/__init__.py new file mode 100644 index 0000000..c7e6419 --- /dev/null +++ b/src/domain/utils/__init__.py @@ -0,0 +1,3 @@ +from .types import NotBlankStr, UtcDateTime, ensure_not_blank, to_rfc3339_utc + +__all__ = ["NotBlankStr", "UtcDateTime", "ensure_not_blank", "to_rfc3339_utc"] diff --git a/src/domain/utils/types.py b/src/domain/utils/types.py new file mode 100644 index 0000000..54bcec0 --- /dev/null +++ b/src/domain/utils/types.py @@ -0,0 +1,25 @@ +from datetime import UTC, datetime +from typing import Annotated + +from pydantic import AfterValidator, PlainSerializer, StrictStr + + +def ensure_not_blank(value: str) -> str: + """Обязательная строка не может состоять только из пробельных символов""" + if not value.strip(): + raise ValueError("Строка не может быть пустой или пробельной") + return value + + +def to_rfc3339_utc(value: datetime) -> str: + """RFC 3339 в UTC с суффиксом Z и микросекундами""" + return ( + value.astimezone(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z") + ) + + +NotBlankStr = Annotated[StrictStr, AfterValidator(ensure_not_blank)] + +UtcDateTime = Annotated[ + datetime, PlainSerializer(to_rfc3339_utc, return_type=str, when_used="json") +] diff --git a/src/gateway.py b/src/gateway.py new file mode 100644 index 0000000..5b5066d --- /dev/null +++ b/src/gateway.py @@ -0,0 +1,51 @@ +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import uvicorn +from fastapi import FastAPI + +from application import api_endpoints, health_endpoints +from application.api.handlers import register_exception_handlers +from application.api.middlewares import RequestContextMiddleware +from config import APP_ENV, APP_HOST, APP_PORT, LOGGER, SHUTDOWN_TIMEOUT_SEC +from infrastructure import InMemoryStorage + + +@asynccontextmanager +async def lifespan(app: FastAPI) -> AsyncIterator[None]: + app.state.storage = InMemoryStorage() + app.state.is_ready = True + LOGGER.info(f"Application started, env={APP_ENV}, state is in-memory only") + yield + app.state.is_ready = False + LOGGER.info("Application stopped, in-memory state discarded") + + +app = FastAPI( + title="mtuci-labs-messanger", + description="мессенджер-конкурент-максу", + version="1.2.0", + lifespan=lifespan, +) + +app.add_middleware(RequestContextMiddleware) +register_exception_handlers(app) + +app.include_router(health_endpoints) +app.include_router(api_endpoints) + + +def main(host: str, port: int, shutdown_timeout: int) -> None: + """Функция для запуска api""" + uvicorn.run( + app, + host=host, + port=port, + timeout_graceful_shutdown=shutdown_timeout, + access_log=False, + server_header=False, + ) + + +if __name__ == "__main__": + main(host=APP_HOST, port=APP_PORT, shutdown_timeout=SHUTDOWN_TIMEOUT_SEC) diff --git a/src/healthcheck.py b/src/healthcheck.py new file mode 100644 index 0000000..66d7ed8 --- /dev/null +++ b/src/healthcheck.py @@ -0,0 +1,20 @@ +import sys +import urllib.request + +from config import APP_PORT + +READY_URL = f"http://127.0.0.1:{APP_PORT}/health/ready" + +REQUEST_TIMEOUT_SEC = 2 + + +def main() -> int: + try: + with urllib.request.urlopen(READY_URL, timeout=REQUEST_TIMEOUT_SEC) as response: + return 0 if response.status == 200 else 1 + except OSError: + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/infrastructure/__init__.py b/src/infrastructure/__init__.py new file mode 100644 index 0000000..8e3436c --- /dev/null +++ b/src/infrastructure/__init__.py @@ -0,0 +1,3 @@ +from .storage import InMemoryStorage + +__all__ = ["InMemoryStorage"] diff --git a/src/infrastructure/dependencies/__init__.py b/src/infrastructure/dependencies/__init__.py new file mode 100644 index 0000000..821c6e4 --- /dev/null +++ b/src/infrastructure/dependencies/__init__.py @@ -0,0 +1,4 @@ +from .service_creator import ServiceCreator +from .storage import get_storage + +__all__ = ["ServiceCreator", "get_storage"] diff --git a/src/infrastructure/dependencies/service_creator.py b/src/infrastructure/dependencies/service_creator.py new file mode 100644 index 0000000..28a8d89 --- /dev/null +++ b/src/infrastructure/dependencies/service_creator.py @@ -0,0 +1,51 @@ +from fastapi import Depends + +from infrastructure.dependencies.storage import get_storage +from infrastructure.repositories import ( + InMemoryChatRepository, + InMemoryMessageRepository, + InMemoryUserRepository, +) +from infrastructure.services import ChatService, MessageService, UserService +from infrastructure.storage import InMemoryStorage +from interfaces import ChatRepository, MessageRepository, UserRepository + + +class ServiceCreator: + @staticmethod + def _get_user_repository( + storage: InMemoryStorage = Depends(get_storage), + ) -> UserRepository: + return InMemoryUserRepository(storage) + + @staticmethod + def _get_chat_repository( + storage: InMemoryStorage = Depends(get_storage), + ) -> ChatRepository: + return InMemoryChatRepository(storage) + + @staticmethod + def _get_message_repository( + storage: InMemoryStorage = Depends(get_storage), + ) -> MessageRepository: + return InMemoryMessageRepository(storage) + + @staticmethod + def get_user_service( + repository: UserRepository = Depends(_get_user_repository), + ) -> UserService: + return UserService(repository) + + @staticmethod + def get_chat_service( + chat_repository: ChatRepository = Depends(_get_chat_repository), + user_repository: UserRepository = Depends(_get_user_repository), + ) -> ChatService: + return ChatService(chat_repository, user_repository) + + @staticmethod + def get_message_service( + chat_repository: ChatRepository = Depends(_get_chat_repository), + message_repository: MessageRepository = Depends(_get_message_repository), + ) -> MessageService: + return MessageService(chat_repository, message_repository) diff --git a/src/infrastructure/dependencies/storage.py b/src/infrastructure/dependencies/storage.py new file mode 100644 index 0000000..cf1cd4c --- /dev/null +++ b/src/infrastructure/dependencies/storage.py @@ -0,0 +1,9 @@ +from starlette.requests import HTTPConnection + +from infrastructure.storage import InMemoryStorage + + +def get_storage(connection: HTTPConnection) -> InMemoryStorage: + """Получение in-memory хранилища, созданного в lifespan.""" + storage: InMemoryStorage = connection.app.state.storage + return storage diff --git a/src/infrastructure/repositories/__init__.py b/src/infrastructure/repositories/__init__.py new file mode 100644 index 0000000..9d918b9 --- /dev/null +++ b/src/infrastructure/repositories/__init__.py @@ -0,0 +1,9 @@ +from .chat_repository import InMemoryChatRepository +from .message_repository import InMemoryMessageRepository +from .user_repository import InMemoryUserRepository + +__all__ = [ + "InMemoryUserRepository", + "InMemoryChatRepository", + "InMemoryMessageRepository", +] diff --git a/src/infrastructure/repositories/chat_repository/__init__.py b/src/infrastructure/repositories/chat_repository/__init__.py new file mode 100644 index 0000000..f80bb5d --- /dev/null +++ b/src/infrastructure/repositories/chat_repository/__init__.py @@ -0,0 +1,3 @@ +from .in_memory import InMemoryChatRepository + +__all__ = ["InMemoryChatRepository"] diff --git a/src/infrastructure/repositories/chat_repository/in_memory.py b/src/infrastructure/repositories/chat_repository/in_memory.py new file mode 100644 index 0000000..c3db650 --- /dev/null +++ b/src/infrastructure/repositories/chat_repository/in_memory.py @@ -0,0 +1,36 @@ +from uuid import UUID, uuid4 + +from domain import ChatSchema, PageKey +from infrastructure.storage import InMemoryStorage +from infrastructure.utils import slice_after +from interfaces import ChatRepository + + +class InMemoryChatRepository(ChatRepository): + def __init__(self, storage: InMemoryStorage) -> None: + self._storage = storage + + async def create(self, title: str, member_ids: list[UUID]) -> ChatSchema: + async with self._storage.chats_lock: + chat = ChatSchema( + id=uuid4(), + title=title, + member_ids=member_ids, + created_at=self._storage.chats_clock.now(), + ) + self._storage.chats[chat.id] = chat + for member_id in chat.member_ids: + self._storage.chats_by_member.setdefault(member_id, []).append(chat) + return chat + + async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None: + chat = self._storage.chats.get(chat_id) + if chat is None or member_id not in chat.member_ids: + return None + return chat + + async def list_for_member( + self, member_id: UUID, after: PageKey | None, limit: int + ) -> list[ChatSchema]: + chats = self._storage.chats_by_member.get(member_id, []) + return slice_after(chats, after, limit) diff --git a/src/infrastructure/repositories/message_repository/__init__.py b/src/infrastructure/repositories/message_repository/__init__.py new file mode 100644 index 0000000..d5c5d43 --- /dev/null +++ b/src/infrastructure/repositories/message_repository/__init__.py @@ -0,0 +1,3 @@ +from .in_memory import InMemoryMessageRepository + +__all__ = ["InMemoryMessageRepository"] diff --git a/src/infrastructure/repositories/message_repository/in_memory.py b/src/infrastructure/repositories/message_repository/in_memory.py new file mode 100644 index 0000000..adef757 --- /dev/null +++ b/src/infrastructure/repositories/message_repository/in_memory.py @@ -0,0 +1,29 @@ +from uuid import UUID, uuid4 + +from domain import MessageSchema, PageKey +from infrastructure.storage import InMemoryStorage +from infrastructure.utils import slice_after +from interfaces import MessageRepository + + +class InMemoryMessageRepository(MessageRepository): + def __init__(self, storage: InMemoryStorage) -> None: + self._storage = storage + + async def create(self, chat_id: UUID, sender_id: UUID, text: str) -> MessageSchema: + async with self._storage.messages_lock: + message = MessageSchema( + id=uuid4(), + chat_id=chat_id, + sender_id=sender_id, + text=text, + created_at=self._storage.messages_clock.now(), + ) + self._storage.messages_by_chat.setdefault(chat_id, []).append(message) + return message + + async def list_for_chat( + self, chat_id: UUID, after: PageKey | None, limit: int + ) -> list[MessageSchema]: + history = self._storage.messages_by_chat.get(chat_id, []) + return slice_after(history, after, limit) diff --git a/src/infrastructure/repositories/user_repository/__init__.py b/src/infrastructure/repositories/user_repository/__init__.py new file mode 100644 index 0000000..a2878ed --- /dev/null +++ b/src/infrastructure/repositories/user_repository/__init__.py @@ -0,0 +1,3 @@ +from .in_memory import InMemoryUserRepository + +__all__ = ["InMemoryUserRepository"] diff --git a/src/infrastructure/repositories/user_repository/in_memory.py b/src/infrastructure/repositories/user_repository/in_memory.py new file mode 100644 index 0000000..ac5b99b --- /dev/null +++ b/src/infrastructure/repositories/user_repository/in_memory.py @@ -0,0 +1,32 @@ +from datetime import UTC, datetime +from uuid import UUID, uuid4 + +from domain import UserSchema +from domain.errors import ConflictError +from infrastructure.storage import InMemoryStorage +from interfaces import UserRepository + + +class InMemoryUserRepository(UserRepository): + def __init__(self, storage: InMemoryStorage) -> None: + self._storage = storage + + async def create(self, username: str, display_name: str) -> UserSchema: + async with self._storage.users_lock: + if username in self._storage.user_ids_by_username: + raise ConflictError("Имя пользователя уже занято") + user = UserSchema( + id=uuid4(), + username=username, + display_name=display_name, + created_at=datetime.now(UTC), + ) + self._storage.users[user.id] = user + self._storage.user_ids_by_username[user.username] = user.id + return user + + async def get_by_id(self, user_id: UUID) -> UserSchema | None: + return self._storage.users.get(user_id) + + async def get_missing_ids(self, user_ids: list[UUID]) -> set[UUID]: + return {user_id for user_id in user_ids if user_id not in self._storage.users} diff --git a/src/infrastructure/services/__init__.py b/src/infrastructure/services/__init__.py new file mode 100644 index 0000000..c1a297e --- /dev/null +++ b/src/infrastructure/services/__init__.py @@ -0,0 +1,5 @@ +from .chat_service import ChatService +from .message_service import MessageService +from .user_service import UserService + +__all__ = ["UserService", "ChatService", "MessageService"] diff --git a/src/infrastructure/services/chat_service/__init__.py b/src/infrastructure/services/chat_service/__init__.py new file mode 100644 index 0000000..800f4e1 --- /dev/null +++ b/src/infrastructure/services/chat_service/__init__.py @@ -0,0 +1,3 @@ +from .chat_service import ChatService + +__all__ = ["ChatService"] diff --git a/src/infrastructure/services/chat_service/chat_service.py b/src/infrastructure/services/chat_service/chat_service.py new file mode 100644 index 0000000..3c6d3a4 --- /dev/null +++ b/src/infrastructure/services/chat_service/chat_service.py @@ -0,0 +1,47 @@ +from uuid import UUID + +from config import LOGGER +from domain import ChatPageSchema, ChatSchema, CreateChatSchema, UserSchema +from domain.errors import InvalidRequestError, NotFoundError +from infrastructure.utils import build_page, decode_cursor +from interfaces import ChatRepository, UserRepository + + +class ChatService: + def __init__( + self, chat_repository: ChatRepository, user_repository: UserRepository + ) -> None: + self._chats = chat_repository + self._users = user_repository + + async def create_chat( + self, current_user: UserSchema, data: CreateChatSchema + ) -> ChatSchema: + """Чат создаётся из явного списка существующих участников, включая создателя""" + if current_user.id not in data.member_ids: + raise InvalidRequestError( + "member_ids должен содержать текущего пользователя" + ) + if await self._users.get_missing_ids(data.member_ids): + raise InvalidRequestError("member_ids содержит неизвестных пользователей") + chat = await self._chats.create(data.title, data.member_ids) + LOGGER.info( + f"Создан чат {chat.id} пользователем {current_user.id}, " + f"участников: {len(chat.member_ids)}" + ) + return chat + + async def get_chat(self, current_user: UserSchema, chat_id: UUID) -> ChatSchema: + chat = await self._chats.get_for_member(chat_id, current_user.id) + if chat is None: + raise NotFoundError() + return chat + + async def list_chats( + self, current_user: UserSchema, limit: int, cursor: str | None + ) -> ChatPageSchema: + scope = f"chats:{current_user.id}" + after = decode_cursor(cursor, scope) + fetched = await self._chats.list_for_member(current_user.id, after, limit + 1) + items, next_cursor = build_page(fetched, limit, scope) + return ChatPageSchema(items=items, next_cursor=next_cursor) diff --git a/src/infrastructure/services/message_service/__init__.py b/src/infrastructure/services/message_service/__init__.py new file mode 100644 index 0000000..d834d91 --- /dev/null +++ b/src/infrastructure/services/message_service/__init__.py @@ -0,0 +1,3 @@ +from .message_service import MessageService + +__all__ = ["MessageService"] diff --git a/src/infrastructure/services/message_service/message_service.py b/src/infrastructure/services/message_service/message_service.py new file mode 100644 index 0000000..3b2061a --- /dev/null +++ b/src/infrastructure/services/message_service/message_service.py @@ -0,0 +1,42 @@ +from uuid import UUID + +from config import LOGGER +from domain import CreateMessageSchema, MessagePageSchema, MessageSchema, UserSchema +from domain.errors import NotFoundError +from infrastructure.utils import build_page, decode_cursor +from interfaces import ChatRepository, MessageRepository + + +class MessageService: + def __init__( + self, chat_repository: ChatRepository, message_repository: MessageRepository + ) -> None: + self._chats = chat_repository + self._messages = message_repository + + async def send_message( + self, current_user: UserSchema, chat_id: UUID, data: CreateMessageSchema + ) -> MessageSchema: + """Отправитель берётся из текущей идентификации; текст в логи не пишется""" + await self._ensure_member(current_user, chat_id) + message = await self._messages.create(chat_id, current_user.id, data.text) + LOGGER.info( + f"Сообщение {message.id} отправлено в чат {chat_id} " + f"пользователем {current_user.id}" + ) + return message + + async def list_messages( + self, current_user: UserSchema, chat_id: UUID, limit: int, cursor: str | None + ) -> MessagePageSchema: + await self._ensure_member(current_user, chat_id) + scope = f"messages:{chat_id}" + after = decode_cursor(cursor, scope) + fetched = await self._messages.list_for_chat(chat_id, after, limit + 1) + items, next_cursor = build_page(fetched, limit, scope) + return MessagePageSchema(items=items, next_cursor=next_cursor) + + async def _ensure_member(self, current_user: UserSchema, chat_id: UUID) -> None: + """Посторонний получает 404: существование чужого чата не раскрывается""" + if await self._chats.get_for_member(chat_id, current_user.id) is None: + raise NotFoundError() diff --git a/src/infrastructure/services/user_service/__init__.py b/src/infrastructure/services/user_service/__init__.py new file mode 100644 index 0000000..3b69507 --- /dev/null +++ b/src/infrastructure/services/user_service/__init__.py @@ -0,0 +1,3 @@ +from .user_service import UserService + +__all__ = ["UserService"] diff --git a/src/infrastructure/services/user_service/user_service.py b/src/infrastructure/services/user_service/user_service.py new file mode 100644 index 0000000..00a27a2 --- /dev/null +++ b/src/infrastructure/services/user_service/user_service.py @@ -0,0 +1,34 @@ +from uuid import UUID + +from config import LOGGER +from domain import CreateUserSchema, UserSchema +from domain.errors import UnauthorizedError +from interfaces import UserRepository + + +class UserService: + def __init__(self, repository: UserRepository) -> None: + self._repo = repository + + async def register(self, data: CreateUserSchema) -> UserSchema: + user = await self._repo.create(data.username, data.display_name) + LOGGER.info(f"Зарегистрирован пользователь {user.id}") + return user + + async def authenticate(self, raw_user_id: str | None) -> UserSchema: + """ + Учебная идентификация lab1: X-User-Id с UUID существующего пользователя. + + Raises: + UnauthorizedError: заголовка нет, он не UUID или пользователь неизвестен + """ + if not raw_user_id: + raise UnauthorizedError() + try: + user_id = UUID(raw_user_id) + except ValueError: + raise UnauthorizedError() from None + user = await self._repo.get_by_id(user_id) + if user is None: + raise UnauthorizedError() + return user diff --git a/src/infrastructure/storage/__init__.py b/src/infrastructure/storage/__init__.py new file mode 100644 index 0000000..58e4016 --- /dev/null +++ b/src/infrastructure/storage/__init__.py @@ -0,0 +1,3 @@ +from .in_memory import InMemoryStorage + +__all__ = ["InMemoryStorage"] diff --git a/src/infrastructure/storage/in_memory.py b/src/infrastructure/storage/in_memory.py new file mode 100644 index 0000000..2d0acb2 --- /dev/null +++ b/src/infrastructure/storage/in_memory.py @@ -0,0 +1,23 @@ +import asyncio +from uuid import UUID + +from domain import ChatSchema, MessageSchema, UserSchema +from infrastructure.utils import MonotonicClock + + +class InMemoryStorage: + """Всё состояние мессенджера в памяти одного процесса.""" + + def __init__(self) -> None: + self.users: dict[UUID, UserSchema] = {} + self.user_ids_by_username: dict[str, UUID] = {} + self.users_lock = asyncio.Lock() + + self.chats: dict[UUID, ChatSchema] = {} + self.chats_by_member: dict[UUID, list[ChatSchema]] = {} + self.chats_lock = asyncio.Lock() + self.chats_clock = MonotonicClock() + + self.messages_by_chat: dict[UUID, list[MessageSchema]] = {} + self.messages_lock = asyncio.Lock() + self.messages_clock = MonotonicClock() diff --git a/src/infrastructure/utils/__init__.py b/src/infrastructure/utils/__init__.py new file mode 100644 index 0000000..c53e37b --- /dev/null +++ b/src/infrastructure/utils/__init__.py @@ -0,0 +1,17 @@ +from .clock import MonotonicClock +from .pagination import ( + build_page, + decode_cursor, + encode_cursor, + page_key, + slice_after, +) + +__all__ = [ + "MonotonicClock", + "page_key", + "slice_after", + "encode_cursor", + "decode_cursor", + "build_page", +] diff --git a/src/infrastructure/utils/clock.py b/src/infrastructure/utils/clock.py new file mode 100644 index 0000000..a33fcd8 --- /dev/null +++ b/src/infrastructure/utils/clock.py @@ -0,0 +1,22 @@ +from datetime import UTC, datetime, timedelta + +CLOCK_STEP = timedelta(microseconds=1) + + +class MonotonicClock: + """ + Строго возрастающее время UTC. + + Две записи не получат одинаковый created_at, а перевод системных часов назад + не поставит новую запись перед уже прочитанной. Вызывать под локом коллекции. + """ + + 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 + CLOCK_STEP + self._last = current + return current diff --git a/src/infrastructure/utils/pagination.py b/src/infrastructure/utils/pagination.py new file mode 100644 index 0000000..8f4b53a --- /dev/null +++ b/src/infrastructure/utils/pagination.py @@ -0,0 +1,53 @@ +import base64 +import binascii +from bisect import bisect_right + +from pydantic import ValidationError + +from domain import ChatSchema, MessageSchema, PageCursorSchema, PageKey +from domain.errors import InvalidRequestError + +PageItem = ChatSchema | MessageSchema + + +def page_key(item: PageItem) -> PageKey: + return PageKey(item.created_at, item.id) + + +def slice_after( + items: list[PageItem], after: PageKey | None, limit: int +) -> list[PageItem]: + """Элементы строго после ключа; items отсортированы по page_key""" + start = 0 if after is None else bisect_right(items, after, key=page_key) + return items[start : start + limit] + + +def encode_cursor(scope: str, key: PageKey) -> str: + """Непрозрачный cursor: base64url от JSON с ресурсом и ключом последнего элемента""" + payload = PageCursorSchema(scope=scope, created_at=key.created_at, id=key.id) + encoded = base64.urlsafe_b64encode(payload.model_dump_json().encode()) + return encoded.decode().rstrip("=") + + +def decode_cursor(raw: str | None, scope: str) -> PageKey | None: + """Разбор cursor, привязанного к ресурсу.""" + if raw is None: + return None + try: + decoded = base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4)) + cursor = PageCursorSchema.model_validate_json(decoded) + except (binascii.Error, ValueError, ValidationError): + raise InvalidRequestError("Некорректный cursor") from None + if cursor.scope != scope: + raise InvalidRequestError("cursor выдан для другого ресурса") + return cursor.key + + +def build_page( + fetched: list[PageItem], limit: int, scope: str +) -> tuple[list[PageItem], str | None]: + """Отрезает страницу из limit + 1 полученных элементов.""" + items = fetched[:limit] + if len(fetched) <= limit: + return items, None + return items, encode_cursor(scope, page_key(items[-1])) diff --git a/src/interfaces/__init__.py b/src/interfaces/__init__.py new file mode 100644 index 0000000..76e8e8e --- /dev/null +++ b/src/interfaces/__init__.py @@ -0,0 +1,5 @@ +from .chat_repository import ChatRepository +from .message_repository import MessageRepository +from .user_repository import UserRepository + +__all__ = ["UserRepository", "ChatRepository", "MessageRepository"] diff --git a/src/interfaces/chat_repository.py b/src/interfaces/chat_repository.py new file mode 100644 index 0000000..70c3c5d --- /dev/null +++ b/src/interfaces/chat_repository.py @@ -0,0 +1,25 @@ +from abc import ABC, abstractmethod +from uuid import UUID + +from domain import ChatSchema, PageKey + + +class ChatRepository(ABC): + """Слой абстракции хранилища чатов""" + + @abstractmethod + async def create(self, title: str, member_ids: list[UUID]) -> ChatSchema: + """сохраняет чат и индексирует его по участникам.""" + pass + + @abstractmethod + async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None: + """Получение чата, только если пользователь является его участником.""" + pass + + @abstractmethod + async def list_for_member( + self, member_id: UUID, after: PageKey | None, limit: int + ) -> list[ChatSchema]: + """Чаты пользователя по (created_at, id) по возрастанию.""" + pass diff --git a/src/interfaces/message_repository.py b/src/interfaces/message_repository.py new file mode 100644 index 0000000..66cbd16 --- /dev/null +++ b/src/interfaces/message_repository.py @@ -0,0 +1,20 @@ +from abc import ABC, abstractmethod +from uuid import UUID + +from domain import MessageSchema, PageKey + + +class MessageRepository(ABC): + """Слой абстракции хранилища сообщений""" + + @abstractmethod + async def create(self, chat_id: UUID, sender_id: UUID, text: str) -> MessageSchema: + """Атомарно назначает id, created_at и добавляет сообщение в конец истории чата.""" + pass + + @abstractmethod + async def list_for_chat( + self, chat_id: UUID, after: PageKey | None, limit: int + ) -> list[MessageSchema]: + """История чата по (created_at, id) по возрастанию.""" + pass diff --git a/src/interfaces/user_repository.py b/src/interfaces/user_repository.py new file mode 100644 index 0000000..24dc493 --- /dev/null +++ b/src/interfaces/user_repository.py @@ -0,0 +1,23 @@ +from abc import ABC, abstractmethod +from uuid import UUID + +from domain import UserSchema + + +class UserRepository(ABC): + """Слой абстракции хранилища пользователей""" + + @abstractmethod + async def create(self, username: str, display_name: str) -> UserSchema: + """проверяет уникальность username и сохраняет пользователя.""" + pass + + @abstractmethod + async def get_by_id(self, user_id: UUID) -> UserSchema | None: + """Получение пользователя по ID.""" + pass + + @abstractmethod + async def get_missing_ids(self, user_ids: list[UUID]) -> set[UUID]: + """Возвращает ID из списка, для которых пользователей не существует.""" + pass diff --git a/student-tests/conftest.py b/student-tests/conftest.py new file mode 100644 index 0000000..bdeaab6 --- /dev/null +++ b/student-tests/conftest.py @@ -0,0 +1,63 @@ +import json +import os +from collections.abc import Callable, Iterator +from pathlib import Path + +import httpx +import pytest +from helpers import auth, unique_username + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"] + +REQUEST_TIMEOUT_SEC = 10 + + +@pytest.fixture(scope="session") +def base_url() -> str: + return os.environ.get("BASE_URL") or DEFAULT_BASE_URL + + +@pytest.fixture(scope="session") +def api(base_url: str) -> Iterator[httpx.Client]: + with httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SEC) as client: + yield client + + +@pytest.fixture +def make_user(api: httpx.Client) -> Callable[..., dict]: + def create(label: str = "user", display_name: str | None = None) -> dict: + body = { + "username": unique_username(label), + "display_name": display_name or f"Студент {label}", + } + response = api.post("/api/v1/users", json=body) + assert response.status_code == 201, response.text + return response.json() + + return create + + +@pytest.fixture +def make_chat(api: httpx.Client) -> Callable[..., dict]: + def create(owner: dict, members: list[dict], title: str = "Тестовый чат") -> dict: + body = {"title": title, "member_ids": [member["id"] for member in members]} + response = api.post("/api/v1/chats", json=body, headers=auth(owner)) + assert response.status_code == 201, response.text + return response.json() + + return create + + +@pytest.fixture +def send_message(api: httpx.Client) -> Callable[..., dict]: + def send(user: dict, chat: dict, text: str) -> dict: + response = api.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": text}, + headers=auth(user), + ) + assert response.status_code == 201, response.text + return response.json() + + return send diff --git a/student-tests/helpers.py b/student-tests/helpers.py new file mode 100644 index 0000000..94aef6b --- /dev/null +++ b/student-tests/helpers.py @@ -0,0 +1,43 @@ +"""Общие проверки для собственных black-box тестов""" + +import uuid + +import httpx + + +def unique_username(label: str) -> str: + return f"st_{label}_{uuid.uuid4().hex[:12]}" + + +def auth(user: dict) -> dict[str, str]: + return {"X-User-Id": user["id"]} + + +def assert_error(response: httpx.Response, status: int, code: str) -> None: + """Код ответа и единый формат ошибки: request_id совпадает с заголовком""" + assert response.status_code == status, response.text + assert response.headers["content-type"].startswith("application/json") + error = response.json()["error"] + assert error["code"] == code + assert error["message"] + assert error["request_id"] == response.headers["X-Request-Id"] + + +def read_all_messages( + api: httpx.Client, user: dict, chat_id: str, limit: int +) -> tuple[list[dict], int]: + """Обход истории по next_cursor; возвращает сообщения и число страниц""" + items: list[dict] = [] + pages = 0 + params: dict[str, str | int] = {"limit": limit} + while True: + response = api.get( + f"/api/v1/chats/{chat_id}/messages", params=params, headers=auth(user) + ) + assert response.status_code == 200, response.text + page = response.json() + items.extend(page["items"]) + pages += 1 + if page["next_cursor"] is None: + return items, pages + params = {"limit": limit, "cursor": page["next_cursor"]} diff --git a/student-tests/test_concurrency.py b/student-tests/test_concurrency.py new file mode 100644 index 0000000..896c904 --- /dev/null +++ b/student-tests/test_concurrency.py @@ -0,0 +1,77 @@ +"""Защита состояния от гонок: 100 сообщений от 10 параллельных клиентов""" + +import asyncio +import json +import time + +import httpx +from helpers import read_all_messages + +CLIENTS = 10 +MESSAGES_PER_CLIENT = 10 +TOTAL_MESSAGES = CLIENTS * MESSAGES_PER_CLIENT +PAGE_LIMIT = 30 + + +async def _send_concurrently( + base_url: str, chat_id: str, users: list[dict] +) -> list[int]: + """Каждый клиент — отдельный пользователь и пул соединений; старт по сигналу""" + start = asyncio.Event() + + async def client_worker(user: dict) -> list[int]: + async with httpx.AsyncClient( + base_url=base_url, headers={"X-User-Id": user["id"]}, timeout=30 + ) as client: + await start.wait() + responses = await asyncio.gather( + *( + client.post( + f"/api/v1/chats/{chat_id}/messages", + json={"text": f"{user['username']}#{n}"}, + ) + for n in range(MESSAGES_PER_CLIENT) + ) + ) + return [response.status_code for response in responses] + + workers = [asyncio.create_task(client_worker(user)) for user in users] + await asyncio.sleep(0) + start.set() + results = await asyncio.gather(*workers) + return [status for statuses in results for status in statuses] + + +def test_parallel_messages_are_not_lost_or_duplicated( + api: httpx.Client, base_url: str, make_user, make_chat +) -> None: + users = [make_user(f"c{n}") for n in range(CLIENTS)] + chat = make_chat(users[0], users) + + started = time.perf_counter() + statuses = asyncio.run(_send_concurrently(base_url, chat["id"], users)) + elapsed = time.perf_counter() - started + + items, pages = read_all_messages(api, users[-1], chat["id"], PAGE_LIMIT) + expected_texts = { + f"{user['username']}#{n}" for user in users for n in range(MESSAGES_PER_CLIENT) + } + summary = { + "clients": CLIENTS, + "messages_sent": len(statuses), + "status_201": statuses.count(201), + "messages_read": len(items), + "unique_ids": len({item["id"] for item in items}), + "unique_texts": len({item["text"] for item in items}), + "pages_read": pages, + "send_seconds": round(elapsed, 3), + } + print("\nCONCURRENCY RESULT:", json.dumps(summary, ensure_ascii=False)) + + assert statuses == [201] * TOTAL_MESSAGES + assert len(items) == TOTAL_MESSAGES + assert summary["unique_ids"] == TOTAL_MESSAGES + assert {item["text"] for item in items} == expected_texts + keys = [(item["created_at"], item["id"]) for item in items] + assert keys == sorted(keys) + assert len(set(keys)) == TOTAL_MESSAGES diff --git a/student-tests/test_foreign_chat.py b/student-tests/test_foreign_chat.py new file mode 100644 index 0000000..e720cf9 --- /dev/null +++ b/student-tests/test_foreign_chat.py @@ -0,0 +1,49 @@ +"""Чужой чат: посторонний получает 404, существование чата не раскрывается""" + +import uuid + +import httpx +from helpers import assert_error, auth + + +def test_outsider_cannot_access_chat( + api: httpx.Client, make_user, make_chat, send_message +) -> None: + alice = make_user("alice") + bob = make_user("bob") + eve = make_user("eve") + chat = make_chat(alice, [alice, bob]) + send_message(alice, chat, "секрет") + path = f"/api/v1/chats/{chat['id']}" + + assert_error(api.get(path, headers=auth(eve)), 404, "not_found") + assert_error(api.get(f"{path}/messages", headers=auth(eve)), 404, "not_found") + response = api.post(f"{path}/messages", json={"text": "чужое"}, headers=auth(eve)) + assert_error(response, 404, "not_found") + + history = api.get(f"{path}/messages", headers=auth(bob)).json() + assert [item["text"] for item in history["items"]] == ["секрет"] + + +def test_foreign_and_missing_chat_are_indistinguishable( + api: httpx.Client, make_user, make_chat +) -> None: + alice = make_user("alice") + eve = make_user("eve") + chat = make_chat(alice, [alice]) + foreign = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(eve)).json() + missing = api.get(f"/api/v1/chats/{uuid.uuid4()}", headers=auth(eve)).json() + assert foreign["error"]["code"] == missing["error"]["code"] == "not_found" + assert foreign["error"]["message"] == missing["error"]["message"] + + +def test_chat_list_contains_only_own_chats( + api: httpx.Client, make_user, make_chat +) -> None: + alice = make_user("alice") + eve = make_user("eve") + chat = make_chat(alice, [alice]) + own = api.get("/api/v1/chats", headers=auth(eve)).json() + assert own == {"items": [], "next_cursor": None} + listed = api.get("/api/v1/chats", headers=auth(alice)).json() + assert [item["id"] for item in listed["items"]] == [chat["id"]] diff --git a/student-tests/test_health.py b/student-tests/test_health.py new file mode 100644 index 0000000..a8b1dbb --- /dev/null +++ b/student-tests/test_health.py @@ -0,0 +1,15 @@ +import httpx +from helpers import assert_error + + +def test_health_endpoints_have_request_id(api: httpx.Client) -> None: + for path in ("/health/live", "/health/ready"): + response = api.get(path) + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + assert response.headers["X-Request-Id"] + + +def test_unknown_route_uses_error_format(api: httpx.Client) -> None: + assert_error(api.get("/api/v1/unknown"), 404, "not_found") + diff --git a/student-tests/test_invalid_json.py b/student-tests/test_invalid_json.py new file mode 100644 index 0000000..7d44e9d --- /dev/null +++ b/student-tests/test_invalid_json.py @@ -0,0 +1,94 @@ +"""Неверный JSON и неверная структура тела — 400 invalid_request""" + +import httpx +import pytest +from helpers import assert_error, auth + +MALFORMED_BODIES = [ + b'{"username": "abc",', + b"not json at all", + b'{"text": "\xff\xfe"}', + b"", +] + + +@pytest.mark.parametrize("raw", MALFORMED_BODIES) +def test_malformed_json_on_register(api: httpx.Client, raw: bytes) -> None: + response = api.post( + "/api/v1/users", content=raw, headers={"Content-Type": "application/json"} + ) + assert_error(response, 400, "invalid_request") + + +@pytest.mark.parametrize("raw", MALFORMED_BODIES) +def test_malformed_json_on_create_chat_and_message( + api: httpx.Client, make_user, make_chat, raw: bytes +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + headers = {**auth(alice), "Content-Type": "application/json"} + assert_error( + api.post("/api/v1/chats", content=raw, headers=headers), 400, "invalid_request" + ) + assert_error( + api.post(f"/api/v1/chats/{chat['id']}/messages", content=raw, headers=headers), + 400, + "invalid_request", + ) + + +@pytest.mark.parametrize( + "body", + [ + [], + "alice", + {"username": "valid_name"}, + {"username": 123, "display_name": "x"}, + {"username": "valid_name", "display_name": None}, + {"username": "valid_name", "display_name": "x", "is_admin": True}, + {"username": "Upper_Case", "display_name": "x"}, + {"username": "ab", "display_name": "x"}, + {"username": "valid_name", "display_name": " "}, + {"username": "valid_name", "display_name": "я" * 101}, + ], +) +def test_invalid_user_payload(api: httpx.Client, body: object) -> None: + assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request") + + +@pytest.mark.parametrize( + "body", + [ + {"text": 42}, + {"text": "привет", "sender_id": "11111111-1111-4111-8111-111111111111"}, + {}, + ], +) +def test_invalid_message_payload( + api: httpx.Client, make_user, make_chat, body: dict +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + response = api.post( + f"/api/v1/chats/{chat['id']}/messages", json=body, headers=auth(alice) + ) + assert_error(response, 400, "invalid_request") + + +def test_invalid_chat_payload(api: httpx.Client, make_user) -> None: + alice = make_user("alice") + bob = make_user("bob") + cases = [ + {"title": "t", "member_ids": [bob["id"]]}, + {"title": "t", "member_ids": [alice["id"], alice["id"]]}, + { + "title": "t", + "member_ids": [alice["id"], "11111111-1111-4111-8111-111111111111"], + }, + {"title": "t", "member_ids": [alice["id"], "not-a-uuid"]}, + {"title": "t", "member_ids": []}, + {"title": " ", "member_ids": [alice["id"]]}, + ] + for body in cases: + response = api.post("/api/v1/chats", json=body, headers=auth(alice)) + assert_error(response, 400, "invalid_request") diff --git a/student-tests/test_messages.py b/student-tests/test_messages.py new file mode 100644 index 0000000..6236deb --- /dev/null +++ b/student-tests/test_messages.py @@ -0,0 +1,59 @@ +"""Пустые сообщения, границы длины и Unicode""" + +import httpx +import pytest +from helpers import assert_error, auth + + +@pytest.mark.parametrize("text", ["", " ", " \n\t ", " "]) +def test_empty_or_blank_message_is_rejected( + api: httpx.Client, make_user, make_chat, text: str +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + response = api.post( + f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=auth(alice) + ) + assert_error(response, 400, "invalid_request") + history = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)) + assert history.json()["items"] == [] + + +def test_message_length_is_counted_in_code_points( + api: httpx.Client, make_user, make_chat, send_message +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + longest = "😀" * 4000 + assert send_message(alice, chat, longest)["text"] == longest + response = api.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "😀" * 4001}, + headers=auth(alice), + ) + assert_error(response, 400, "invalid_request") + + +def test_unicode_is_preserved( + api: httpx.Client, make_user, make_chat, send_message +) -> None: + name = "Алиса 👩‍💻 é" + alice = make_user("alice", display_name=name) + assert alice["display_name"] == name + chat = make_chat(alice, [alice], title="Чат 🚀 中文") + assert chat["title"] == "Чат 🚀 中文" + text = "Привет, мир 👋 — «кавычки» \u0000 и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢" + message = send_message(alice, chat, text) + assert message["text"] == text + page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)).json() + assert page["items"][0]["text"] == text + + +def test_sender_is_taken_from_x_user_id(make_user, make_chat, send_message) -> None: + alice = make_user("alice") + bob = make_user("bob") + chat = make_chat(alice, [alice, bob]) + message = send_message(bob, chat, "от Боба") + assert message["sender_id"] == bob["id"] + assert message["chat_id"] == chat["id"] + assert message["created_at"].endswith("Z") diff --git a/student-tests/test_pagination.py b/student-tests/test_pagination.py new file mode 100644 index 0000000..2515434 --- /dev/null +++ b/student-tests/test_pagination.py @@ -0,0 +1,138 @@ +"""Обход нескольких страниц истории и списка чатов по cursor""" + +import httpx +import pytest +from helpers import assert_error, auth, read_all_messages + + +@pytest.mark.parametrize( + ("total", "limit", "expected_pages"), + [(7, 3, 3), (6, 3, 2), (5, 1, 5), (3, 100, 1)], +) +def test_walk_message_pages( + api: httpx.Client, + make_user, + make_chat, + send_message, + total: int, + limit: int, + expected_pages: int, +) -> None: + alice = make_user("alice") + bob = make_user("bob") + chat = make_chat(alice, [alice, bob]) + sent = [send_message(alice if n % 2 else bob, chat, f"m{n}") for n in range(total)] + + items, pages = read_all_messages(api, bob, chat["id"], limit) + + assert pages == expected_pages + assert items == sent + assert len({item["id"] for item in items}) == total + keys = [(item["created_at"], item["id"]) for item in items] + assert keys == sorted(keys) + + +def test_limit_can_change_between_pages( + api: httpx.Client, make_user, make_chat, send_message +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + sent = [send_message(alice, chat, f"m{n}") for n in range(6)] + path = f"/api/v1/chats/{chat['id']}/messages" + + first = api.get(path, params={"limit": 2}, headers=auth(alice)).json() + second = api.get( + path, params={"limit": 4, "cursor": first["next_cursor"]}, headers=auth(alice) + ).json() + + assert first["items"] + second["items"] == sent + assert second["next_cursor"] is None + + +def test_new_message_appears_after_cursor( + api: httpx.Client, make_user, make_chat, send_message +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + send_message(alice, chat, "m0") + send_message(alice, chat, "m1") + path = f"/api/v1/chats/{chat['id']}/messages" + first = api.get(path, params={"limit": 1}, headers=auth(alice)).json() + late = send_message(alice, chat, "m2") + rest = api.get( + path, params={"limit": 10, "cursor": first["next_cursor"]}, headers=auth(alice) + ).json() + assert [item["text"] for item in rest["items"]] == ["m1", "m2"] + assert rest["items"][-1] == late + + +def test_cursor_is_bound_to_chat( + api: httpx.Client, make_user, make_chat, send_message +) -> None: + alice = make_user("alice") + chat_a = make_chat(alice, [alice], title="A") + chat_b = make_chat(alice, [alice], title="B") + for n in range(3): + send_message(alice, chat_a, f"a{n}") + cursor = api.get( + f"/api/v1/chats/{chat_a['id']}/messages", + params={"limit": 1}, + headers=auth(alice), + ).json()["next_cursor"] + response = api.get( + f"/api/v1/chats/{chat_b['id']}/messages", + params={"cursor": cursor}, + headers=auth(alice), + ) + assert_error(response, 400, "invalid_request") + + +@pytest.mark.parametrize( + "params", + [ + {"limit": 0}, + {"limit": 101}, + {"limit": "abc"}, + {"cursor": ""}, + {"cursor": "not-a-cursor"}, + {"cursor": "eyJzY29wZSI6IDF9"}, + ], +) +def test_invalid_limit_or_cursor( + api: httpx.Client, make_user, make_chat, params: dict +) -> None: + alice = make_user("alice") + chat = make_chat(alice, [alice]) + response = api.get( + f"/api/v1/chats/{chat['id']}/messages", params=params, headers=auth(alice) + ) + assert_error(response, 400, "invalid_request") + + +def test_walk_chat_list_pages(api: httpx.Client, make_user, make_chat) -> None: + alice = make_user("alice") + created = [make_chat(alice, [alice], title=f"chat {n}") for n in range(5)] + listed: list[dict] = [] + params: dict[str, str | int] = {"limit": 2} + pages = 0 + while True: + page = api.get("/api/v1/chats", params=params, headers=auth(alice)).json() + listed.extend(page["items"]) + pages += 1 + if page["next_cursor"] is None: + break + params = {"limit": 2, "cursor": page["next_cursor"]} + assert pages == 3 + assert listed == created + + +def test_chat_cursor_is_bound_to_user(api: httpx.Client, make_user, make_chat) -> None: + alice = make_user("alice") + bob = make_user("bob") + for n in range(2): + make_chat(alice, [alice, bob], title=f"chat {n}") + cursor = api.get("/api/v1/chats", params={"limit": 1}, headers=auth(alice)).json()[ + "next_cursor" + ] + response = api.get("/api/v1/chats", params={"cursor": cursor}, headers=auth(bob)) + assert_error(response, 400, "invalid_request") diff --git a/student-tests/test_users.py b/student-tests/test_users.py new file mode 100644 index 0000000..eda9eb6 --- /dev/null +++ b/student-tests/test_users.py @@ -0,0 +1,40 @@ +"""Дубликат username и идентификация через X-User-Id""" + +import uuid + +import httpx +import pytest +from helpers import assert_error, unique_username + + +def test_duplicate_username_is_conflict(api: httpx.Client) -> None: + username = unique_username("dup") + first = api.post("/api/v1/users", json={"username": username, "display_name": "A"}) + assert first.status_code == 201 + second = api.post("/api/v1/users", json={"username": username, "display_name": "B"}) + assert_error(second, 409, "conflict") + me = api.get("/api/v1/users/me", headers={"X-User-Id": first.json()["id"]}) + assert me.json()["display_name"] == "A" + + +@pytest.mark.parametrize( + "headers", + [ + {}, + {"X-User-Id": ""}, + {"X-User-Id": "not-a-uuid"}, + {"X-User-Id": str(uuid.uuid4())}, + ], +) +def test_missing_or_unknown_user_is_unauthorized( + api: httpx.Client, headers: dict +) -> None: + assert_error(api.get("/api/v1/users/me", headers=headers), 401, "unauthorized") + assert_error(api.get("/api/v1/chats", headers=headers), 401, "unauthorized") + + +def test_current_user(api: httpx.Client, make_user) -> None: + alice = make_user("alice") + me = api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}) + assert me.status_code == 200 + assert me.json() == alice