| 1 | """Base adapter interface + graceful-degradation wrapper.""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import asyncio |
| 5 | import time |
| 6 | from abc import ABC, abstractmethod |
| 7 | from typing import Any |
| 8 | |
| 9 | from models import EngineStatus, Hit |
| 10 | |
| 11 | TIMEOUT_S: float = 6.0 |
| 12 | |
| 13 | |
| 14 | class BaseAdapter(ABC): |
| 15 | engine: str = "" |
| 16 | authority_tier: str = "older-note" |
| 17 | |
| 18 | @abstractmethod |
| 19 | async def _fetch(self, query: str, k: int) -> list[Hit]: |
| 20 | """Override in subclass - may raise freely.""" |
| 21 | ... |
| 22 | |
| 23 | async def query(self, query: str, k: int = 12) -> tuple[list[Hit], EngineStatus]: |
| 24 | """Public entry point - always returns (hits, status), never raises.""" |
| 25 | t0 = time.monotonic() |
| 26 | try: |
| 27 | hits = await asyncio.wait_for(self._fetch(query, k), timeout=TIMEOUT_S) |
| 28 | for h in hits: |
| 29 | if h.authority_tier == "older-note" and self.authority_tier != "older-note": |
| 30 | h.authority_tier = self.authority_tier |
| 31 | ms = int((time.monotonic() - t0) * 1000) |
| 32 | return hits, EngineStatus(engine=self.engine, status="up", ms=ms) |
| 33 | except Exception: |
| 34 | ms = int((time.monotonic() - t0) * 1000) |
| 35 | return [], EngineStatus(engine=self.engine, status="down", ms=ms) |