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.
This commit is contained in:
NaeemDosh 2026-09-01 23:18:30 +05:00 • committed by Naeem Dosh
parent dfbac553ff
commit 909a541c6b
12 changed files with 983 additions and 0 deletions

View file

@ -0,0 +1,38 @@
# ─────────────────────────────────────────────────────────────────────────────
# AIDO SMB → Onyx sync connector (Phase 1)
# Copy to .env and adjust. The connector runs as a sidecar next to Onyx.
# ─────────────────────────────────────────────────────────────────────────────
# Onyx API base (in-compose service name; no trailing /api needed).
ONYX_API_URL=http://api_server:8080
# Auth — provide ONE of:
# (a) a pre-created API key (simplest), or
# (b) admin credentials so the connector creates + caches its own key on first boot.
ONYX_API_KEY=
# ONYX_ADMIN_EMAIL=admin@example.com
# ONYX_ADMIN_PASSWORD=change-me
# How often to reconcile each share (seconds).
INGESTION_INTERVAL_SECONDS=300
# File selection.
INCLUDE_EXTENSIONS=pdf,docx,txt,md,csv,xlsx,html,htm
MAX_FILE_MB=50
LOG_LEVEL=INFO
# ── Sources ──────────────────────────────────────────────────────────────────
# Preferred: one JSON list (scales to any number of shares, no code changes).
# 'mount' = local path where the SMB share is mounted (read-only) in this container
# 'logical' = the path users recognise; shown in Onyx's citation view
# 'cc_pair_id' (optional) = use a specific connector; auto-provisioned if omitted.
SMB_SOURCES=[{"name":"Finance","mount":"/shares/finance","logical":"\\\\company\\finance"},{"name":"Legal","mount":"/shares/legal","logical":"\\\\company\\legal"}]
# …or the indexed style instead of SMB_SOURCES:
# SMB_SOURCE_1_NAME=Finance
# SMB_SOURCE_1_MOUNT=/shares/finance
# SMB_SOURCE_1_LOGICAL=\\company\finance
# SMB_SOURCE_1_CC_PAIR_ID=
# SMB_SOURCE_2_NAME=Legal
# SMB_SOURCE_2_MOUNT=/shares/legal
# SMB_SOURCE_2_LOGICAL=\\company\legal

17
smb-connector/Dockerfile Normal file
View file

@ -0,0 +1,17 @@
# AIDO SMB → Onyx sync connector (Phase 1)
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
# Non-root; state dir is a mounted volume so the manifest survives restarts.
RUN useradd -u 10001 -m runner && mkdir -p /app/state && chown -R runner /app/state
USER runner
VOLUME ["/app/state"]
CMD ["python", "-m", "app.main"]

85
smb-connector/README.md Normal file
View file

