s365b.modules.sdk ================= .. py:module:: s365b.modules.sdk .. autoapi-nested-parse:: The module contract: what every backup module implements. The core calls modules only through :class:`BackupModule`. A module never opens database connections or storage handles itself; everything it may use is passed in a :class:`ModuleContext`. Backup flow, from a module's point of view: 1. :meth:`BackupModule.discover` lists what can be protected (:class:`ProtectedObject`: a mailbox, a drive, the tenant directory…). 2. For each selected object the core calls :meth:`BackupModule.backup` with the object's saved :class:`SyncState`. The module yields :class:`ItemVersion` records for new, changed and deleted items, :class:`GroupChange` records for renamed or removed containers, and :class:`Checkpoint` markers. 3. At each :class:`Checkpoint` the core makes everything yielded so far durable (repository flush + catalog commit) and saves the checkpoint's state. After a crash the next run resumes from the last checkpoint, so a module should checkpoint after each folder/page it finishes. Attributes ---------- .. autoapisummary:: s365b.modules.sdk.MODULE_ID_RE Exceptions ---------- .. autoapisummary:: s365b.modules.sdk.ModuleError s365b.modules.sdk.NotSupportedError Classes ------- .. autoapisummary:: s365b.modules.sdk.Severity s365b.modules.sdk.EmptyConfig s365b.modules.sdk.ProtectedObject s365b.modules.sdk.SyncState s365b.modules.sdk.ItemVersion s365b.modules.sdk.GroupChange s365b.modules.sdk.Checkpoint s365b.modules.sdk.Column s365b.modules.sdk.ItemTypeInfo s365b.modules.sdk.EventType s365b.modules.sdk.HealthReport s365b.modules.sdk.ExtraWanted s365b.modules.sdk.StoredItem s365b.modules.sdk.RestoreRequest s365b.modules.sdk.RestoreResult s365b.modules.sdk.ExportRequest s365b.modules.sdk.ExportFile s365b.modules.sdk.ModuleContext s365b.modules.sdk.BackupModule Module Contents --------------- .. py:data:: MODULE_ID_RE .. py:exception:: ModuleError Bases: :py:obj:`Exception` Base class for errors raised by modules. .. py:exception:: NotSupportedError Bases: :py:obj:`ModuleError` Raised when a module does not support an operation (e.g. restore). .. py:class:: Severity Bases: :py:obj:`enum.StrEnum` Severity of a notification event. .. py:attribute:: INFO :value: 'info' .. py:attribute:: WARNING :value: 'warning' .. py:attribute:: ERROR :value: 'error' .. py:class:: EmptyConfig Bases: :py:obj:`pydantic.BaseModel` Config model for modules without settings. .. py:class:: ProtectedObject Something a module can back up as a unit. :ivar kind: Object type within the module, e.g. ``"mailbox"`` or ``"site"``. :ivar external_id: Stable Microsoft 365 ID (user ID, site ID, …). :ivar display_name: Name shown in the UI. :ivar metadata: Extra details for selection rules and the UI, such as ``{"upn": "...", "groups": [...]}``. .. py:attribute:: kind :type: str .. py:attribute:: external_id :type: str .. py:attribute:: display_name :type: str .. py:attribute:: metadata :type: dict[str, Any] .. py:class:: SyncState Per-object state a module keeps between runs (e.g. delta links). The content of :attr:`data` is private to the module and must be JSON-serialisable. :ivar data: Module-defined state. .. py:attribute:: data :type: dict[str, Any] .. py:class:: ItemVersion One new, changed or deleted item, yielded by :meth:`BackupModule.backup`. :ivar item_key: Stable ID of the item within its protected object (e.g. a message ID). Versions of the same item share the key. :ivar item_type: Item type, one of the module's :meth:`BackupModule.item_types`. :ivar name: Display name (subject, file name, object name). :ivar path: Location within the object for browsing, e.g. ``"Inbox/Projects"``; empty for flat items. :ivar modified_at: When the item last changed in Microsoft 365. :ivar deleted: True if the item was deleted since the last run. Deleted items carry no content. :ivar metadata: Searchable/displayable fields (from, to, size, …). :ivar content: Item content: bytes, or an async iterable of byte pieces for large content that should be streamed. ``None`` for metadata-only items. .. py:attribute:: item_key :type: str .. py:attribute:: item_type :type: str .. py:attribute:: name :type: str .. py:attribute:: path :type: str :value: '' .. py:attribute:: modified_at :type: datetime.datetime | None :value: None .. py:attribute:: deleted :type: bool :value: False .. py:attribute:: metadata :type: dict[str, Any] .. py:attribute:: content :type: bytes | collections.abc.AsyncIterable[bytes] | None :value: None .. py:class:: GroupChange A change to every current item in a group, such as a mail folder. For when a container is renamed, moved or removed and the module cannot list the items that were in it. It applies to every current (not deleted) item of the protected object whose ``metadata[key]`` equals ``value``: each gets a new version with the new path (same content), or a deletion marker. :ivar key: Metadata key identifying the group, e.g. ``"folder_id"``. :ivar value: The group's value of that key. :ivar path: New path for the items; ``None`` keeps their paths. :ivar deleted: Mark the items deleted. .. py:attribute:: key :type: str .. py:attribute:: value :type: str .. py:attribute:: path :type: str | None :value: None .. py:attribute:: deleted :type: bool :value: False .. py:class:: Checkpoint Marker meaning "everything yielded so far matches this state". :ivar state: The sync state to save once preceding items are durable. .. py:attribute:: state :type: SyncState .. py:class:: Column A metadata column in the browse view. :ivar key: Metadata key, e.g. ``"mail"``. :ivar label: Column heading, e.g. ``"Primary email address"``. :ivar format: How to show the value: ``text``, ``bool`` (a check or a cross), ``datetime`` or ``list`` (comma-separated). .. py:attribute:: key :type: str .. py:attribute:: label :type: str .. py:attribute:: format :type: Literal['text', 'bool', 'datetime', 'list'] :value: 'text' .. py:class:: ItemTypeInfo Describes an item type for the browse UI. :ivar id: Item type ID, e.g. ``"message"``. :ivar label: Human-readable label. :ivar icon: Icon name used by the web UI. :ivar columns: Metadata shown as columns when browsing. A plain string is a text column headed by its key. :ivar preview: Whether the UI can preview content of this type. :ivar media_type: What the stored content is: ``application/json`` (shown and compared as JSON) or ``message/rfc822`` (an email, shown as a message). :ivar extension: File extension for downloads, without the dot. :ivar exports: Export formats offered for items of this type, e.g. ``("ics",)``; see :meth:`BackupModule.export`. .. py:attribute:: id :type: str .. py:attribute:: label :type: str .. py:attribute:: icon :type: str :value: 'file' .. py:attribute:: columns :type: tuple[Column | str, ...] :value: () .. py:attribute:: preview :type: bool :value: False .. py:attribute:: media_type :type: str :value: 'application/json' .. py:attribute:: extension :type: str :value: 'json' .. py:attribute:: exports :type: tuple[str, ...] :value: () .. py:class:: EventType A module-specific notification event. :ivar id: Event ID, unique within the module, e.g. ``"ca_policy_changed"``. :ivar label: Human-readable name shown in notification settings. :ivar default_severity: Severity used unless the admin changes it. .. py:attribute:: id :type: str .. py:attribute:: label :type: str .. py:attribute:: default_severity :type: Severity .. py:class:: HealthReport Result of :meth:`BackupModule.health_check`. :ivar ok: True if the module can work. :ivar messages: Human-readable findings. :ivar missing_permissions: Required Graph permissions that are not granted. :ivar details: Extra information (e.g. counts of discoverable objects). .. py:attribute:: ok :type: bool .. py:attribute:: messages :type: list[str] :value: [] .. py:attribute:: missing_permissions :type: set[str] .. py:attribute:: details :type: dict[str, Any] .. py:class:: ExtraWanted An item that needs an extra copy (see :meth:`BackupModule.extra_copies`). :ivar item_key: The item's key. :ivar size: Size of its stored content in bytes, to batch requests. :ivar change_key: The stored version's ``change_key`` metadata, if it has one, so a module can tell whether the copy it gets is of the same version. .. py:attribute:: item_key :type: str .. py:attribute:: size :type: int .. py:attribute:: change_key :type: str | None :value: None .. py:class:: StoredItem An item version selected for restore or export, as read from the catalog. :ivar object: The protected object it belongs to. :ivar version: The item version (content is loaded lazily via ``read``). :ivar read: Call to stream the stored content. :ivar extras: Names of the extra copies stored with it (see :meth:`BackupModule.extra_copies`). :ivar read_extra: Call with a copy's name to stream that copy. :ivar size: Size of the stored content (what ``read`` streams) in bytes. .. py:attribute:: object :type: ProtectedObject .. py:attribute:: version :type: ItemVersion .. py:attribute:: read :type: collections.abc.Callable[[], collections.abc.AsyncIterator[bytes]] .. py:attribute:: extras :type: frozenset[str] .. py:attribute:: read_extra :type: collections.abc.Callable[[str], collections.abc.AsyncIterator[bytes]] | None :value: None .. py:attribute:: size :type: int :value: 0 .. py:class:: RestoreRequest What to restore and where. :ivar items: Items to restore. :ivar target: Where to restore to; ``None`` means the original location. Its meaning is module-specific (e.g. another mailbox ID). :ivar options: Module-specific options (e.g. restore folder name, overwrite policy). .. py:attribute:: items :type: list[StoredItem] .. py:attribute:: target :type: ProtectedObject | None :value: None .. py:attribute:: options :type: dict[str, Any] .. py:class:: RestoreResult Outcome of a restore. :ivar restored: Number of items written. :ivar skipped: Number of items skipped (e.g. already present). :ivar failed: Number of items that could not be written. :ivar errors: Error messages, one per failed item (the first ones). :ivar folders_created: Folders the restore created, by path. .. py:attribute:: restored :type: int :value: 0 .. py:attribute:: skipped :type: int :value: 0 .. py:attribute:: failed :type: int :value: 0 .. py:attribute:: errors :type: list[str] :value: [] .. py:attribute:: folders_created :type: list[str] :value: [] .. py:method:: fail(message: str, limit: int = 100) -> None Count a failed item and keep its message (up to ``limit``). .. py:class:: ExportRequest What to export and in which format. :ivar items: Items to export. :ivar format: Format ID, one of the module's :meth:`BackupModule.export_formats`. :ivar options: Module-specific options. .. py:attribute:: items :type: list[StoredItem] .. py:attribute:: format :type: str .. py:attribute:: options :type: dict[str, Any] .. py:class:: ExportFile One file produced by an export. :ivar path: Path inside the export archive. :ivar content: File content. .. py:attribute:: path :type: str .. py:attribute:: content :type: bytes | collections.abc.AsyncIterable[bytes] .. py:class:: ModuleContext Everything a module may use while running. :ivar tenant_id: Entra tenant ID being backed up. :ivar config: The module's settings (an instance of its ``config_model``). :ivar graph: Graph client authenticated for the current job (backup or restore app). :ivar log: Structured logger bound with job and module fields. :ivar cancel: Set when the job is cancelled; long loops should check it. :ivar progress: Callback to report progress within the current object, e.g. ``progress(done=10, total=200, message="Inbox", unit="items")``. ``total`` may be ``None`` when unknown; ``unit`` names what ``done`` counts (default: steps). :ivar reader: During a restore, a client authenticated as the Backup app, for reads the Restore app has no permission for (e.g. whether a message is still in the mailbox). ``None`` otherwise. :ivar current_items: During a backup, returns the object's current (not deleted) items whose metadata field equals a value, as the catalog has them, by item key with their metadata: ``await current_items("folder_id", fid)``. For comparing a full listing with what is stored. An item whose current version is in another repository than the backup's comes with empty metadata (see :meth:`BackupModule.state_for_new_repository`). ``None`` otherwise. .. py:attribute:: tenant_id :type: str .. py:attribute:: config :type: pydantic.BaseModel .. py:attribute:: graph :type: s365b.graph.client.GraphClient .. py:attribute:: log :type: Any .. py:attribute:: cancel :type: asyncio.Event .. py:attribute:: progress :type: collections.abc.Callable[..., None] .. py:attribute:: reader :type: s365b.graph.client.GraphClient | None :value: None .. py:attribute:: current_items :type: collections.abc.Callable[[str, str], collections.abc.Awaitable[dict[str, dict[str, Any]]]] | None :value: None .. py:method:: check_cancelled() -> None Raise :class:`asyncio.CancelledError` if the job was cancelled. :raises asyncio.CancelledError: If cancellation was requested. .. py:class:: BackupModule Bases: :py:obj:`abc.ABC` Base class for a backup workload such as Exchange or Entra ID. Subclasses set the class attributes and implement :meth:`discover`, :meth:`backup`, :meth:`item_types` and :meth:`required_permissions`. Restore, export, events and health checks have defaults. :ivar id: Module ID, lowercase, e.g. ``"exchange"``. Must equal the entry point name it is registered under. :ivar display_name: Name shown in the UI. :ivar description: One-line description shown in the UI. :ivar version: Module version, recorded with every backup it makes. Bump it when the stored form of items changes: the first run with a new version stores the new form without change alerts. :ivar config_model: Pydantic model of the module's settings; it must be constructible with no arguments (all fields have defaults). The UI renders it as a form. :ivar object_noun: Singular and plural name of its protected objects in the UI, e.g. ``("mailbox", "mailboxes")``. :ivar parallel_objects: How many protected objects a job backs up at the same time. Raise it when Microsoft throttles per object (Exchange limits each mailbox separately), not per tenant. .. py:attribute:: id :type: ClassVar[str] .. py:attribute:: display_name :type: ClassVar[str] .. py:attribute:: description :type: ClassVar[str] :value: '' .. py:attribute:: version :type: ClassVar[str] :value: '0.0.0' .. py:attribute:: config_model :type: ClassVar[type[pydantic.BaseModel]] .. py:attribute:: object_noun :type: ClassVar[tuple[str, str]] :value: ('object', 'objects') .. py:attribute:: parallel_objects :type: ClassVar[int] :value: 1 .. py:method:: required_permissions(config: pydantic.BaseModel, *, restore: bool) -> set[str] :abstractmethod: Return the Microsoft Graph application permissions needed. :param config: The module's settings. :param restore: True for the restore app's permissions, False for the backup app's (read-only) permissions. :returns: Permission names, e.g. ``{"Mail.Read"}``. .. py:method:: optional_permissions(config: pydantic.BaseModel) -> set[str] Name the backup permissions a backup can run without. They are still requested when the tenant's permissions are updated, but a backup job does not refuse to start without them; the module does less instead (e.g. keeps no restore copies). :param config: The module's settings. :returns: A subset of the backup permissions; empty by default. .. py:method:: discover(ctx: ModuleContext) -> collections.abc.AsyncIterator[ProtectedObject] :abstractmethod: List the objects this module can protect. :param ctx: Module context. :returns: Async iterator of protected objects. .. py:method:: backup(ctx: ModuleContext, obj: ProtectedObject, state: SyncState) -> collections.abc.AsyncIterator[ItemVersion | GroupChange | Checkpoint] :abstractmethod: Back up one protected object incrementally. :param ctx: Module context. :param obj: The object to back up. :param state: State saved at the last checkpoint (empty on first run). :returns: Async iterator of item versions, group changes and checkpoints. .. py:method:: item_types() -> list[ItemTypeInfo] :abstractmethod: Describe this module's item types for the browse UI. :returns: Item type descriptions. .. py:method:: estimate(ctx: ModuleContext, obj: ProtectedObject, state: SyncState) -> int | None :async: Estimate how many items the next backup of an object will process. Used for progress and the time-left estimate; it should be cheap (a few requests). The count is in the same unit as the items the backup yields. :param ctx: Module context. :param obj: The object about to be backed up. :param state: Its saved state. :returns: The expected number of items, or ``None`` if unknown. .. py:method:: state_for_new_repository(state: SyncState) -> SyncState Return the state to back up an object into another repository from. A backup that goes to a different repository than the object's last one must yield every current item again: the catalog stores each in the new repository, even if unchanged, so that repository alone holds the object. Keep only what finds deletions and renames; drop anything that skips items, such as delta tokens. :attr:`ModuleContext.current_items` returns items whose current version is in another repository without their metadata, so comparisons with it re-read them. :param state: The state saved by the backup into the other repository. :returns: The state to start from; empty by default (a first backup). .. py:method:: extra_copies(config: pydantic.BaseModel) -> tuple[str, ...] Name the extra copies kept of each item, besides its content. An extra copy is another form of the same item that a restore needs, such as Exchange's own export of a message. After each object's backup the core asks :meth:`fetch_extras` for every current item that lacks one, so items backed up before a copy existed get it too. :param config: Module settings. :returns: Copy names, e.g. ``("fts",)``; empty by default. .. py:method:: extra_label(name: str) -> str Progress text while fetching an extra copy. :param name: Copy name. :returns: Text shown as the current step. .. py:method:: fetch_extras(ctx: ModuleContext, obj: ProtectedObject, name: str, items: list[ExtraWanted]) -> collections.abc.AsyncIterator[tuple[str, bytes]] Fetch one kind of extra copy for some items. Items that are gone or fail are left out; they are asked for again after the next backup. Raise to stop for this object (for example when a permission is missing); the backup itself still succeeds. :param ctx: Module context. :param obj: The protected object. :param name: Copy name, one of :meth:`extra_copies`. :param items: Items to fetch it for. :returns: Async iterator of ``(item_key, data)``. :raises NotSupportedError: If the module keeps no extra copies. .. py:method:: supports_restore() -> bool :classmethod: Whether the module implements :meth:`restore`. .. py:method:: restore(ctx: ModuleContext, request: RestoreRequest) -> RestoreResult :async: Write items back to Microsoft 365. :param ctx: Module context (with the restore app's Graph client). :param request: What to restore and where. :returns: The outcome. :raises NotSupportedError: If the module cannot restore. .. py:method:: export_formats() -> list[str] Return the export formats this module offers (e.g. ``["eml"]``). :returns: Format IDs, by default those of its item types; empty if export is not supported. .. py:method:: export(config: pydantic.BaseModel, request: ExportRequest) -> collections.abc.AsyncIterator[ExportFile] Produce portable files from backed-up items. Export works from what is stored only: no Microsoft 365 access. :param config: The module's settings. :param request: What to export and in which format. :returns: Async iterator of export files. :raises NotSupportedError: If the format is not supported. .. py:method:: event_types() -> list[EventType] Return module-specific notification events. :returns: Event types; empty by default. .. py:method:: change_event(item_type: str, change: str, version: ItemVersion) -> str | None Classify a change found by a backup as an alert, or ignore it. Called for each item that was added, changed or deleted in an object that already had a backup (never for a first backup, where everything is new). Changes with the same event ID in one job run are sent as a single alert listing the items. :param item_type: The item's type. :param change: ``new``, ``changed`` or ``deleted``. :param version: The new version (content not loaded). :returns: One of the IDs from :meth:`event_types`, or ``None``. .. py:method:: health_check(ctx: ModuleContext) -> HealthReport :async: Check that the module can work (permissions, connectivity). The default implementation reports healthy; modules should override it to try a cheap read. :param ctx: Module context. :returns: The health report.