feat: перенос 5 лабы логики
This commit is contained in:
+147
@@ -0,0 +1,147 @@
|
||||
import asyncio
|
||||
import socket
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
|
||||
from application import api_endpoints, health_endpoints
|
||||
from application.api.handlers import register_exception_handlers
|
||||
from application.api.middlewares import RequestContextMiddleware
|
||||
from config import (
|
||||
APP_ENV,
|
||||
APP_HOST,
|
||||
APP_KEEPALIVE_TIMEOUT_SEC,
|
||||
APP_PORT,
|
||||
APP_REVISION,
|
||||
DB_STARTUP_TIMEOUT_SEC,
|
||||
IMAGE_INSPECT_WORKERS,
|
||||
INSTANCE_ID,
|
||||
INSTANCE_ID_FILE,
|
||||
LOGGER,
|
||||
MAX_IMAGE_PIXELS,
|
||||
PASSWORD_HASH_WORKERS,
|
||||
SESSION_TTL_SECONDS,
|
||||
SHUTDOWN_DRAIN_SEC,
|
||||
SHUTDOWN_TIMEOUT_SEC,
|
||||
)
|
||||
from infrastructure import (
|
||||
ImageInspector,
|
||||
PasswordHasher,
|
||||
cache_manager,
|
||||
database_pool_manager,
|
||||
storage_manager,
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
"""
|
||||
uvicorn открывает порт только после startup: реплика без БД или со старой
|
||||
схемой не принимает соединений, и LB отправляет запросы другим репликам.
|
||||
|
||||
S3 на старт не влияет: реплика стартует и обслуживает сообщения,
|
||||
а readiness остаётся 503, пока bucket недоступен.
|
||||
"""
|
||||
await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC)
|
||||
await database_pool_manager.check_migrations()
|
||||
cache_manager.create_client()
|
||||
await storage_manager.create_client()
|
||||
if await storage_manager.check():
|
||||
LOGGER.info("Bucket S3 доступен")
|
||||
else:
|
||||
LOGGER.warning("Bucket S3 недоступен: вложения отвечают 503")
|
||||
password_hasher = PasswordHasher(PASSWORD_HASH_WORKERS)
|
||||
image_inspector = ImageInspector(IMAGE_INSPECT_WORKERS, MAX_IMAGE_PIXELS)
|
||||
app.state.database = database_pool_manager
|
||||
app.state.cache = cache_manager
|
||||
app.state.storage = storage_manager
|
||||
app.state.password_hasher = password_hasher
|
||||
app.state.image_inspector = image_inspector
|
||||
INSTANCE_ID_FILE.write_text(INSTANCE_ID)
|
||||
app.state.is_ready = True
|
||||
LOGGER.info(
|
||||
f"Application started, env={APP_ENV}, revision={APP_REVISION}, "
|
||||
f"instance={INSTANCE_ID}, session ttl={SESSION_TTL_SECONDS} s"
|
||||
)
|
||||
yield
|
||||
app.state.is_ready = False
|
||||
await cache_manager.close()
|
||||
await storage_manager.close()
|
||||
await database_pool_manager.close()
|
||||
password_hasher.close()
|
||||
image_inspector.close()
|
||||
LOGGER.info(f"Application stopped, instance={INSTANCE_ID}, connections closed")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="mtuci-labs-messanger",
|
||||
description="мессенджер-конкурент-максу",
|
||||
version="1.5.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
register_exception_handlers(app)
|
||||
|
||||
app.include_router(health_endpoints)
|
||||
app.include_router(api_endpoints)
|
||||
|
||||
|
||||
class DrainingServer(uvicorn.Server):
|
||||
"""
|
||||
SIGTERM: сначала drain, затем штатный graceful shutdown uvicorn.
|
||||
"""
|
||||
|
||||
def __init__(self, config: uvicorn.Config, drain_seconds: float) -> None:
|
||||
super().__init__(config)
|
||||
self._drain_seconds = drain_seconds
|
||||
|
||||
async def shutdown(self, sockets: list[socket.socket] | None = None) -> None:
|
||||
for server in getattr(self, "servers", []):
|
||||
server.close()
|
||||
app.state.is_ready = False
|
||||
app.state.is_draining = True
|
||||
LOGGER.info(
|
||||
f"SIGTERM: drain {self._drain_seconds} с, instance={INSTANCE_ID}: "
|
||||
"порт закрыт, keep-alive соединения закрываются после ответа"
|
||||
)
|
||||
await asyncio.sleep(self._drain_seconds)
|
||||
await super().shutdown(sockets)
|
||||
|
||||
|
||||
def main(
|
||||
host: str,
|
||||
port: int,
|
||||
shutdown_timeout: int,
|
||||
keepalive_timeout: int,
|
||||
drain_seconds: float,
|
||||
) -> None:
|
||||
"""
|
||||
Функция для запуска api.
|
||||
|
||||
SIGTERM: drain_seconds без приёма новых соединений, затем uvicorn ждёт
|
||||
текущих запросов не дольше shutdown_timeout, и lifespan закрывает пулы.
|
||||
Сумма меньше stop_grace_period контейнера (10 с).
|
||||
"""
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
host=host,
|
||||
port=port,
|
||||
timeout_graceful_shutdown=shutdown_timeout,
|
||||
timeout_keep_alive=keepalive_timeout,
|
||||
access_log=False,
|
||||
server_header=False,
|
||||
)
|
||||
DrainingServer(config, drain_seconds).run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(
|
||||
host=APP_HOST,
|
||||
port=APP_PORT,
|
||||
shutdown_timeout=SHUTDOWN_TIMEOUT_SEC,
|
||||
keepalive_timeout=APP_KEEPALIVE_TIMEOUT_SEC,
|
||||
drain_seconds=SHUTDOWN_DRAIN_SEC,
|
||||
)
|
||||
Reference in New Issue
Block a user