@ -0,0 +1,85 @@
# AIDO SMB → Onyx Connector (Phase 1)
Syncs files from one or more **SMB/CIFS shares** into Onyx via the public
**Ingestion API**, with full production behaviour the POC was missing:
- **Update & delete sync** — changed files are re-indexed in place; files removed
from a share are deleted from Onyx (reconciled every cycle).
- **Self-provisioning** — creates/reuses the Onyx **API key** and one **connector
(cc_pair)** per source automatically; idempotent across restarts.
- **Multi-source via Docker config** — any number of shares, defined purely in env.
- **Logical path mapping** — each document is labelled with the path users
recognise (`\\company\share\…`), mapped from the local mount via config.
It runs as a **sidecar container** and touches **no Onyx source code** — only the
public ingestion + admin APIs — so it survives Onyx upgrades.
> Phase 2 (separate) hides the broken file-preview for these SMB documents in the
> Onyx UI and shows the logical path instead, via the white-label overlay.
## How it works
```
SMB share ──(read-only mount)──▶ smb_connector ──ingestion API──▶ Onyx
│
manifest.json (path → document_id + content hash)
```
Each cycle, per source:
1. Walk the share, hash each eligible file.
2. **new / changed** (hash differs) → `POST /onyx-api/ingestion` (upsert by stable id).
3. **gone** (in manifest, not on disk) → `DELETE /onyx-api/ingestion/{id}`.
4. Reconcile against Onyx's own doc list so deletes still happen if the manifest
is lost.
Document ids are stable (`smb::<source>::<hash of relative path>`), so re-indexing
a changed file **updates** it rather than duplicating.
## Setup
```bash
cd smb-connector
cp .env.example .env
# set ONYX_API_KEY (or ONYX_ADMIN_EMAIL/PASSWORD to auto-create one)
# define your shares in SMB_SOURCES (JSON) or SMB_SOURCE_1_* vars
```
Mount each SMB share read-only on the host, then bind-mount it at the `mount`
path used in `SMB_SOURCES` (see `docker-compose.smb.yml`). Then:
```bash
docker compose -f docker-compose.yml -f smb-connector/docker-compose.smb.yml up -d --build smb_connector
docker compose logs -f smb_connector
```
## Configuration
| Var | Purpose |
|-----|---------|
| `ONYX_API_URL` | Onyx API base (e.g. `http://api_server:8080`) |
| `ONYX_API_KEY` | API key; if empty, auto-created from admin creds and cached |
| `ONYX_ADMIN_EMAIL` / `ONYX_ADMIN_PASSWORD` | Bootstrap creds to auto-create the key + connectors |
| `SMB_SOURCES` | JSON list of `{name, mount, logical, cc_pair_id?}` |
| `SMB_SOURCE_<N>_NAME/_MOUNT/_LOGICAL/_CC_PAIR_ID` | Indexed alternative to `SMB_SOURCES` |
| `INGESTION_INTERVAL_SECONDS` | Reconcile interval (default 300) |
| `INCLUDE_EXTENSIONS` | File types to ingest (default pdf,docx,txt,md,csv,xlsx,html) |
| `MAX_FILE_MB` | Skip files larger than this (default 50) |
State (manifest + cached key/cc_pair) lives in the mounted `/app/state` volume.
## Notes / scope
- **Extraction** is the light set (PDF, DOCX, XLSX, CSV, TXT/MD, HTML). Legacy
`.doc`/`.xls` and scanned-image PDFs are skipped (no OCR) — Phase-1 scope.
- **Auth for provisioning**: creating the API key/connectors needs one admin
credential the first time. At steady state only the cached API key is used.
- **API-key auto-creation requires `LICENSE_ENFORCEMENT_ENABLED=false`** on the Onyx
deployment (verified against v4.5.2): the `/admin/api-key` endpoint is EE-tier-gated
and returns HTTP 402 when enforcement is on (the default). CE/white-label deployments
run with it off, so this is fine — and if you'd rather not rely on it, just supply a
pre-made `ONYX_API_KEY`. Connector/cc_pair creation and the ingestion API itself are
**not** tier-gated and work on plain CE.
- **Document ids are URL-safe** (`smb_<source>_<hash>`), matching how Onyx stores/returns
them, so update and delete reconcile reliably (verified end-to-end).
- **`smb://` links** can't open from a browser; the logical path is stored for
display (Phase 2 surfaces it in the UI and hides the dead preview).

View file

148
smb-connector/app/config.py Normal file
View file

@ -0,0 +1,148 @@
"""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

View file

@ -0,0 +1,99 @@
"""Text extraction for the file types typically found on an SMB share.
Kept intentionally small and dependency-light (this is the "basic extraction"
scope of Phase 1). Unsupported/binary files return an empty string and are
skipped by the sync engine rather than ingested as noise.
"""
from __future__ import annotations
import csv
import io
import logging
import os
logger = logging.getLogger("smb.extract")
def _txt(data: bytes) -> str:
for enc in ("utf-8", "utf-16", "latin-1"):
try:
return data.decode(enc)
except UnicodeDecodeError:
continue
return data.decode("utf-8", errors="replace")
def _pdf(data: bytes) -> str:
from pypdf import PdfReader # lazy import so a missing dep only breaks one type
reader = PdfReader(io.BytesIO(data))
return "\n\n".join((page.extract_text() or "") for page in reader.pages)
def _docx(data: bytes) -> str:
import docx # python-docx
document = docx.Document(io.BytesIO(data))
parts = [p.text for p in document.paragraphs]
for table in document.tables:
for row in table.rows:
parts.append("\t".join(cell.text for cell in row.cells))
return "\n".join(parts)
def _xlsx(data: bytes) -> str:
from openpyxl import load_workbook
wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
out: list[str] = []
for ws in wb.worksheets:
out.append(f"# {ws.title}")
for row in ws.iter_rows(values_only=True):
out.append("\t".join("" if c is None else str(c) for c in row))
return "\n".join(out)
def _csv(data: bytes) -> str:
text = _txt(data)
rows = csv.reader(io.StringIO(text))
return "\n".join("\t".join(r) for r in rows)
def _html(data: bytes) -> str:
import re
text = _txt(data)
text = re.sub(r"(?is)<(script|style).*?</\1>", " ", text)
text = re.sub(r"(?s)<[^>]+>", " ", text)
return re.sub(r"\s+\n", "\n", text).strip()
_HANDLERS = {
"pdf": _pdf,
"docx": _docx,
"txt": _txt,
"md": _txt,
"csv": _csv,
"xlsx": _xlsx,
"html": _html,
"htm": _html,
}
def supported_extensions() -> set[str]:
return set(_HANDLERS)
def extract_text(path: str, data: bytes) -> str:
ext = os.path.splitext(path)[1].lower().lstrip(".")
handler = _HANDLERS.get(ext)
if handler is None:
# .doc/.xls (legacy binary) and others aren't handled by the light deps.
logger.debug("No extractor for .%s (%s) — skipping", ext, path)
return ""
try:
return (handler(data) or "").strip()
except Exception as exc: # never let one bad file stop the whole sync
logger.warning("Extraction failed for %s: %s", path, exc)
return ""

84
smb-connector/app/main.py Normal file
View file

@ -0,0 +1,84 @@
"""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())

