"""Unified collection storage & snapshot retention policy service.""" from __future__ import annotations from copy import deepcopy import hashlib import json from typing import Any, Callable, Iterable, Literal from sqlalchemy import select, text from sqlalchemy.ext.asyncio import AsyncSession from app.core.logging import get_logger from app.models.system_setting import SystemSetting logger = get_logger(__name__, service="storage_policy") SnapshotMode = Literal["single", "annual", "history"] GlobalSnapshotAction = Literal["all_single", "all_history", "recommended_default"] class StoragePolicyLockedError(ValueError): """Raised when a per-source snapshot override violates global all-single lock.""" STORAGE_POLICY_CATEGORY = "collection_storage" STORAGE_POLICY_TX_LOCK_KEY = (17001614, 2) STORAGE_POLICY_SINGLE_VIOLATION_CODE = "planet_storage_policy_single_violation" VALID_SNAPSHOT_MODES: tuple[SnapshotMode, ...] = ("single", "annual", "history") ANNUAL_ELIGIBLE_SOURCES: frozenset[str] = frozenset({"top500", "epoch_ai_gpu"}) HIGH_VOLUME_SOURCES: dict[str, dict[str, str]] = { "iptoasn_prefix_geo": { "estimated_monthly_growth": "~14 GB / 月", "note": "全量 IPv4/IPv6 ASN 前缀约 72 万行,每 6 小时重采开启历史快照将快速膨胀", }, "nro_delegated_prefix_geo": { "estimated_monthly_growth": "~12 GB / 月", "note": "五大 RIR IP 分配表约 65 万行,每 12 小时全量落盘对磁盘与触发器压力较大", }, "barentswatch_vessels": { "estimated_monthly_growth": "~25 GB / 月", "note": "每 5 分钟拉取近实时 AIS 报文,开启历史快照将持续写入 ais_raw_observations", }, "aisstream_vessels": { "estimated_monthly_growth": "~15 GB / 月", "note": "WebSocket 高频 AIS 报文流,开启历史快照将高频写入 ais_raw_observations", }, } DEFAULT_RECOMMENDED_OVERRIDES: dict[str, SnapshotMode] = { "top500": "annual", "epoch_ai_gpu": "annual", } DEFAULT_STORAGE_POLICY: dict[str, Any] = { "default_mode": "single", "overrides": deepcopy(DEFAULT_RECOMMENDED_OVERRIDES), "global_single_lock": False, "history_retention_days": 30, "bgp_observation_retention_days": 7, "bgp_single_batch_max_rows": 500, "auto_prune_enabled": False, } def compute_record_content_hash(payload: dict[str, Any]) -> str: """Return a deterministic SHA-256 hex digest for a comparable collector record payload.""" canonical = json.dumps( payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str, ) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() def _clamp_int(value: Any, default: int, *, minimum: int, maximum: int) -> int: try: parsed = int(value) except (TypeError, ValueError): return default return max(minimum, min(parsed, maximum)) def _normalize_mode(value: Any, fallback: SnapshotMode = "single") -> SnapshotMode: if isinstance(value, str): candidate = value.strip().lower() if candidate in VALID_SNAPSHOT_MODES: return candidate # type: ignore[return-value] return fallback def normalize_storage_policy( raw: dict[str, Any] | None, *, fallback_auto_prune: bool = False, ) -> dict[str, Any]: """Validate and normalize a raw storage policy dictionary, dropping redundant overrides.""" data = raw if isinstance(raw, dict) else {} global_single_lock_raw = data.get("global_single_lock") if isinstance(global_single_lock_raw, bool): global_single_lock = global_single_lock_raw elif global_single_lock_raw is None: global_single_lock = False else: global_single_lock = str(global_single_lock_raw).strip().lower() in { "1", "true", "yes", "on", } default_mode = "single" if global_single_lock else _normalize_mode(data.get("default_mode"), "single") overrides_raw = data.get("overrides") if global_single_lock: cleaned_overrides: dict[str, SnapshotMode] = {} elif isinstance(overrides_raw, dict): cleaned_overrides = {} for source, mode_raw in overrides_raw.items(): source_key = str(source or "").strip() if not source_key: continue mode = _normalize_mode(mode_raw, default_mode) if mode == "annual" and source_key not in ANNUAL_ELIGIBLE_SOURCES: mode = "history" if mode != default_mode: cleaned_overrides[source_key] = mode else: cleaned_overrides = { source: mode for source, mode in DEFAULT_RECOMMENDED_OVERRIDES.items() if mode != default_mode } auto_prune_raw = data.get("auto_prune_enabled") if isinstance(auto_prune_raw, bool): auto_prune_enabled = auto_prune_raw elif auto_prune_raw is None: auto_prune_enabled = fallback_auto_prune else: auto_prune_enabled = str(auto_prune_raw).strip().lower() in {"1", "true", "yes", "on"} return { "default_mode": default_mode, "overrides": cleaned_overrides, "global_single_lock": global_single_lock, "history_retention_days": _clamp_int( data.get("history_retention_days"), int(DEFAULT_STORAGE_POLICY["history_retention_days"]), minimum=1, maximum=3650, ), "bgp_observation_retention_days": _clamp_int( data.get("bgp_observation_retention_days"), int(DEFAULT_STORAGE_POLICY["bgp_observation_retention_days"]), minimum=1, maximum=365, ), "bgp_single_batch_max_rows": _clamp_int( data.get("bgp_single_batch_max_rows"), int(DEFAULT_STORAGE_POLICY["bgp_single_batch_max_rows"]), minimum=50, maximum=5000, ), "auto_prune_enabled": auto_prune_enabled, } def resolve_snapshot_mode(policy: dict[str, Any] | None, source: str) -> SnapshotMode: """Resolve effective snapshot mode for one datasource from a single unified policy.""" normalized = normalize_storage_policy(policy) if normalized.get("global_single_lock"): return "single" overrides: dict[str, SnapshotMode] = normalized["overrides"] default_mode: SnapshotMode = normalized["default_mode"] mode = overrides.get(source, default_mode) if mode == "annual" and source not in ANNUAL_ELIGIBLE_SOURCES: return "history" return mode def set_source_snapshot_mode( policy: dict[str, Any] | None, source: str, mode: SnapshotMode, ) -> dict[str, Any]: """Update a single datasource override sparsely, deleting override when equal to default.""" normalized = normalize_storage_policy(policy) target_mode = _normalize_mode(mode, normalized["default_mode"]) if target_mode == "annual" and source not in ANNUAL_ELIGIBLE_SOURCES: target_mode = "history" if normalized.get("global_single_lock") and target_mode != "single": raise StoragePolicyLockedError( "Global all-single lock is active; switch off all-single before enabling history or annual snapshots for a source." ) next_overrides = dict(normalized["overrides"]) if target_mode == normalized["default_mode"]: next_overrides.pop(source, None) else: next_overrides[source] = target_mode return normalize_storage_policy({**normalized, "overrides": next_overrides}) def apply_global_snapshot_action( policy: dict[str, Any] | None, action: GlobalSnapshotAction, ) -> dict[str, Any]: """Apply tri-state master switch actions cleanly without leaving stale overrides.""" normalized = normalize_storage_policy(policy) if action == "all_single": return normalize_storage_policy( {**normalized, "default_mode": "single", "overrides": {}, "global_single_lock": True} ) if action == "all_history": return normalize_storage_policy( {**normalized, "default_mode": "history", "overrides": {}, "global_single_lock": False} ) if action == "recommended_default": return normalize_storage_policy( { **normalized, "default_mode": "single", "overrides": deepcopy(DEFAULT_RECOMMENDED_OVERRIDES), "global_single_lock": False, } ) return normalized def summarize_storage_policy( policy: dict[str, Any] | None, sources: Iterable[str], ) -> dict[str, Any]: """Compute effective per-source counts and tri-state master status (`off`/`partial`/`all`).""" normalized = normalize_storage_policy(policy) unique_sources = sorted({str(source).strip() for source in sources if str(source or "").strip()}) effective_modes: dict[str, SnapshotMode] = {} single_count = 0 annual_count = 0 history_count = 0 for source in unique_sources: mode = resolve_snapshot_mode(normalized, source) effective_modes[source] = mode if mode == "single": single_count += 1 elif mode == "annual": annual_count += 1 else: history_count += 1 total_sources = len(unique_sources) snapshot_enabled_count = annual_count + history_count if total_sources == 0 or snapshot_enabled_count == 0: master_state: Literal["off", "partial", "all"] = "off" elif snapshot_enabled_count == total_sources: master_state = "all" else: master_state = "partial" return { **normalized, "total_sources": total_sources, "single_count": single_count, "annual_count": annual_count, "history_count": history_count, "snapshot_enabled_count": snapshot_enabled_count, "master_state": master_state, "annual_eligible_sources": sorted(ANNUAL_ELIGIBLE_SOURCES), "high_volume_sources": deepcopy(HIGH_VOLUME_SOURCES), "effective_modes": effective_modes, } def _is_postgresql_session(db: AsyncSession | None) -> bool: if db is None or not callable(getattr(db, "get_bind", None)): return False try: bind = db.get_bind() return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql" except Exception: return False def is_storage_policy_single_violation(exc: BaseException) -> bool: """Return True if an exception (or wrapped DBAPI cause) came from the single-mode publish guard.""" visited: set[int] = set() pending: list[BaseException | None] = [exc] while pending: current = pending.pop() if current is None or id(current) in visited: continue visited.add(id(current)) if STORAGE_POLICY_SINGLE_VIOLATION_CODE in str(current): return True pending.append(getattr(current, "__cause__", None)) pending.append(getattr(current, "__context__", None)) pending.append(getattr(current, "orig", None)) return False async def acquire_storage_policy_write_lock(db: AsyncSession | None) -> None: """Take transaction-scoped exclusive lock serializing storage policy changes with snapshot publish.""" if not _is_postgresql_session(db): return await db.execute( # type: ignore[union-attr] text("SELECT pg_advisory_xact_lock(:key1, :key2)"), {"key1": STORAGE_POLICY_TX_LOCK_KEY[0], "key2": STORAGE_POLICY_TX_LOCK_KEY[1]}, ) async def acquire_storage_policy_publish_lock( db: AsyncSession | None, source: str, ) -> tuple[SnapshotMode, dict[str, Any]]: """Take transaction-scoped shared lock and read the latest committed storage policy.""" if db is None or not callable(getattr(db, "execute", None)): policy = normalize_storage_policy(None) return resolve_snapshot_mode(policy, source), policy is_pg = _is_postgresql_session(db) if is_pg: await db.execute( text("SELECT pg_advisory_xact_lock_shared(:key1, :key2)"), {"key1": STORAGE_POLICY_TX_LOCK_KEY[0], "key2": STORAGE_POLICY_TX_LOCK_KEY[1]}, ) stmt = ( select(SystemSetting.payload) .where(SystemSetting.category == STORAGE_POLICY_CATEGORY) .limit(1) ) if is_pg and hasattr(stmt, "with_for_update"): stmt = stmt.with_for_update(read=True) try: result = await db.execute(stmt) except Exception: policy = normalize_storage_policy(None) return resolve_snapshot_mode(policy, source), policy raw_payload = None if result is not None and callable(getattr(result, "scalar_one_or_none", None)): raw_payload = result.scalar_one_or_none() if isinstance(raw_payload, SystemSetting): raw_payload = raw_payload.payload policy = normalize_storage_policy(raw_payload if isinstance(raw_payload, dict) else None) return resolve_snapshot_mode(policy, source), policy async def _load_setting_row( db: AsyncSession, category: str, *, for_update: bool = False, ) -> SystemSetting | None: try: stmt = select(SystemSetting).where(SystemSetting.category == category).limit(1) if hasattr(stmt, "execution_options"): stmt = stmt.execution_options(populate_existing=True) if for_update and _is_postgresql_session(db) and hasattr(stmt, "with_for_update"): stmt = stmt.with_for_update() result = await db.execute(stmt) except Exception: return None if result is None or not callable(getattr(result, "scalar_one_or_none", None)): return None record = result.scalar_one_or_none() if isinstance(record, SystemSetting): return record return None async def get_storage_policy(db: AsyncSession | None) -> dict[str, Any]: """Load storage policy fresh from DB, safely falling back when called with fake/None sessions.""" if db is None or not callable(getattr(db, "execute", None)): return normalize_storage_policy(None) try: result = await db.execute( select(SystemSetting.payload) .where(SystemSetting.category == STORAGE_POLICY_CATEGORY) .limit(1) ) except Exception: return normalize_storage_policy(None) if result is not None and callable(getattr(result, "scalar_one_or_none", None)): raw_payload = result.scalar_one_or_none() if isinstance(raw_payload, SystemSetting): raw_payload = raw_payload.payload if isinstance(raw_payload, dict): return normalize_storage_policy(raw_payload) return normalize_storage_policy(None) async def resolve_collector_storage_policy( db: AsyncSession | None, source: str, ) -> tuple[SnapshotMode, dict[str, Any]]: """Return `(effective_mode, full_policy)` for a collector source.""" policy = await get_storage_policy(db) return resolve_snapshot_mode(policy, source), policy async def mutate_storage_policy( db: AsyncSession, mutator: Callable[[dict[str, Any]], dict[str, Any]], *, sync_system_retention: bool = True, commit: bool = True, ) -> dict[str, Any]: """Read, validate, merge, and persist storage policy inside one locked transaction.""" await acquire_storage_policy_write_lock(db) record = await _load_setting_row(db, STORAGE_POLICY_CATEGORY, for_update=True) current_policy = normalize_storage_policy( record.payload if record is not None and isinstance(record.payload, dict) else None ) normalized = normalize_storage_policy(mutator(deepcopy(current_policy))) if record is None: record = SystemSetting(category=STORAGE_POLICY_CATEGORY, payload=normalized) db.add(record) else: record.payload = normalized if sync_system_retention: # Canonical lock order: advisory lock -> collection_storage -> system. system_record = await _load_setting_row(db, "system", for_update=True) if system_record is not None and isinstance(system_record.payload, dict): next_system_payload = dict(system_record.payload) next_system_payload["data_retention_days"] = normalized["history_retention_days"] system_record.payload = next_system_payload if commit: await db.commit() if hasattr(db, "refresh"): await db.refresh(record) return normalized async def save_storage_policy( db: AsyncSession, policy: dict[str, Any], *, sync_system_retention: bool = True, commit: bool = True, ) -> dict[str, Any]: """Persist storage policy under an exclusive transaction lock blocking incompatible snapshot commits.""" return await mutate_storage_policy( db, lambda _current: policy, sync_system_retention=sync_system_retention, commit=commit, ) async def _detect_existing_collection_data(db: AsyncSession) -> bool: """Return True if any historical collection or AIS raw table already holds data.""" probes = ( text("SELECT 1 FROM data_snapshots LIMIT 1"), text("SELECT 1 FROM collected_data LIMIT 1"), text("SELECT 1 FROM ais_raw_observations LIMIT 1"), ) for probe in probes: try: result = await db.execute(probe) if result is not None and result.fetchone() is not None: return True except Exception: continue return False async def ensure_default_storage_policy(db: AsyncSession) -> dict[str, Any]: """Seed `collection_storage` once under lock; protect existing DB history by setting auto_prune=False.""" await acquire_storage_policy_write_lock(db) existing = await _load_setting_row(db, STORAGE_POLICY_CATEGORY, for_update=True) if existing is not None and isinstance(existing.payload, dict): return normalize_storage_policy(existing.payload) has_existing_data = await _detect_existing_collection_data(db) history_retention_days = int(DEFAULT_STORAGE_POLICY["history_retention_days"]) system_record = await _load_setting_row(db, "system") if system_record is not None and isinstance(system_record.payload, dict): history_retention_days = _clamp_int( system_record.payload.get("data_retention_days"), history_retention_days, minimum=1, maximum=3650, ) seed_policy = normalize_storage_policy( { **deepcopy(DEFAULT_STORAGE_POLICY), "history_retention_days": history_retention_days, "auto_prune_enabled": not has_existing_data, }, fallback_auto_prune=not has_existing_data, ) record = SystemSetting(category=STORAGE_POLICY_CATEGORY, payload=seed_policy) db.add(record) await db.commit() if hasattr(db, "refresh"): await db.refresh(record) logger.info_event( "Initialized default collection storage policy", event="storage_policy.seeded", context={ "has_existing_data": has_existing_data, "default_mode": seed_policy["default_mode"], "overrides": seed_policy["overrides"], "auto_prune_enabled": seed_policy["auto_prune_enabled"], "history_retention_days": seed_policy["history_retention_days"], }, ) return seed_policy