aido-onyx/smb-connector/app/onyx_client.py
NaeemDosh 909a541c6b SMB connector Phase 1: sync + self-provisioning + multi-source (E2E-verified)
Production SMB->Onyx sync sidecar (public ingestion + admin APIs only; no Onyx
source changes; upgrade-safe). Verified end-to-end against a live Onyx v4.5.2.

Core (app/sync.py): per-cycle reconcile — upsert new/changed (stable url-safe
document ids so updates replace in place), delete files removed from the share,
plus manifest-independent reconcile against Onyx's own doc list. Content-hash change
detection; per-source + per-file failure isolation.

Self-provisioning (app/onyx_client.py): create/cache API key (admin bootstrap) and
one connector/cc_pair per source via connector-with-mock-credential; idempotent
reuse via the grouped indexing-status lookup.

Multi-source (app/config.py): JSON SMB_SOURCES or indexed SMB_SOURCE_N_*; logical
path mapping (mount -> \\company\share) shown in citations.

Extraction (app/extract.py): pdf/docx/xlsx/csv/txt/md/html, light deps. State manifest
(atomic), entrypoint loop w/ graceful shutdown + retry/backoff. Dockerfile, compose
snippet, .env.example, README.

Bugs caught + fixed during live E2E (missed by code review + stub tests):
- Onyx URL-encodes document ids -> switched to url-safe ids + store Onyx's returned
  canonical id, so delete/reconcile match.
- connector listing endpoint + provision-response parsing corrected (indexing-status
  is grouped by source; StatusResponse.data = cc_pair_id).
- Documented: auto API-key creation needs LICENSE_ENFORCEMENT_ENABLED=false (the
  /admin/api-key endpoint is EE-tier-gated); ingestion + connector creation are not.

E2E results (live Onyx): ingest 2 docs w/ logical paths; change->update-in-place with
stable ids; remove->delete synced; auto-provision create + idempotent reuse; multi-
source config both styles.
2026-09-01 23:18:33 +05:00

205 lines
8.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)
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)
return int(cc)
# -- 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