Add optional per-source modified-date filter

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).
This commit is contained in:
Jannic Debus 2026-11-16 15:19:54 +01:00
parent cc28ee9758
commit fba30fe8b4
3 changed files with 70 additions and 3 deletions

View file

@ -119,6 +119,8 @@ CIFS-mounted a second time — `_MOUNT` then just points at the bind-mounted pat
| `SMB_WRITE_INDEX` | Write a per-source index (table-of-contents) document listing every file, so the assistant is aware of the full set (default on; `0`/`false` to disable) |
| `SMB_SOURCE_<N>_GROUPS` | Onyx user-group ids (comma-separated) allowed to access this connector. Set → connector created **private** and restricted to those groups; empty → **public**. Applied only at connector creation. Needs the Onyx Business licence. In `SMB_SOURCES` JSON use `"groups": [id, …]`. |
| `SMB_DEFAULT_GROUP_IDS` | Fallback group ids for any source that has none set |
| `SMB_SOURCE_<N>_MODIFIED_AFTER` / `_MODIFIED_BEFORE` | Optional modified-date filter per source (`YYYY-MM-DD`). Only files whose modified date is in range are indexed. Both optional: set both for a range, only `_AFTER` for everything newer than that date, only `_BEFORE` for everything older. `_AFTER` is inclusive, `_BEFORE` is exclusive (dates read as UTC). In `SMB_SOURCES` JSON use `"modified_after"` / `"modified_before"`. A file that falls outside the range is removed from Onyx if it was indexed under an earlier range. |
| `SMB_DEFAULT_MODIFIED_AFTER` / `_BEFORE` | Fallback date filter for any source that sets none |
| `ONYX_NETWORK` | Standalone mode only: name of Onyx's Docker network (default `onyx_default`) |
State (manifest + cached key/cc_pair) lives in the mounted `/app/state` volume.
@ -144,4 +146,4 @@ State (manifest + cached key/cc_pair) lives in the mounted `/app/state` volume.
them, so update and delete reconcile reliably (verified end-to-end).
- **`smb://` links** can't open from a browser; the full network path is stored in
the document metadata, and the UI overlay copies it to the clipboard on click
(see `branding/smb/smb-ui.patch`).
(see `branding/smb/smb-ui.patch`).

View file

@ -27,6 +27,7 @@ from __future__ import annotations
import json
import os
from dataclasses import dataclass, field
from datetime import datetime, timezone
@dataclass
@ -42,6 +43,14 @@ class SourceConfig:
# 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.
@ -98,8 +107,27 @@ def _parse_group_ids(value) -> list[int]:
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:
@ -117,6 +145,16 @@ def _load_sources() -> list[SourceConfig]:
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
@ -130,6 +168,8 @@ def _load_sources() -> list[SourceConfig]:
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,
@ -138,6 +178,8 @@ def _load_sources() -> list[SourceConfig]:
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
@ -153,6 +195,10 @@ def _load_sources() -> list[SourceConfig]:
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
@ -191,4 +237,4 @@ def load_config() -> Config:
raise SystemExit(
"No SMB sources configured. Set SMB_SOURCES (JSON) or SMB_SOURCE_1_NAME/_MOUNT."
)
return cfg
return cfg

View file

@ -89,6 +89,17 @@ def _eligible(path: str, cfg: Config) -> bool:
return not os.path.basename(path).startswith(".")
def _within_date_range(mtime: float, source: SourceConfig) -> bool:
"""True if the file's modified time is inside the source's optional date
filter. Either bound may be None (open-ended). MODIFIED_BEFORE is exclusive
of the given day's start (``< start-of-day``); MODIFIED_AFTER is inclusive."""
if source.modified_after is not None and mtime < source.modified_after:
return False
if source.modified_before is not None and mtime >= source.modified_before:
return False
return True
def _build_document(
source: SourceConfig, rel_path: str, doc_id: str, text: str, mtime: float
) -> dict:
@ -192,6 +203,14 @@ def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: St
abspath = os.path.join(root, fname)
if not _eligible(abspath, cfg):
continue
# Optional per-source modified-date filter. A file outside the range
# is skipped here, so it is not added to `seen` and the reconcile pass
# removes it from Onyx if it was indexed under an earlier range.
try:
if not _within_date_range(os.path.getmtime(abspath), source):
continue
except OSError:
continue
rel = os.path.relpath(abspath, source.mount).replace(os.sep, "/")
# Normalise non-UTF-8 filenames (surrogate-escaped) so the id hash,
# the ingestion payload and the manifest are all UTF-8/JSON-safe.
@ -309,4 +328,4 @@ def sync_all(client: OnyxClient, cfg: Config, state: State) -> None:
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)
logger.exception("Source '%s' failed this cycle: %s", source.name, exc)