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

82 lines
2.6 KiB
Python

"""Persistent sync state (the manifest).
The manifest is what makes update/delete sync possible: it remembers, per source,
which files were ingested, their stable Onyx ``document_id`` and a content hash.
On each cycle the engine diffs the share against this manifest to decide what to
upsert (new/changed) and what to delete (gone from disk).
It also caches the auto-provisioned ``cc_pair_id`` per source so provisioning is
idempotent across restarts.
"""
from __future__ import annotations
import json
import os
import tempfile
from dataclasses import dataclass, field
@dataclass
class FileRecord:
document_id: str
content_hash: str
logical_path: str
size: int
mtime: float
@dataclass
class SourceState:
cc_pair_id: int | None = None
# relative-path -> FileRecord
files: dict[str, FileRecord] = field(default_factory=dict)
class State:
def __init__(self, path: str) -> None:
self.path = path
self.api_key: str | None = None
self.sources: dict[str, SourceState] = {}
# -- load/save -----------------------------------------------------------
@classmethod
def load(cls, path: str) -> "State":
state = cls(path)
if not os.path.exists(path):
return state
with open(path, "r", encoding="utf-8") as fh:
raw = json.load(fh)
state.api_key = raw.get("api_key")
for name, s in (raw.get("sources") or {}).items():
ss = SourceState(cc_pair_id=s.get("cc_pair_id"))
for rel, rec in (s.get("files") or {}).items():
ss.files[rel] = FileRecord(**rec)
state.sources[name] = ss
return state
def save(self) -> None:
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
data = {
"api_key": self.api_key,
"sources": {
name: {
"cc_pair_id": ss.cc_pair_id,
"files": {rel: vars(rec) for rel, rec in ss.files.items()},
}
for name, ss in self.sources.items()
},
}
# Atomic write so a crash mid-write can't corrupt the manifest.
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(self.path) or ".", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2)
os.replace(tmp, self.path)
finally:
if os.path.exists(tmp):
os.remove(tmp)
# -- accessors -----------------------------------------------------------
def source(self, name: str) -> SourceState:
return self.sources.setdefault(name, SourceState())