"""Thin, typed client for the Onyx public + admin APIs used by the connector. Endpoints (stable across Onyx v4.5–v4.8): POST /onyx-api/ingestion upsert a document (by DocumentBase.id) DELETE /onyx-api/ingestion/{document_id} remove a document entirely GET /onyx-api/connector-docs/{cc_pair_id} list docs for a cc_pair (reconcile) POST /admin/api-key create an API key (bootstrap only) GET /manage/connector list connectors (idempotent provision) POST /manage/admin/connector-with-mock-credential create connector+credential+cc_pair Auth is a bearer token: ``Authorization: Bearer ``. """ from __future__ import annotations import logging import time from typing import Any import requests logger = logging.getLogger("smb.onyx") _RETRYABLE = {429, 500, 502, 503, 504} class OnyxError(RuntimeError): pass class OnyxClient: def __init__(self, base_url: str, api_key: str | None, timeout: int = 60) -> None: self.base_url = base_url.rstrip("/") self.api_key = api_key self.timeout = timeout self._session = requests.Session() # -- low level ----------------------------------------------------------- def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]: headers = {"Content-Type": "application/json"} if self.api_key: headers["Authorization"] = f"Bearer {self.api_key}" if extra: headers.update(extra) return headers def _request( self, method: str, path: str, *, json: Any = None, auth: tuple[str, str] | None = None, retries: int = 4, ) -> requests.Response: url = f"{self.base_url}{path}" last_exc: Exception | None = None for attempt in range(1, retries + 1): try: resp = self._session.request( method, url, json=json, headers=self._headers(), auth=auth, timeout=self.timeout, ) if resp.status_code in _RETRYABLE: raise OnyxError(f"{resp.status_code} from {method} {path}") return resp except (requests.RequestException, OnyxError) as exc: last_exc = exc if attempt == retries: break backoff = min(2 ** attempt, 30) logger.warning( "%s %s failed (attempt %d/%d): %s — retrying in %ds", method, path, attempt, retries, exc, backoff, ) time.sleep(backoff) raise OnyxError(f"{method} {path} failed after {retries} attempts: {last_exc}") # -- ingestion ----------------------------------------------------------- def upsert_document(self, document: dict[str, Any], cc_pair_id: int) -> dict[str, Any]: """Create or update a document. Onyx keys on ``document.id`` so re-posting the same id updates in place — that's how change-sync works.""" payload = {"document": document, "cc_pair_id": cc_pair_id} resp = self._request("POST", "/onyx-api/ingestion", json=payload) if resp.status_code >= 400: raise OnyxError(f"ingestion upsert failed [{resp.status_code}]: {resp.text[:400]}") return resp.json() def delete_document(self, document_id: str) -> bool: resp = self._request("DELETE", f"/onyx-api/ingestion/{document_id}") if resp.status_code in (200, 204): return True if resp.status_code == 404: return False raise OnyxError(f"delete failed [{resp.status_code}]: {resp.text[:300]}") def list_cc_pair_documents(self, cc_pair_id: int) -> list[dict[str, Any]]: """Docs Onyx currently holds for a cc_pair — used to reconcile deletes even if our local manifest is lost.""" resp = self._request("GET", f"/onyx-api/connector-docs/{cc_pair_id}") if resp.status_code >= 400: raise OnyxError(f"list docs failed [{resp.status_code}]: {resp.text[:300]}") return resp.json() # -- bootstrap: API key -------------------------------------------------- def create_api_key(self, name: str) -> str: """Create an admin-scoped API key via basic-auth admin login. Only used once, when ONYX_API_KEY is not supplied.""" if not self._admin_auth: raise OnyxError( "Cannot create an API key: provide ONYX_API_KEY, or " "ONYX_ADMIN_EMAIL/ONYX_ADMIN_PASSWORD to bootstrap one." ) resp = self._request( "POST", "/admin/api-key", json={"name": name, "role": "admin"}, auth=self._admin_auth, ) if resp.status_code >= 400: raise OnyxError(f"api-key create failed [{resp.status_code}]: {resp.text[:300]}") key = resp.json().get("api_key") if not key: raise OnyxError(f"api-key response missing 'api_key': {resp.text[:300]}") self.api_key = key return key # -- idempotent connector provisioning ----------------------------------- def find_cc_pair_id_by_name(self, name: str) -> int | None: """Look up an existing connector/credential pair by name so provisioning is idempotent even if the local state (cached id) was lost.""" resp = self._request( "POST", "/manage/admin/connector/indexing-status", json={"secondary_index": False}, auth=self._admin_auth, ) if resp.status_code >= 400: return None body = resp.json() # Response is a list grouped by source; each group nests the actual # cc_pairs under "indexing_statuses": [{cc_pair_id, name, ...}]. groups = body if isinstance(body, list) else [body] for group in groups: statuses = (group or {}).get("indexing_statuses") or [] for row in statuses: if isinstance(row, dict) and row.get("name") == name and row.get("cc_pair_id"): return int(row["cc_pair_id"]) return None def provision_cc_pair(self, name: str, group_ids: list[int] | None = None) -> int: """Create a File connector + mock credential + cc_pair. Returns the cc_pair id. Idempotent: reuses an existing one with the same name. The connector is a File connector (documents are pushed in via the Ingestion API with from_ingestion_api=True). File is a first-class, chat-searchable source, so the documents show up in Default Chat and the source filters; the older ingestion_api source is hidden there. When ``group_ids`` is given, the connector is created PRIVATE and restricted to those Onyx user groups (needs the Business licence). Access is set only at creation; an existing connector is reused as-is.""" existing = self.find_cc_pair_id_by_name(name) if existing: logger.info("Reusing existing connector '%s' (cc_pair_id=%s)", name, existing) self.set_cc_pair_active(existing) return existing groups = group_ids or [] connector = { "name": name, "source": "file", "input_type": "load_state", "connector_specific_config": { "file_locations": [] }, "refresh_freq": None, "prune_freq": None, "indexing_start": None, "access_type": "private" if groups else "public", "groups": groups, } if groups: logger.info("Creating connector '%s' private, restricted to groups %s", name, groups) resp = self._request( "POST", "/manage/admin/connector-with-mock-credential", json=connector, auth=self._admin_auth, ) if resp.status_code >= 400: raise OnyxError( f"connector provision failed [{resp.status_code}]: {resp.text[:400]}" ) body = resp.json() # add_credential_to_connector returns StatusResponse[int] with data = cc_pair_id. data = body.get("data") cc = data if isinstance(data, int) else body.get("cc_pair_id") if not cc: # Fall back to a name lookup — the create call may return only a status. cc = self.find_cc_pair_id_by_name(name) if not cc: raise OnyxError(f"could not determine cc_pair_id after provisioning: {body}") logger.info("Provisioned connector '%s' → cc_pair_id=%s", name, cc) self.set_cc_pair_active(int(cc)) return int(cc) def set_cc_pair_active(self, cc_pair_id: int) -> None: """Mark the cc_pair ACTIVE so the connector is enabled and its documents are searchable. Documents are pushed via the Ingestion API rather than polled from a file location. Best-effort.""" try: resp = self._request( "PUT", f"/manage/admin/cc-pair/{cc_pair_id}/status", json={"status": "ACTIVE"}, auth=self._admin_auth, ) if resp.status_code >= 400: logger.warning( "Could not set cc_pair %s ACTIVE [%s]: %s", cc_pair_id, resp.status_code, resp.text[:200], ) except OnyxError as exc: logger.warning("Could not set cc_pair %s ACTIVE: %s", cc_pair_id, exc) # -- helpers ------------------------------------------------------------- _admin_email: str | None = None _admin_password: str | None = None def set_admin_credentials(self, email: str | None, password: str | None) -> None: self._admin_email = email self._admin_password = password @property def _admin_auth(self) -> tuple[str, str] | None: if self._admin_email and self._admin_password: return (self._admin_email, self._admin_password) return None