diff --git a/openspec/changes/add-lab3-load-balanced-replicas/tasks.md b/openspec/changes/add-lab3-load-balanced-replicas/tasks.md index 934576d0..1469c856 100644 --- a/openspec/changes/add-lab3-load-balanced-replicas/tasks.md +++ b/openspec/changes/add-lab3-load-balanced-replicas/tasks.md @@ -6,8 +6,8 @@ ## 2. Идентификатор реплики (платформа) -- [ ] 2.1 `PlatformSettings.instance_id` по умолчанию из `socket.gethostname()`; заголовок `X-Instance-Id` в конвейере и в обработчике `500` -- [ ] 2.2 Версия приложения 1.3.0; проверка группы: тесты — `X-Instance-Id` на `200`, `204`, `401`, `404`, `405`, `413`, `500`, одно значение на процесс +- [x] 2.1 `PlatformSettings.instance_id` по умолчанию из `socket.gethostname()`; заголовок `X-Instance-Id` в конвейере и в обработчике `500` +- [x] 2.2 Версия приложения 1.3.0; проверка группы: тесты — `X-Instance-Id` на `200`, `204`, `401`, `404`, `405`, `413`, `500`, одно значение на процесс ## 3. Схема diff --git a/src/messenger/main.py b/src/messenger/main.py index b9b75546..d198d943 100644 --- a/src/messenger/main.py +++ b/src/messenger/main.py @@ -80,7 +80,7 @@ def create_app( app = FastAPI( title="MTUSI Messenger", - version="1.2.0", + version="1.3.0", lifespan=lifespan, docs_url="/docs" if transport.docs else None, redoc_url=None, @@ -92,8 +92,9 @@ def create_app( max_bytes=transport.max_body_bytes, timeout=transport.request_timeout_seconds, guard=guard, + instance=platform.instance_id, ) - errors.install(app, logger, ERROR_CODES, challenge_for) + errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id) app.include_router(health.router) app.include_router(users_router) app.include_router(sessions_router) diff --git a/src/messenger/shared/config.py b/src/messenger/shared/config.py index 0d2eb631..8eff8736 100644 --- a/src/messenger/shared/config.py +++ b/src/messenger/shared/config.py @@ -1,4 +1,5 @@ import os +import socket from pathlib import Path from typing import Any @@ -39,7 +40,7 @@ class Settings(BaseSettings): class PlatformSettings(Settings): log_level: str = "INFO" - instance_id: str = "" + instance_id: str = Field(default_factory=socket.gethostname, min_length=1) event_queue_max: int = Field(default=10_000, ge=16) database_url: SecretStr db_pool_max_size: int = Field(default=8, ge=1, le=50) diff --git a/src/messenger/shared/entrypoints/errors.py b/src/messenger/shared/entrypoints/errors.py index b53994f7..e32c6e72 100644 --- a/src/messenger/shared/entrypoints/errors.py +++ b/src/messenger/shared/entrypoints/errors.py @@ -10,6 +10,7 @@ from messenger.shared.domain.errors import DomainError from messenger.shared.entrypoints.schemas import ErrorEnvelope REQUEST_ID_HEADER = "X-Request-Id" +INSTANCE_ID_HEADER = "X-Instance-Id" type ErrorCodes = Mapping[type[DomainError], tuple[str, int]] type Challenge = Callable[[str], str] @@ -56,10 +57,12 @@ def route_of(request: Request) -> str: return getattr(route, "path", request.url.path) -def install(app: FastAPI, logger: Logger, codes: ErrorCodes, challenge: Challenge) -> None: +def install( + app: FastAPI, logger: Logger, codes: ErrorCodes, challenge: Challenge, instance: str +) -> None: def error_response(request: Request, code: str, detail: str, http_status: int) -> Response: request_id = getattr(request.state, "request_id", "") or "unknown" - headers = {REQUEST_ID_HEADER: request_id} + headers = {REQUEST_ID_HEADER: request_id, INSTANCE_ID_HEADER: instance} if http_status == status.HTTP_401_UNAUTHORIZED: headers["WWW-Authenticate"] = challenge(request.url.path) return Response( diff --git a/src/messenger/shared/entrypoints/pipeline.py b/src/messenger/shared/entrypoints/pipeline.py index 566c8182..e88c995d 100644 --- a/src/messenger/shared/entrypoints/pipeline.py +++ b/src/messenger/shared/entrypoints/pipeline.py @@ -8,7 +8,7 @@ from starlette.types import ASGIApp, Message, Receive, Scope, Send from messenger.shared.application.errors import Unavailable from messenger.shared.application.ports import Logger -from messenger.shared.entrypoints.errors import MESSAGES, REQUEST_ID_HEADER +from messenger.shared.entrypoints.errors import INSTANCE_ID_HEADER, MESSAGES, REQUEST_ID_HEADER from messenger.shared.entrypoints.schemas import ErrorEnvelope type Headers = tuple[tuple[str, str], ...] @@ -24,6 +24,8 @@ class Rejection: type Guard = Callable[[Scope], Awaitable[Rejection | None]] HEADER_BYTES = REQUEST_ID_HEADER.lower().encode() +INSTANCE_BYTES = INSTANCE_ID_HEADER.lower().encode() +STAMPED = frozenset({HEADER_BYTES, INSTANCE_BYTES}) MAX_REQUEST_ID = 200 @@ -54,7 +56,7 @@ async def send_error( class RequestPipeline: - __slots__ = ("_app", "_guard", "_logger", "_max_bytes", "_timeout") + __slots__ = ("_app", "_guard", "_instance", "_logger", "_max_bytes", "_timeout") def __init__( self, @@ -63,12 +65,14 @@ class RequestPipeline: max_bytes: int, timeout: float, guard: Guard, + instance: str, ) -> None: self._app = app self._logger = logger self._max_bytes = max_bytes self._timeout = timeout self._guard = guard + self._instance = instance.encode() async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": @@ -91,9 +95,10 @@ class RequestPipeline: headers = [ (key, value) for key, value in message.get("headers", []) - if key.lower() != HEADER_BYTES + if key.lower() not in STAMPED ] headers.append((HEADER_BYTES, request_id.encode("latin-1", "replace"))) + headers.append((INSTANCE_BYTES, self._instance)) message = {**message, "headers": headers} await send(message) diff --git a/student-tests/api/test_instance.py b/student-tests/api/test_instance.py new file mode 100644 index 00000000..b76fe4fb --- /dev/null +++ b/student-tests/api/test_instance.py @@ -0,0 +1,64 @@ +import socket +from uuid import uuid4 + +from httpx import ASGITransport, AsyncClient, Response + +from conftest import actor, register, running_app, split_settings +from messenger.main import create_app +from messenger.shared.config import PlatformSettings + +REPLICA = "replica-7f3a" + + +def stamped(response: Response) -> bool: + return bool(response.headers.get("X-Request-Id")) and ( + response.headers.get("X-Instance-Id") == REPLICA + ) + + +async def test_every_response_names_the_replica() -> None: + async with running_app(instance_id=REPLICA) as http: + alice = await register(http, "alice") + probes = [ + await http.get("/health/live"), + await http.get("/health/ready"), + await http.get("/api/v1/users/me", headers=actor(alice)), + await http.get("/api/v1/users/me"), + await http.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)), + await http.get("/nothing-here"), + await http.delete("/health/live"), + await http.post("/api/v1/users", json={"username": "x"}), + await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)), + ] + assert [probe.status_code for probe in probes] == [200, 200, 200, 401, 404, 404, 404, 400, 204] + assert all(stamped(probe) for probe in probes) + + +async def test_rejected_body_names_the_replica() -> None: + async with running_app(instance_id=REPLICA, max_body_bytes=4096) as http: + response = await http.post("/api/v1/users", content=b"x" * 5000) + assert response.status_code == 413 + assert stamped(response) + + +async def test_unhandled_error_names_the_replica() -> None: + app = create_app(**split_settings(instance_id=REPLICA)) + + async def boom() -> None: + raise RuntimeError("сбой") + + app.add_api_route("/health/boom", boom) + transport = ASGITransport(app=app, raise_app_exceptions=False) + async with ( + app.router.lifespan_context(app), + AsyncClient(transport=transport, base_url="http://testserver") as http, + ): + response = await http.get("/health/boom") + assert response.status_code == 500 + assert response.json()["error"]["code"] == "internal_error" + assert stamped(response) + + +def test_replica_defaults_to_container_hostname() -> None: + settings = PlatformSettings.model_validate({"database_url": "postgresql://u@h/d"}) + assert settings.instance_id == socket.gethostname() diff --git a/student-tests/conftest.py b/student-tests/conftest.py index 35113048..17f27645 100644 --- a/student-tests/conftest.py +++ b/student-tests/conftest.py @@ -75,7 +75,7 @@ def answering(name: str, *probe: str) -> bool: @pytest.fixture(scope="session") def valkey() -> Iterator[dict[str, str]]: - name = f"mtusi-lab2-test-valkey-{uuid4().hex[:8]}" + name = f"mtusi-lab3-test-valkey-{uuid4().hex[:8]}" container(name, "-p", "127.0.0.1::6379", image(VALKEY_IMAGE)) try: deadline = time.monotonic() + STARTUP_SECONDS @@ -89,7 +89,7 @@ def valkey() -> Iterator[dict[str, str]]: @pytest.fixture(scope="session") def database() -> Iterator[str]: - name = f"mtusi-lab2-test-{uuid4().hex[:8]}" + name = f"mtusi-lab3-test-{uuid4().hex[:8]}" tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"] environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"] container(name, *environment, "-p", "127.0.0.1::5432", image(POSTGRES_IMAGE), *tuning)