forked from mtusi2026/mtusi2026lab3
Name the serving replica in every response
The platform settings default the instance id to the container hostname, computed once per process, so every gunicorn worker of a replica reports the same value and it matches docker ps. The request pipeline stamps X-Instance-Id next to X-Request-Id on every response it sends, and the unhandled error handler adds it itself, because the 500 answer is produced outside the pipeline. Own tests cover 200, 204, 400, 401, 404, the hidden 405, 413 and 500 with a fixed instance id, and the hostname default. The application version follows the contract version 1.3.0. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9db7a24362
commit
bf0f0b4c07
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user