"""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.
"""
from __future__ import annotations
import abc
import asyncio
import enum
import re
from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING, Any, ClassVar, Literal
from pydantic import BaseModel
if TYPE_CHECKING:
from s365b.graph.client import GraphClient
[docs]
MODULE_ID_RE = re.compile(r"^[a-z][a-z0-9_]{1,31}$")
[docs]
class ModuleError(Exception):
"""Base class for errors raised by modules."""
[docs]
class NotSupportedError(ModuleError):
"""Raised when a module does not support an operation (e.g. restore)."""
[docs]
class Severity(enum.StrEnum):
"""Severity of a notification event."""
[docs]
class EmptyConfig(BaseModel):
"""Config model for modules without settings."""
@dataclass(frozen=True, slots=True)
[docs]
class ProtectedObject:
"""Something a module can back up as a unit.
Attributes:
kind: Object type within the module, e.g. ``"mailbox"`` or ``"site"``.
external_id: Stable Microsoft 365 ID (user ID, site ID, …).
display_name: Name shown in the UI.
metadata: Extra details for selection rules and the UI, such as
``{"upn": "...", "groups": [...]}``.
"""
@dataclass(slots=True)
[docs]
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.
Attributes:
data: Module-defined state.
"""
[docs]
data: dict[str, Any] = field(default_factory=dict)
@dataclass(slots=True)
[docs]
class ItemVersion:
"""One new, changed or deleted item, yielded by :meth:`BackupModule.backup`.
Attributes:
item_key: Stable ID of the item within its protected object (e.g. a
message ID). Versions of the same item share the key.
item_type: Item type, one of the module's :meth:`BackupModule.item_types`.
name: Display name (subject, file name, object name).
path: Location within the object for browsing, e.g.
``"Inbox/Projects"``; empty for flat items.
modified_at: When the item last changed in Microsoft 365.
deleted: True if the item was deleted since the last run. Deleted
items carry no content.
metadata: Searchable/displayable fields (from, to, size, …).
content: Item content: bytes, or an async iterable of byte pieces for
large content that should be streamed. ``None`` for metadata-only
items.
"""
[docs]
modified_at: datetime | None = None
[docs]
content: bytes | AsyncIterable[bytes] | None = None
@dataclass(frozen=True, slots=True)
[docs]
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.
Attributes:
key: Metadata key identifying the group, e.g. ``"folder_id"``.
value: The group's value of that key.
path: New path for the items; ``None`` keeps their paths.
deleted: Mark the items deleted.
"""
[docs]
path: str | None = None
@dataclass(slots=True)
[docs]
class Checkpoint:
"""Marker meaning "everything yielded so far matches this state".
Attributes:
state: The sync state to save once preceding items are durable.
"""
@dataclass(frozen=True, slots=True)
[docs]
class Column:
"""A metadata column in the browse view.
Attributes:
key: Metadata key, e.g. ``"mail"``.
label: Column heading, e.g. ``"Primary email address"``.
format: How to show the value: ``text``, ``bool`` (a check or a
cross), ``datetime`` or ``list`` (comma-separated).
"""
@dataclass(frozen=True, slots=True)
[docs]
class ItemTypeInfo:
"""Describes an item type for the browse UI.
Attributes:
id: Item type ID, e.g. ``"message"``.
label: Human-readable label.
icon: Icon name used by the web UI.
columns: Metadata shown as columns when browsing. A plain string is
a text column headed by its key.
preview: Whether the UI can preview content of this type.
media_type: What the stored content is: ``application/json``
(shown and compared as JSON) or ``message/rfc822`` (an email,
shown as a message).
extension: File extension for downloads, without the dot.
exports: Export formats offered for items of this type, e.g.
``("ics",)``; see :meth:`BackupModule.export`.
"""
[docs]
columns: tuple[Column | str, ...] = ()
[docs]
extension: str = "json"
[docs]
exports: tuple[str, ...] = ()
@dataclass(frozen=True, slots=True)
[docs]
class EventType:
"""A module-specific notification event.
Attributes:
id: Event ID, unique within the module, e.g. ``"ca_policy_changed"``.
label: Human-readable name shown in notification settings.
default_severity: Severity used unless the admin changes it.
"""
[docs]
default_severity: Severity = Severity.INFO
@dataclass(slots=True)
[docs]
class HealthReport:
"""Result of :meth:`BackupModule.health_check`.
Attributes:
ok: True if the module can work.
messages: Human-readable findings.
missing_permissions: Required Graph permissions that are not granted.
details: Extra information (e.g. counts of discoverable objects).
"""
[docs]
messages: list[str] = field(default_factory=list)
[docs]
missing_permissions: set[str] = field(default_factory=set)
[docs]
details: dict[str, Any] = field(default_factory=dict)
@dataclass(frozen=True, slots=True)
@dataclass(frozen=True, slots=True)
[docs]
class StoredItem:
"""An item version selected for restore or export, as read from the catalog.
Attributes:
object: The protected object it belongs to.
version: The item version (content is loaded lazily via ``read``).
read: Call to stream the stored content.
extras: Names of the extra copies stored with it (see
:meth:`BackupModule.extra_copies`).
read_extra: Call with a copy's name to stream that copy.
size: Size of the stored content (what ``read`` streams) in bytes.
"""
[docs]
object: ProtectedObject
[docs]
read: Callable[[], AsyncIterator[bytes]]
@dataclass(frozen=True, slots=True)
[docs]
class RestoreRequest:
"""What to restore and where.
Attributes:
items: Items to restore.
target: Where to restore to; ``None`` means the original location.
Its meaning is module-specific (e.g. another mailbox ID).
options: Module-specific options (e.g. restore folder name,
overwrite policy).
"""
[docs]
items: list[StoredItem]
[docs]
target: ProtectedObject | None = None
[docs]
options: dict[str, Any] = field(default_factory=dict)
@dataclass(slots=True)
[docs]
class RestoreResult:
"""Outcome of a restore.
Attributes:
restored: Number of items written.
skipped: Number of items skipped (e.g. already present).
failed: Number of items that could not be written.
errors: Error messages, one per failed item (the first ones).
folders_created: Folders the restore created, by path.
"""
[docs]
errors: list[str] = field(default_factory=list)
[docs]
folders_created: list[str] = field(default_factory=list)
[docs]
def fail(self, message: str, limit: int = 100) -> None:
"""Count a failed item and keep its message (up to ``limit``)."""
self.failed += 1
if len(self.errors) < limit:
self.errors.append(message)
@dataclass(frozen=True, slots=True)
[docs]
class ExportRequest:
"""What to export and in which format.
Attributes:
items: Items to export.
format: Format ID, one of the module's :meth:`BackupModule.export_formats`.
options: Module-specific options.
"""
[docs]
items: list[StoredItem]
[docs]
options: dict[str, Any] = field(default_factory=dict)
@dataclass(slots=True)
[docs]
class ExportFile:
"""One file produced by an export.
Attributes:
path: Path inside the export archive.
content: File content.
"""
[docs]
content: bytes | AsyncIterable[bytes]
@dataclass(slots=True)
[docs]
class ModuleContext:
"""Everything a module may use while running.
Attributes:
tenant_id: Entra tenant ID being backed up.
config: The module's settings (an instance of its ``config_model``).
graph: Graph client authenticated for the current job (backup or
restore app).
log: Structured logger bound with job and module fields.
cancel: Set when the job is cancelled; long loops should check it.
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).
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.
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.
"""
[docs]
graph: GraphClient
[docs]
cancel: asyncio.Event = field(default_factory=asyncio.Event)
[docs]
progress: Callable[..., None] = lambda **_: None
[docs]
reader: GraphClient | None = None
[docs]
current_items: Callable[[str, str], Awaitable[dict[str, dict[str, Any]]]] | None = None
[docs]
def check_cancelled(self) -> None:
"""Raise :class:`asyncio.CancelledError` if the job was cancelled.
Raises:
asyncio.CancelledError: If cancellation was requested.
"""
if self.cancel.is_set():
raise asyncio.CancelledError("job cancelled")
[docs]
class BackupModule(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.
Attributes:
id: Module ID, lowercase, e.g. ``"exchange"``. Must equal the entry
point name it is registered under.
display_name: Name shown in the UI.
description: One-line description shown in the UI.
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.
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.
object_noun: Singular and plural name of its protected objects in
the UI, e.g. ``("mailbox", "mailboxes")``.
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.
"""
[docs]
display_name: ClassVar[str]
[docs]
description: ClassVar[str] = ""
[docs]
version: ClassVar[str] = "0.0.0"
[docs]
config_model: ClassVar[type[BaseModel]] = EmptyConfig
[docs]
object_noun: ClassVar[tuple[str, str]] = ("object", "objects")
[docs]
parallel_objects: ClassVar[int] = 1
@abc.abstractmethod
[docs]
def required_permissions(self, config: BaseModel, *, restore: bool) -> set[str]:
"""Return the Microsoft Graph application permissions needed.
Args:
config: The module's settings.
restore: True for the restore app's permissions, False for the
backup app's (read-only) permissions.
Returns:
Permission names, e.g. ``{"Mail.Read"}``.
"""
[docs]
def optional_permissions(self, config: 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).
Args:
config: The module's settings.
Returns:
A subset of the backup permissions; empty by default.
"""
return set()
@abc.abstractmethod
[docs]
def discover(self, ctx: ModuleContext) -> AsyncIterator[ProtectedObject]:
"""List the objects this module can protect.
Args:
ctx: Module context.
Returns:
Async iterator of protected objects.
"""
@abc.abstractmethod
[docs]
def backup(
self, ctx: ModuleContext, obj: ProtectedObject, state: SyncState
) -> AsyncIterator[ItemVersion | GroupChange | Checkpoint]:
"""Back up one protected object incrementally.
Args:
ctx: Module context.
obj: The object to back up.
state: State saved at the last checkpoint (empty on first run).
Returns:
Async iterator of item versions, group changes and checkpoints.
"""
@abc.abstractmethod
[docs]
def item_types(self) -> list[ItemTypeInfo]:
"""Describe this module's item types for the browse UI.
Returns:
Item type descriptions.
"""
[docs]
async def estimate(
self, ctx: ModuleContext, obj: ProtectedObject, state: SyncState
) -> int | None:
"""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.
Args:
ctx: Module context.
obj: The object about to be backed up.
state: Its saved state.
Returns:
The expected number of items, or ``None`` if unknown.
"""
return None
[docs]
def state_for_new_repository(self, 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.
Args:
state: The state saved by the backup into the other repository.
Returns:
The state to start from; empty by default (a first backup).
"""
return SyncState()
@classmethod
[docs]
def supports_restore(cls) -> bool:
"""Whether the module implements :meth:`restore`."""
return cls.restore is not BackupModule.restore
[docs]
async def restore(self, ctx: ModuleContext, request: RestoreRequest) -> RestoreResult:
"""Write items back to Microsoft 365.
Args:
ctx: Module context (with the restore app's Graph client).
request: What to restore and where.
Returns:
The outcome.
Raises:
NotSupportedError: If the module cannot restore.
"""
raise NotSupportedError(f"{self.id} does not support restore")
[docs]
def export(self, config: BaseModel, request: ExportRequest) -> AsyncIterator[ExportFile]:
"""Produce portable files from backed-up items.
Export works from what is stored only: no Microsoft 365 access.
Args:
config: The module's settings.
request: What to export and in which format.
Returns:
Async iterator of export files.
Raises:
NotSupportedError: If the format is not supported.
"""
raise NotSupportedError(f"{self.id} does not support export to {request.format}")
[docs]
def event_types(self) -> list[EventType]:
"""Return module-specific notification events.
Returns:
Event types; empty by default.
"""
return []
[docs]
def change_event(self, 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.
Args:
item_type: The item's type.
change: ``new``, ``changed`` or ``deleted``.
version: The new version (content not loaded).
Returns:
One of the IDs from :meth:`event_types`, or ``None``.
"""
return None
[docs]
async def health_check(self, ctx: ModuleContext) -> HealthReport:
"""Check that the module can work (permissions, connectivity).
The default implementation reports healthy; modules should override
it to try a cheap read.
Args:
ctx: Module context.
Returns:
The health report.
"""
return HealthReport(ok=True)