aido-onyx/smb-connector/app/onyx_client.py
Naeem Dosh 26d3262cfb SMB connector: per-connector group access + standalone Docker mode
1. Optional Onyx group per connector. Set SMB_SOURCE_<N>_GROUPS (or
   "groups" in SMB_SOURCES JSON, or SMB_DEFAULT_GROUP_IDS as a fallback)
   to a list of Onyx user-group ids. The connector is then created
   PRIVATE and restricted to those groups; empty stays PUBLIC. Applied
   only at connector creation, as requested. Needs the Business licence.

2. Standalone deployment. New docker-compose.standalone.yml runs the
   connector as its own Compose project next to Onyx (no -f injection),
   joining Onyx's network (onyx_default, override via ONYX_NETWORK) to
   reach the API by service name. Suits Compose management tools that
   cannot handle multiple injected compose files. The legacy injected
   compose still works.

Verified: group-id parsing across all three source styles, the
private+groups vs public payload, standalone compose config, and the
full index/sync simulation (still green).
2026-09-24 14:20:39 +05:00

233 lines
9.7 KiB
Python

"""Thin, typed client for the Onyx public + admin APIs used by the connector.
Endpoints (verified against Onyx v4.5.2):
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 <api_key>``.
"""
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 an ingestion-API connector + mock credential + cc_pair. Returns
the cc_pair id. Idempotent: reuses an existing one with the same name.
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": "ingestion_api",
"input_type": "poll",
"connector_specific_config": {},
"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. Onyx never runs a classic index attempt for
ingestion-API connectors (docs are pushed via the API, not polled), so
without this they sit in SCHEDULED/INITIAL_INDEXING forever. 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