Index only files whose modified date is within an optional range, set per SMB source. Both bounds are optional: SMB_SOURCE_<N>_MODIFIED_AFTER=2024-01-01 (inclusive) SMB_SOURCE_<N>_MODIFIED_BEFORE=2025-01-01 (exclusive) Set both for a range, only AFTER for everything newer, only BEFORE for everything older, neither for no filter. Also JSON keys modified_after / modified_before, and SMB_DEFAULT_MODIFIED_AFTER/_BEFORE fallbacks. Dates are read as UTC so the filter is reproducible across hosts. A file outside the range is skipped during the walk, so it is excluded from `seen` and the reconcile pass removes it from Onyx — narrowing the range prunes out-of-range documents. Verified with unit + end-to-end tests (in-range only, widening adds, narrowing deletes).
240 lines
No EOL
9.7 KiB
Python
240 lines
No EOL
9.7 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
|
|
from datetime import datetime, timezone
|
|
|
|
|
|
@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
|
|
# Onyx user-group ids that may access this connector. When set, the connector
|
|
# is created PRIVATE and restricted to these groups; empty means PUBLIC.
|
|
# Applied only when the connector is first provisioned (not on later runs).
|
|
# Group permissions need the Onyx Business licence.
|
|
group_ids: list[int] = field(default_factory=list)
|
|
# Optional modified-date filter (POSIX timestamps). Only files whose mtime is
|
|
# within [modified_after, modified_before] are indexed. Either bound may be
|
|
# None: after-only indexes everything newer than the start, before-only
|
|
# everything older than the end, neither means no date filter. A file that
|
|
# falls outside the range is treated as absent (removed from Onyx if it was
|
|
# indexed before), so narrowing the range prunes out-of-range documents.
|
|
modified_after: float | None = None
|
|
modified_before: float | 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
|
|
filename_encoding: str = "cp1252"
|
|
connector_name_prefix: str = "AIDO SMB"
|
|
http_timeout: int = 60
|
|
# Write one table-of-contents (index) document per source, listing every
|
|
# file on the share so the assistant is aware of the full document set.
|
|
write_index: bool = True
|
|
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 _parse_group_ids(value) -> list[int]:
|
|
"""Accept a JSON list, a comma-separated string, or a single id."""
|
|
if value is None or value == "":
|
|
return []
|
|
if isinstance(value, (list, tuple)):
|
|
items = value
|
|
else:
|
|
items = str(value).split(",")
|
|
out: list[int] = []
|
|
for item in items:
|
|
s = str(item).strip()
|
|
if not s:
|
|
continue
|
|
try:
|
|
out.append(int(s))
|
|
except ValueError as exc:
|
|
raise SystemExit(f"Invalid Onyx group id '{s}': {exc}") from exc
|
|
return out
|
|
|
|
|
|
def _parse_date(value) -> float | None:
|
|
"""Parse a YYYY-MM-DD (or ISO 8601) date to a POSIX timestamp. None if empty.
|
|
A naive value is read as UTC, so the filter is reproducible across hosts."""
|
|
if value is None:
|
|
return None
|
|
s = str(value).strip()
|
|
if not s:
|
|
return None
|
|
try:
|
|
dt = datetime.fromisoformat(s)
|
|
except ValueError as exc:
|
|
raise SystemExit(f"Invalid date '{s}' (use YYYY-MM-DD): {exc}") from exc
|
|
if dt.tzinfo is None:
|
|
dt = dt.replace(tzinfo=timezone.utc)
|
|
return dt.timestamp()
|
|
|
|
|
|
def _load_sources() -> list[SourceConfig]:
|
|
default_groups = _parse_group_ids(os.environ.get("SMB_DEFAULT_GROUP_IDS"))
|
|
default_after = _parse_date(os.environ.get("SMB_DEFAULT_MODIFIED_AFTER"))
|
|
default_before = _parse_date(os.environ.get("SMB_DEFAULT_MODIFIED_BEFORE"))
|
|
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),
|
|
group_ids=_parse_group_ids(item.get("groups")) or default_groups,
|
|
modified_after=(
|
|
_parse_date(item.get("modified_after"))
|
|
if item.get("modified_after")
|
|
else default_after
|
|
),
|
|
modified_before=(
|
|
_parse_date(item.get("modified_before"))
|
|
if item.get("modified_before")
|
|
else default_before
|
|
),
|
|
)
|
|
)
|
|
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")
|
|
ma = os.environ.get(f"SMB_SOURCE_{i}_MODIFIED_AFTER")
|
|
mb = os.environ.get(f"SMB_SOURCE_{i}_MODIFIED_BEFORE")
|
|
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,
|
|
group_ids=_parse_group_ids(os.environ.get(f"SMB_SOURCE_{i}_GROUPS"))
|
|
or default_groups,
|
|
modified_after=_parse_date(ma) if ma else default_after,
|
|
modified_before=_parse_date(mb) if mb else default_before,
|
|
)
|
|
)
|
|
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
|
|
),
|
|
group_ids=_parse_group_ids(os.environ.get("SMB_GROUPS")) or default_groups,
|
|
modified_after=_parse_date(os.environ.get("SMB_MODIFIED_AFTER"))
|
|
or default_after,
|
|
modified_before=_parse_date(os.environ.get("SMB_MODIFIED_BEFORE"))
|
|
or default_before,
|
|
)
|
|
)
|
|
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(),
|
|
# Codepage used to recover filenames whose bytes aren't valid UTF-8 (common
|
|
# on Windows/Latin-1 shares, e.g. 0xE4 = ä). cp1252 covers Western European.
|
|
filename_encoding=os.environ.get("SMB_FILENAME_ENCODING", "cp1252"),
|
|
# Prefix for the auto-created Onyx connector names ("<prefix> - <source>").
|
|
connector_name_prefix=os.environ.get("ONYX_CONNECTOR_NAME_PREFIX", "AIDO SMB"),
|
|
# HTTP timeout for Onyx API calls; raise it for large embeddings/ingests.
|
|
http_timeout=int(os.environ.get("ONYX_HTTP_TIMEOUT", "60")),
|
|
# Write a per-source index (table-of-contents) document. Set to 0/false to disable.
|
|
write_index=os.environ.get("SMB_WRITE_INDEX", "1").strip().lower()
|
|
not in ("0", "false", "no", "off"),
|
|
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 |