# fabledscryer/core/plugin_index.py """Remote plugin catalog: fetch, parse, and cache the plugin index.yaml.""" from __future__ import annotations import logging import time from typing import Any logger = logging.getLogger(__name__) _CACHE_TTL = 300 # seconds _cache: tuple[dict, float] | None = None # (raw_data, fetched_at monotonic) class CatalogPlugin: """One entry from the remote plugin index.""" __slots__ = ( "name", "version", "description", "author", "min_app_version", "download_url", "checksum_sha256", "repository_url", "homepage", "license", "tags", ) def __init__(self, data: dict[str, Any]) -> None: self.name: str = data.get("name", "") self.version: str = data.get("version", "0.0.0") self.description: str = data.get("description", "") self.author: str = data.get("author", "") self.min_app_version: str | None = data.get("min_app_version") self.download_url: str = data.get("download_url", "") self.checksum_sha256: str = data.get("checksum_sha256", "") self.repository_url: str = data.get("repository_url", "") self.homepage: str = data.get("homepage", "") self.license: str = data.get("license", "") self.tags: list[str] = data.get("tags", []) async def fetch_catalog(index_url: str, force: bool = False) -> list[CatalogPlugin]: """Fetch and parse the remote plugin catalog. Results are cached in-process for _CACHE_TTL seconds. Pass force=True to bypass the cache. On network failure, stale cached data is returned if available; otherwise an empty list is returned. """ global _cache import httpx import yaml now = time.monotonic() if not force and _cache is not None: raw, fetched_at = _cache if now - fetched_at < _CACHE_TTL: return [CatalogPlugin(p) for p in raw.get("plugins", [])] try: async with httpx.AsyncClient(timeout=10) as client: resp = await client.get(index_url) resp.raise_for_status() raw = yaml.safe_load(resp.text) or {} _cache = (raw, now) logger.info( "Plugin catalog fetched from %s: %d plugin(s)", index_url, len(raw.get("plugins", [])), ) return [CatalogPlugin(p) for p in raw.get("plugins", [])] except Exception: logger.exception("Failed to fetch plugin catalog from %s", index_url) if _cache is not None: raw, _ = _cache logger.warning("Returning stale cached catalog") return [CatalogPlugin(p) for p in raw.get("plugins", [])] return [] def clear_catalog_cache() -> None: """Invalidate the in-process catalog cache.""" global _cache _cache = None