215 lines
5.8 KiB
Python
215 lines
5.8 KiB
Python
"""Shared PocketBase admin client for all FastAPI verticals."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
import time
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from nomadro_pb.config import PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD, PB_URL
|
|
|
|
log = logging.getLogger("nomadro_pb")
|
|
|
|
|
|
class PocketBaseError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def pb_quote(value: str) -> str:
|
|
return '"' + str(value).replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
|
|
|
|
class PocketBaseClient:
|
|
def __init__(
|
|
self,
|
|
*,
|
|
base_url: str | None = None,
|
|
email: str | None = None,
|
|
password: str | None = None,
|
|
) -> None:
|
|
self.base_url = (base_url or PB_URL).rstrip("/")
|
|
self.email = email or PB_ADMIN_EMAIL
|
|
self.password = password or PB_ADMIN_PASSWORD
|
|
self._admin_token: str | None = None
|
|
self._token_at = 0.0
|
|
self._client: httpx.Client | None = None
|
|
self._http_lock = threading.Lock()
|
|
self._auth_lock = threading.Lock()
|
|
|
|
def _http(self) -> httpx.Client:
|
|
with self._http_lock:
|
|
if self._client is None:
|
|
self._client = httpx.Client(timeout=25.0, trust_env=False)
|
|
return self._client
|
|
|
|
def request(
|
|
self,
|
|
method: str,
|
|
path: str,
|
|
*,
|
|
admin: bool = False,
|
|
json: dict[str, Any] | None = None,
|
|
params: dict[str, Any] | None = None,
|
|
) -> Any:
|
|
headers: dict[str, str] = {}
|
|
if admin:
|
|
headers["Authorization"] = self.admin_token()
|
|
url = f"{self.base_url}{path}"
|
|
res = self._http().request(method, url, headers=headers, json=json, params=params)
|
|
# A rejected credential did not authorize the operation. Refresh once;
|
|
# never replay timeouts, 5xx responses or transport failures for writes.
|
|
if admin and res.status_code == 401:
|
|
with self._auth_lock:
|
|
if self._admin_token == headers["Authorization"]:
|
|
self._admin_token = None
|
|
self._token_at = 0.0
|
|
headers["Authorization"] = self.admin_token()
|
|
res = self._http().request(method, url, headers=headers, json=json, params=params)
|
|
if res.status_code >= 400:
|
|
try:
|
|
detail = res.json()
|
|
except Exception:
|
|
detail = res.text
|
|
raise PocketBaseError(f"PocketBase {res.status_code}: {detail}")
|
|
if not res.content:
|
|
return None
|
|
return res.json()
|
|
|
|
def admin_token(self) -> str:
|
|
with self._auth_lock:
|
|
return self._refresh_admin_token()
|
|
|
|
def _refresh_admin_token(self) -> str:
|
|
if self._admin_token and (time.monotonic() - self._token_at) < 280:
|
|
return self._admin_token
|
|
body = {"identity": self.email, "password": self.password}
|
|
last: Exception | None = None
|
|
for endpoint in (
|
|
"/api/collections/_superusers/auth-with-password",
|
|
"/api/admins/auth-with-password",
|
|
):
|
|
try:
|
|
data = self.request("POST", endpoint, json=body)
|
|
token = (data or {}).get("token")
|
|
if token:
|
|
self._admin_token = str(token)
|
|
self._token_at = time.monotonic()
|
|
return self._admin_token
|
|
except Exception as exc:
|
|
last = exc
|
|
raise PocketBaseError(f"Unable to authenticate PocketBase admin: {last}")
|
|
|
|
def health_ok(self) -> bool:
|
|
try:
|
|
res = self._http().get(f"{self.base_url}/api/health", timeout=3.0)
|
|
return res.status_code == 200
|
|
except Exception:
|
|
return False
|
|
|
|
def get_collection(self, name: str) -> dict[str, Any] | None:
|
|
try:
|
|
return self.request("GET", f"/api/collections/{name}", admin=True)
|
|
except PocketBaseError:
|
|
return None
|
|
|
|
def create_collection(self, body: dict[str, Any]) -> dict[str, Any]:
|
|
return self.request("POST", "/api/collections", admin=True, json=body)
|
|
|
|
def list_records(
|
|
self,
|
|
collection: str,
|
|
*,
|
|
filter: str | None = None,
|
|
sort: str | None = None,
|
|
page: int = 1,
|
|
per_page: int = 200,
|
|
) -> dict[str, Any]:
|
|
params: dict[str, Any] = {"page": page, "perPage": per_page}
|
|
if filter:
|
|
params["filter"] = filter
|
|
if sort:
|
|
params["sort"] = sort
|
|
return self.request(
|
|
"GET",
|
|
f"/api/collections/{collection}/records",
|
|
admin=True,
|
|
params=params,
|
|
)
|
|
|
|
def list_all(
|
|
self,
|
|
collection: str,
|
|
*,
|
|
filter: str | None = None,
|
|
sort: str | None = None,
|
|
hard_limit: int = 5000,
|
|
) -> list[dict[str, Any]]:
|
|
page = 1
|
|
items: list[dict[str, Any]] = []
|
|
while True:
|
|
data = self.list_records(
|
|
collection, filter=filter, sort=sort, page=page, per_page=200
|
|
)
|
|
batch = data.get("items") or []
|
|
items.extend(batch)
|
|
if page >= (data.get("totalPages") or 1) or len(items) >= hard_limit:
|
|
break
|
|
page += 1
|
|
return items[:hard_limit]
|
|
|
|
def first(
|
|
self, collection: str, *, filter: str
|
|
) -> dict[str, Any] | None:
|
|
data = self.list_records(collection, filter=filter, per_page=1)
|
|
items = data.get("items") or []
|
|
return items[0] if items else None
|
|
|
|
def create(self, collection: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
return self.request(
|
|
"POST",
|
|
f"/api/collections/{collection}/records",
|
|
admin=True,
|
|
json=payload,
|
|
)
|
|
|
|
def update(
|
|
self, collection: str, record_id: str, payload: dict[str, Any]
|
|
) -> dict[str, Any]:
|
|
return self.request(
|
|
"PATCH",
|
|
f"/api/collections/{collection}/records/{record_id}",
|
|
admin=True,
|
|
json=payload,
|
|
)
|
|
|
|
def delete(self, collection: str, record_id: str) -> None:
|
|
self.request(
|
|
"DELETE",
|
|
f"/api/collections/{collection}/records/{record_id}",
|
|
admin=True,
|
|
)
|
|
|
|
def upsert(
|
|
self,
|
|
collection: str,
|
|
*,
|
|
filter: str,
|
|
payload: dict[str, Any],
|
|
) -> dict[str, Any]:
|
|
existing = self.first(collection, filter=filter)
|
|
if existing:
|
|
return self.update(collection, existing["id"], payload)
|
|
return self.create(collection, payload)
|
|
|
|
|
|
_pb: PocketBaseClient | None = None
|
|
|
|
|
|
def get_pb() -> PocketBaseClient:
|
|
global _pb
|
|
if _pb is None:
|
|
_pb = PocketBaseClient()
|
|
return _pb
|