"""Database overrides with versioned revision ledger, as-of replay, and atomic publishing.""" from __future__ import annotations from datetime import UTC, datetime, timedelta import hashlib import json from pathlib import Path from typing import Any from uuid import uuid4 from fastapi import HTTPException from sqlalchemy import desc, select from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.ext.asyncio import AsyncSession from app.core.request_context import get_request_id from app.core.time import to_iso8601_utc from app.models.compute_configuration_revision import ComputeConfigurationRevision from app.models.situational_assessment import ComputeEvidenceCandidate from app.models.system_log import AuditLog from app.models.system_setting import SystemSetting from app.models.user import User from app.schemas.compute_configuration import ( SHARE_METRICS, ComputeConfiguration, has_mixed_sources, ) from app.services.compute_catalog import COUNTRY_CATALOG from app.services.compute_revision_diff import ( diff_compute_configurations, has_observation_value_delta, summarize_diff, ) CATEGORY = "compute_comparison" DEFAULT_PATH = Path(__file__).with_name("compute_history_defaults.json") DEFAULT_CONFIGURATION = ComputeConfiguration.model_validate_json(DEFAULT_PATH.read_text()) DEFAULT_REVISION = hashlib.sha256(DEFAULT_PATH.read_bytes()).hexdigest() INCOMPLETE_SNAPSHOT_NOTICE = ( "历史快照不完整:所选系统发布时间早于版本库基线时间,无法还原当时的系统台账。" ) def compute_content_fingerprint(config: ComputeConfiguration | dict[str, Any]) -> str: """Return canonical SHA-256 hex digest of a compute configuration payload.""" payload = ( config.model_dump(mode="json") if isinstance(config, ComputeConfiguration) else ComputeConfiguration.model_validate(config).model_dump(mode="json") ) canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() DEFAULT_CONTENT_FINGERPRINT = compute_content_fingerprint(DEFAULT_CONFIGURATION) def default_envelope() -> dict[str, Any]: return { "config": DEFAULT_CONFIGURATION.model_dump(mode="json"), "revision": DEFAULT_REVISION, "publish_id": DEFAULT_REVISION, "published_at": None, "action": "baseline", "is_default": True, "snapshot_unavailable": False, } def _dialect_name(db: AsyncSession) -> str: bind = getattr(db, "bind", None) name = getattr(getattr(bind, "dialect", None), "name", None) if isinstance(name, str) and name: return name getter = getattr(db, "get_bind", None) # Avoid invoking AsyncMock attributes as coroutines in unit tests. if callable(getter) and not hasattr(getter, "assert_awaited"): try: resolved = getter() name = getattr(getattr(resolved, "dialect", None), "name", None) if isinstance(name, str) and name: return name except Exception: pass return "" def _is_relational_session(db: AsyncSession) -> bool: return _dialect_name(db) in {"postgresql", "sqlite"} def _parse_as_of(as_of: datetime | str | None) -> datetime | None: if as_of is None: return None if isinstance(as_of, datetime): return as_of.astimezone(UTC) if as_of.tzinfo else as_of.replace(tzinfo=UTC) raw = str(as_of).strip() if not raw: return None try: if len(raw) == 10 and raw[4] == "-" and raw[7] == "-": return datetime.fromisoformat(f"{raw}T23:59:59.999999+00:00") normalized = raw.replace("Z", "+00:00") # Recover '+' decoded as space in unencoded URL query strings (e.g. '...52.97 00:00'). if "T" in normalized and " " in normalized: date_part, tz_part = normalized.rsplit(" ", 1) if len(tz_part) == 5 and tz_part[2] == ":" and tz_part[:2].isdigit() and tz_part[3:].isdigit(): normalized = f"{date_part}+{tz_part}" parsed = datetime.fromisoformat(normalized) return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC) except ValueError as exc: raise HTTPException(422, f"Invalid as_of timestamp: {as_of}") from exc def _db_timestamp(dt: datetime, dialect: str) -> datetime: utc_dt = dt.astimezone(UTC) if dt.tzinfo else dt.replace(tzinfo=UTC) if dialect == "sqlite": return utc_dt.replace(tzinfo=None) return utc_dt def _envelope_from_revision( row: ComputeConfigurationRevision, *, as_of_dt: datetime | None = None, ) -> dict[str, Any]: return { "config": dict(row.config_payload or {}), "revision": row.publish_id, "publish_id": row.publish_id, "published_at": to_iso8601_utc(row.published_at), "action": row.action, "is_default": bool(row.is_default_content), "as_of": to_iso8601_utc(as_of_dt) if as_of_dt else None, "snapshot_unavailable": False, "presentation_status": row.presentation_status, } def _normalize_cached_envelope(payload: dict[str, Any]) -> dict[str, Any]: out = dict(payload) rev = out.get("revision") or out.get("publish_id") or DEFAULT_REVISION out["revision"] = rev out["publish_id"] = rev out.setdefault("published_at", None) out.setdefault("action", "baseline" if out.get("is_default") else "publish") out.setdefault("is_default", False) out.setdefault("snapshot_unavailable", False) return out async def ensure_compute_revision_baseline( db: AsyncSession, *, commit: bool = True, published_at: datetime | None = None, ) -> ComputeConfigurationRevision | None: """Idempotently seal the initial compute configuration baseline into the revision ledger.""" if not _is_relational_session(db): return None existing = ( await db.execute( select(ComputeConfigurationRevision) .order_by(ComputeConfigurationRevision.id.asc()) .limit(1) ) ).scalar_one_or_none() if isinstance(existing, ComputeConfigurationRevision): return existing setting_row = ( await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) ).scalar_one_or_none() if setting_row is not None and isinstance(setting_row.payload, dict): config_dict = dict(setting_row.payload.get("config") or default_envelope()["config"]) publish_id = str(setting_row.payload.get("revision") or DEFAULT_REVISION) else: config_dict = default_envelope()["config"] publish_id = DEFAULT_REVISION fp = compute_content_fingerprint(config_dict) now = published_at or datetime.now(UTC) dialect = _dialect_name(db) baseline = ComputeConfigurationRevision( publish_id=publish_id, parent_publish_id=None, action="baseline", content_fingerprint=fp, is_default_content=(fp == DEFAULT_CONTENT_FINGERPRINT), config_payload=config_dict, diff_summary=[], source_candidate_ids=[], publish_note="", published_by_id=None, published_by_name=None, published_by_role=None, published_at=_db_timestamp(now, dialect), presentation_status="skipped", presentation_attempts=0, presentation_error="", ) db.add(baseline) await db.flush() if commit: await db.commit() return baseline async def read_configuration( db: AsyncSession, *, as_of: datetime | str | None = None, publish_id: str | None = None, ) -> dict[str, Any]: """Read current, pinned `publish_id`, or `as_of` historical compute configuration.""" as_of_dt = _parse_as_of(as_of) pid = (publish_id or "").strip() or None dialect = _dialect_name(db) if pid is not None: row = ( await db.execute( select(ComputeConfigurationRevision).where( ComputeConfigurationRevision.publish_id == pid ) ) ).scalar_one_or_none() if not isinstance(row, ComputeConfigurationRevision): raise HTTPException(404, f"Compute configuration revision not found: {pid}") return _envelope_from_revision(row, as_of_dt=as_of_dt) if as_of_dt is not None: bound_ts = _db_timestamp(as_of_dt, dialect) row = ( await db.execute( select(ComputeConfigurationRevision) .where(ComputeConfigurationRevision.published_at <= bound_ts) .order_by( desc(ComputeConfigurationRevision.published_at), desc(ComputeConfigurationRevision.id), ) .limit(1) ) ).scalar_one_or_none() if not isinstance(row, ComputeConfigurationRevision): return { "config": None, "revision": None, "publish_id": None, "published_at": None, "action": None, "is_default": False, "as_of": to_iso8601_utc(as_of_dt), "snapshot_unavailable": True, "notice": INCOMPLETE_SNAPSHOT_NOTICE, } return _envelope_from_revision(row, as_of_dt=as_of_dt) record = ( await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) ).scalar_one_or_none() if record is not None and isinstance(record.payload, dict): return _normalize_cached_envelope(record.payload) return default_envelope() def configuration_response(envelope: dict[str, Any]) -> dict[str, Any]: return { **envelope, "countries": [ {key: country[key] for key in ("code", "name", "name_en")} for country in COUNTRY_CATALOG ], } async def _load_locked_setting(db: AsyncSession, dialect: str) -> SystemSetting: if dialect == "postgresql": await db.execute( pg_insert(SystemSetting) .values(category=CATEGORY, payload=default_envelope()) .on_conflict_do_nothing(index_elements=[SystemSetting.category]) ) return ( await db.execute( select(SystemSetting) .where(SystemSetting.category == CATEGORY) .with_for_update() ) ).scalar_one() if dialect == "sqlite": existing = ( await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) ).scalar_one_or_none() if existing is None: existing = SystemSetting(category=CATEGORY, payload=default_envelope()) db.add(existing) await db.flush() return existing # Fallback for mock DB sessions in isolated unit tests. await db.execute( pg_insert(SystemSetting) .values(category=CATEGORY, payload=default_envelope()) .on_conflict_do_nothing(index_elements=[SystemSetting.category]) ) return ( await db.execute( select(SystemSetting) .where(SystemSetting.category == CATEGORY) .with_for_update() ) ).scalar_one() async def publish_configuration( db: AsyncSession, *, revision: str, config: ComputeConfiguration, actor: User, reset: bool = False, publish_note: str = "", source_candidate_ids: list[int] | None = None, ) -> dict[str, Any]: """Atomically publish or reset compute configuration, writing revision history and cache together.""" dialect = _dialect_name(db) relational = dialect in {"postgresql", "sqlite"} record = await _load_locked_setting(db, dialect) before = _normalize_cached_envelope(record.payload) current_publish_id = str(before["revision"]) if current_publish_id != revision: await db.rollback() raise HTTPException(409, "Configuration changed. Reload before saving your edits.") effective_config = DEFAULT_CONFIGURATION if reset else config note = (publish_note or "").strip() candidate_ids = list(dict.fromkeys(int(cid) for cid in (source_candidate_ids or []))) old_config = ComputeConfiguration.model_validate(before["config"]) old_fp = compute_content_fingerprint(old_config) new_config_dict = effective_config.model_dump(mode="json") new_fp = compute_content_fingerprint(effective_config) if new_fp == old_fp and (not reset or bool(before.get("is_default"))): return { **before, "publish_id": current_publish_id, "no_changes": True, "presentation_status": "skipped", } # Share-metric mixed-source guard (M2): require explicit denominator note in publish_note. if not reset and not note: for obs in effective_config.observations: if obs.metric in SHARE_METRICS and has_mixed_sources(obs): await db.rollback() raise HTTPException( 422, "跨报告局部修订份额数据时,必须在发布说明中写明同分母依据。", ) referenced_candidates: list[ComputeEvidenceCandidate] = [] if candidate_ids and relational: found = ( ( await db.execute( select(ComputeEvidenceCandidate).where( ComputeEvidenceCandidate.id.in_(candidate_ids) ) ) ) .scalars() .all() ) by_id = {c.id: c for c in found} for cid in candidate_ids: cand = by_id.get(cid) if cand is None or cand.status != "approved" or cand.published_publish_id: await db.rollback() raise HTTPException( 422, f"候选证据 #{cid} 不存在、未审核通过或已随其他版本发布。", ) referenced_candidates.append(cand) now = datetime.now(UTC) if relational: latest_rev = ( await db.execute( select(ComputeConfigurationRevision) .order_by(desc(ComputeConfigurationRevision.id)) .limit(1) ) ).scalar_one_or_none() if not isinstance(latest_rev, ComputeConfigurationRevision): latest_rev = await ensure_compute_revision_baseline( db, commit=False, published_at=now - timedelta(milliseconds=1) ) if latest_rev is not None and latest_rev.published_at is not None: prev_ts = latest_rev.published_at prev_utc = prev_ts.astimezone(UTC) if prev_ts.tzinfo else prev_ts.replace(tzinfo=UTC) if now <= prev_utc: now = prev_utc + timedelta(milliseconds=1) diff_summary = diff_compute_configurations(old_config, effective_config) new_publish_id = uuid4().hex is_default_content = new_fp == DEFAULT_CONTENT_FINGERPRINT action = "reset" if reset else "publish" presentation_status = "pending" if has_observation_value_delta(diff_summary) else "skipped" envelope: dict[str, Any] = { "config": new_config_dict, "revision": new_publish_id, "publish_id": new_publish_id, "published_at": to_iso8601_utc(now), "action": action, "is_default": is_default_content, "no_changes": False, "presentation_status": presentation_status, "snapshot_unavailable": False, } if relational: revision_row = ComputeConfigurationRevision( publish_id=new_publish_id, parent_publish_id=current_publish_id, action=action, content_fingerprint=new_fp, is_default_content=is_default_content, config_payload=new_config_dict, diff_summary=diff_summary, source_candidate_ids=candidate_ids, publish_note=note, published_by_id=getattr(actor, "id", None), published_by_name=getattr(actor, "username", None), published_by_role=getattr(actor, "role", None), published_at=_db_timestamp(now, dialect), presentation_status=presentation_status, presentation_attempts=0, presentation_error="", ) db.add(revision_row) for cand in referenced_candidates: cand.published_publish_id = new_publish_id # Keep SystemSetting as synchronized current-version cache (never delete on reset). record.payload = { "config": new_config_dict, "revision": new_publish_id, "publish_id": new_publish_id, "published_at": to_iso8601_utc(now), "action": action, "is_default": is_default_content, } db.add( AuditLog( actor_id=getattr(actor, "id", None), actor_name=getattr(actor, "username", None), action="compute_comparison.reset" if reset else "compute_comparison.update", target_type="system_setting", target_id=CATEGORY, result="success", request_id=get_request_id(), details={ "before": before, "after": envelope, "publish_id": new_publish_id, "parent_publish_id": current_publish_id, "publish_note": note, "source_candidate_ids": candidate_ids, "diff_summary": diff_summary[:25], }, ) ) await db.commit() return envelope async def list_configuration_revisions( db: AsyncSession, *, limit: int = 20, redact: bool = False, ) -> list[dict[str, Any]]: """List recent compute configuration revisions newest first.""" bounded = max(1, min(int(limit), 100)) rows = ( ( await db.execute( select(ComputeConfigurationRevision) .order_by(desc(ComputeConfigurationRevision.id)) .limit(bounded) ) ) .scalars() .all() ) items: list[dict[str, Any]] = [] for row in rows: change_count, summary_text = summarize_diff(row.diff_summary or [], action=row.action) if redact: items.append( { "id": row.id, "publish_id": row.publish_id, "action": row.action, "published_at": to_iso8601_utc(row.published_at), "is_default_content": bool(row.is_default_content), "change_count": change_count, "summary": summary_text, } ) else: items.append( { "id": row.id, "publish_id": row.publish_id, "parent_publish_id": row.parent_publish_id, "action": row.action, "published_at": to_iso8601_utc(row.published_at), "is_default_content": bool(row.is_default_content), "change_count": change_count, "summary": summary_text, "diff_summary": list(row.diff_summary or []), "publish_note": row.publish_note or "", "published_by_name": row.published_by_name, "published_by_role": row.published_by_role, "source_candidate_ids": list(row.source_candidate_ids or []), "presentation_status": row.presentation_status, "presentation_attempts": int(row.presentation_attempts or 0), "presentation_error": row.presentation_error or "", "presentation_delivered_at": to_iso8601_utc(row.presentation_delivered_at), } ) return items