Skip to content

Index

files

The files memory backend: journaled, custody-checked scope-tree memory on disk.

Classes

FilesBackend

FilesBackend(config)

memory-backend/1.1 over Markdown tier files; see the module docstring.

Source code in src/marianne/memory/backends/files/backend.py
def __init__(self, config: Mapping[str, Any]) -> None:
    try:
        cfg = FilesBackendConfig.model_validate(dict(config))
    except ValidationError as exc:
        detail = "; ".join(
            f"{'.'.join(str(p) for p in e['loc']) or 'config'}: {e['msg']}"
            for e in exc.errors()
        )
        raise files_error(
            "config_invalid", detail, remedy="fix the attachment configuration",
        ) from None
    if cfg.registry_root:
        raise files_error(
            "config_invalid", "registry persons are not supported in wave A",
            remedy="leave registry_root empty",
        )
    if cfg.legacy != "sectioned":
        raise files_error(
            "config_invalid", "only legacy=sectioned is built in wave A",
            remedy="use legacy: sectioned",
        )
    self._cfg = cfg
    self._scope = cfg.scope
    self._tree = Path(cfg.memory_tree)
    self._attach = Path(cfg.attachment_dir)
    key = hashlib.sha256(cfg.memory_tree.encode("utf-8")).hexdigest()[:16]
    self._state_dir = Path(cfg.state_root) / key
    self._failpoint: Callable[[str], None] | None = None
    self._closed = False
    with _TREES_LOCK:
        held = _TREES.get(cfg.memory_tree)
        if held is not None and held[0] != self._scope:
            raise files_error(
                "config_invalid",
                f"conflicting_scope_alias: tree {cfg.memory_tree} already serves "
                f"{held[0]!r}, not {self._scope!r}",
                remedy="give each scope its own tree",
            )
        _TREES[cfg.memory_tree] = (self._scope, (held[1] if held else 0) + 1)
Methods:
close
close()

Release this binding's claim on its tree (idempotent).

Source code in src/marianne/memory/backends/files/backend.py
def close(self) -> None:
    """Release this binding's claim on its tree (idempotent)."""
    if self._closed:
        return
    self._closed = True
    with _TREES_LOCK:
        held = _TREES.get(self._cfg.memory_tree)
        if held is not None:
            if held[1] <= 1:
                del _TREES[self._cfg.memory_tree]
            else:
                _TREES[self._cfg.memory_tree] = (held[0], held[1] - 1)
reconcile
reconcile(ctx, resolve_interrupted_journal=False)

Adopt the tiers as they are on disk (admin). Never rewrites a tier.

Source code in src/marianne/memory/backends/files/backend.py
def reconcile(
    self, ctx: RequestContext, resolve_interrupted_journal: bool = False,
) -> dict[str, Any]:
    """Adopt the tiers as they are on disk (admin). Never rewrites a tier."""
    self._guard(ctx, Permission.ADMIN)
    self._check_deadline(ctx)
    with self._storage(), self._locked(ctx, resolve=bool(resolve_interrupted_journal)):
        state = self._load_state()
        tiers = self._scan()
        adopted = sorted(
            name for name, t in tiers.items() if state["tiers"].get(name) != t.digest
        )
        state["tiers"] = {name: t.digest for name, t in tiers.items()}
        self._save_state(state)
        return {"adopted": adopted, "revision": int(state["revision"])}

FilesBackendConfig

Bases: BaseModel

One files-backend attachment, as the gateway hands it to the factory.

FilesLocation dataclass

FilesLocation(memory_tree, attachment_dir, state_root)

Where one scope's files live: the tier tree, its attachment dir, the state root.

Functions:

files_backend_factory

files_backend_factory(config)

Build a :class:FilesBackend from an attachment config. Does no I/O.

Source code in src/marianne/memory/backends/files/backend.py
def files_backend_factory(config: Mapping[str, Any]) -> FilesBackend:
    """Build a :class:`FilesBackend` from an attachment config. Does no I/O."""
    return FilesBackend(config)

resolve_files_location

resolve_files_location(scope, root=None)

Map a scope onto its scope-family tree under root.

project/demo -> <root>/project/demo; local:default -> <root>/local/default; organization/x -> <root>/org/x. Writer state for every tree lives under <root>/trees. A scope that would resolve outside root is refused (E3 scope_unknown). No I/O.

Source code in src/marianne/memory/backends/files/config.py
def resolve_files_location(scope: str, root: Path | str | None = None) -> FilesLocation:
    """Map a scope onto its scope-family tree under ``root``.

    ``project/demo`` -> ``<root>/project/demo``; ``local:default`` ->
    ``<root>/local/default``; ``organization/x`` -> ``<root>/org/x``. Writer
    state for every tree lives under ``<root>/trees``. A scope that would
    resolve outside ``root`` is refused (E3 ``scope_unknown``). No I/O.
    """
    try:
        key = parse_scope(scope)
    except ScopeRefused as exc:
        raise files_error("scope_unknown", exc.detail, remedy=exc.remedy) from None
    chosen = root if root is not None else default_files_root()
    base = os.path.normpath(os.path.abspath(os.fspath(chosen)))
    tree = os.path.normpath(os.path.join(base, key.family, key.ident))
    if os.path.dirname(os.path.dirname(tree)) != base:
        raise files_error(
            "scope_unknown",
            f"scope {key.canonical!r} resolves outside the memory root",
            remedy="use a scope id made of a-z 0-9 _ . - that is not a path",
        )
    return FilesLocation(
        memory_tree=tree,
        attachment_dir=tree,
        state_root=os.path.join(base, "trees"),
    )