s365b.modules.sdk

The module contract: what every backup module implements.

The core calls modules only through BackupModule. A module never opens database connections or storage handles itself; everything it may use is passed in a ModuleContext.

Backup flow, from a module’s point of view:

  1. BackupModule.discover() lists what can be protected (ProtectedObject: a mailbox, a drive, the tenant directory…).

  2. For each selected object the core calls BackupModule.backup() with the object’s saved SyncState. The module yields ItemVersion records for new, changed and deleted items, GroupChange records for renamed or removed containers, and Checkpoint markers.

  3. At each 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

Exceptions

ModuleError

Base class for errors raised by modules.

NotSupportedError

Raised when a module does not support an operation (e.g. restore).

Classes

Severity

Severity of a notification event.

EmptyConfig

Config model for modules without settings.

ProtectedObject

Something a module can back up as a unit.

SyncState

Per-object state a module keeps between runs (e.g. delta links).

ItemVersion

One new, changed or deleted item, yielded by BackupModule.backup().

GroupChange

A change to every current item in a group, such as a mail folder.

Checkpoint

Marker meaning "everything yielded so far matches this state".

Column

A metadata column in the browse view.

ItemTypeInfo

Describes an item type for the browse UI.

EventType

A module-specific notification event.

HealthReport

Result of BackupModule.health_check().

ExtraWanted

An item that needs an extra copy (see BackupModule.extra_copies()).

StoredItem

An item version selected for restore or export, as read from the catalog.

RestoreRequest

What to restore and where.

RestoreResult

Outcome of a restore.

ExportRequest

What to export and in which format.

ExportFile

One file produced by an export.

ModuleContext

Everything a module may use while running.

BackupModule

Base class for a backup workload such as Exchange or Entra ID.

Module Contents

s365b.modules.sdk.MODULE_ID_RE[source]
exception s365b.modules.sdk.ModuleError[source]

Bases: Exception

Base class for errors raised by modules.

exception s365b.modules.sdk.NotSupportedError[source]

Bases: ModuleError

Raised when a module does not support an operation (e.g. restore).

class s365b.modules.sdk.Severity[source]

Bases: enum.StrEnum

Severity of a notification event.

INFO = 'info'[source]
WARNING = 'warning'[source]
ERROR = 'error'[source]
class s365b.modules.sdk.EmptyConfig[source]

Bases: pydantic.BaseModel

Config model for modules without settings.

class s365b.modules.sdk.ProtectedObject[source]

Something a module can back up as a unit.

Variables:
  • 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": [...]}.

kind: str[source]
external_id: str[source]
display_name: str[source]
metadata: dict[str, Any][source]
class s365b.modules.sdk.SyncState[source]

Per-object state a module keeps between runs (e.g. delta links).

The content of data is private to the module and must be JSON-serialisable.

Variables:

data – Module-defined state.

data: dict[str, Any][source]
class s365b.modules.sdk.ItemVersion[source]

One new, changed or deleted item, yielded by BackupModule.backup().

Variables:
  • 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 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.

item_key: str[source]
item_type: str[source]
name: str[source]
path: str = ''[source]
modified_at: datetime.datetime | None = None[source]
deleted: bool = False[source]
metadata: dict[str, Any][source]
content: bytes | collections.abc.AsyncIterable[bytes] | None = None[source]
class s365b.modules.sdk.GroupChange[source]

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.

Variables:
  • 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.

key: str[source]
value: str[source]
path: str | None = None[source]
deleted: bool = False[source]
class s365b.modules.sdk.Checkpoint[source]

Marker meaning “everything yielded so far matches this state”.

Variables:

state – The sync state to save once preceding items are durable.

state: SyncState[source]
class s365b.modules.sdk.Column[source]

A metadata column in the browse view.

Variables:
  • 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).

key: str[source]
label: str[source]
format: Literal['text', 'bool', 'datetime', 'list'] = 'text'[source]
class s365b.modules.sdk.ItemTypeInfo[source]

Describes an item type for the browse UI.

Variables:
  • 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 BackupModule.export().

id: str[source]
label: str[source]
icon: str = 'file'[source]
columns: tuple[Column | str, ...] = ()[source]
preview: bool = False[source]
media_type: str = 'application/json'[source]
extension: str = 'json'[source]
exports: tuple[str, ...] = ()[source]
class s365b.modules.sdk.EventType[source]

A module-specific notification event.

Variables:
  • 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.

id: str[source]
label: str[source]
default_severity: Severity[source]
class s365b.modules.sdk.HealthReport[source]

Result of BackupModule.health_check().

Variables:
  • 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).

ok: bool[source]
messages: list[str] = [][source]
missing_permissions: set[str][source]
details: dict[str, Any][source]
class s365b.modules.sdk.ExtraWanted[source]

An item that needs an extra copy (see BackupModule.extra_copies()).

Variables:
  • item_key – The item’s key.

  • size – Size of its stored content in bytes, to batch requests.

  • 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.

item_key: str[source]
size: int[source]
change_key: str | None = None[source]
class s365b.modules.sdk.StoredItem[source]

An item version selected for restore or export, as read from the catalog.

Variables:
  • 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 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.

object: ProtectedObject[source]
version: ItemVersion[source]
read: collections.abc.Callable[[], collections.abc.AsyncIterator[bytes]][source]
extras: frozenset[str][source]
read_extra: collections.abc.Callable[[str], collections.abc.AsyncIterator[bytes]] | None = None[source]
size: int = 0[source]
class s365b.modules.sdk.RestoreRequest[source]

What to restore and where.

Variables:
  • 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).