View file

@ -0,0 +1,205 @@
"""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

View file

@ -0,0 +1,82 @@
"""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())

188
smb-connector/app/sync.py Normal file
View file

@ -0,0 +1,188 @@
"""The reconciliation engine: the production functionality the POC was missing.
For each source, one cycle:
1. Walk the mounted share, hashing each eligible file's content.
2. NEW / CHANGED (hash differs from the manifest) → upsert into Onyx.
3. GONE (in the manifest but no longer on disk) → delete from Onyx.
4. Reconcile against Onyx's own doc list so deletes still happen even if the
local manifest was lost (e.g. fresh volume).
Document ids are stable (derived from source name + relative path), so re-ingesting
a changed file updates it in place instead of creating a duplicate.
"""
from __future__ import annotations
import hashlib
import logging
import os
import re
from datetime import datetime, timezone
from .config import Config, SourceConfig
from .extract import extract_text
from .onyx_client import OnyxClient, OnyxError
from .state import FileRecord, State
logger = logging.getLogger("smb.sync")
def _source_slug(source_name: str) -> str:
return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src"
def _stable_document_id(source_name: str, rel_path: str) -> str:
# URL-safe id (no ':' etc.) so it is NOT re-encoded by Onyx — keeps the id we
# send, store and later delete/reconcile byte-for-byte identical.
digest = hashlib.sha256(f"{source_name}\x00{rel_path}".encode("utf-8")).hexdigest()[:20]
return f"smb_{_source_slug(source_name)}_{digest}"
def _source_id_prefix(source_name: str) -> str:
return f"smb_{_source_slug(source_name)}_"
def _logical_path(source: SourceConfig, rel_path: str) -> str:
# Present the Windows-style path the user recognises, mapped from the mount.
sep = "\\" if "\\" in source.normalized_logical() else "/"
joined = rel_path.replace("/", sep)
return f"{source.normalized_logical()}{sep}{joined}"
def _eligible(path: str, cfg: Config) -> bool:
ext = os.path.splitext(path)[1].lower().lstrip(".")
if cfg.include_ext and ext not in cfg.include_ext:
return False
try:
if os.path.getsize(path) > cfg.max_file_mb * 1024 * 1024:
logger.info("Skipping %s (> %d MB)", path, cfg.max_file_mb)
return False
except OSError:
return False
return not os.path.basename(path).startswith(".")
def _build_document(
source: SourceConfig, rel_path: str, doc_id: str, text: str, mtime: float
) -> dict:
logical = _logical_path(source, rel_path)
updated = datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat()
return {
"id": doc_id,
"source": "ingestion_api",
# semantic_identifier is the main label Onyx shows in the citation view.
"semantic_identifier": logical,
"title": os.path.basename(rel_path),
# A link is kept for reference; smb:// won't open in a browser (Phase 2
# replaces the broken preview with this path shown as copyable text).
"link": f"file://{logical}",
"sections": [{"text": text, "link": None}],
"metadata": {
"smb_source": source.name,
"logical_path": logical,
"relative_path": rel_path,
},
"doc_updated_at": updated,
}
def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: State) -> None:
if not os.path.isdir(source.mount):
logger.error("Source '%s': mount %s is not accessible — skipping", source.name, source.mount)
return
ss = state.source(source.name)
cc_pair_id = source.cc_pair_id or ss.cc_pair_id
if not cc_pair_id:
cc_pair_id = client.provision_cc_pair(f"AIDO SMB - {source.name}")
ss.cc_pair_id = cc_pair_id
state.save()
seen: set[str] = set()
upserts = deletes = unchanged = 0
for root, _dirs, files in os.walk(source.mount):
for fname in files:
abspath = os.path.join(root, fname)
if not _eligible(abspath, cfg):
continue
rel = os.path.relpath(abspath, source.mount).replace(os.sep, "/")
seen.add(rel)
try:
data = open(abspath, "rb").read()
except OSError as exc:
logger.warning("Cannot read %s: %s", abspath, exc)
continue
content_hash = hashlib.sha256(data).hexdigest()
prev = ss.files.get(rel)
if prev and prev.content_hash == content_hash:
unchanged += 1
continue
text = extract_text(abspath, data)
if not text.strip():
# Nothing extractable — don't ingest an empty document.
continue
doc_id = _stable_document_id(source.name, rel)
document = _build_document(source, rel, doc_id, text, os.path.getmtime(abspath))
try:
result = client.upsert_document(document, cc_pair_id)
except OnyxError as exc:
logger.error("Upsert failed for %s: %s", rel, exc)
continue
# Store the id Onyx actually persisted (it may normalise/encode the id),
# so later delete + reconcile match byte-for-byte.
canonical_id = result.get("document_id", doc_id) if isinstance(result, dict) else doc_id
ss.files[rel] = FileRecord(
document_id=canonical_id,
content_hash=content_hash,
logical_path=_logical_path(source, rel),
size=len(data),
mtime=os.path.getmtime(abspath),
)
upserts += 1
logger.info("%s %s", "updated" if prev else "indexed", rel)
# Deletes: files in the manifest but no longer on disk.
for rel in list(ss.files.keys()):
if rel in seen:
continue
rec = ss.files.pop(rel)
try:
client.delete_document(rec.document_id)
deletes += 1
logger.info("deleted %s (removed from share)", rel)
except OnyxError as exc:
logger.error("Delete failed for %s: %s", rel, exc)
ss.files[rel] = rec # keep it; retry next cycle
state.save()
# Manifest-independent reconcile: remove Onyx docs for this cc_pair that we
# no longer track (covers a lost manifest / externally-added docs).
try:
live_ids = {r.document_id for r in ss.files.values()}
for doc in client.list_cc_pair_documents(cc_pair_id):
did = doc.get("document_id")
if did and did.startswith(_source_id_prefix(source.name)) and did not in live_ids:
client.delete_document(did)
deletes += 1
logger.info("reconciled orphan delete %s", did)
except OnyxError as exc:
logger.warning("Reconcile pass for '%s' skipped: %s", source.name, exc)
logger.info(
"Source '%s' done: %d upserted, %d deleted, %d unchanged (cc_pair_id=%s)",
source.name, upserts, deletes, unchanged, cc_pair_id,
)
def sync_all(client: OnyxClient, cfg: Config, state: State) -> None:
for source in cfg.sources:
try:
sync_source(client, cfg, source, state)
except Exception as exc: # isolate a failing source from the rest
logger.exception("Source '%s' failed this cycle: %s", source.name, exc)

