"""Optr monitoring SDK (Python 3.10+, standard library only).""" import json from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen from urllib.parse import urlsplit class OptrError(Exception): def __init__(self, message, status=0): super().__init__(message) self.status = status class OptrClient: def __init__(self, base_url="https://optr.dev", timeout=6): url = urlsplit(base_url) local = url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1", "::1") if not url.hostname or (url.scheme != "https" and not local) or url.username or url.password or url.path not in ("", "/") or url.query or url.fragment: raise ValueError("Expected HTTPS origin or local HTTP origin") if not 0 < timeout <= 60: raise ValueError("Invalid timeout") self.base_url = base_url.rstrip("/") self.timeout = timeout def health(self): return self._read("/api/v1/health") def ready(self): return self._read("/api/v1/ready") def _read(self, path): try: req = Request(self.base_url + path, headers={"Accept": "application/json"}) with urlopen(req, timeout=self.timeout) as response: body = json.loads(response.read(8192)) if not isinstance(body, dict) or body.get("service") != "optr-api" or body.get("status") != "ok" or not isinstance(body.get("version"), str): raise OptrError("Unexpected service response", response.status) return {key: body[key] for key in ("service", "status", "version")} except HTTPError as exc: raise OptrError("Service is unavailable", exc.code) from exc except (URLError, TimeoutError, ValueError) as exc: raise OptrError("Unable to reach Optr") from exc