Source code for s365b.jobs.progress

"""Live progress of a running job, saved on the job run for the web UI.

The runner reports what it is doing to a :class:`ProgressTracker`; the
tracker keeps it in memory and writes a snapshot to ``job_run.progress``
every few seconds, so a busy backup does not write to the database for
every item.

Percent and time left are estimates. When the module can estimate the
items each object will process (Exchange counts the messages in folders not
yet backed up), progress is by items; otherwise it is by objects.
"""

from __future__ import annotations

import asyncio
import contextlib
import time
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any

from sqlalchemy import update

from s365b.core.catalog import VersionStats
from s365b.core.logging import get_logger
from s365b.db.models import JobRun
from s365b.db.session import Database

[docs] log = get_logger(__name__)
# Progress by items needs a meaningful amount of work; small incremental # runs are measured by objects instead.
[docs] MIN_ITEMS_FOR_ITEM_PROGRESS = 200
# No time-left estimate until this much is known.
[docs] MIN_FRACTION_FOR_ETA = 0.02
[docs] MIN_SECONDS_FOR_ETA = 20.0
@dataclass(slots=True) class _Active: name: str message: str = "" done: int = 0 total: int | None = None unit: str = "" expected: int | None = None items: int = 0
[docs] class ProgressTracker: """Collects progress for one job run and saves it periodically. Args: db: Database. run_id: The job run. modules_total: Number of modules in the job. interval: Seconds between saves. """ def __init__( self, db: Database, run_id: int, modules_total: int, interval: float = 3.0, stop: asyncio.Event | None = None, ) -> None:
[docs] self.db = db
[docs] self.stop = stop or asyncio.Event()
[docs] self.stopped_by: str | None = None
[docs] self.run_id = run_id
[docs] self.interval = interval
[docs] self.phase = "starting"
[docs] self.modules_total = modules_total
[docs] self.modules_done = 0
[docs] self.module = ""
[docs] self.module_name = ""
[docs] self.noun: tuple[str, str] = ("object", "objects")
[docs] self.objects_total = 0
[docs] self.objects_done = 0
[docs] self.objects_failed = 0
[docs] self.items_expected: int | None = None
[docs] self.module_items = 0
[docs] self.module_started = time.monotonic()
[docs] self.totals = VersionStats()
[docs] self.active: dict[int, _Active] = {}
[docs] self.expected: dict[int, int | None] = {}
[docs] self.started_at = datetime.now(UTC)
self._task: asyncio.Task[None] | None = None # -- reporting -----------------------------------------------------------
[docs] def start_module( self, module_id: str, name: str, noun: tuple[str, str], objects_total: int ) -> None: """A module starts: discovery is done, objects are known.""" self.module, self.module_name, self.noun = module_id, name, noun self.objects_total, self.objects_done, self.objects_failed = objects_total, 0, 0 self.items_expected, self.module_items = None, 0 self.expected = {} self.module_started = time.monotonic()
[docs] def set_phase(self, phase: str) -> None: """Set the phase: discovering, estimating, backing_up (or restoring), finishing.""" if self.phase != "stopping": self.phase = phase
[docs] def set_estimates(self, estimates: dict[int, int | None]) -> None: """Record per-object item estimates (``None`` where unknown).""" self.expected = dict(estimates) known = [v for v in estimates.values() if v is not None] self.items_expected = sum(known) if known and len(known) == len(estimates) else None self.module_started = time.monotonic() # the rate counts from here
[docs] def object_started(self, key: int, name: str) -> None: """An object's backup started.""" self.active[key] = _Active(name, expected=self.expected.get(key))
[docs] def object_progress( self, key: int, *, done: int = 0, total: int | None = None, message: str = "", unit: str = "", **_: Any, ) -> None: """The module reported progress within an object (``ctx.progress``).""" a = self.active.get(key) if a is not None: a.done, a.total, a.message, a.unit = done, total, message, unit
[docs] def object_stats(self, key: int, stats: VersionStats) -> None: """Items stored for an object since the last report.""" self.totals.add(stats) processed = stats.new + stats.changed + stats.unchanged + stats.deleted self.module_items += processed a = self.active.get(key) if a is not None: a.items += processed
[docs] def object_finished(self, key: int, failed: bool) -> None: """An object's backup ended.""" a = self.active.pop(key, None) self.objects_done += 1 self.objects_failed += int(failed) # Items an object was expected to process but did not (an estimate # that was too high, or a failure) must not hold back the percentage. if a is not None and self.items_expected is not None and a.expected: self.items_expected -= max(0, a.expected - a.items)
[docs] def finish_module(self) -> None: """A module's objects are all done.""" self.modules_done += 1
# -- output --------------------------------------------------------------
[docs] def fraction(self) -> float | None: """Estimated share of the current module that is done (0 to 1).""" if self.phase not in ("backing_up", "restoring", "stopping"): return None if self.items_expected is not None and self.items_expected >= MIN_ITEMS_FOR_ITEM_PROGRESS: return min(1.0, self.module_items / self.items_expected) if not self.objects_total: return None partial = sum( min(1.0, a.done / a.total) for a in self.active.values() if a.total and a.unit ) return min(1.0, (self.objects_done + partial) / self.objects_total)
[docs] def snapshot(self) -> dict[str, Any]: """The progress document saved on the job run.""" frac = self.fraction() elapsed = time.monotonic() - self.module_started eta = None if frac is not None and frac >= MIN_FRACTION_FOR_ETA and elapsed >= MIN_SECONDS_FOR_ETA: eta = round(elapsed * (1 - frac) / frac) return { "phase": self.phase, "modules_total": self.modules_total, "modules_done": self.modules_done, "module": self.module, "module_name": self.module_name, "noun": list(self.noun), "objects_total": self.objects_total, "objects_done": self.objects_done, "objects_failed": self.objects_failed, "items_expected": self.items_expected, "items_done": self.module_items, "percent": None if frac is None else round(frac * 100, 1), "eta_seconds": eta, "items_per_minute": round(self.module_items / elapsed * 60) if elapsed > 5 else None, "stored": self.totals.as_dict(), "active": [ { "object": a.name, "message": a.message, "done": a.done, "total": a.total, "unit": a.unit, } for a in self.active.values() ], "started_at": self.started_at.isoformat(), "updated_at": datetime.now(UTC).isoformat(), }
[docs] async def save(self) -> None: """Write the current snapshot to the job run; notice stop requests.""" async with self.db.session() as s: row = ( await s.execute( update(JobRun) .where(JobRun.id == self.run_id) .values(progress=self.snapshot()) .returning(JobRun.stop_requested_at, JobRun.stop_requested_by) ) ).first() if row is not None and row[0] is not None and not self.stop.is_set(): self.stopped_by = row[1] self.phase = "stopping" self.stop.set()
async def _loop(self) -> None: while True: await asyncio.sleep(self.interval) try: await self.save() except Exception as exc: # progress must never break a backup log.warning("job.progress_save_failed", run_id=self.run_id, error=str(exc)) async def __aenter__(self) -> ProgressTracker: await self.save() self._task = asyncio.create_task(self._loop()) return self async def __aexit__(self, *exc: object) -> None: if self._task is not None: self._task.cancel() with contextlib.suppress(asyncio.CancelledError): await self._task self.phase = "done" await self.save()