"""Downloads the sources and keeps the stored JSON files up to date.""" import asyncio import logging from datetime import UTC, datetime from pathlib import Path import httpx from app.models import RateSheet from app.sources import SOURCES from app.sources.base import Source from app.storage import write_sheet logger = logging.getLogger(__name__) # Identifies the service honestly, so a bank can recognise it and decide how to treat it. USER_AGENT = "exchange-rates-service/1.0" REQUEST_TIMEOUT_SECONDS = 30.0 async def refresh_source(client: httpx.AsyncClient, source: Source, data_dir: Path) -> None: if source.request_json is None: response = await client.get(source.url) else: response = await client.post(source.url, json=source.request_json) response.raise_for_status() parsed = source.parse(response.text) sheet = RateSheet( source=source.id, source_name=source.name, source_url=source.url, fetched_at=datetime.now(UTC), valid_date=parsed.valid_date, rates=sorted(parsed.rates, key=lambda rate: rate.currency), ) write_sheet(data_dir, sheet) logger.info("Refreshed source %s with %d rates", source.id, len(sheet.rates)) async def refresh_all(client: httpx.AsyncClient, data_dir: Path) -> None: """A failed source keeps its last good file and does not affect the others.""" for source in SOURCES.values(): try: await refresh_source(client, source, data_dir) except Exception: logger.exception("Refresh of source %s failed, keeping the last stored data", source.id) async def refresh_forever(data_dir: Path, interval_minutes: int) -> None: async with httpx.AsyncClient( headers={"User-Agent": USER_AGENT}, timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=True, ) as client: while True: await refresh_all(client, data_dir) await asyncio.sleep(interval_minutes * 60)