forked from mtusi2026/mtusi2026lab3
feat: HAProxy и N API-реплик, X-Instance-Id, общая идемпотентность, drain при SIGTERM
- compose: один масштабируемый сервис api (deploy.replicas=2, без ports и container_name), HAProxy 3.2 LTS по digest — единственная точка входа (127.0.0.1), разовый migrate до старта реплик, CPU/RAM-лимиты у всех сервисов, каждому сервису только его secrets. - HAProxy: server-template + Docker DNS (re-resolve 1 с), активная проверка GET /health/ready каждую 1 с (fall 2 / rise 2), без backup-серверов, retry только conn-failure, ошибки самого LB — в формате контракта с X-Request-Id. - API: X-Instance-Id = hostname контейнера на каждом ответе (и на 500/503); Idempotency-Key обязателен; ключ, сообщение и результат пишутся в ОДНОЙ транзакции (миграция 0002), конкурентный повтор ждёт уникальный индекс; другой body — 409, посторонний — всегда 404; attachment_ids=[] равен отсутствию поля; дубли ключей JSON и тело у POST /auth/sessions — 400. - SIGTERM: readiness 503 + DRAIN_SECONDS=3 обслуживания, затем graceful stop. - scripts: stop-one.sh (+ .cmd для Windows), restore-api.sh, restart.sh перезапускает и LB, lbctl.py — состояние бэкендов HAProxy -> контейнеры. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4f6cfda37a
commit
3f12698676
+65
-12
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
@@ -19,7 +21,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen
|
||||
from . import authhdr, cursor, docs, passwords, repo, validation
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .sessions import SessionStore, build_store
|
||||
from .timefmt import rfc3339
|
||||
|
||||
@@ -56,10 +58,12 @@ async def http_exception_handler(request: Request, exc: Exception) -> JSONRespon
|
||||
# Middleware (pure ASGI, so it also covers 404/405 and unexpected exceptions)
|
||||
# --------------------------------------------------------------------------
|
||||
class RequestContextMiddleware:
|
||||
"""Assigns X-Request-Id to every response, writes one access-log line, turns crashes into 500."""
|
||||
"""Adds X-Request-Id and X-Instance-Id to EVERY response (errors, health and crash 500/503
|
||||
included), writes one access-log line, turns crashes into 500."""
|
||||
|
||||
def __init__(self, app: ASGIApp):
|
||||
def __init__(self, app: ASGIApp, instance_id: str):
|
||||
self.app = app
|
||||
self.instance_id = instance_id.encode("ascii")
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
@@ -77,8 +81,10 @@ class RequestContextMiddleware:
|
||||
if message["type"] == "http.response.start":
|
||||
started = True
|
||||
status = message["status"]
|
||||
headers = [(k, v) for k, v in message.get("headers", []) if k.lower() != b"x-request-id"]
|
||||
headers = [(k, v) for k, v in message.get("headers", [])
|
||||
if k.lower() not in (b"x-request-id", b"x-instance-id")]
|
||||
headers.append((b"x-request-id", request_id.encode("latin-1")))
|
||||
headers.append((b"x-instance-id", self.instance_id))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
@@ -90,20 +96,21 @@ class RequestContextMiddleware:
|
||||
if not started:
|
||||
status = 503
|
||||
response = error_response(request_id, 503, "unavailable", "Сервер завершает работу")
|
||||
await response(scope, receive, send)
|
||||
await response(scope, receive, send_with_id)
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("unhandled_error", extra={"fields": {"request_id": request_id}})
|
||||
if not started:
|
||||
status = 500
|
||||
response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
await response(scope, receive, send)
|
||||
await response(scope, receive, send_with_id)
|
||||
finally:
|
||||
access_log.info("request", extra={"fields": {
|
||||
"request_id": request_id,
|
||||
"method": scope["method"],
|
||||
"path": scope["path"], # ids only; query (cursor) and bodies are never logged
|
||||
"status": status,
|
||||
"instance_id": self.instance_id.decode("ascii"),
|
||||
"duration_ms": round((time.perf_counter() - begin) * 1000, 3),
|
||||
}})
|
||||
|
||||
@@ -166,6 +173,27 @@ def page_params(request: Request) -> tuple[int, str | None]:
|
||||
return limit, raw_cursor
|
||||
|
||||
|
||||
async def reject_body(request: Request) -> None:
|
||||
"""POST /auth/sessions takes credentials only from the Basic header; any body is 400."""
|
||||
if request.headers.get("transfer-encoding") or request.headers.get("content-length", "0") != "0":
|
||||
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
|
||||
async for chunk in request.stream():
|
||||
if chunk:
|
||||
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
|
||||
|
||||
|
||||
def idempotency_key(request: Request) -> str:
|
||||
values = request.headers.getlist("idempotency-key")
|
||||
return validation.idempotency_key(values[0] if len(values) == 1 else None)
|
||||
|
||||
|
||||
def request_fingerprint(text: str, attachment_ids: list[str]) -> bytes:
|
||||
"""SHA-256 of the canonical body: key order and an absent attachment_ids vs [] do not matter."""
|
||||
canonical = json.dumps({"attachment_ids": attachment_ids, "text": text},
|
||||
ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).digest()
|
||||
|
||||
|
||||
def ok(body: Any, status: int = 200) -> JSONResponse:
|
||||
return JSONResponse(body, status_code=status)
|
||||
|
||||
@@ -205,6 +233,7 @@ async def register_user(request: Request) -> JSONResponse:
|
||||
async def create_session(request: Request) -> JSONResponse:
|
||||
"""Login: only `Authorization: Basic`; wrong user and wrong password give the same 401."""
|
||||
username, password = authhdr.parse_basic(request.headers.get("authorization"))
|
||||
await reject_body(request)
|
||||
found = await repo.get_credentials(db_of(request), username)
|
||||
user, stored_hash = found if found else (None, None)
|
||||
if not await passwords.verify_password(stored_hash, password) or user is None:
|
||||
@@ -262,13 +291,23 @@ async def create_message(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before the body is read
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before key/body are looked at
|
||||
key = idempotency_key(request)
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"text"})
|
||||
validation.check_fields(data, {"text"}, frozenset({"attachment_ids"}))
|
||||
text = validation.text_field(data, "text", 4000)
|
||||
attachment_ids = validation.attachment_ids_field(data)
|
||||
if attachment_ids:
|
||||
# Lab 3 has no attachments: every referenced ID is unknown (lab 4 semantics: 404).
|
||||
raise NotFound("Вложение не найдено")
|
||||
# sender_id is derived from the session, never taken from the body.
|
||||
message = await repo.add_message(db, user_id, chat_id, text)
|
||||
return ok(message.to_json(), 201)
|
||||
settings = request.app.state.settings
|
||||
result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds)
|
||||
if result.replayed:
|
||||
log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id,
|
||||
"message_id": result.message.id}})
|
||||
return ok(result.message.to_json(), 201)
|
||||
|
||||
|
||||
async def list_messages(request: Request) -> JSONResponse:
|
||||
@@ -288,16 +327,30 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
db = Database(settings)
|
||||
sessions = build_store(settings, db)
|
||||
|
||||
async def purge_loop() -> None:
|
||||
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
|
||||
while True:
|
||||
await asyncio.sleep(600)
|
||||
try:
|
||||
deleted = await repo.purge_idempotency_keys(db, settings.idempotency_ttl_seconds)
|
||||
if deleted:
|
||||
log.info("idempotency_keys_purged", extra={"fields": {"deleted": deleted}})
|
||||
except ApiError:
|
||||
pass # database unavailable right now; next round
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
await db.open()
|
||||
log.info("dependencies_configured", extra={"fields": {
|
||||
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds}})
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds}})
|
||||
purge = asyncio.create_task(purge_loop())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
purge.cancel()
|
||||
await sessions.close()
|
||||
await db.close()
|
||||
|
||||
@@ -324,7 +377,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler},
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
app.add_middleware(RequestContextMiddleware, instance_id=settings.instance_id)
|
||||
app.state.settings = settings
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
|
||||
Reference in New Issue
Block a user