Source code for s365b.jobs.repair

"""Find unreadable blobs in a repository and repair the backup around them.

A blob can become unreadable through disk faults or (before it was fixed) a
compression bug. Its content cannot be recovered from the repository, but the
item usually still exists in Microsoft 365. Repair therefore:

1. removes the catalog versions that use an unreadable blob (items left
   without versions are removed too),
2. resets the sync state of the affected objects, so the next backup reads
   them in full and stores those items again,
3. deletes the unreadable blobs, and only those, from the repository. This
   matters: storage is deduplicated by content, so as long as a blob ID is
   in the index, a new backup of the same content would reuse the broken
   copy.

It holds the repository's lock exclusively, like retention.
"""

from __future__ import annotations

from dataclasses import asdict, dataclass, field
from typing import Any

from sqlalchemy import delete, exists, select

from s365b.core.audit import audit
from s365b.core.services import Services
from s365b.db.models import (
    Item,
    ItemVersionRow,
    ProtectedObjectRow,
    RepositoryConfig,
    SyncStateRow,
)
from s365b.jobs.locks import repository_lock
from s365b.storage.repository import content_blobs


@dataclass(slots=True)
[docs] class RepairReport: """What a check found and (unless a dry run) repaired. Attributes: blobs: Blobs checked. unreadable: Unreadable blob IDs. versions: Item versions that use them. objects: Affected objects, as "module: name" with a version count. repaired: Whether the repair was applied. """
[docs] blobs: int = 0
[docs] unreadable: list[str] = field(default_factory=list)
[docs] versions: int = 0
[docs] objects: dict[str, int] = field(default_factory=dict)
[docs] repaired: bool = False
[docs] async def check_repository( services: Services, repository_fk: int, *, repair: bool, actor: str = "cli" ) -> RepairReport: """Read every blob; optionally repair around the unreadable ones. Args: services: Process services. repository_fk: Repository. repair: Apply the repair (otherwise only report). actor: Who ran it, for the audit log. Returns: The report. """ db = services.db async with repository_lock(db, repository_fk, exclusive=True, wait=False): async with db.session() as s: row = await s.get(RepositoryConfig, repository_fk) if row is None: raise ValueError(f"repository {repository_fk} does not exist") name = row.name repo = await services.open_repository(row) report = RepairReport(blobs=len(repo._index)) bad = await repo.unreadable_blobs() report.unreadable = sorted(bad) if not bad: return report hits: list[tuple[int, int]] = [] # (version id, object id) async with db.session() as s: result = await s.stream( select( ItemVersionRow.id, ItemVersionRow.content, Item.protected_object_fk, ProtectedObjectRow.module_id, ProtectedObjectRow.display_name, ) .join(Item, Item.id == ItemVersionRow.item_fk) .join(ProtectedObjectRow, ProtectedObjectRow.id == Item.protected_object_fk) .where( ItemVersionRow.repository_fk == repository_fk, ItemVersionRow.content.is_not(None), ) .execution_options(yield_per=5000) ) async for vid, content, obj_id, module_id, obj_name in result: if bad.intersection(content_blobs(content)): hits.append((vid, obj_id)) key = f"{module_id}: {obj_name}" report.objects[key] = report.objects.get(key, 0) + 1 report.versions = len(hits) if not repair: return report async with db.session() as s: await s.execute( delete(ItemVersionRow).where(ItemVersionRow.id.in_([v for v, _ in hits])) ) await s.execute( delete(Item).where( Item.protected_object_fk.in_({o for _, o in hits}), ~exists().where(ItemVersionRow.item_fk == Item.id), ) ) await s.execute( delete(SyncStateRow).where( SyncStateRow.protected_object_fk.in_({o for _, o in hits}) ) ) # Only the unreadable blobs: packs holding them are rewritten without # them (or deleted). Everything else stays, even data this database # may not know about (see core.generation). await repo.remove_blobs(bad) report.repaired = True async with db.session() as s: details: dict[str, Any] = asdict(report) await audit(s, actor, "repository.repair", target=name, details=details) return report