import asyncio import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager, suppress from datetime import UTC, datetime, timedelta from fastapi import FastAPI, HTTPException, Path, Query from app.config import load_settings from app.conversion import CZK, BaseCurrencyNotAvailable, rebase_rates from app.models import RateSheetResponse from app.refresh import refresh_forever from app.sources import SOURCES from app.storage import read_sheet logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") # A single missed refresh is normal, for example a short outage on the bank side. # Three missed refreshes in a row mean the consumer should know about it. STALE_AFTER_REFRESH_INTERVALS = 3 settings = load_settings() @asynccontextmanager async def lifespan(_: FastAPI) -> AsyncIterator[None]: # Runs in the background, so the health check answers while the first refresh is in progress. task = asyncio.create_task(refresh_forever(settings.data_dir, settings.refresh_interval_minutes)) yield task.cancel() with suppress(asyncio.CancelledError): await task app = FastAPI( title=settings.app_name, version=settings.app_version, root_path=settings.root_path, lifespan=lifespan, ) @app.get("/health") def health() -> dict[str, str]: return {"status": "ok"} @app.get("/version") def version() -> dict[str, str]: return { "app": settings.app_name, "version": settings.app_version, "language": "python", "root_path": settings.root_path, } # Must stay the last route, otherwise it would capture the static paths above. @app.get( "/{source_id}", response_model=RateSheetResponse, responses={ 404: {"description": "Unknown source, or the source does not publish the base currency"}, 503: {"description": "The source has no stored data yet"}, }, ) def get_rates( source_id: str = Path(description=f"Source identifier: {', '.join(SOURCES)}"), base: str = Query( default=CZK, pattern=r"^[A-Z]{3}$", description="Currency to express the prices in. Other than CZK is computed through CZK.", ), ) -> RateSheetResponse: if source_id not in SOURCES: raise HTTPException(status_code=404, detail=f"Unknown source. Available: {', '.join(SOURCES)}") sheet = read_sheet(settings.data_dir, source_id) if sheet is None: raise HTTPException(status_code=503, detail="No data has been downloaded for this source yet") try: rates = rebase_rates(sheet.rates, base) except BaseCurrencyNotAvailable as error: raise HTTPException( status_code=404, detail=f"Source {source_id} does not publish base currency {base}", ) from error max_age = timedelta(minutes=settings.refresh_interval_minutes * STALE_AFTER_REFRESH_INTERVALS) return RateSheetResponse( **sheet.model_dump(exclude={"rates"}), rates=rates, base=base, stale=datetime.now(UTC) - sheet.fetched_at > max_age, )