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

84 lines
2.4 KiB
Python

"""Entry point: bootstrap auth, then run the sync loop on an interval."""
from __future__ import annotations
import logging
import signal
import sys
import time
from .config import load_config
from .onyx_client import OnyxClient, OnyxError
from .state import State
from .sync import sync_all
_stop = False
def _handle_signal(signum, _frame):
global _stop
logging.getLogger("smb").info("Received signal %s — finishing current cycle then exiting", signum)
_stop = True
def bootstrap_api_key(client: OnyxClient, state: State) -> None:
"""Ensure we have a usable API key. Preference order:
1. ONYX_API_KEY (already on the client) 2. cached key in the state file
3. create one via admin bootstrap credentials."""
if client.api_key:
return
if state.api_key:
client.api_key = state.api_key
return
key = client.create_api_key("AIDO SMB Connector")
state.api_key = key
state.save()
logging.getLogger("smb").info("Created and cached a new Onyx API key")
def main() -> int:
cfg = load_config()
logging.basicConfig(
level=getattr(logging, cfg.log_level, logging.INFO),
format="%(asctime)s %(levelname)-7s %(name)s | %(message)s",
)
log = logging.getLogger("smb")
signal.signal(signal.SIGTERM, _handle_signal)
signal.signal(signal.SIGINT, _handle_signal)
state = State.load(cfg.state_path)
client = OnyxClient(cfg.api_url, cfg.api_key)
client.set_admin_credentials(cfg.admin_email, cfg.admin_password)
try:
bootstrap_api_key(client, state)
except OnyxError as exc:
log.error("Could not obtain an API key: %s", exc)
return 2
log.info(
"AIDO SMB connector started: %d source(s), every %ds → %s",
len(cfg.sources), cfg.interval_seconds, cfg.api_url,
)
while not _stop:
started = time.time()
try:
sync_all(client, cfg, state)
except Exception as exc: # never crash the loop
log.exception("Sync cycle error: %s", exc)
elapsed = time.time() - started
log.info("Cycle finished in %.1fs; next in %ds", elapsed, cfg.interval_seconds)
# Sleep in small slices so SIGTERM is responsive.
remaining = cfg.interval_seconds
while remaining > 0 and not _stop:
time.sleep(min(2, remaining))
remaining -= 2
log.info("Shut down cleanly.")
return 0
if __name__ == "__main__":
sys.exit(main())