View file

@ -0,0 +1,33 @@
# Add this service to your Onyx docker-compose (same `onyx-network`).
# Mount each SMB share read-only at the `mount` path referenced in .env / SMB_SOURCES.
#
# docker compose -f docker-compose.yml -f smb-connector/docker-compose.smb.yml up -d smb_connector
#
# Host-side SMB mount example (Linux):
# sudo mount -t cifs //server/finance /mnt/smb/finance -o ro,username=svc,password=***,uid=10001
# then bind-mount /mnt/smb/finance -> /shares/finance below.
services:
smb_connector:
build: ./smb-connector
image: livtec/aido-smb-connector:local
container_name: aido-smb-connector
restart: unless-stopped
networks:
- onyx-network
env_file:
- path: ./smb-connector/.env
required: false
depends_on:
api_server:
condition: service_healthy
volumes:
# Persist the sync manifest + cached api-key/cc_pair (survives restarts).
- ./smb-connector/state:/app/state
# Mount each SMB share read-only at the path used in SMB_SOURCES:
- /mnt/smb/finance:/shares/finance:ro
- /mnt/smb/legal:/shares/legal:ro
logging:
driver: json-file
options:
max-size: "50m"
max-file: "6"

View file

@ -0,0 +1,4 @@
requests==2.32.3
pypdf==5.1.0
python-docx==1.1.2
openpyxl==3.1.5