| """ |
| backup_retention.py -- Policy-aware snapshot retention planning. |
| |
| Pure-function module: given a list of :class:`SnapshotInfo` and a |
| :class:`BackupRetention` policy, return the snapshots that should be |
| kept and the snapshots that should be deleted. No filesystem writes |
| happen here — the caller decides whether to act on the plan. |
| |
| Policy semantics |
| ---------------- |
| |
| ``keep_latest = N`` |
| Always keep the ``N`` most-recent snapshots (by ``created_at``). |
| |
| ``keep_daily = M`` |
| For each of the ``M`` most-recent calendar days (UTC) that have |
| at least one snapshot, keep the newest snapshot from that day. |
| |
| The protected set is the **union** of the two rules. A snapshot only |
| gets pruned when it is in neither set. When both rules are zero, every |
| snapshot is prunable — that is the opt-in "keep nothing" setting. |
| |
| Snapshots with ``created_at <= 0`` (malformed manifest / missing |
| timestamp) are always protected. We refuse to delete something we |
| can't confidently place in time. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import time |
| from dataclasses import dataclass |
| from datetime import datetime, timezone |
| from typing import Sequence |
|
|
| from backup_config import BackupRetention |
|
|
|
|
| @dataclass(frozen=True) |
| class RetentionPlan: |
| """Result of planning a prune pass against a retention policy.""" |
|
|
| keep: tuple[str, ...] |
| delete: tuple[str, ...] |
| protected_by_latest: tuple[str, ...] |
| protected_by_daily: tuple[str, ...] |
|
|
| def to_dict(self) -> dict: |
| return { |
| "keep": list(self.keep), |
| "delete": list(self.delete), |
| "protected_by_latest": list(self.protected_by_latest), |
| "protected_by_daily": list(self.protected_by_daily), |
| } |
|
|
|
|
| def _utc_date(epoch: float) -> str: |
| """YYYY-MM-DD string for a Unix timestamp, UTC.""" |
| return datetime.fromtimestamp(epoch, tz=timezone.utc).strftime("%Y-%m-%d") |
|
|
|
|
| def plan_prune( |
| snapshots: Sequence, |
| retention: BackupRetention, |
| *, |
| now: float | None = None, |
| ) -> RetentionPlan: |
| """Decide which snapshots survive a retention sweep. |
| |
| Parameters |
| ---------- |
| snapshots |
| Iterable of objects with ``snapshot_id: str`` and |
| ``created_at: float`` attributes. Order does not matter. |
| retention |
| Policy to apply. |
| now |
| UTC timestamp treated as "right now" for the keep_daily window. |
| Defaults to :func:`time.time`. Tests pin this for determinism. |
| |
| Returns |
| ------- |
| RetentionPlan |
| Structured report of which snapshot IDs should be kept and |
| which can be deleted. Never raises on empty input. |
| """ |
| if retention.keep_latest < 0 or retention.keep_daily < 0: |
| raise ValueError("retention.keep_latest and keep_daily must be >= 0") |
|
|
| now_ts = now if now is not None else time.time() |
| items = list(snapshots) |
|
|
| |
| |
| items.sort(key=lambda s: (-float(s.created_at), s.snapshot_id)) |
|
|
| |
| |
| |
| undated_ids = [s.snapshot_id for s in items if float(s.created_at) <= 0] |
| dated = [s for s in items if float(s.created_at) > 0] |
|
|
| |
| latest_ids = [s.snapshot_id for s in dated[: retention.keep_latest]] |
|
|
| |
| |
| daily_ids: list[str] = [] |
| if retention.keep_daily > 0: |
| today = _utc_date(now_ts) |
| seen_days: dict[str, str] = {} |
| for s in dated: |
| day = _utc_date(float(s.created_at)) |
| |
| if day > today: |
| continue |
| if day not in seen_days: |
| seen_days[day] = s.snapshot_id |
| |
| recent_days = sorted(seen_days.keys(), reverse=True)[: retention.keep_daily] |
| daily_ids = [seen_days[d] for d in recent_days] |
|
|
| protected = set(latest_ids) | set(daily_ids) | set(undated_ids) |
|
|
| keep: list[str] = [] |
| delete: list[str] = [] |
| |
| for s in items: |
| if s.snapshot_id in protected: |
| keep.append(s.snapshot_id) |
| else: |
| delete.append(s.snapshot_id) |
|
|
| return RetentionPlan( |
| keep=tuple(keep), |
| delete=tuple(delete), |
| protected_by_latest=tuple(latest_ids), |
| protected_by_daily=tuple(daily_ids), |
| ) |
|
|