summaryrefslogtreecommitdiff
path: root/app/main.py
blob: f1c556ad428ae1bfc262febaea9fc218d360e71d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import time
from contextlib import asynccontextmanager

from fastapi import FastAPI
from sqlalchemy import text

from app.routes import router as api_router
from app.utils.cors import setup_cors
from app.utils.create_tables import init_db
from app.utils.db import engine
from app.utils.logger_cfg import logger

app_start_time = time.perf_counter()
logger.debug("App start timestamp recorded")


@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("Application startup initiated")

    try:
        async with engine.begin() as conn:
            logger.debug("Executing test query: SELECT 1")
            db_status = await conn.scalar(text("SELECT 1"))
            logger.info("Database connection successful: {}", db_status)

        logger.debug("Starting database table initialization")
        await init_db()
        logger.info("Database initialization completed")

    except Exception:
        logger.exception("Database startup failed")
        raise

    elapsed = time.perf_counter() - app_start_time
    app.state.startup_elapsed = elapsed
    app.state.startup_completed = True

    logger.success(
        "Application startup completed in {:.2f} ms ({:.6f} s)",
        elapsed * 1000,
        elapsed,
    )

    yield

    logger.info("Application shutdown initiated")
    try:
        await engine.dispose()
        logger.info("Database engine disposed successfully")
    except Exception:
        logger.exception("Error during shutdown")


app = FastAPI(lifespan=lifespan)
setup_cors(app)
app.include_router(api_router, prefix="/api")