items: list[StoredItem][source]
target: ProtectedObject | None = None[source]
options: dict[str, Any][source]
class s365b.modules.sdk.RestoreResult[source]

Outcome of a restore.

Variables:
  • 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.

restored: int = 0[source]
skipped: int = 0[source]
failed: int = 0[source]
errors: list[str] = [][source]
folders_created: list[str] = [][source]
fail(message: str, limit: int = 100) → None[source]

Count a failed item and keep its message (up to limit).

class s365b.modules.sdk.ExportRequest[source]

What to export and in which format.

Variables:
items: list[StoredItem][source]
format: str[source]
options: dict[str, Any][source]
class s365b.modules.sdk.ExportFile[source]

One file produced by an export.

Variables:
  • path – Path inside the export archive.

  • content – File content.

path: str[source]
content: bytes | collections.abc.AsyncIterable[bytes][source]
class s365b.modules.sdk.ModuleContext[source]

Everything a module may use while running.

Variables:
  • 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 BackupModule.state_for_new_repository()). None otherwise.

tenant_id: str[source]
config: pydantic.BaseModel[source]
graph: s365b.graph.client.GraphClient[source]
log: Any[source]
cancel: asyncio.Event[source]
progress: collections.abc.Callable[..., None][source]
reader: s365b.graph.client.GraphClient | None = None[source]
current_items: collections.abc.Callable[[str, str], collections.abc.Awaitable[dict[str, dict[str, Any]]]] | None = None[source]
check_cancelled() → None[source]

Raise asyncio.CancelledError if the job was cancelled.

Raises:

asyncio.CancelledError – If cancellation was requested.

class s365b.modules.sdk.BackupModule[source]

Bases: abc.ABC

Base class for a backup workload such as Exchange or Entra ID.

Subclasses set the class attributes and implement discover(), backup(), item_types() and required_permissions(). Restore, export, events and health checks have defaults.

Variables:
  • 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.

id: ClassVar[str][source]
display_name: ClassVar[str][source]
description: ClassVar[str] = ''[source]
version: ClassVar[str] = '0.0.0'[source]
config_model: ClassVar[type[pydantic.BaseModel]][source]
object_noun: ClassVar[tuple[str, str]] = ('object', 'objects')[source]
parallel_objects: ClassVar[int] = 1[source]
abstractmethod required_permissions(config: pydantic.BaseModel, *, restore: bool) → set[str][source]

Return the Microsoft Graph application permissions needed.

Parameters:
  • 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"}.

optional_permissions(config: pydantic.BaseModel) → set[str][source]

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).

Parameters:

config – The module’s settings.

Returns:

A subset of the backup permissions; empty by default.

abstractmethod discover(ctx: ModuleContext) → collections.abc.AsyncIterator[ProtectedObject][source]

List the objects this module can protect.

Parameters:

ctx – Module context.

Returns:

Async iterator of protected objects.

abstractmethod backup(ctx: ModuleContext, obj: ProtectedObject, state: SyncState) → collections.abc.AsyncIterator[ItemVersion | GroupChange | Checkpoint][source]

Back up one protected object incrementally.

Parameters:
  • 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.

abstractmethod item_types() → list[ItemTypeInfo][source]

Describe this module’s item types for the browse UI.

Returns:

Item type descriptions.

async estimate(ctx: ModuleContext, obj: ProtectedObject, state: SyncState) → int | None[source]

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.

Parameters:
  • 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.

state_for_new_repository(state: SyncState) → SyncState[source]

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. ModuleContext.current_items returns items whose current version is in another repository without their metadata, so comparisons with it re-read them.

Parameters:

state – The state saved by the backup into the other repository.

Returns:

The state to start from; empty by default (a first backup).

extra_copies(config: pydantic.BaseModel) → tuple[str, ...][source]

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 fetch_extras() for every current item that lacks one, so items backed up before a copy existed get it too.

Parameters:

config – Module settings.

Returns:

Copy names, e.g. ("fts",); empty by default.

extra_label(name: str) → str[source]

Progress text while fetching an extra copy.

Parameters:

name – Copy name.

Returns:

Text shown as the current step.

fetch_extras(ctx: ModuleContext, obj: ProtectedObject, name: str, items: list[ExtraWanted]) → collections.abc.AsyncIterator[tuple[str, bytes]][source]

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.

Parameters:
  • ctx – Module context.

  • obj – The protected object.

  • name – Copy name, one of extra_copies().

  • items – Items to fetch it for.

Returns:

Async iterator of (item_key, data).

Raises:

NotSupportedError – If the module keeps no extra copies.

classmethod supports_restore() → bool[source]

Whether the module implements restore().

async restore(ctx: ModuleContext, request: RestoreRequest) → RestoreResult[source]

Write items back to Microsoft 365.

Parameters:
  • 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.

export_formats() → list[str][source]

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.

export(config: pydantic.BaseModel, request: ExportRequest) → collections.abc.AsyncIterator[ExportFile][source]

Produce portable files from backed-up items.

Export works from what is stored only: no Microsoft 365 access.

Parameters:
  • 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.

event_types() → list[EventType][source]

Return module-specific notification events.

Returns:

Event types; empty by default.

change_event(item_type: str, change: str, version: ItemVersion) → str | None[source]

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.

Parameters:
  • item_type – The item’s type.

  • change – new, changed or deleted.

  • version – The new version (content not loaded).

Returns:

One of the IDs from event_types(), or None.

async health_check(ctx: ModuleContext) → HealthReport[source]

Check that the module can work (permissions, connectivity).

The default implementation reports healthy; modules should override it to try a cheap read.

Parameters:

ctx – Module context.

Returns:

The health report.