init commit
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""Клиент Remnawave API (только чтение)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
class RemnawaveError(Exception):
|
||||
"""Ошибка обращения к панели. Токен в сообщения не попадает."""
|
||||
|
||||
def __init__(self, message: str, code: str = "upstream_error", http_status: int = 502):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.http_status = http_status
|
||||
|
||||
|
||||
class RemnawaveClient:
|
||||
def __init__(self, base_url: str, token: str, timeout: float = 10.0,
|
||||
verify: bool = True, extra_headers: dict[str, str] | None = None):
|
||||
self.base = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.verify = verify
|
||||
self.headers = {"Authorization": f"Bearer {token}", "Accept": "application/json",
|
||||
**(extra_headers or {})}
|
||||
|
||||
def _get(self, path: str) -> Any:
|
||||
try:
|
||||
r = requests.get(f"{self.base}{path}", headers=self.headers,
|
||||
timeout=self.timeout, verify=self.verify)
|
||||
except requests.Timeout:
|
||||
raise RemnawaveError(f"Таймаут запроса {path}", "upstream_timeout", 504) from None
|
||||
except requests.RequestException as e:
|
||||
raise RemnawaveError(f"Не удалось подключиться к Remnawave ({type(e).__name__})",
|
||||
"upstream_unreachable") from None
|
||||
if r.status_code in (401, 403):
|
||||
raise RemnawaveError("Remnawave отклонил токен (401/403)", "upstream_auth")
|
||||
if not r.ok:
|
||||
raise RemnawaveError(f"{path}: HTTP {r.status_code}", "upstream_http")
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
raise RemnawaveError(f"{path}: ответ не JSON (проверь REMNAWAVE_URL)",
|
||||
"upstream_bad_response") from None
|
||||
return body.get("response", body) if isinstance(body, dict) else body
|
||||
|
||||
def profiles(self) -> list[dict]:
|
||||
data = self._get("/api/config-profiles")
|
||||
return data.get("configProfiles", []) if isinstance(data, dict) else data
|
||||
|
||||
def hosts(self) -> list[dict]:
|
||||
return self._get("/api/hosts")
|
||||
|
||||
def nodes(self) -> list[dict]:
|
||||
return self._get("/api/nodes")
|
||||
|
||||
def fetch_all(self) -> dict[str, list[dict]]:
|
||||
"""Три запроса параллельно."""
|
||||
calls = {"profiles": self.profiles, "hosts": self.hosts, "nodes": self.nodes}
|
||||
with ThreadPoolExecutor(max_workers=3) as ex:
|
||||
futures = {k: ex.submit(fn) for k, fn in calls.items()}
|
||||
return {k: f.result() for k, f in futures.items()}
|
||||
Reference in New Issue
Block a user