Добавить приватное хранилище вложений и отдачу файла через API.

Байты лежат в SeaweedFS, метаданные в Postgres. Другая реплика скачивает тот же объект, потому что локальный диск API не является источником файла.
This commit is contained in:
2026-11-09 00:25:36 +03:00
parent d208a87ae8
commit 00445bc41b
19 changed files with 889 additions and 52 deletions
+40 -25
View File
@@ -1,11 +1,10 @@
import logging
import time
import uuid
from typing import Callable
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.datastructures import MutableHeaders
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
@@ -13,36 +12,52 @@ from app.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
def _stamp(response: Response, request_id: str) -> Response:
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
class RequestContextMiddleware:
"""Pure ASGI middleware so upload handlers can read the body stream themselves."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
class RequestContextMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: Callable) -> Response:
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
if request.app.state.shutting_down and request.url.path not in ("/health/live", "/health/ready"):
return _stamp(error_response(503, "service is shutting down", request_id), request_id)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
headers = {key.decode("latin1").lower(): value.decode("latin1") for key, value in scope.get("headers", [])}
request_id = headers.get("x-request-id") or str(uuid.uuid4())
raw_state = scope.get("state")
if not isinstance(raw_state, dict):
raw_state = {}
scope["state"] = raw_state
raw_state["request_id"] = request_id
path = scope.get("path", "")
started = time.perf_counter()
async def send_wrapper(message: Message) -> None:
if message["type"] == "http.response.start":
response_headers = MutableHeaders(scope=message)
response_headers["X-Request-Id"] = request_id
response_headers["X-Instance-Id"] = INSTANCE_ID
await send(message)
app = scope.get("app")
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
if shutting_down and path not in ("/health/live", "/health/ready"):
response: Response = error_response(503, "service is shutting down", request_id)
await response(scope, receive, send_wrapper)
return
try:
response = await call_next(request)
await self.app(scope, receive, send_wrapper)
except AppError as exc:
return _stamp(from_app_error(exc, request_id), request_id)
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
except Exception:
logger.exception("request_id=%s unhandled error path=%s", request_id, request.url.path)
return _stamp(error_response(500, "internal error", request_id), request_id)
logger.exception("request_id=%s unhandled error path=%s", request_id, path)
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
return
elapsed_ms = (time.perf_counter() - started) * 1000
_stamp(response, request_id)
logger.info(
"request_id=%s method=%s path=%s status=%s duration_ms=%.2f",
"request_id=%s method=%s path=%s duration_ms=%.2f",
request_id,
request.method,
request.url.path,
response.status_code,
scope.get("method", ""),
path,
elapsed_ms,
)
return response