"""The backup engine: drives a module's backup of one protected object.
It connects the three parts that do not know about each other: the module
(what to read), the repository (where content goes) and the catalog (what
was stored when).
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field, replace
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import Select, func, select
from s365b.core.catalog import Catalog, VersionStats, refresh_summary
from s365b.core.generation import bump
from s365b.core.logging import get_logger
from s365b.db.models import Item, ItemVersionRow, ProtectedObjectRow
from s365b.db.session import Database
from s365b.modules.sdk import (
BackupModule,
Checkpoint,
ExtraWanted,
GroupChange,
ItemVersion,
ModuleContext,
ProtectedObject,
SyncState,
)
from s365b.storage.repository import ContentRef, Repository
# Commit at least this often even if the module checkpoints rarely, so the
# transaction and the in-memory list stay small. State is only advanced at
# real checkpoints.
# Items asked for extra copies per round (one commit each).
[docs]
log = get_logger(__name__)
@dataclass(slots=True)
[docs]
class ObjectResult:
"""Outcome of backing up one protected object.
Attributes:
object_fk: Protected object row ID.
stats: What was stored.
checkpoints: Number of checkpoints committed.
error: Error message if the backup failed part-way.
changes: ``(change, version)`` for each item added, changed or
deleted, only if the object had been backed up before.
track_changes: Whether ``changes`` is collected (not the object's
first backup, nor the first with a new module version).
extras: Extra copies added to items (see
:meth:`BackupModule.extra_copies`).
extras_missing: Current items still without an extra copy after
this run (e.g. messages that cannot be restored yet).
extras_error: Why the last extras pass stopped, if it failed.
"""
[docs]
stats: VersionStats = field(default_factory=VersionStats)
[docs]
error: str | None = None
[docs]
changes: list[tuple[str, ItemVersion]] = field(default_factory=list)
[docs]
track_changes: bool = False
[docs]
class BackupEngine:
"""Runs module backups and records the results.
Args:
db: Database.
repo: Open repository for content.
repository_fk: Database ID of that repository.
"""
def __init__(self, db: Database, repo: Repository, repository_fk: int) -> None:
[docs]
self.repository_fk = repository_fk
[docs]
async def backup_object(
self,
module: BackupModule,
ctx: ModuleContext,
row: ProtectedObjectRow,
*,
run_fk: int | None = None,
on_stats: Callable[[VersionStats], None] | None = None,
) -> ObjectResult:
"""Back up one protected object incrementally.
Errors inside the module are caught and reported in the result;
everything up to the last checkpoint stays committed, so the next run
resumes from there.
Args:
module: The module that owns the object.
ctx: Module context for this job.
row: The protected object's catalog row.
run_fk: Current job run, recorded on each version.
on_stats: Called after each commit with what that commit stored
(for live progress).
Returns:
The outcome.
"""
result = ObjectResult(row.id)
obj = ProtectedObject(row.kind, row.external_id, row.display_name, dict(row.meta))
async def current_items(field: str, value: str) -> dict[str, dict[str, Any]]:
"""What the catalog has committed for this object (see ModuleContext)."""
async with self.db.session() as s:
return await Catalog(s).current_items(row.id, field, value, self.repository_fk)
ctx = replace(ctx, current_items=current_items)
async with self.db.session() as s:
catalog = Catalog(s)
state = await catalog.state_for(row.id, self.repository_fk, module)
saved_by = await catalog.state_version(row.id)
# No change alerts on a first backup, nor on the first run of a new
# module version: a new storage format is not a change in the tenant.
result.track_changes = bool(state.data) and saved_by == module.version
pending: list[tuple[ItemVersion | GroupChange, ContentRef | None]] = []
try:
async for record in module.backup(ctx, obj, state):
ctx.check_cancelled()
if isinstance(record, Checkpoint):
await self._commit(
module, row.id, pending, record.state, run_fk, result, on_stats
)
result.checkpoints += 1
continue
if isinstance(record, GroupChange):
pending.append((record, None))
continue
ref = None
if record.content is not None and not record.deleted:
ref = await self.repo.put_content(record.content)
# Keep a content-free copy: content is in the repository now,
# and the module's own object is left untouched.
pending.append((replace(record, content=None), ref))
if len(pending) >= MAX_PENDING:
await self._commit(module, row.id, pending, None, run_fk, result, on_stats)
except asyncio.CancelledError:
if not ctx.cancel.is_set():
raise # the task itself was cancelled (shutdown)
result.error = "Stopped before this finished; the next run continues from here."
except Exception as exc:
result.error = f"{type(exc).__name__}: {exc}"
log.warning(
"backup.object_failed",
module=module.id,
object=row.display_name,
object_id=row.external_id,
run_id=run_fk,
stored_before_failure=result.stats.as_dict(),
graph_status=getattr(exc, "status", None),
graph_code=getattr(exc, "code", None),
graph_request_id=getattr(exc, "request_id", None),
exc_info=exc,
)
# Items after the last checkpoint are stored too; their state is not
# advanced, so the next run re-reads and de-duplicates them.
await self._commit(module, row.id, pending, None, run_fk, result, on_stats)
if result.error is None:
for name in module.extra_copies(ctx.config):
await self._extras(module, ctx, row, obj, name, result)
async with self.db.session() as s:
result.extras_missing += (
await s.scalar(
select(func.count()).select_from(self._missing(row.id, name).subquery())
)
or 0
)
async with self.db.session() as s:
await refresh_summary(s, row.id)
return result
def _missing(self, object_fk: int, name: str) -> Select[str, int, int, str | None]:
"""Current items of an object without the extra copy ``name``.
Only versions stored in this repository: restore reads a version's
copies from the repository holding the version.
"""
return (
select(
Item.item_key,
ItemVersionRow.id,
ItemVersionRow.size,
ItemVersionRow.meta["change_key"].astext.label("change_key"),
)
.join(Item, Item.id == ItemVersionRow.item_fk)
.where(
Item.protected_object_fk == object_fk,
ItemVersionRow.repository_fk == self.repository_fk,
ItemVersionRow.valid_to.is_(None),
ItemVersionRow.deleted.is_(False),
ItemVersionRow.content.is_not(None),
ItemVersionRow.content["extra"][name].is_(None),
)
)
async def _extras(
self,
module: BackupModule,
ctx: ModuleContext,
row: ProtectedObjectRow,
obj: ProtectedObject,
name: str,
result: ObjectResult,
) -> None:
"""Add an extra copy to every current item of an object that lacks it.
The copy is attached to the current version in place: it is the same
item, in another form. A failure stops this pass for the object but
not the backup; the next run tries again.
"""
missing = self._missing(row.id, name)
async with self.db.session() as s:
total = await s.scalar(select(func.count()).select_from(missing.subquery()))
done, after = 0, 0
while total:
ctx.check_cancelled()
async with self.db.session() as s:
rows = (
await s.execute(
missing.where(ItemVersionRow.id > after)
.order_by(ItemVersionRow.id)
.limit(EXTRAS_BATCH)
)
).all()
if not rows:
break
after = rows[-1].id
version_of = {r.item_key: r.id for r in rows}
wanted = [ExtraWanted(r.item_key, r.size, r.change_key) for r in rows]
got: dict[int, ContentRef] = {}
try:
async for key, data in module.fetch_extras(ctx, obj, name, wanted):
if (vid := version_of.get(key)) is not None:
got[vid] = await self.repo.put_content(data)
except asyncio.CancelledError:
raise
except Exception as exc:
log.warning(
"backup.extras_failed",
module=module.id,
object=row.display_name,
copy=name,
stored=result.extras,
graph_status=getattr(exc, "status", None),
graph_code=getattr(exc, "code", None),
error=str(exc),
)
result.extras_error = str(exc) or type(exc).__name__
await self._attach(name, got, result)
return
await self._attach(name, got, result)
done += len(rows)
ctx.progress(done=done, total=total, message=module.extra_label(name), unit="items")
async def _attach(self, name: str, got: dict[int, ContentRef], result: ObjectResult) -> None:
"""Store fetched extra copies on their versions."""
if not got:
return
await self.repo.flush() # durable before the catalog points at it
on_disk = await self.repo.read_generation()
async with self.db.session() as s:
for vid, ref in got.items():
v = await s.get(ItemVersionRow, vid, with_for_update=True)
if (
v is None
or v.content is None
or v.valid_to is not None
or v.repository_fk != self.repository_fk
):
continue
content = dict(v.content)
content["extra"] = {**(content.get("extra") or {}), name: ref.to_json()}
v.content = content
result.extras += 1
result.stats.bytes += ref.size
generation = await bump(s, self.repository_fk, on_disk)
if generation is not None:
await self.repo.write_generation(generation)
async def _commit(
self,
module: BackupModule,
object_fk: int,
pending: list[tuple[ItemVersion | GroupChange, ContentRef | None]],
state: SyncState | None,
run_fk: int | None,
result: ObjectResult,
on_stats: Callable[[VersionStats], None] | None = None,
) -> None:
if not pending and state is None:
return
await self.repo.flush() # content must be durable before the catalog points at it
on_disk = await self.repo.read_generation()
now = datetime.now(UTC)
batch = VersionStats()
async with self.db.session() as s:
catalog = Catalog(s)
for version, ref in pending:
if isinstance(version, GroupChange):
group_stats, changed = await catalog.apply_group(
object_fk,
version,
repository_fk=self.repository_fk,
run_fk=run_fk,
now=now,
)
result.stats.add(group_stats)
batch.add(group_stats)
if result.track_changes:
group_kind = "deleted" if version.deleted else "changed"
result.changes.extend((group_kind, v) for v in changed)
continue
stats = await catalog.record(
object_fk,
version,
ref,
repository_fk=self.repository_fk,
run_fk=run_fk,
now=now,
)
result.stats.add(stats)
batch.add(stats)
if result.track_changes:
kind = (
"new"
if stats.new
else "changed"
if stats.changed
else "deleted"
if stats.deleted
else None
)
if kind:
result.changes.append((kind, version))
if state is not None:
await catalog.save_state(object_fk, state, module.version, self.repository_fk)
# Last, in the same transaction (see core.generation).
generation = await bump(s, self.repository_fk, on_disk)
if generation is not None:
await self.repo.write_generation(generation)
pending.clear()
if on_stats is not None:
on_stats(batch)