"""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.status import RefreshAttempt, RefreshHistory 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 _download(client: httpx.AsyncClient, source: Source) -> str: if source.fetch is not None: return await source.fetch(client) 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() return response.text async def refresh_source(client: httpx.AsyncClient, source: Source, data_dir: Path) -> None: parsed = source.parse(await _download(client, source)) 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)) def _describe_error(error: Exception) -> str: """Only the first line, the full detail with a traceback goes to the log.""" message = str(error).splitlines()[0] if str(error) else "" return f"{type(error).__name__}: {message}" async def refresh_all( client: httpx.AsyncClient, data_dir: Path, history: RefreshHistory, ) -> None: """A failed source keeps its last good file and does not affect the others.""" for source in SOURCES.values(): error = None try: await refresh_source(client, source, data_dir) except Exception as caught: logger.exception("Refresh of source %s failed, keeping the last stored data", source.id) error = _describe_error(caught) history[source.id] = RefreshAttempt(attempted_at=datetime.now(UTC), error=error) async def refresh_forever( data_dir: Path, interval_minutes: int, history: RefreshHistory, ) -> 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, history) await asyncio.sleep(interval_minutes * 60)