Four items from client feedback:
1. Stuck 'Initial Indexing' status. Root cause (by design in Onyx):
docprocessing/utils.py never runs a classic index attempt for INGESTION_API
connectors — documents are pushed via the API, not polled — so
last_finished_status stays null and the badge is stuck even though the docs
are indexed and searchable (also why it's safe: no risk of re-index deleting
the pushed docs). Two-part fix:
- Connector now sets each cc_pair ACTIVE after provisioning (set_cc_pair_active),
which fixes the connector detail page + 'Active Connectors' count.
- Frontend overlay (branding/smb/smb-ui.patch): the Ingestion table shows the
real cc_pair_status for ingestion_api connectors instead of forcing
'Initial Indexing'. Verified live: new cc_pair comes up ACTIVE.
2. Connector name now configurable: ONYX_CONNECTOR_NAME_PREFIX (default 'AIDO SMB').
3. HTTP timeout now configurable: ONYX_HTTP_TIMEOUT (default 60), for large embeds.
4. (Phase 2 already delivered in ab64692 — the preview/path overlay.)
Verified live against running Onyx: provisioning sets ACTIVE, custom prefix
'Livtec Docs - Sales' applied, timeout honoured, ä-filename still indexed. Full
overlay apply green, no conflict markers, connector modules parse.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
226 lines
9.3 KiB
Python
226 lines
9.3 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) -> int:
|
|
"""Create an ingestion-API connector + mock credential + cc_pair. Returns
|
|
the cc_pair id. Idempotent: reuses an existing one with the same name."""
|
|
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
|
|
|
|
connector = {
|
|
"name": name,
|
|
"source": "ingestion_api",
|
|
"input_type": "poll",
|
|
"connector_specific_config": {},
|
|
"refresh_freq": None,
|
|
"prune_freq": None,
|
|
"indexing_start": None,
|
|
"access_type": "public",
|
|
"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
|