Source code for s365b.modules.registry

"""Finding, loading and validating modules.

Modules register under the ``s365b.modules`` entry point group, e.g. in a
module package's ``pyproject.toml``::

    [project.entry-points."s365b.modules"]
    exchange = "s365b.modules.exchange:ExchangeModule"

Two layers decide whether a module runs:

* **Allowed** (this file): the ``S365B_MODULES`` allow-list. A module not on
  the list is never imported.
* **Enabled** (database, toggled in the UI): checked by the core before it
  schedules work. A module that is allowed but disabled is still loaded so
  its existing backups can be browsed and restored.
"""

from __future__ import annotations

from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from importlib.metadata import EntryPoint, entry_points

from pydantic import BaseModel, ValidationError

from s365b.core.logging import get_logger
from s365b.modules.sdk import MODULE_ID_RE, BackupModule

[docs] ENTRY_POINT_GROUP = "s365b.modules"
[docs] log = get_logger(__name__)
[docs] class RegistryError(Exception): """Raised when a module is invalid or cannot be found."""
@dataclass(frozen=True, slots=True)
[docs] class ModuleInfo: """Summary of a module for the API and UI. Attributes: id: Module ID. display_name: Name shown in the UI. description: One-line description. version: Module version. """
[docs] id: str
[docs] display_name: str
[docs] description: str
[docs] version: str
[docs] def validate_module_class(cls: type[BackupModule], expected_id: str | None = None) -> None: """Check that a class meets the module contract's static rules. Args: cls: The module class. expected_id: Entry point name it was registered under, if any. Raises: RegistryError: Describing the first problem found. """ if not (isinstance(cls, type) and issubclass(cls, BackupModule)): raise RegistryError(f"{cls!r} is not a BackupModule subclass") module_id = getattr(cls, "id", None) if not isinstance(module_id, str) or not MODULE_ID_RE.match(module_id): raise RegistryError(f"{cls.__name__}: invalid module id {module_id!r}") if expected_id is not None and module_id != expected_id: raise RegistryError(f"{cls.__name__}: id {module_id!r} != entry point {expected_id!r}") if not getattr(cls, "display_name", None): raise RegistryError(f"{module_id}: display_name is required") if not (isinstance(cls.config_model, type) and issubclass(cls.config_model, BaseModel)): raise RegistryError(f"{module_id}: config_model must be a pydantic model") try: cls.config_model() except ValidationError as exc: raise RegistryError(f"{module_id}: config_model needs defaults for all fields") from exc if getattr(cls, "__abstractmethods__", None): missing = ", ".join(sorted(cls.__abstractmethods__)) raise RegistryError(f"{module_id}: abstract methods not implemented: {missing}")
[docs] class ModuleRegistry: """The set of modules this process may use. Args: modules: Module classes, keyed by ID. """ def __init__(self, modules: dict[str, type[BackupModule]]) -> None: self._classes = dict(modules) self._instances: dict[str, BackupModule] = {} @classmethod
[docs] def from_entry_points(cls, allowed: Iterable[str] = ()) -> ModuleRegistry: """Load modules from installed entry points. Invalid modules are logged and skipped, so one broken third-party module cannot stop the whole application. Args: allowed: Allow-list of module IDs; empty allows all installed. Returns: The registry. """ allow = set(allowed) classes: dict[str, type[BackupModule]] = {} for ep in entry_points(group=ENTRY_POINT_GROUP): if allow and ep.name not in allow: log.info("module.skipped", module=ep.name, reason="not in S365B_MODULES") continue try: classes[ep.name] = _load(ep) except Exception as exc: log.error("module.invalid", module=ep.name, error=str(exc)) for missing in sorted(allow - classes.keys()): log.warning("module.not_installed", module=missing) return cls(classes)
@classmethod
[docs] def from_classes(cls, classes: Iterable[type[BackupModule]]) -> ModuleRegistry: """Build a registry from classes directly (tests, embedding). Args: classes: Module classes. Returns: The registry. Raises: RegistryError: If a class is invalid or IDs collide. """ result: dict[str, type[BackupModule]] = {} for c in classes: validate_module_class(c) if c.id in result: raise RegistryError(f"duplicate module id {c.id!r}") result[c.id] = c return cls(result)
[docs] def ids(self) -> list[str]: """Return the IDs of all loaded modules, sorted. Returns: Module IDs. """ return sorted(self._classes)
def __contains__(self, module_id: object) -> bool: return module_id in self._classes def __iter__(self) -> Iterator[BackupModule]: return (self.get(i) for i in self.ids())
[docs] def get(self, module_id: str) -> BackupModule: """Return the (shared) instance of a module. Args: module_id: Module ID. Returns: The module instance. Raises: RegistryError: If the module is not loaded. """ if module_id not in self._classes: raise RegistryError(f"module {module_id!r} is not installed or not allowed") if module_id not in self._instances: self._instances[module_id] = self._classes[module_id]() return self._instances[module_id]
[docs] def info(self, module_id: str) -> ModuleInfo: """Return a module's summary. Args: module_id: Module ID. Returns: The summary. """ c = self._classes[module_id] return ModuleInfo(c.id, c.display_name, c.description, c.version)
[docs] def parse_config(self, module_id: str, raw: dict[str, object] | None) -> BaseModel: """Validate stored settings against a module's config model. Args: module_id: Module ID. raw: Stored settings; ``None`` means defaults. Returns: The config model instance. """ return self._classes[module_id].config_model.model_validate(raw or {})
[docs] def required_permissions( self, enabled: dict[str, BaseModel], *, restore: bool ) -> dict[str, set[str]]: """Return the Graph permissions needed by the enabled modules. Args: enabled: Enabled module IDs mapped to their config. restore: Restore-app permissions instead of backup-app ones. Returns: Permission name mapped to the IDs of the modules that need it, so the UI can explain why each permission is requested. """ needed: dict[str, set[str]] = {} for module_id, config in enabled.items(): for perm in self.get(module_id).required_permissions(config, restore=restore): needed.setdefault(perm, set()).add(module_id) return needed
def _load(ep: EntryPoint) -> type[BackupModule]: cls = ep.load() validate_module_class(cls, expected_id=ep.name) return cls # type: ignore[no-any-return]