41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
"""Идентификатор API-реплики и заголовок X-Instance-Id."""
|
|
|
|
import os
|
|
from uuid import uuid4
|
|
|
|
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
|
from starlette.requests import Request
|
|
from starlette.responses import Response
|
|
|
|
INSTANCE_ID_HEADER = "X-Instance-Id"
|
|
|
|
|
|
def resolve_instance_id(configured: str | None) -> str:
|
|
"""Выбирает INSTANCE_ID, HOSTNAME или UUID при старте приложения."""
|
|
if configured and configured.strip():
|
|
return configured.strip()
|
|
|
|
hostname = os.getenv("HOSTNAME", "").strip()
|
|
if hostname:
|
|
return hostname
|
|
|
|
return str(uuid4())
|
|
|
|
|
|
class InstanceIdMiddleware(BaseHTTPMiddleware):
|
|
"""Добавляет сохранённый идентификатор реплики в ответ."""
|
|
|
|
def __init__(self, app, instance_id: str) -> None:
|
|
super().__init__(app)
|
|
self.instance_id = instance_id
|
|
|
|
async def dispatch(
|
|
self,
|
|
request: Request,
|
|
call_next: RequestResponseEndpoint,
|
|
) -> Response:
|
|
response = await call_next(request)
|
|
response.headers[INSTANCE_ID_HEADER] = self.instance_id
|
|
|
|
return response
|