app/collectors/base.py (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Protocol
import httpx
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import Settings
from app.db.models import CollectorCache, SourceImportRun, Tracker, TrackerSource
from app.services.normalize import (
NormalizationError,
NormalizedTracker,
normalize_tracker_url,
parse_tracker_list_text,
)
@dataclass
class ImportStats:
received: int = 0
valid: int = 0
new: int = 0
unsupported: int = 0
skipped_invalid: int = 0
not_modified: bool = False
error: str | None = None
@dataclass
class FeedFetchResult:
body: str | None
etag: str | None
last_modified: str | None
not_modified: bool = False
status_code: int = 0
async def fetch_text_feed(
client: httpx.AsyncClient,
url: str,
*,
etag: str | None = None,
last_modified: str | None = None,
) -> FeedFetchResult:
headers: dict[str, str] = {}
if etag:
headers["If-None-Match"] = etag
if last_modified:
headers["If-Modified-Since"] = last_modified
response = await client.get(url, headers=headers)
if response.status_code == 304:
return FeedFetchResult(
body=None,
etag=etag,
last_modified=last_modified,
not_modified=True,
status_code=304,
)
response.raise_for_status()
return FeedFetchResult(
body=response.text,
etag=response.headers.get("ETag"),
last_modified=response.headers.get("Last-Modified"),
not_modified=False,
status_code=response.status_code,
)
async def get_cache(session: AsyncSession, feed_url: str) -> CollectorCache | None:
result = await session.execute(
select(CollectorCache).where(CollectorCache.feed_url == feed_url)
)
return result.scalar_one_or_none()
async def upsert_cache(
session: AsyncSession,
*,
source_name: str,
feed_url: str,
etag: str | None,
last_modified: str | None,
) -> None:
row = await get_cache(session, feed_url)
now = datetime.now(UTC)
if row is None:
session.add(
CollectorCache(
source_name=source_name,
feed_url=feed_url,
etag=etag,
last_modified=last_modified,
updated_at=now,
)
)
else:
row.etag = etag
row.last_modified = last_modified
row.updated_at = now
def sanitize_error(message: str, limit: int = 512) -> str:
text = " ".join(message.split())
return text[:limit]
async def upsert_tracker_from_normalized(
session: AsyncSession,
normalized: NormalizedTracker,
*,
source_name: str,
source_url: str,
is_best: bool = False,
is_stable: bool = False,
is_live: bool = False,
) -> tuple[Tracker, bool]:
"""Insert or update tracker + source association. Returns (tracker, created)."""
now = datetime.now(UTC)
result = await session.execute(
select(Tracker).where(Tracker.canonical_url == normalized.canonical_url)
)
tracker = result.scalar_one_or_none()
created = False
if tracker is None:
created = True
tracker = Tracker(
canonical_url=normalized.canonical_url,
scheme=normalized.scheme,
hostname=normalized.hostname,
port=normalized.port,
path=normalized.path,
current_status="unsupported" if normalized.unsupported else "unknown",
first_seen_at=now,
last_seen_at=now,
consecutive_failures=0,
)
session.add(tracker)
await session.flush()
else:
tracker.last_seen_at = now
if normalized.unsupported:
tracker.current_status = "unsupported"
src_result = await session.execute(
select(TrackerSource).where(
TrackerSource.tracker_id == tracker.id,
TrackerSource.source_name == source_name,
)
)
association = src_result.scalar_one_or_none()
if association is None:
session.add(
TrackerSource(
tracker_id=tracker.id,
source_name=source_name,
source_url=source_url,
is_best_at_source=is_best,
is_stable_at_source=is_stable,
is_live_at_source=is_live,
first_seen_at=now,
last_seen_at=now,
)
)
else:
association.last_seen_at = now
association.source_url = source_url
if is_best:
association.is_best_at_source = True
if is_stable:
association.is_stable_at_source = True
if is_live:
association.is_live_at_source = True
return tracker, created
@dataclass
class ParsedEntries:
valid: list[NormalizedTracker] = field(default_factory=list)
unsupported: list[NormalizedTracker] = field(default_factory=list)
invalid: int = 0
received: int = 0
def parse_and_normalize(body: str) -> ParsedEntries:
raw_urls = parse_tracker_list_text(body)
parsed = ParsedEntries(received=len(raw_urls))
seen_canonical: set[str] = set()
for raw in raw_urls:
try:
normalized = normalize_tracker_url(raw)
except NormalizationError:
parsed.invalid += 1
continue
if normalized.canonical_url in seen_canonical:
continue
seen_canonical.add(normalized.canonical_url)
if normalized.unsupported:
parsed.unsupported.append(normalized)
else:
parsed.valid.append(normalized)
return parsed
@dataclass
class EnrichmentFeed:
"""A secondary feed that only sets provenance flags (best/stable/live).
Enrichment feeds are best-effort: a failure never fails the whole import and
never touches measurement data.
"""
url: str
is_best: bool = False
is_stable: bool = False
is_live: bool = False
async def import_source_feeds(
session: AsyncSession,
client: httpx.AsyncClient,
*,
source_name: str,
primary_url: str,
enrichments: Sequence[EnrichmentFeed] = (),
) -> ImportStats:
"""Run the full import lifecycle for a text-feed source.
Generalizes the pattern used by the trackerslist/newTrackon collectors:
one primary feed (cached via ETag/Last-Modified, guarded against empty
responses) plus zero or more best-effort enrichment feeds.
"""
stats = ImportStats()
run = SourceImportRun(
source_name=source_name,
started_at=datetime.now(UTC),
status="running",
received_count=0,
valid_count=0,
new_count=0,
unsupported_count=0,
)
session.add(run)
await session.flush()
try:
cache = await get_cache(session, primary_url)
feed = await fetch_text_feed(
client,
primary_url,
etag=cache.etag if cache else None,
last_modified=cache.last_modified if cache else None,
)
if feed.not_modified:
stats.not_modified = True
run.status = "not_modified"
run.etag = feed.etag
run.last_modified = feed.last_modified
run.finished_at = datetime.now(UTC)
await session.commit()
return stats
if not feed.body or not feed.body.strip():
# Empty body must not wipe existing data.
run.status = "failed"
run.error_message = sanitize_error(f"empty response from {source_name}")
run.finished_at = datetime.now(UTC)
stats.error = run.error_message
await session.commit()
return stats
parsed = parse_and_normalize(feed.body)
stats.received = parsed.received
stats.unsupported = len(parsed.unsupported)
stats.skipped_invalid = parsed.invalid
for item in parsed.valid:
_, created = await upsert_tracker_from_normalized(
session,
item,
source_name=source_name,
source_url=primary_url,
)
stats.valid += 1
if created:
stats.new += 1
for enrichment in enrichments:
try:
enrich_feed = await fetch_text_feed(client, enrichment.url)
if not enrich_feed.body:
continue
for item in parse_and_normalize(enrich_feed.body).valid:
await upsert_tracker_from_normalized(
session,
item,
source_name=source_name,
source_url=enrichment.url,
is_best=enrichment.is_best,
is_stable=enrichment.is_stable,
is_live=enrichment.is_live,
)
except Exception: # noqa: BLE001 — enrichment is best-effort
continue
await upsert_cache(
session,
source_name=source_name,
feed_url=primary_url,
etag=feed.etag,
last_modified=feed.last_modified,
)
run.received_count = stats.received
run.valid_count = stats.valid
run.new_count = stats.new
run.unsupported_count = stats.unsupported
run.status = "ok"
run.etag = feed.etag
run.last_modified = feed.last_modified
run.finished_at = datetime.now(UTC)
await session.commit()
return stats
except Exception as exc: # noqa: BLE001
await session.rollback()
session.add(
SourceImportRun(
source_name=source_name,
started_at=datetime.now(UTC),
finished_at=datetime.now(UTC),
status="failed",
received_count=0,
valid_count=0,
new_count=0,
unsupported_count=0,
error_message=sanitize_error(str(exc)),
)
)
await session.commit()
stats.error = sanitize_error(str(exc))
return stats
class Collector(Protocol):
name: str
async def import_once(
self, session: AsyncSession, client: httpx.AsyncClient, settings: Settings
) -> ImportStats: ...
|