forked from linkong/planet
1802 lines
73 KiB
Python
1802 lines
73 KiB
Python
"""Base collector class for all data sources"""
|
|
|
|
import asyncio
|
|
from abc import ABC, abstractmethod
|
|
from typing import Dict, List, Any, Optional
|
|
from datetime import UTC, datetime
|
|
from time import perf_counter
|
|
from urllib.parse import urlparse
|
|
import httpx
|
|
from sqlalchemy import delete, insert, select, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.collected_data_fields import build_dynamic_metadata, get_record_field
|
|
from app.core.countries import normalize_country
|
|
from app.core.enums import JobStatus, SnapshotStatus
|
|
from app.core.logging import get_logger
|
|
from app.core.time import to_iso8601_utc
|
|
from app.core.websocket.broadcaster import broadcaster
|
|
from app.services.business_logs import emit_business_log, exception_context
|
|
from app.services.storage_policy import (
|
|
SnapshotMode,
|
|
compute_record_content_hash,
|
|
is_storage_policy_single_violation,
|
|
resolve_collector_storage_policy,
|
|
)
|
|
|
|
|
|
logger = get_logger(__name__, service="collector")
|
|
|
|
|
|
class _StoragePolicyDowngradedToSingle(Exception):
|
|
"""Internal signal when storage policy switches to single before snapshot commit."""
|
|
|
|
|
|
class BaseCollector(ABC):
|
|
"""Abstract base class for data collectors"""
|
|
|
|
name: str = "base_collector"
|
|
priority: str = "P1"
|
|
module: str = "L1"
|
|
frequency_hours: int = 4
|
|
data_type: str = "generic"
|
|
fail_on_empty: bool = False
|
|
preserve_snapshot_on_failure: bool = False
|
|
full_snapshot_reconcile: bool = False
|
|
|
|
def __init__(self):
|
|
self._current_task = None
|
|
self._db_session = None
|
|
self._datasource_id = 1
|
|
self._resolved_url: Optional[str] = None
|
|
self._last_broadcast_progress: Optional[int] = None
|
|
self._last_save_summary: dict[str, int] = {}
|
|
self._storage_policy: Optional[Dict[str, Any]] = None
|
|
self._snapshot_mode: Optional[SnapshotMode] = None
|
|
self._reused_snapshot_id: Optional[int] = None
|
|
self._reused_snapshot_backup: Optional[Dict[str, Any]] = None
|
|
self._annual_rollover_from_snapshot_id: Optional[int] = None
|
|
self._annual_rollover_milestone_year: Optional[int] = None
|
|
self._pending_new_snapshot_id: Optional[int] = None
|
|
self._previous_current_snapshot_id: Optional[int] = None
|
|
self._active_snapshot_id: Optional[int] = None
|
|
self._deduped_unchanged_snapshot_id: Optional[int] = None
|
|
self._last_source_file_sha256: Optional[str] = None
|
|
self._short_circuited_snapshot_id: Optional[int] = None
|
|
self._fetch_is_complete: bool = False
|
|
self._fetch_is_sample_fallback: bool = False
|
|
self._sample_fallback_reason: Optional[str] = None
|
|
self._db_commit_lock: Optional[asyncio.Lock] = asyncio.Lock()
|
|
|
|
def _get_db_commit_lock(self) -> asyncio.Lock:
|
|
"""Return the per-collector lock used to serialize DB session commits."""
|
|
lock = getattr(self, "_db_commit_lock", None)
|
|
if lock is None:
|
|
lock = asyncio.Lock()
|
|
self._db_commit_lock = lock
|
|
return lock
|
|
|
|
def _mark_fetch_complete(self, complete: bool = True) -> None:
|
|
"""Mark the current fetch payload as a verified full-universe snapshot."""
|
|
self._fetch_is_complete = bool(complete) and not self._fetch_is_sample_fallback
|
|
|
|
def _mark_sample_fallback(self, reason: str = "sample_fallback") -> None:
|
|
"""Mark the current fetch payload as synthetic sample fallback data."""
|
|
self._fetch_is_sample_fallback = True
|
|
self._sample_fallback_reason = reason
|
|
self._fetch_is_complete = False
|
|
|
|
def _can_reconcile_missing(self, *, existing_count: int, incoming_count: int) -> bool:
|
|
"""Allow deleting vanished entities only for verified complete non-sample snapshots."""
|
|
if self._fetch_is_sample_fallback or incoming_count <= 0:
|
|
return False
|
|
if not (self._fetch_is_complete or self.full_snapshot_reconcile):
|
|
return False
|
|
if existing_count >= 10 and incoming_count < existing_count * 0.5:
|
|
logger.warning_event(
|
|
"Skipped missing-record reconciliation due to sharp record count drop",
|
|
event="collector.reconcile.skipped_suspicious_drop",
|
|
context={
|
|
"collector_name": self.name,
|
|
"existing_count": existing_count,
|
|
"incoming_count": incoming_count,
|
|
},
|
|
)
|
|
return False
|
|
return True
|
|
|
|
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
|
|
"""Return True if persisted current records already exist for this source."""
|
|
if db is None or not callable(getattr(db, "execute", None)):
|
|
return False
|
|
from app.models.collected_data import CollectedData
|
|
|
|
try:
|
|
result = await db.execute(
|
|
select(CollectedData.id)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.is_current.is_(True),
|
|
CollectedData.deleted_at.is_(None),
|
|
)
|
|
.limit(1)
|
|
)
|
|
except Exception:
|
|
return False
|
|
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
|
return False
|
|
return result.scalar_one_or_none() is not None
|
|
|
|
async def resolve_url(self, db: AsyncSession) -> None:
|
|
from app.core.data_sources import get_data_sources_config
|
|
|
|
config = get_data_sources_config()
|
|
self._resolved_url = await config.get_url(self.name, db)
|
|
|
|
async def _publish_task_update(self, force: bool = False):
|
|
if not self._current_task:
|
|
return
|
|
|
|
progress = float(self._current_task.progress or 0.0)
|
|
rounded_progress = int(round(progress))
|
|
if not force and self._last_broadcast_progress == rounded_progress:
|
|
return
|
|
|
|
await broadcaster.broadcast_datasource_task_update(
|
|
{
|
|
"datasource_id": getattr(self, "_datasource_id", None),
|
|
"collector_name": self.name,
|
|
"task_id": self._current_task.id,
|
|
"status": self._current_task.status,
|
|
"phase": self._current_task.phase,
|
|
"phase_progress": self._current_task.phase_progress,
|
|
"phase_message": self._current_task.phase_message,
|
|
"phase_current": self._current_task.phase_current,
|
|
"phase_total": self._current_task.phase_total,
|
|
"phase_unit": self._current_task.phase_unit,
|
|
"progress": progress,
|
|
"records_processed": self._current_task.records_processed,
|
|
"total_records": self._current_task.total_records,
|
|
"started_at": to_iso8601_utc(self._current_task.started_at),
|
|
"completed_at": to_iso8601_utc(self._current_task.completed_at),
|
|
"error_message": self._current_task.error_message,
|
|
}
|
|
)
|
|
self._last_broadcast_progress = rounded_progress
|
|
|
|
async def update_progress(self, records_processed: int, *, commit: bool = False, force: bool = False):
|
|
"""Update task progress - call this during data processing"""
|
|
if not self._current_task or not self._db_session:
|
|
return
|
|
async with self._get_db_commit_lock():
|
|
self._current_task.records_processed = records_processed
|
|
if self._current_task.total_records and self._current_task.total_records > 0:
|
|
self._current_task.progress = (
|
|
records_processed / self._current_task.total_records
|
|
) * 100
|
|
else:
|
|
self._current_task.progress = 0.0
|
|
|
|
if commit:
|
|
await self._db_session.commit()
|
|
|
|
await self._publish_task_update(force=force)
|
|
|
|
async def set_phase(self, phase: str, *, message: str | None = None, reset_progress: bool = True):
|
|
if not self._current_task or not self._db_session:
|
|
return
|
|
async with self._get_db_commit_lock():
|
|
self._current_task.phase = phase
|
|
self._current_task.phase_message = message
|
|
if reset_progress:
|
|
self._current_task.phase_progress = None
|
|
self._current_task.phase_current = None
|
|
self._current_task.phase_total = None
|
|
self._current_task.phase_unit = None
|
|
await self._db_session.commit()
|
|
await self._publish_task_update(force=True)
|
|
|
|
async def update_phase_progress(
|
|
self,
|
|
*,
|
|
current: int | None = None,
|
|
total: int | None = None,
|
|
unit: str | None = None,
|
|
message: str | None = None,
|
|
progress: float | None = None,
|
|
commit: bool = False,
|
|
force: bool = False,
|
|
):
|
|
"""Update progress for the current phase without changing task totals."""
|
|
if not self._current_task or not self._db_session:
|
|
return
|
|
|
|
async with self._get_db_commit_lock():
|
|
if progress is None and current is not None and total and total > 0:
|
|
progress = (current / total) * 100
|
|
|
|
if progress is not None:
|
|
self._current_task.phase_progress = max(0.0, min(float(progress), 100.0))
|
|
if current is not None:
|
|
self._current_task.phase_current = max(0, int(current))
|
|
if total is not None:
|
|
self._current_task.phase_total = max(0, int(total))
|
|
if unit is not None:
|
|
self._current_task.phase_unit = unit
|
|
if message is not None:
|
|
self._current_task.phase_message = message
|
|
|
|
if commit:
|
|
await self._db_session.commit()
|
|
|
|
await self._publish_task_update(force=force)
|
|
|
|
@abstractmethod
|
|
async def fetch(self) -> List[Dict[str, Any]]:
|
|
"""Fetch raw data from source"""
|
|
pass
|
|
|
|
def transform(self, raw_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
"""Transform raw data to internal format (default: pass through)"""
|
|
return raw_data
|
|
|
|
def _parse_reference_date(self, value: Any) -> Optional[datetime]:
|
|
if not value:
|
|
return None
|
|
if isinstance(value, datetime):
|
|
return value
|
|
if isinstance(value, str):
|
|
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
return None
|
|
|
|
@staticmethod
|
|
def _utc_year(value: datetime | None) -> int:
|
|
dt = value or datetime.now(UTC)
|
|
if dt.tzinfo is None:
|
|
dt = dt.replace(tzinfo=UTC)
|
|
return dt.astimezone(UTC).year
|
|
|
|
async def _resolve_storage_policy(
|
|
self,
|
|
db: AsyncSession | None,
|
|
) -> tuple[SnapshotMode, Dict[str, Any]]:
|
|
mode, policy = await resolve_collector_storage_policy(db, self.name)
|
|
self._snapshot_mode = mode
|
|
self._storage_policy = policy
|
|
return mode, policy
|
|
|
|
async def _can_short_circuit_unchanged_file(
|
|
self,
|
|
db: AsyncSession | None,
|
|
*,
|
|
file_sha256: str | None,
|
|
reference_year: int | None = None,
|
|
):
|
|
"""Return active current snapshot if source file SHA-256 is unchanged in single/same-year annual mode."""
|
|
if not file_sha256 or db is None or not callable(getattr(db, "execute", None)):
|
|
return None
|
|
from app.models.collected_data import CollectedData
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
mode = self._snapshot_mode
|
|
if callable(getattr(db, "execute", None)):
|
|
mode, _ = await self._resolve_storage_policy(db)
|
|
elif mode is None:
|
|
mode = "single"
|
|
if mode not in ("single", "annual"):
|
|
return None
|
|
|
|
result = await db.execute(
|
|
select(DataSnapshot)
|
|
.where(
|
|
DataSnapshot.source == self.name,
|
|
DataSnapshot.is_current.is_(True),
|
|
DataSnapshot.status == SnapshotStatus.SUCCESS.value,
|
|
)
|
|
.order_by(DataSnapshot.completed_at.desc().nullslast(), DataSnapshot.id.desc())
|
|
.limit(1)
|
|
)
|
|
snapshot = result.scalar_one_or_none()
|
|
if not isinstance(snapshot, DataSnapshot):
|
|
return None
|
|
if mode == "annual":
|
|
target_year = reference_year or datetime.now(UTC).year
|
|
snap_dt = snapshot.completed_at or snapshot.started_at
|
|
if snap_dt is None or self._utc_year(snap_dt) != target_year:
|
|
return None
|
|
|
|
summary = snapshot.summary if isinstance(snapshot.summary, dict) else {}
|
|
if summary.get("file_sha256") != file_sha256:
|
|
return None
|
|
|
|
has_current_row = await db.scalar(
|
|
select(CollectedData.id)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.is_current.is_(True),
|
|
CollectedData.deleted_at.is_(None),
|
|
)
|
|
.limit(1)
|
|
)
|
|
if has_current_row is None:
|
|
return None
|
|
return snapshot
|
|
|
|
@staticmethod
|
|
def _backup_snapshot_state(snapshot: Any) -> Dict[str, Any]:
|
|
return {
|
|
"task_id": snapshot.task_id,
|
|
"started_at": snapshot.started_at,
|
|
"completed_at": snapshot.completed_at,
|
|
"reference_date": snapshot.reference_date,
|
|
"status": snapshot.status,
|
|
"is_current": snapshot.is_current,
|
|
"record_count": snapshot.record_count,
|
|
"summary": dict(snapshot.summary or {}),
|
|
}
|
|
|
|
@staticmethod
|
|
def _restore_snapshot_state(snapshot: Any, backup: Dict[str, Any]) -> None:
|
|
snapshot.task_id = backup["task_id"]
|
|
snapshot.started_at = backup["started_at"]
|
|
snapshot.completed_at = backup["completed_at"]
|
|
snapshot.reference_date = backup["reference_date"]
|
|
snapshot.status = backup["status"]
|
|
snapshot.is_current = backup["is_current"]
|
|
snapshot.record_count = backup["record_count"]
|
|
snapshot.summary = dict(backup["summary"])
|
|
|
|
def _build_comparable_payload(self, record: Any) -> Dict[str, Any]:
|
|
return {
|
|
"name": getattr(record, "name", None),
|
|
"title": getattr(record, "title", None),
|
|
"description": getattr(record, "description", None),
|
|
"country": get_record_field(record, "country"),
|
|
"city": get_record_field(record, "city"),
|
|
"latitude": get_record_field(record, "latitude"),
|
|
"longitude": get_record_field(record, "longitude"),
|
|
"value": get_record_field(record, "value"),
|
|
"unit": get_record_field(record, "unit"),
|
|
"metadata": getattr(record, "extra_data", None) or {},
|
|
"reference_date": (
|
|
getattr(record, "reference_date", None).isoformat()
|
|
if getattr(record, "reference_date", None)
|
|
else None
|
|
),
|
|
}
|
|
|
|
def _build_comparable_dict(
|
|
self,
|
|
*,
|
|
name: Any,
|
|
title: Any,
|
|
description: Any,
|
|
extra_data: Dict[str, Any],
|
|
reference_date: Optional[datetime],
|
|
) -> Dict[str, Any]:
|
|
return {
|
|
"name": name,
|
|
"title": title,
|
|
"description": description,
|
|
"country": extra_data.get("country"),
|
|
"city": extra_data.get("city"),
|
|
"latitude": extra_data.get("latitude"),
|
|
"longitude": extra_data.get("longitude"),
|
|
"value": extra_data.get("value"),
|
|
"unit": extra_data.get("unit"),
|
|
"metadata": extra_data,
|
|
"reference_date": reference_date.isoformat() if reference_date else None,
|
|
}
|
|
|
|
async def _create_snapshot(
|
|
self,
|
|
db: AsyncSession,
|
|
task_id: int,
|
|
data: List[Dict[str, Any]],
|
|
started_at: datetime,
|
|
) -> int:
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
if callable(getattr(db, "execute", None)):
|
|
mode, _ = await self._resolve_storage_policy(db)
|
|
else:
|
|
mode = self._snapshot_mode or "single"
|
|
|
|
reference_dates = [
|
|
parsed
|
|
for parsed in (self._parse_reference_date(item.get("reference_date")) for item in data)
|
|
if parsed is not None
|
|
]
|
|
reference_date = max(reference_dates) if reference_dates else None
|
|
|
|
result = await db.execute(
|
|
select(DataSnapshot)
|
|
.where(DataSnapshot.source == self.name, DataSnapshot.is_current.is_(True))
|
|
.order_by(DataSnapshot.completed_at.desc().nullslast(), DataSnapshot.id.desc())
|
|
.limit(1)
|
|
)
|
|
previous_snapshot = result.scalar_one_or_none()
|
|
|
|
self._reused_snapshot_id = None
|
|
self._reused_snapshot_backup = None
|
|
self._annual_rollover_from_snapshot_id = None
|
|
self._annual_rollover_milestone_year = None
|
|
self._pending_new_snapshot_id = None
|
|
self._previous_current_snapshot_id = previous_snapshot.id if previous_snapshot else None
|
|
|
|
if mode in ("single", "annual") and previous_snapshot is not None:
|
|
if mode == "annual":
|
|
run_year = self._utc_year(started_at)
|
|
prev_year = self._utc_year(
|
|
previous_snapshot.completed_at or previous_snapshot.started_at
|
|
)
|
|
if run_year > prev_year:
|
|
# Keep previous year's snapshot current until new save succeeds atomically.
|
|
self._annual_rollover_from_snapshot_id = previous_snapshot.id
|
|
self._annual_rollover_milestone_year = prev_year
|
|
|
|
snapshot = DataSnapshot(
|
|
datasource_id=getattr(self, "_datasource_id", 1),
|
|
task_id=task_id,
|
|
source=self.name,
|
|
snapshot_key=f"{self.name}:{task_id}",
|
|
reference_date=reference_date,
|
|
started_at=started_at,
|
|
status=SnapshotStatus.RUNNING.value,
|
|
is_current=False,
|
|
parent_snapshot_id=previous_snapshot.id,
|
|
summary={},
|
|
)
|
|
db.add(snapshot)
|
|
await db.commit()
|
|
self._pending_new_snapshot_id = snapshot.id
|
|
self._active_snapshot_id = snapshot.id
|
|
return snapshot.id
|
|
|
|
self._reused_snapshot_backup = self._backup_snapshot_state(previous_snapshot)
|
|
self._reused_snapshot_id = previous_snapshot.id
|
|
self._active_snapshot_id = previous_snapshot.id
|
|
previous_snapshot.task_id = task_id
|
|
previous_snapshot.started_at = started_at
|
|
previous_snapshot.reference_date = reference_date or previous_snapshot.reference_date
|
|
previous_snapshot.status = SnapshotStatus.RUNNING.value
|
|
await db.commit()
|
|
return previous_snapshot.id
|
|
|
|
# Pending snapshot stays non-current until `_save_data` commits cleanly.
|
|
snapshot = DataSnapshot(
|
|
datasource_id=getattr(self, "_datasource_id", 1),
|
|
task_id=task_id,
|
|
source=self.name,
|
|
snapshot_key=f"{self.name}:{task_id}",
|
|
reference_date=reference_date,
|
|
started_at=started_at,
|
|
status=SnapshotStatus.RUNNING.value,
|
|
is_current=False,
|
|
parent_snapshot_id=previous_snapshot.id if previous_snapshot else None,
|
|
summary={},
|
|
)
|
|
db.add(snapshot)
|
|
await db.commit()
|
|
self._pending_new_snapshot_id = snapshot.id
|
|
self._active_snapshot_id = snapshot.id
|
|
return snapshot.id
|
|
|
|
async def _promote_snapshot_to_current(
|
|
self,
|
|
db: AsyncSession,
|
|
snapshot: Any,
|
|
) -> None:
|
|
"""Atomically promote a saved snapshot to `is_current=True` and demote any prior current."""
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
if (
|
|
self._previous_current_snapshot_id is not None
|
|
and self._previous_current_snapshot_id != snapshot.id
|
|
):
|
|
previous_snapshot = await db.get(DataSnapshot, self._previous_current_snapshot_id)
|
|
if previous_snapshot is not None:
|
|
if (
|
|
self._annual_rollover_from_snapshot_id == previous_snapshot.id
|
|
and self._annual_rollover_milestone_year is not None
|
|
):
|
|
prev_summary = dict(previous_snapshot.summary or {})
|
|
prev_summary["milestone_year"] = self._annual_rollover_milestone_year
|
|
previous_snapshot.summary = prev_summary
|
|
previous_snapshot.is_current = False
|
|
|
|
if callable(getattr(db, "execute", None)):
|
|
await db.execute(
|
|
update(DataSnapshot)
|
|
.where(
|
|
DataSnapshot.source == self.name,
|
|
DataSnapshot.id != snapshot.id,
|
|
DataSnapshot.is_current.is_(True),
|
|
)
|
|
.values(is_current=False)
|
|
)
|
|
snapshot.is_current = True
|
|
|
|
async def _rollback_incomplete_run(
|
|
self,
|
|
db: AsyncSession,
|
|
*,
|
|
task_id: int,
|
|
snapshot_id: Optional[int],
|
|
reason: str,
|
|
failed_snapshot: bool = False,
|
|
) -> None:
|
|
from app.models.collected_data import CollectedData
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
if (
|
|
snapshot_id is not None
|
|
and snapshot_id == self._reused_snapshot_id
|
|
and self._reused_snapshot_backup is not None
|
|
):
|
|
await db.execute(
|
|
delete(CollectedData).where(CollectedData.task_id == task_id)
|
|
)
|
|
reused = await db.get(DataSnapshot, snapshot_id)
|
|
if reused is not None:
|
|
self._restore_snapshot_state(reused, self._reused_snapshot_backup)
|
|
return
|
|
|
|
if snapshot_id is not None:
|
|
await db.execute(
|
|
delete(CollectedData).where(
|
|
(CollectedData.task_id == task_id) | (CollectedData.snapshot_id == snapshot_id)
|
|
)
|
|
)
|
|
else:
|
|
await db.execute(delete(CollectedData).where(CollectedData.task_id == task_id))
|
|
|
|
restore_snapshot_id: Optional[int] = self._previous_current_snapshot_id
|
|
if snapshot_id is not None:
|
|
snapshot = await db.get(DataSnapshot, snapshot_id)
|
|
if snapshot:
|
|
if restore_snapshot_id is None:
|
|
restore_snapshot_id = snapshot.parent_snapshot_id
|
|
snapshot.status = (
|
|
SnapshotStatus.FAILED.value if failed_snapshot else SnapshotStatus.CANCELLED.value
|
|
)
|
|
snapshot.is_current = False
|
|
snapshot.completed_at = datetime.now(UTC)
|
|
summary = dict(snapshot.summary or {})
|
|
if failed_snapshot:
|
|
summary["error"] = reason
|
|
else:
|
|
summary["rollback"] = True
|
|
summary["rollback_reason"] = reason
|
|
snapshot.summary = summary
|
|
|
|
if restore_snapshot_id is not None and restore_snapshot_id != snapshot_id:
|
|
await db.execute(
|
|
update(DataSnapshot)
|
|
.where(
|
|
DataSnapshot.source == self.name,
|
|
DataSnapshot.id != restore_snapshot_id,
|
|
DataSnapshot.is_current.is_(True),
|
|
)
|
|
.values(is_current=False)
|
|
)
|
|
parent_snapshot = await db.get(DataSnapshot, restore_snapshot_id)
|
|
if parent_snapshot:
|
|
parent_snapshot.is_current = True
|
|
has_current_row = await db.scalar(
|
|
select(CollectedData.id)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.is_current.is_(True),
|
|
CollectedData.deleted_at.is_(None),
|
|
)
|
|
.limit(1)
|
|
)
|
|
if has_current_row is None:
|
|
await db.execute(
|
|
update(CollectedData)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.snapshot_id == restore_snapshot_id,
|
|
CollectedData.deleted_at.is_(None),
|
|
)
|
|
.values(is_current=True)
|
|
)
|
|
|
|
async def run(self, db: AsyncSession) -> Dict[str, Any]:
|
|
"""Full pipeline: fetch -> transform -> save"""
|
|
from app.services.collectors.registry import collector_registry
|
|
from app.models.task import CollectionTask
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
start_time = datetime.now(UTC)
|
|
started_at = perf_counter()
|
|
datasource_id = getattr(self, "_datasource_id", 1)
|
|
snapshot_id: Optional[int] = None
|
|
|
|
if not collector_registry.is_active(self.name):
|
|
await self._log_collection_event(
|
|
"collector.run.skipped_disabled",
|
|
"Collector skipped because it is disabled",
|
|
level="info",
|
|
context={"status": "skipped", "reason": "disabled"},
|
|
)
|
|
return {"status": "skipped", "reason": "Collector is disabled"}
|
|
|
|
task = self._current_task if isinstance(self._current_task, CollectionTask) else None
|
|
if task is None:
|
|
task = CollectionTask(
|
|
datasource_id=datasource_id,
|
|
source=self.name,
|
|
task_type="collect",
|
|
status="running",
|
|
phase="queued",
|
|
started_at=start_time,
|
|
)
|
|
db.add(task)
|
|
else:
|
|
task.datasource_id = datasource_id
|
|
task.source = task.source or self.name
|
|
task.task_type = task.task_type or "collect"
|
|
task.status = JobStatus.RUNNING.value
|
|
task.phase = "queued"
|
|
task.started_at = task.started_at or start_time
|
|
task.completed_at = None
|
|
task.error_message = None
|
|
await db.commit()
|
|
task_id = task.id
|
|
|
|
self._current_task = task
|
|
self._db_session = db
|
|
self._last_broadcast_progress = None
|
|
self._reused_snapshot_id = None
|
|
self._reused_snapshot_backup = None
|
|
self._annual_rollover_from_snapshot_id = None
|
|
self._annual_rollover_milestone_year = None
|
|
self._pending_new_snapshot_id = None
|
|
self._previous_current_snapshot_id = None
|
|
self._active_snapshot_id = None
|
|
self._deduped_unchanged_snapshot_id = None
|
|
self._last_source_file_sha256 = None
|
|
self._short_circuited_snapshot_id = None
|
|
self._fetch_is_complete = False
|
|
self._fetch_is_sample_fallback = False
|
|
self._sample_fallback_reason = None
|
|
await self._resolve_storage_policy(db)
|
|
|
|
await self.resolve_url(db)
|
|
await self._publish_task_update(force=True)
|
|
await self._log_collection_event(
|
|
"collector.run.started",
|
|
"Collector run started",
|
|
context={"status": "running", "task_id": task_id, "storage_mode": self._snapshot_mode},
|
|
)
|
|
|
|
try:
|
|
phase_started_at = perf_counter()
|
|
await self.set_phase("fetching", message="正在拉取原始数据")
|
|
await self._log_collection_event(
|
|
"collector.phase.fetching.start",
|
|
"Collector fetch phase started",
|
|
context={"task_id": task_id, "snapshot_id": snapshot_id},
|
|
)
|
|
raw_data = await self.fetch()
|
|
if self._short_circuited_snapshot_id is not None:
|
|
short_snapshot = await db.get(DataSnapshot, self._short_circuited_snapshot_id)
|
|
if short_snapshot is not None:
|
|
checked_at = datetime.now(UTC)
|
|
short_summary = dict(short_snapshot.summary or {})
|
|
short_summary["unchanged_file_skip"] = True
|
|
short_summary["storage_mode"] = self._snapshot_mode or "single"
|
|
short_summary["last_checked_at"] = to_iso8601_utc(checked_at)
|
|
short_snapshot.summary = short_summary
|
|
short_snapshot.task_id = task_id
|
|
short_snapshot.completed_at = checked_at
|
|
records_count = int(short_snapshot.record_count or 0)
|
|
task.status = JobStatus.SUCCESS.value
|
|
task.phase = "completed"
|
|
task.phase_progress = 100.0
|
|
task.phase_message = "源文件未变化,沿用当前数据"
|
|
task.phase_current = records_count
|
|
task.phase_total = records_count
|
|
task.phase_unit = "records"
|
|
task.records_processed = records_count
|
|
task.total_records = records_count
|
|
task.progress = 100.0
|
|
task.completed_at = checked_at
|
|
self._last_save_summary = {
|
|
"created": 0,
|
|
"updated": 0,
|
|
"unchanged": records_count,
|
|
"deleted": 0,
|
|
}
|
|
await db.commit()
|
|
await self._publish_task_update(force=True)
|
|
await self._log_collection_event(
|
|
"collector.run.unchanged_file_skip",
|
|
"Collector skipped parsing/saving because source file hash is unchanged",
|
|
context={
|
|
"status": "success",
|
|
"task_id": task_id,
|
|
"snapshot_id": short_snapshot.id,
|
|
"saved_count": records_count,
|
|
"storage_mode": self._snapshot_mode,
|
|
"duration_ms": self._duration_ms(started_at),
|
|
},
|
|
)
|
|
return {
|
|
"status": "success",
|
|
"task_id": task_id,
|
|
"records_processed": records_count,
|
|
"unchanged_file_skip": True,
|
|
"execution_time_seconds": (datetime.now(UTC) - start_time).total_seconds(),
|
|
}
|
|
|
|
raw_count = len(raw_data)
|
|
task.total_records = raw_count
|
|
await db.commit()
|
|
await self._publish_task_update(force=True)
|
|
await self._log_collection_event(
|
|
"collector.phase.fetching.success",
|
|
"Collector fetch phase completed",
|
|
context={
|
|
"task_id": task_id,
|
|
"raw_count": raw_count,
|
|
"duration_ms": self._duration_ms(phase_started_at),
|
|
},
|
|
)
|
|
|
|
if self.fail_on_empty and not raw_data:
|
|
raise RuntimeError(f"Collector {self.name} returned no data")
|
|
|
|
if self._fetch_is_sample_fallback and await self._has_existing_current_data(db):
|
|
raise RuntimeError(
|
|
f"Collector {self.name} fell back to sample data ({self._sample_fallback_reason}); preserving existing records"
|
|
)
|
|
|
|
phase_started_at = perf_counter()
|
|
await self.set_phase("transforming", message="正在转换采集数据")
|
|
await self._log_collection_event(
|
|
"collector.phase.transforming.start",
|
|
"Collector transform phase started",
|
|
context={"task_id": task_id, "raw_count": raw_count},
|
|
)
|
|
data = (
|
|
await asyncio.to_thread(self.transform, raw_data)
|
|
if raw_count >= 1000
|
|
else self.transform(raw_data)
|
|
)
|
|
raw_data = []
|
|
if self.fail_on_empty and not data:
|
|
raise RuntimeError(f"Collector {self.name} produced no valid records")
|
|
await self._log_collection_event(
|
|
"collector.phase.transforming.success",
|
|
"Collector transform phase completed",
|
|
context={
|
|
"task_id": task_id,
|
|
"raw_count": raw_count,
|
|
"transformed_count": len(data),
|
|
"duration_ms": self._duration_ms(phase_started_at),
|
|
},
|
|
)
|
|
snapshot_id = await self._create_snapshot(db, task_id, data, start_time)
|
|
|
|
phase_started_at = perf_counter()
|
|
await self.set_phase("saving", message="正在保存采集数据")
|
|
await self._log_collection_event(
|
|
"collector.phase.saving.start",
|
|
"Collector save phase started",
|
|
context={"task_id": task_id, "snapshot_id": snapshot_id, "transformed_count": len(data)},
|
|
)
|
|
records_count = await self._save_data(db, data, task_id=task_id, snapshot_id=snapshot_id)
|
|
effective_snapshot_id = (
|
|
self._deduped_unchanged_snapshot_id
|
|
or self._reused_snapshot_id
|
|
or self._active_snapshot_id
|
|
or snapshot_id
|
|
)
|
|
await self._log_collection_event(
|
|
"collector.phase.saving.success",
|
|
"Collector save phase completed",
|
|
context={
|
|
"task_id": task_id,
|
|
"snapshot_id": effective_snapshot_id,
|
|
"saved_count": records_count,
|
|
**self._last_save_summary,
|
|
"duration_ms": self._duration_ms(phase_started_at),
|
|
},
|
|
)
|
|
|
|
task.status = JobStatus.SUCCESS.value
|
|
task.phase = "completed"
|
|
task.phase_progress = 100.0
|
|
task.phase_message = "采集完成"
|
|
task.phase_current = records_count
|
|
task.phase_total = records_count
|
|
task.phase_unit = "records"
|
|
task.records_processed = records_count
|
|
task.progress = 100.0
|
|
task.completed_at = datetime.now(UTC)
|
|
await db.commit()
|
|
await self._publish_task_update(force=True)
|
|
await self._log_collection_event(
|
|
"collector.run.completed",
|
|
"Collector run completed",
|
|
context={
|
|
"status": "success",
|
|
"task_id": task_id,
|
|
"snapshot_id": effective_snapshot_id,
|
|
"raw_count": raw_count,
|
|
"transformed_count": len(data),
|
|
"saved_count": records_count,
|
|
**self._last_save_summary,
|
|
"duration_ms": self._duration_ms(started_at),
|
|
},
|
|
)
|
|
|
|
return {
|
|
"status": "success",
|
|
"task_id": task_id,
|
|
"records_processed": records_count,
|
|
"execution_time_seconds": (datetime.now(UTC) - start_time).total_seconds(),
|
|
}
|
|
except asyncio.CancelledError:
|
|
await db.rollback()
|
|
if self._current_task is not None and hasattr(db, "refresh"):
|
|
try:
|
|
await db.refresh(self._current_task)
|
|
except Exception:
|
|
pass
|
|
target_snapshot_id = self._active_snapshot_id or snapshot_id
|
|
task.status = JobStatus.CANCELLED.value
|
|
task.phase = "cancelled"
|
|
task.phase_message = "采集已取消"
|
|
task.error_message = "Collection cancelled by operator and rolled back"
|
|
task.completed_at = datetime.now(UTC)
|
|
if target_snapshot_id is not None:
|
|
await self._rollback_incomplete_run(
|
|
db,
|
|
task_id=task_id,
|
|
snapshot_id=target_snapshot_id,
|
|
reason="cancelled_by_operator",
|
|
failed_snapshot=False,
|
|
)
|
|
await db.commit()
|
|
await self._publish_task_update(force=True)
|
|
await self._log_collection_event(
|
|
"collector.run.cancelled",
|
|
"Collector run cancelled",
|
|
level="warning",
|
|
context={
|
|
"status": "cancelled",
|
|
"task_id": task_id,
|
|
"snapshot_id": target_snapshot_id,
|
|
"duration_ms": self._duration_ms(started_at),
|
|
},
|
|
)
|
|
raise
|
|
except Exception as e:
|
|
await db.rollback()
|
|
if self._current_task is not None and hasattr(db, "refresh"):
|
|
try:
|
|
await db.refresh(self._current_task)
|
|
except Exception:
|
|
pass
|
|
target_snapshot_id = self._active_snapshot_id or snapshot_id
|
|
if target_snapshot_id is not None:
|
|
await self._rollback_incomplete_run(
|
|
db,
|
|
task_id=task_id,
|
|
snapshot_id=target_snapshot_id,
|
|
reason=str(e),
|
|
failed_snapshot=True,
|
|
)
|
|
task.status = JobStatus.FAILED.value
|
|
task.phase = "failed"
|
|
task.phase_message = str(e)
|
|
task.error_message = str(e)
|
|
task.completed_at = datetime.now(UTC)
|
|
await db.commit()
|
|
await self._publish_task_update(force=True)
|
|
await self._log_collection_event(
|
|
"collector.run.failed",
|
|
"Collector run failed",
|
|
level="error",
|
|
context=exception_context(
|
|
e,
|
|
{
|
|
"status": "failed",
|
|
"task_id": task_id,
|
|
"snapshot_id": target_snapshot_id,
|
|
"duration_ms": self._duration_ms(started_at),
|
|
},
|
|
),
|
|
)
|
|
|
|
return {
|
|
"status": "failed",
|
|
"task_id": task_id,
|
|
"error": str(e),
|
|
"execution_time_seconds": (datetime.now(UTC) - start_time).total_seconds(),
|
|
}
|
|
|
|
def _prepare_collected_items(self, data: List[Dict[str, Any]]) -> list[dict[str, Any]]:
|
|
"""Normalize incoming transformed records and compute deterministic content hashes."""
|
|
prepared: list[dict[str, Any]] = []
|
|
for i, item in enumerate(data):
|
|
raw_metadata = item.get("metadata", {})
|
|
extra_data = build_dynamic_metadata(
|
|
raw_metadata,
|
|
country=item.get("country"),
|
|
city=item.get("city"),
|
|
latitude=item.get("latitude"),
|
|
longitude=item.get("longitude"),
|
|
value=item.get("value"),
|
|
unit=item.get("unit"),
|
|
)
|
|
normalized_country = normalize_country(item.get("country"))
|
|
if normalized_country is not None:
|
|
extra_data["country"] = normalized_country
|
|
|
|
if item.get("country") and normalized_country != item.get("country"):
|
|
extra_data["raw_country"] = item.get("country")
|
|
if normalized_country is None:
|
|
extra_data["country_validation"] = "invalid"
|
|
|
|
source_id = item.get("source_id") or item.get("id")
|
|
reference_date = self._parse_reference_date(item.get("reference_date"))
|
|
source_id_str = str(source_id) if source_id is not None else None
|
|
entity_key = f"{self.name}:{source_id_str}" if source_id_str else f"{self.name}:{i}"
|
|
comparable_payload = self._build_comparable_dict(
|
|
name=item.get("name"),
|
|
title=item.get("title"),
|
|
description=item.get("description"),
|
|
extra_data=extra_data,
|
|
reference_date=reference_date,
|
|
)
|
|
prepared.append(
|
|
{
|
|
"source_id": source_id_str,
|
|
"entity_key": entity_key,
|
|
"name": item.get("name"),
|
|
"title": item.get("title"),
|
|
"description": item.get("description"),
|
|
"extra_data": extra_data,
|
|
"reference_date": reference_date,
|
|
"content_hash": compute_record_content_hash(comparable_payload),
|
|
}
|
|
)
|
|
return prepared
|
|
|
|
async def _finalize_snapshot_after_save(
|
|
self,
|
|
db: AsyncSession,
|
|
*,
|
|
snapshot_id: Optional[int],
|
|
record_count: int,
|
|
created_count: int,
|
|
updated_count: int,
|
|
unchanged_count: int,
|
|
deleted_count: int,
|
|
storage_mode: str,
|
|
) -> None:
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
self._last_save_summary = {
|
|
"created": created_count,
|
|
"updated": updated_count,
|
|
"unchanged": unchanged_count,
|
|
"deleted": deleted_count,
|
|
}
|
|
if snapshot_id is None:
|
|
return
|
|
if storage_mode == "history" or self._annual_rollover_from_snapshot_id is not None:
|
|
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
|
|
snapshot = await db.get(DataSnapshot, snapshot_id)
|
|
if not snapshot:
|
|
return
|
|
await self._promote_snapshot_to_current(db, snapshot)
|
|
summary_payload: Dict[str, Any] = {
|
|
"created": created_count,
|
|
"updated": updated_count,
|
|
"unchanged": unchanged_count,
|
|
"deleted": deleted_count,
|
|
"storage_mode": storage_mode,
|
|
}
|
|
if self._last_source_file_sha256:
|
|
summary_payload["file_sha256"] = self._last_source_file_sha256
|
|
snapshot.record_count = record_count
|
|
snapshot.status = SnapshotStatus.SUCCESS.value
|
|
snapshot.completed_at = datetime.now(UTC)
|
|
snapshot.summary = summary_payload
|
|
|
|
async def _assert_versioned_publish_allowed(
|
|
self,
|
|
db: AsyncSession,
|
|
*,
|
|
snapshot_id: Optional[int],
|
|
) -> None:
|
|
"""Abort pending new-snapshot promotion if DB policy switched to `single` before publish."""
|
|
if (
|
|
not callable(getattr(db, "execute", None))
|
|
or snapshot_id is None
|
|
or snapshot_id != self._pending_new_snapshot_id
|
|
or self._previous_current_snapshot_id is None
|
|
):
|
|
return
|
|
mode, _ = await self._resolve_storage_policy(db)
|
|
if mode == "single":
|
|
raise _StoragePolicyDowngradedToSingle()
|
|
|
|
async def _downgrade_pending_snapshot_to_single(
|
|
self,
|
|
db: AsyncSession,
|
|
*,
|
|
task_id: Optional[int],
|
|
snapshot_id: Optional[int],
|
|
) -> Optional[int]:
|
|
"""Roll back pending versioned transaction, delete unused pending snapshot, and reuse prior current."""
|
|
from app.models.collected_data import CollectedData
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
await db.rollback()
|
|
if self._current_task is not None and hasattr(db, "refresh"):
|
|
try:
|
|
await db.refresh(self._current_task)
|
|
except Exception:
|
|
pass
|
|
|
|
self._snapshot_mode = "single"
|
|
self._deduped_unchanged_snapshot_id = None
|
|
|
|
if snapshot_id is not None and snapshot_id == self._pending_new_snapshot_id:
|
|
await db.execute(delete(CollectedData).where(CollectedData.snapshot_id == snapshot_id))
|
|
await db.execute(delete(DataSnapshot).where(DataSnapshot.id == snapshot_id))
|
|
self._pending_new_snapshot_id = None
|
|
self._annual_rollover_from_snapshot_id = None
|
|
self._annual_rollover_milestone_year = None
|
|
|
|
if self._previous_current_snapshot_id is not None:
|
|
prev_snapshot = await db.get(DataSnapshot, self._previous_current_snapshot_id)
|
|
if prev_snapshot is not None:
|
|
self._reused_snapshot_backup = self._backup_snapshot_state(prev_snapshot)
|
|
self._reused_snapshot_id = prev_snapshot.id
|
|
self._active_snapshot_id = prev_snapshot.id
|
|
prev_snapshot.task_id = task_id
|
|
prev_snapshot.status = SnapshotStatus.RUNNING.value
|
|
return prev_snapshot.id
|
|
|
|
return None
|
|
|
|
async def _save_data(
|
|
self,
|
|
db: AsyncSession,
|
|
data: List[Dict[str, Any]],
|
|
task_id: Optional[int] = None,
|
|
snapshot_id: Optional[int] = None,
|
|
) -> int:
|
|
"""Save transformed data to database according to effective storage mode."""
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
if callable(getattr(db, "execute", None)):
|
|
mode, _ = await self._resolve_storage_policy(db)
|
|
else:
|
|
mode = self._snapshot_mode or "single"
|
|
|
|
if self._fetch_is_sample_fallback and await self._has_existing_current_data(db):
|
|
raise RuntimeError(
|
|
f"Collector {self.name} refused to save sample fallback data over existing records"
|
|
)
|
|
|
|
if not data:
|
|
if (
|
|
self._previous_current_snapshot_id is not None
|
|
and await self._has_existing_current_data(db)
|
|
):
|
|
preserved_count = 0
|
|
prev_snapshot = await db.get(DataSnapshot, self._previous_current_snapshot_id)
|
|
if prev_snapshot is not None:
|
|
preserved_count = int(prev_snapshot.record_count or 0)
|
|
if (
|
|
snapshot_id is not None
|
|
and snapshot_id == self._reused_snapshot_id
|
|
and self._reused_snapshot_backup is not None
|
|
):
|
|
reused = await db.get(DataSnapshot, snapshot_id)
|
|
if reused is not None:
|
|
self._restore_snapshot_state(reused, self._reused_snapshot_backup)
|
|
elif snapshot_id is not None and snapshot_id == self._pending_new_snapshot_id:
|
|
await db.execute(delete(DataSnapshot).where(DataSnapshot.id == snapshot_id))
|
|
self._pending_new_snapshot_id = None
|
|
self._deduped_unchanged_snapshot_id = self._previous_current_snapshot_id
|
|
self._last_save_summary = {
|
|
"created": 0,
|
|
"updated": 0,
|
|
"unchanged": preserved_count,
|
|
"deleted": 0,
|
|
}
|
|
await db.commit()
|
|
return preserved_count
|
|
|
|
self._last_save_summary = {"created": 0, "updated": 0, "unchanged": 0, "deleted": 0}
|
|
if snapshot_id is not None:
|
|
snapshot = await db.get(DataSnapshot, snapshot_id)
|
|
if snapshot:
|
|
await self._promote_snapshot_to_current(db, snapshot)
|
|
snapshot.record_count = 0
|
|
snapshot.summary = {
|
|
"created": 0,
|
|
"updated": 0,
|
|
"unchanged": 0,
|
|
"deleted": 0,
|
|
"storage_mode": mode,
|
|
}
|
|
snapshot.status = SnapshotStatus.SUCCESS.value
|
|
snapshot.completed_at = datetime.now(UTC)
|
|
await db.commit()
|
|
return 0
|
|
|
|
# Reconcile mid-flight policy switches between _create_snapshot and _save_data.
|
|
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
|
|
db,
|
|
mode=mode,
|
|
task_id=task_id,
|
|
snapshot_id=snapshot_id,
|
|
)
|
|
|
|
if mode == "history" or self._annual_rollover_from_snapshot_id is not None:
|
|
try:
|
|
return await self._save_data_versioned(
|
|
db,
|
|
data,
|
|
task_id=task_id,
|
|
snapshot_id=snapshot_id,
|
|
storage_mode=mode,
|
|
)
|
|
except Exception as exc:
|
|
if (
|
|
not isinstance(exc, _StoragePolicyDowngradedToSingle)
|
|
and not is_storage_policy_single_violation(exc)
|
|
) or self._previous_current_snapshot_id is None:
|
|
raise
|
|
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
|
|
db,
|
|
task_id=task_id,
|
|
snapshot_id=snapshot_id,
|
|
)
|
|
return await self._save_data_incremental_upsert(
|
|
db,
|
|
data,
|
|
task_id=task_id,
|
|
snapshot_id=downgraded_snapshot_id,
|
|
storage_mode="single",
|
|
)
|
|
return await self._save_data_incremental_upsert(
|
|
db,
|
|
data,
|
|
task_id=task_id,
|
|
snapshot_id=snapshot_id,
|
|
storage_mode=mode,
|
|
)
|
|
|
|
async def _reconcile_snapshot_for_mode_switch(
|
|
self,
|
|
db: AsyncSession,
|
|
*,
|
|
mode: str,
|
|
task_id: Optional[int],
|
|
snapshot_id: Optional[int],
|
|
) -> Optional[int]:
|
|
"""Reconcile pending vs reused snapshot if policy switched mid-fetch before saving."""
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
if snapshot_id is None:
|
|
return None
|
|
if (
|
|
mode == "single"
|
|
and snapshot_id == self._pending_new_snapshot_id
|
|
and self._previous_current_snapshot_id is not None
|
|
):
|
|
await db.execute(delete(DataSnapshot).where(DataSnapshot.id == snapshot_id))
|
|
prev_snapshot = await db.get(DataSnapshot, self._previous_current_snapshot_id)
|
|
if prev_snapshot is not None:
|
|
self._reused_snapshot_backup = self._backup_snapshot_state(prev_snapshot)
|
|
self._reused_snapshot_id = prev_snapshot.id
|
|
self._active_snapshot_id = prev_snapshot.id
|
|
self._pending_new_snapshot_id = None
|
|
self._annual_rollover_from_snapshot_id = None
|
|
self._annual_rollover_milestone_year = None
|
|
prev_snapshot.task_id = task_id
|
|
prev_snapshot.status = SnapshotStatus.RUNNING.value
|
|
return prev_snapshot.id
|
|
elif (
|
|
mode == "history"
|
|
and snapshot_id == self._reused_snapshot_id
|
|
and self._reused_snapshot_backup is not None
|
|
):
|
|
reused = await db.get(DataSnapshot, snapshot_id)
|
|
if reused is not None:
|
|
self._restore_snapshot_state(reused, self._reused_snapshot_backup)
|
|
new_snapshot = DataSnapshot(
|
|
datasource_id=getattr(self, "_datasource_id", 1),
|
|
task_id=task_id,
|
|
source=self.name,
|
|
snapshot_key=f"{self.name}:{task_id}" if task_id is not None else self.name,
|
|
started_at=datetime.now(UTC),
|
|
status=SnapshotStatus.RUNNING.value,
|
|
is_current=False,
|
|
parent_snapshot_id=snapshot_id,
|
|
summary={},
|
|
)
|
|
db.add(new_snapshot)
|
|
if hasattr(db, "flush"):
|
|
await db.flush()
|
|
self._reused_snapshot_id = None
|
|
self._reused_snapshot_backup = None
|
|
self._pending_new_snapshot_id = new_snapshot.id
|
|
self._active_snapshot_id = new_snapshot.id
|
|
return new_snapshot.id
|
|
return snapshot_id
|
|
|
|
async def _save_data_incremental_upsert(
|
|
self,
|
|
db: AsyncSession,
|
|
data: List[Dict[str, Any]],
|
|
*,
|
|
task_id: Optional[int],
|
|
snapshot_id: Optional[int],
|
|
storage_mode: str,
|
|
) -> int:
|
|
"""In-place diff upsert keeping one current row per entity without adding history."""
|
|
from app.models.collected_data import CollectedData
|
|
|
|
collected_at = datetime.now(UTC)
|
|
existing_rows_result = await db.execute(
|
|
select(
|
|
CollectedData.id,
|
|
CollectedData.entity_key,
|
|
CollectedData.content_hash,
|
|
)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.is_current.is_(True),
|
|
CollectedData.deleted_at.is_(None),
|
|
)
|
|
.order_by(CollectedData.collected_at.desc().nullslast(), CollectedData.id.desc())
|
|
)
|
|
|
|
existing_by_key: dict[str, tuple[int, Optional[str]]] = {}
|
|
duplicate_current_ids: list[int] = []
|
|
for row_id, entity_key, content_hash in existing_rows_result.all():
|
|
if not entity_key:
|
|
continue
|
|
if entity_key not in existing_by_key:
|
|
existing_by_key[entity_key] = (int(row_id), content_hash)
|
|
else:
|
|
duplicate_current_ids.append(int(row_id))
|
|
|
|
chunk_size = 500
|
|
for offset in range(0, len(duplicate_current_ids), chunk_size):
|
|
chunk = duplicate_current_ids[offset : offset + chunk_size]
|
|
await db.execute(
|
|
update(CollectedData)
|
|
.where(CollectedData.id.in_(chunk))
|
|
.values(is_current=False)
|
|
)
|
|
|
|
prepared_items = (
|
|
await asyncio.to_thread(self._prepare_collected_items, data)
|
|
if len(data) >= 1000
|
|
else self._prepare_collected_items(data)
|
|
)
|
|
deduped_by_key: dict[str, dict[str, Any]] = {}
|
|
for item in prepared_items:
|
|
deduped_by_key.setdefault(item["entity_key"], item)
|
|
prepared_items.clear()
|
|
|
|
legacy_hash_missing: dict[int, dict[str, Any]] = {}
|
|
known_updates: dict[int, dict[str, Any]] = {}
|
|
new_items: list[dict[str, Any]] = []
|
|
unchanged_count = 0
|
|
|
|
for entity_key, item in deduped_by_key.items():
|
|
existing = existing_by_key.get(entity_key)
|
|
if existing is None:
|
|
new_items.append(item)
|
|
continue
|
|
existing_id, existing_hash = existing
|
|
if existing_hash is None:
|
|
legacy_hash_missing[existing_id] = item
|
|
elif existing_hash == item["content_hash"]:
|
|
unchanged_count += 1
|
|
else:
|
|
known_updates[existing_id] = item
|
|
|
|
updated_count = 0
|
|
for row_id_map in (known_updates, legacy_hash_missing):
|
|
row_ids = list(row_id_map.keys())
|
|
for offset in range(0, len(row_ids), chunk_size):
|
|
chunk = row_ids[offset : offset + chunk_size]
|
|
orm_result = await db.execute(
|
|
select(CollectedData).where(CollectedData.id.in_(chunk))
|
|
)
|
|
for record in orm_result.scalars().all():
|
|
item = row_id_map[record.id]
|
|
if row_id_map is legacy_hash_missing:
|
|
old_payload = self._build_comparable_payload(record)
|
|
if compute_record_content_hash(old_payload) == item["content_hash"]:
|
|
record.content_hash = item["content_hash"]
|
|
unchanged_count += 1
|
|
continue
|
|
else:
|
|
old_payload = self._build_comparable_payload(record)
|
|
|
|
new_payload = self._build_comparable_dict(
|
|
name=item["name"],
|
|
title=item["title"],
|
|
description=item["description"],
|
|
extra_data=item["extra_data"],
|
|
reference_date=item["reference_date"],
|
|
)
|
|
changed_fields = [
|
|
key
|
|
for key in new_payload.keys()
|
|
if new_payload[key] != old_payload.get(key)
|
|
]
|
|
record.snapshot_id = snapshot_id
|
|
record.task_id = task_id
|
|
record.source_id = item["source_id"]
|
|
record.data_type = self.data_type
|
|
record.name = item["name"]
|
|
record.title = item["title"]
|
|
record.description = item["description"]
|
|
record.extra_data = item["extra_data"]
|
|
record.collected_at = collected_at
|
|
record.reference_date = item["reference_date"]
|
|
record.is_valid = 1
|
|
record.is_current = True
|
|
record.previous_record_id = None
|
|
record.change_type = "updated"
|
|
record.change_summary = {"changed_fields": changed_fields}
|
|
record.content_hash = item["content_hash"]
|
|
record.deleted_at = None
|
|
updated_count += 1
|
|
if hasattr(db, "flush"):
|
|
await db.flush()
|
|
|
|
can_reconcile = self._can_reconcile_missing(
|
|
existing_count=len(existing_by_key),
|
|
incoming_count=len(deduped_by_key),
|
|
)
|
|
vanished_ids = (
|
|
[
|
|
row_id
|
|
for entity_key, (row_id, _hash) in existing_by_key.items()
|
|
if entity_key not in deduped_by_key
|
|
]
|
|
if can_reconcile
|
|
else []
|
|
)
|
|
for offset in range(0, len(vanished_ids), chunk_size):
|
|
chunk = vanished_ids[offset : offset + chunk_size]
|
|
await db.execute(
|
|
update(CollectedData)
|
|
.where(CollectedData.previous_record_id.in_(chunk))
|
|
.values(previous_record_id=None)
|
|
.execution_options(synchronize_session="fetch")
|
|
)
|
|
await db.execute(
|
|
delete(CollectedData)
|
|
.where(
|
|
CollectedData.id.in_(chunk),
|
|
CollectedData.source == self.name,
|
|
CollectedData.is_current.is_(True),
|
|
)
|
|
.execution_options(synchronize_session="fetch")
|
|
)
|
|
|
|
for chunk_index, offset in enumerate(range(0, len(new_items), chunk_size), start=1):
|
|
batch_rows = [
|
|
{
|
|
"snapshot_id": snapshot_id,
|
|
"task_id": task_id,
|
|
"source": self.name,
|
|
"source_id": item["source_id"],
|
|
"entity_key": item["entity_key"],
|
|
"data_type": self.data_type,
|
|
"name": item["name"],
|
|
"title": item["title"],
|
|
"description": item["description"],
|
|
"extra_data": item["extra_data"],
|
|
"collected_at": collected_at,
|
|
"reference_date": item["reference_date"],
|
|
"is_valid": 1,
|
|
"is_current": True,
|
|
"previous_record_id": None,
|
|
"change_type": "created",
|
|
"change_summary": {},
|
|
"content_hash": item["content_hash"],
|
|
"deleted_at": None,
|
|
}
|
|
for item in new_items[offset : offset + chunk_size]
|
|
]
|
|
await db.execute(insert(CollectedData), batch_rows)
|
|
if chunk_index % 10 == 0 and hasattr(db, "flush"):
|
|
await db.flush()
|
|
|
|
created_count = len(new_items)
|
|
total_current = len(existing_by_key) - len(vanished_ids) + created_count
|
|
await self._finalize_snapshot_after_save(
|
|
db,
|
|
snapshot_id=snapshot_id,
|
|
record_count=total_current,
|
|
created_count=created_count,
|
|
updated_count=updated_count,
|
|
unchanged_count=unchanged_count,
|
|
deleted_count=len(vanished_ids),
|
|
storage_mode=storage_mode,
|
|
)
|
|
await db.commit()
|
|
await self.update_progress(total_current, force=True)
|
|
return total_current
|
|
|
|
async def _save_data_versioned(
|
|
self,
|
|
db: AsyncSession,
|
|
data: List[Dict[str, Any]],
|
|
*,
|
|
task_id: Optional[int],
|
|
snapshot_id: Optional[int],
|
|
storage_mode: str,
|
|
) -> int:
|
|
"""Append-only versioned snapshot write path used in `history` and annual rollovers."""
|
|
from app.models.collected_data import CollectedData
|
|
from app.models.data_snapshot import DataSnapshot
|
|
|
|
collected_at = datetime.now(UTC)
|
|
created_count = 0
|
|
updated_count = 0
|
|
unchanged_count = 0
|
|
progress_flush_interval = 1000
|
|
chunk_size = 500
|
|
|
|
previous_current_result = await db.execute(
|
|
select(CollectedData)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.is_current.is_(True),
|
|
)
|
|
.order_by(CollectedData.entity_key.asc(), CollectedData.collected_at.desc().nullslast(), CollectedData.id.desc())
|
|
)
|
|
previous_current_records = previous_current_result.scalars().all()
|
|
previous_current_keys = {record.entity_key for record in previous_current_records if record.entity_key}
|
|
previous_current_map: dict[str, CollectedData] = {}
|
|
stale_previous_records: list[CollectedData] = []
|
|
|
|
for existing_record in previous_current_records:
|
|
entity_key = existing_record.entity_key
|
|
if not entity_key:
|
|
continue
|
|
if entity_key not in previous_current_map:
|
|
previous_current_map[entity_key] = existing_record
|
|
continue
|
|
stale_previous_records.append(existing_record)
|
|
|
|
prepared_items = (
|
|
await asyncio.to_thread(self._prepare_collected_items, data)
|
|
if len(data) >= 1000
|
|
else self._prepare_collected_items(data)
|
|
)
|
|
deduped_items: list[dict[str, Any]] = []
|
|
seen_entity_keys: set[str] = set()
|
|
for item in prepared_items:
|
|
entity_key = item["entity_key"]
|
|
if entity_key in seen_entity_keys:
|
|
continue
|
|
seen_entity_keys.add(entity_key)
|
|
deduped_items.append(item)
|
|
prepared_items.clear()
|
|
|
|
classified_items: list[tuple[dict[str, Any], Optional[CollectedData], str, dict[str, Any]]] = []
|
|
for item in deduped_items:
|
|
entity_key = item["entity_key"]
|
|
previous_record = previous_current_map.get(entity_key)
|
|
if previous_record is None:
|
|
change_type = "created"
|
|
change_summary: dict[str, Any] = {}
|
|
created_count += 1
|
|
elif previous_record.content_hash is not None and previous_record.content_hash == item["content_hash"]:
|
|
change_type = "unchanged"
|
|
change_summary = {}
|
|
unchanged_count += 1
|
|
else:
|
|
previous_payload = self._build_comparable_payload(previous_record)
|
|
current_payload = self._build_comparable_dict(
|
|
name=item["name"],
|
|
title=item["title"],
|
|
description=item["description"],
|
|
extra_data=item["extra_data"],
|
|
reference_date=item["reference_date"],
|
|
)
|
|
if current_payload == previous_payload:
|
|
change_type = "unchanged"
|
|
change_summary = {}
|
|
unchanged_count += 1
|
|
else:
|
|
changed_fields = [
|
|
key for key in current_payload.keys() if current_payload[key] != previous_payload.get(key)
|
|
]
|
|
change_type = "updated"
|
|
change_summary = {"changed_fields": changed_fields}
|
|
updated_count += 1
|
|
classified_items.append((item, previous_record, change_type, change_summary))
|
|
|
|
can_reconcile = self._can_reconcile_missing(
|
|
existing_count=len(previous_current_map),
|
|
incoming_count=len(deduped_items),
|
|
)
|
|
deleted_keys = (previous_current_keys - seen_entity_keys) if can_reconcile else set()
|
|
|
|
# In history mode, identical full input must not append a duplicate version/snapshot.
|
|
if (
|
|
storage_mode == "history"
|
|
and self._annual_rollover_from_snapshot_id is None
|
|
and self._previous_current_snapshot_id is not None
|
|
and created_count == 0
|
|
and updated_count == 0
|
|
and len(deleted_keys) == 0
|
|
):
|
|
if snapshot_id is not None and snapshot_id == self._pending_new_snapshot_id:
|
|
await db.execute(delete(DataSnapshot).where(DataSnapshot.id == snapshot_id))
|
|
self._pending_new_snapshot_id = None
|
|
self._deduped_unchanged_snapshot_id = self._previous_current_snapshot_id
|
|
self._last_save_summary = {
|
|
"created": 0,
|
|
"updated": 0,
|
|
"unchanged": unchanged_count,
|
|
"deleted": 0,
|
|
}
|
|
await db.commit()
|
|
preserved_total = len(previous_current_map)
|
|
await self.update_progress(preserved_total, force=True)
|
|
return preserved_total
|
|
|
|
new_records: list[CollectedData] = []
|
|
for i, (item, previous_record, change_type, change_summary) in enumerate(classified_items):
|
|
record = CollectedData(
|
|
snapshot_id=snapshot_id,
|
|
task_id=task_id,
|
|
source=self.name,
|
|
source_id=item["source_id"],
|
|
entity_key=item["entity_key"],
|
|
data_type=self.data_type,
|
|
name=item["name"],
|
|
title=item["title"],
|
|
description=item["description"],
|
|
extra_data=item["extra_data"],
|
|
collected_at=collected_at,
|
|
reference_date=item["reference_date"],
|
|
is_valid=1,
|
|
is_current=False,
|
|
previous_record_id=previous_record.id if previous_record else None,
|
|
change_type=change_type,
|
|
change_summary=change_summary,
|
|
content_hash=item["content_hash"],
|
|
deleted_at=None,
|
|
)
|
|
db.add(record)
|
|
new_records.append(record)
|
|
|
|
if (i + 1) % progress_flush_interval == 0:
|
|
if hasattr(db, "flush"):
|
|
await db.flush()
|
|
await self.update_progress(i + 1, commit=False)
|
|
|
|
if hasattr(db, "flush"):
|
|
await db.flush()
|
|
|
|
for stale_record in stale_previous_records:
|
|
stale_record.is_current = False
|
|
|
|
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
|
|
|
|
records_added = len(new_records)
|
|
total_current = records_added if can_reconcile else (len(previous_current_map) + created_count)
|
|
|
|
if snapshot_id is not None:
|
|
if can_reconcile:
|
|
await db.execute(
|
|
update(CollectedData)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
(CollectedData.snapshot_id != snapshot_id) | (CollectedData.snapshot_id.is_(None)),
|
|
(CollectedData.is_current.is_(True)) | (CollectedData.is_current.is_(None)),
|
|
)
|
|
.values(is_current=False)
|
|
)
|
|
else:
|
|
seen_list = list(seen_entity_keys)
|
|
for offset in range(0, len(seen_list), chunk_size):
|
|
chunk = seen_list[offset : offset + chunk_size]
|
|
await db.execute(
|
|
update(CollectedData)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.entity_key.in_(chunk),
|
|
(CollectedData.snapshot_id != snapshot_id) | (CollectedData.snapshot_id.is_(None)),
|
|
(CollectedData.is_current.is_(True)) | (CollectedData.is_current.is_(None)),
|
|
)
|
|
.values(is_current=False)
|
|
)
|
|
await db.execute(
|
|
update(CollectedData)
|
|
.where(
|
|
CollectedData.source == self.name,
|
|
CollectedData.snapshot_id == snapshot_id,
|
|
)
|
|
.values(is_current=True)
|
|
)
|
|
await self._finalize_snapshot_after_save(
|
|
db,
|
|
snapshot_id=snapshot_id,
|
|
record_count=total_current,
|
|
created_count=created_count,
|
|
updated_count=updated_count,
|
|
unchanged_count=unchanged_count,
|
|
deleted_count=len(deleted_keys),
|
|
storage_mode=storage_mode,
|
|
)
|
|
else:
|
|
for item, previous_record, _change_type, _change_summary in classified_items:
|
|
if previous_record is not None:
|
|
previous_record.is_current = False
|
|
if can_reconcile:
|
|
for key in deleted_keys:
|
|
vanished = previous_current_map.get(key)
|
|
if vanished is not None:
|
|
vanished.is_current = False
|
|
for new_rec in new_records:
|
|
new_rec.is_current = True
|
|
self._last_save_summary = {
|
|
"created": created_count,
|
|
"updated": updated_count,
|
|
"unchanged": unchanged_count,
|
|
"deleted": len(deleted_keys),
|
|
}
|
|
|
|
await db.commit()
|
|
await self.update_progress(total_current, force=True)
|
|
return total_current
|
|
|
|
@staticmethod
|
|
def _duration_ms(started_at: float) -> int:
|
|
return int((perf_counter() - started_at) * 1000)
|
|
|
|
async def _log_collection_event(
|
|
self,
|
|
event: str,
|
|
message: str,
|
|
*,
|
|
level: str = "info",
|
|
context: Dict[str, Any] | None = None,
|
|
) -> None:
|
|
await emit_business_log(
|
|
logger,
|
|
event=event,
|
|
message=message,
|
|
category="collector",
|
|
level=level,
|
|
service="collector",
|
|
module=__name__,
|
|
context={
|
|
"collector_name": self.name,
|
|
"datasource_id": getattr(self, "_datasource_id", None),
|
|
**(context or {}),
|
|
},
|
|
)
|
|
|
|
async def save(self, db: AsyncSession, data: List[Dict[str, Any]]) -> int:
|
|
"""Save data to database (legacy method, use _save_data instead)"""
|
|
return await self._save_data(db, data)
|
|
|
|
|
|
class HTTPCollector(BaseCollector):
|
|
"""Base class for HTTP API collectors"""
|
|
|
|
base_url: str = ""
|
|
headers: Dict[str, str] = {}
|
|
|
|
async def fetch(self) -> List[Dict[str, Any]]:
|
|
started_at = perf_counter()
|
|
request_host = urlparse(self.base_url).netloc
|
|
await emit_business_log(
|
|
logger,
|
|
event="collector.http.fetch.start",
|
|
message="Collector HTTP request started",
|
|
category="collector",
|
|
service="collector",
|
|
module=__name__,
|
|
context={
|
|
"collector_name": self.name,
|
|
"datasource_id": getattr(self, "_datasource_id", None),
|
|
"url_host": request_host,
|
|
},
|
|
)
|
|
async with httpx.AsyncClient(timeout=60.0) as client:
|
|
try:
|
|
response = await client.get(self.base_url, headers=self.headers)
|
|
response.raise_for_status()
|
|
payload = response.json()
|
|
parsed = self.parse_response(payload)
|
|
await emit_business_log(
|
|
logger,
|
|
event="collector.http.fetch.success",
|
|
message="Collector HTTP request completed",
|
|
category="collector",
|
|
service="collector",
|
|
module=__name__,
|
|
context={
|
|
"collector_name": self.name,
|
|
"datasource_id": getattr(self, "_datasource_id", None),
|
|
"url_host": request_host,
|
|
"status_code": response.status_code,
|
|
"response_bytes": len(response.content or b""),
|
|
"parsed_count": len(parsed),
|
|
"duration_ms": BaseCollector._duration_ms(started_at),
|
|
},
|
|
)
|
|
return parsed
|
|
except Exception as exc:
|
|
await emit_business_log(
|
|
logger,
|
|
event="collector.http.fetch.failed",
|
|
message="Collector HTTP request failed",
|
|
category="collector",
|
|
level="error",
|
|
service="collector",
|
|
module=__name__,
|
|
context=exception_context(
|
|
exc,
|
|
{
|
|
"collector_name": self.name,
|
|
"datasource_id": getattr(self, "_datasource_id", None),
|
|
"url_host": request_host,
|
|
"duration_ms": BaseCollector._duration_ms(started_at),
|
|
},
|
|
),
|
|
)
|
|
raise
|
|
|
|
@abstractmethod
|
|
def parse_response(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
pass
|
|
|
|
|
|
class IntervalCollector(BaseCollector):
|
|
"""Base class for collectors that run on intervals"""
|
|
|
|
async def run(self, db: AsyncSession) -> Dict[str, Any]:
|
|
return await super().run(db)
|
|
|
|
|
|
async def log_task(
|
|
db: AsyncSession,
|
|
datasource_id: int,
|
|
status: str,
|
|
records_processed: int = 0,
|
|
error_message: Optional[str] = None,
|
|
):
|
|
"""Log collection task to database"""
|
|
from app.models.task import CollectionTask
|
|
|
|
task = CollectionTask(
|
|
datasource_id=datasource_id,
|
|
status=status,
|
|
records_processed=records_processed,
|
|
error_message=error_message,
|
|
started_at=datetime.now(UTC),
|
|
completed_at=datetime.now(UTC),
|
|
)
|
|
db.add(task)
|
|
await db.commit()
|