feat: carry lab 2 over and add X-Instance-Id and idempotency keys
- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec change instance-id-idempotency) - rename the compose project to mtusi-lab3 and the image to :lab3 - add X-Instance-Id to every response and instance_id to every log record ([app] instance_id, hostname by default) - require Idempotency-Key on POST messages: keys table in Postgres, key and message in one transaction, replay returns the same 201, another body gets 409, TTL from [idempotency] ttl_seconds - send the key from student-tests, k6 scenarios and the skill driver; add idempotency, X-Instance-Id, key race and fault tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+80
@@ -0,0 +1,80 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
|
||||
from src.api import errors
|
||||
from src.api.middlewares import RequestContextMiddleware
|
||||
from src.api.routers import health_router, v1_router
|
||||
from src.config import settings
|
||||
from src.infra.cache.instance import cache
|
||||
from src.infra.db.session import engine
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.password import prepare_dummy_hash
|
||||
from src.schemas.enums import RunModeEnum
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="startup")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||
database = settings.database
|
||||
# engine и кэш подключаются лениво: без Postgres сервис стартует, а
|
||||
# /health/ready отвечает 503; без Valkey запросы идут в Postgres
|
||||
if not database.password.get_secret_value():
|
||||
logger.warning("Database password is empty")
|
||||
if not settings.cache.password.get_secret_value():
|
||||
logger.warning("Cache password is empty")
|
||||
# ~30 мс CPU при старте: время ответа на вход с неизвестным username
|
||||
# ровное с первого запроса
|
||||
await prepare_dummy_hash()
|
||||
logger.info(
|
||||
"Started API",
|
||||
host=settings.app.host,
|
||||
port=settings.app.port,
|
||||
run_mode=settings.app.run_mode,
|
||||
database_host=database.host,
|
||||
database_port=database.port,
|
||||
database_name=database.name,
|
||||
cache_host=settings.cache.host,
|
||||
cache_port=settings.cache.port,
|
||||
)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await engine.dispose()
|
||||
await cache.aclose()
|
||||
logger.info("Stopped API")
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
# версия — info.version контракта (contracts/openapi.json)
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.3.0", lifespan=lifespan)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
errors.register(app)
|
||||
app.include_router(health_router)
|
||||
app.include_router(v1_router)
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
reload = settings.app.run_mode == RunModeEnum.CONSOLE
|
||||
uvicorn.run(
|
||||
"src.main:app",
|
||||
host=settings.app.host,
|
||||
port=settings.app.port,
|
||||
reload=reload,
|
||||
# без reload uvicorn пишет warning на reload_dirs при каждом старте
|
||||
reload_dirs=["src"] if reload else None,
|
||||
# один процесс: реплики — лаба 3, пул соединений рассчитан на один
|
||||
# процесс
|
||||
workers=1,
|
||||
timeout_graceful_shutdown=settings.app.graceful_shutdown_seconds,
|
||||
# логи uvicorn идут через наш JSON-форматтер (src/infra/logger.py)
|
||||
log_config=None,
|
||||
access_log=False,
|
||||
)
|
||||
Reference in New Issue
Block a user