Implement lab4 attachments on RustFS for grade 4.
Carry over lab3 HA stack and add private S3 storage, Attachment API, orphan compensation/reaper, own tests, and evidence for smoke/persistence/failover.
This commit is contained in:
+125
@@ -0,0 +1,125 @@
|
||||
"""Точка входа HTTP-приложения lab4."""
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api import router
|
||||
from app.config import settings
|
||||
from app.db import Database
|
||||
from app.errors import AppError, error_body
|
||||
from app.reconcile import OrphanReaper
|
||||
from app.s3store import S3Store
|
||||
from app.sessions import SessionStore
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
db = Database()
|
||||
sessions = SessionStore()
|
||||
s3 = S3Store()
|
||||
reaper: OrphanReaper | None = None
|
||||
INSTANCE_ID = settings.instance_id
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
global reaper
|
||||
logger.info("server starting; instance_id=%s", INSTANCE_ID)
|
||||
db.open()
|
||||
sessions.open()
|
||||
s3.open()
|
||||
reaper = OrphanReaper(db, s3, interval_seconds=300)
|
||||
reaper.start()
|
||||
_app.state.db = db
|
||||
_app.state.sessions = sessions
|
||||
_app.state.s3 = s3
|
||||
logger.info("dependencies ready")
|
||||
yield
|
||||
if reaper is not None:
|
||||
reaper.stop()
|
||||
db.begin_shutdown()
|
||||
sessions.close()
|
||||
s3.close()
|
||||
db.close()
|
||||
logger.info("SIGTERM/shutdown: stop accepting, ready=false")
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger lab4", lifespan=lifespan)
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
app.state.s3 = s3
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_headers_middleware(request: Request, call_next):
|
||||
"""Чистый ASGI middleware — не буферизует тело (важно для upload ≤10 MiB)."""
|
||||
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
logger.info(
|
||||
"%s %s -> %s request_id=%s instance=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
response.status_code,
|
||||
request_id,
|
||||
INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
async def app_error_handler(request: Request, exc: AppError):
|
||||
request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4())
|
||||
headers = {"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
|
||||
headers.update(exc.headers)
|
||||
return JSONResponse(
|
||||
status_code=exc.status,
|
||||
content=error_body(exc.code, exc.message, request_id),
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_handler(request: Request, _exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4())
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=error_body("invalid_request", "Неверный запрос", request_id),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def internal_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4())
|
||||
logger.exception("unhandled error request_id=%s", request_id)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=error_body("internal_error", "Внутренняя ошибка", request_id),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID},
|
||||
)
|
||||
|
||||
|
||||
def run() -> None:
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
log_level="info",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
Reference in New Issue
Block a user