aido-onyx/smb-connector/app/config.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

148 lines
5.2 KiB
Python

"""Configuration loading for the AIDO SMB → Onyx sync connector.
Multi-source is defined entirely via environment variables, so the number of SMB
shares scales without code changes. Two equivalent styles are supported:
1) JSON list in ``SMB_SOURCES`` (preferred for many sources)::
SMB_SOURCES='[
{"name": "Finance", "mount": "/shares/finance", "logical": "\\\\company\\finance"},
{"name": "Legal", "mount": "/shares/legal", "logical": "\\\\company\\legal"}
]'
2) Indexed vars ``SMB_SOURCE_<N>_*`` (readable for a handful of sources)::
SMB_SOURCE_1_NAME=Finance
SMB_SOURCE_1_MOUNT=/shares/finance
SMB_SOURCE_1_LOGICAL=\\company\finance
SMB_SOURCE_1_CC_PAIR_ID=243 # optional; auto-provisioned if omitted
Each source is mounted read-only into the container (typically a CIFS/SMB mount on
the host, bind-mounted here). ``logical`` is the human-facing path shown in Onyx's
citation view; it is mapped from the local ``mount`` at ingestion time.
"""
from __future__ import annotations
import json
import os
from dataclasses import dataclass, field
@dataclass
class SourceConfig:
name: str
mount: str
logical: str
# Optional explicit connector/credential pair id. When omitted the connector
# is auto-provisioned (idempotently) and the id cached in the state file.
cc_pair_id: int | None = None
def normalized_logical(self) -> str:
# Trim trailing separators so path joins are clean.
return self.logical.rstrip("/\\")
@dataclass
class Config:
api_url: str
api_key: str | None
# Bootstrap admin credentials — only used to auto-create the API key and
# connectors when they are not supplied. Never required at steady state.
admin_email: str | None
admin_password: str | None
interval_seconds: int
state_path: str
include_ext: set[str]
max_file_mb: int
log_level: str
sources: list[SourceConfig] = field(default_factory=list)
def _split_ext(value: str) -> set[str]:
return {
e.strip().lower().lstrip(".")
for e in value.split(",")
if e.strip()
}
def _load_sources() -> list[SourceConfig]:
raw = os.environ.get("SMB_SOURCES", "").strip()
if raw:
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
raise SystemExit(f"SMB_SOURCES is not valid JSON: {exc}") from exc
sources = []
for i, item in enumerate(data, 1):
if not item.get("name") or not item.get("mount"):
raise SystemExit(f"SMB_SOURCES[{i - 1}] needs at least 'name' and 'mount'")
sources.append(
SourceConfig(
name=str(item["name"]),
mount=str(item["mount"]),
logical=str(item.get("logical") or item["mount"]),
cc_pair_id=(int(item["cc_pair_id"]) if item.get("cc_pair_id") else None),
)
)
return sources
# Indexed style: SMB_SOURCE_1_NAME, _MOUNT, _LOGICAL, _CC_PAIR_ID …
sources = []
i = 1
while os.environ.get(f"SMB_SOURCE_{i}_NAME"):
name = os.environ[f"SMB_SOURCE_{i}_NAME"]
mount = os.environ.get(f"SMB_SOURCE_{i}_MOUNT")
if not mount:
raise SystemExit(f"SMB_SOURCE_{i}_MOUNT is required for source '{name}'")
cc = os.environ.get(f"SMB_SOURCE_{i}_CC_PAIR_ID")
sources.append(
SourceConfig(
name=name,
mount=mount,
logical=os.environ.get(f"SMB_SOURCE_{i}_LOGICAL") or mount,
cc_pair_id=int(cc) if cc else None,
)
)
i += 1
# Backwards-compatible single-source fallback (matches the original POC).
if not sources and os.environ.get("DOCUMENT_SOURCE_PATH"):
sources.append(
SourceConfig(
name=os.environ.get("SMB_SOURCE_NAME", "SMB Share"),
mount=os.environ["DOCUMENT_SOURCE_PATH"],
logical=os.environ.get("SMB_LOGICAL_PATH", os.environ["DOCUMENT_SOURCE_PATH"]),
cc_pair_id=(
int(os.environ["CC_PAIR_ID"]) if os.environ.get("CC_PAIR_ID") else None
),
)
)
return sources
def load_config() -> Config:
api_url = os.environ.get("ONYX_API_URL", "http://api_server:8080").rstrip("/")
cfg = Config(
api_url=api_url,
api_key=os.environ.get("ONYX_API_KEY") or None,
admin_email=os.environ.get("ONYX_ADMIN_EMAIL") or None,
admin_password=os.environ.get("ONYX_ADMIN_PASSWORD") or None,
interval_seconds=int(os.environ.get("INGESTION_INTERVAL_SECONDS", "300")),
state_path=os.environ.get("STATE_PATH", "/app/state/manifest.json"),
include_ext=_split_ext(
os.environ.get(
"INCLUDE_EXTENSIONS",
"pdf,docx,doc,txt,md,csv,xlsx,xls,pptx,html,htm",
)
),
max_file_mb=int(os.environ.get("MAX_FILE_MB", "50")),
log_level=os.environ.get("LOG_LEVEL", "INFO").upper(),
sources=_load_sources(),
)
if not cfg.sources:
raise SystemExit(
"No SMB sources configured. Set SMB_SOURCES (JSON) or SMB_SOURCE_1_NAME/_MOUNT."
)
return cfg