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:
BackupModule.discover()lists what can be protected (ProtectedObject: a mailbox, a drive, the tenant directory…).For each selected object the core calls
BackupModule.backup()with the object’s savedSyncState. The module yieldsItemVersionrecords for new, changed and deleted items,GroupChangerecords for renamed or removed containers, andCheckpointmarkers.At each
Checkpointthe 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¶
Base class for errors raised by modules. |
|
Raised when a module does not support an operation (e.g. restore). |
Classes¶
Severity of a notification event. |
|
Config model for modules without settings. |
|
Something a module can back up as a unit. |
|
Per-object state a module keeps between runs (e.g. delta links). |
|
One new, changed or deleted item, yielded by |
|
A change to every current item in a group, such as a mail folder. |
|
Marker meaning "everything yielded so far matches this state". |
|
A metadata column in the browse view. |
|
Describes an item type for the browse UI. |
|
A module-specific notification event. |
|
Result of |
|
An item that needs an extra copy (see |
|
An item version selected for restore or export, as read from the catalog. |
|
What to restore and where. |
|
Outcome of a restore. |
|
What to export and in which format. |
|
One file produced by an export. |
|
Everything a module may use while running. |
|
Base class for a backup workload such as Exchange or Entra ID. |
Module Contents¶
- exception s365b.modules.sdk.ModuleError[source]¶
Bases:
ExceptionBase class for errors raised by modules.
- exception s365b.modules.sdk.NotSupportedError[source]¶
Bases:
ModuleErrorRaised when a module does not support an operation (e.g. restore).
- class s365b.modules.sdk.EmptyConfig[source]¶
Bases:
pydantic.BaseModelConfig 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": [...]}.
- class s365b.modules.sdk.SyncState[source]¶
Per-object state a module keeps between runs (e.g. delta links).
The content of
datais private to the module and must be JSON-serialisable.- Variables:
data – Module-defined state.
- 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.
Nonefor metadata-only items.
- 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]equalsvalue: 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;
Nonekeeps their paths.deleted – Mark the items deleted.
- 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.
- 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),datetimeorlist(comma-separated).
- 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) ormessage/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",); seeBackupModule.export().
- 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.
- 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).
- 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_keymetadata, if it has one, so a module can tell whether the copy it gets is of the same version.
- 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
readstreams) in bytes.
- object: ProtectedObject[source]¶
- version: ItemVersion[source]¶
- class s365b.modules.sdk.RestoreRequest[source]¶
What to restore and where.
- Variables:
items – Items to restore.
target – Where to restore to;
Nonemeans 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]¶
- 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.
- class s365b.modules.sdk.ExportRequest[source]¶
What to export and in which format.
- Variables:
items – Items to export.
format – Format ID, one of the module’s
BackupModule.export_formats().options – Module-specific options.
- items: list[StoredItem][source]¶
- class s365b.modules.sdk.ExportFile[source]¶
One file produced by an export.
- Variables:
path – Path inside the export archive.
content – File content.
- 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").totalmay beNonewhen unknown;unitnames whatdonecounts (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).
Noneotherwise.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 (seeBackupModule.state_for_new_repository()).Noneotherwise.
- reader: s365b.graph.client.GraphClient | None = None[source]¶
- class s365b.modules.sdk.BackupModule[source]¶
Bases:
abc.ABCBase class for a backup workload such as Exchange or Entra ID.
Subclasses set the class attributes and implement
discover(),backup(),item_types()andrequired_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.
- 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
Noneif 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_itemsreturns 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.
- 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,changedordeleted.version – The new version (content not loaded).
- Returns:
One of the IDs from
event_types(), orNone.
- 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.