import asyncio import logging from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from . import store from .api import router from .config import get_settings from .db import migrate, session log = logging.getLogger("solar") PURGE_INTERVAL_SECONDS = 6 * 3600 def purge_once() -> None: with session() as conn: deleted = store.purge(conn, get_settings().retention_days) if deleted: log.info("Retention: purged %d readings", deleted) async def purge_loop() -> None: while True: try: await asyncio.to_thread(purge_once) except Exception: log.exception("Retention purge failed") await asyncio.sleep(PURGE_INTERVAL_SECONDS) @asynccontextmanager async def lifespan(app: FastAPI): migrate() task = asyncio.create_task(purge_loop()) yield task.cancel() app = FastAPI( title="Refusol Solar Monitor", lifespan=lifespan, docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json", ) app.add_middleware( CORSMiddleware, allow_origins=get_settings().cors_origins, allow_methods=["*"], allow_headers=["*"], ) app.include_router(router)