Coverage for app / services / favicons.py: 91%
69 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Site icons for citations, cached so each domain is fetched at most once a week.
4fe-core used to ask Google for every cited domain's icon, disclosing to it
5what each user was reading. The browser now asks svc-core, which answers from
6MinIO or has svc-ai fetch the icon once (svc-core has no route to the web).
7The cited site sees a request from the platform, not from the user, and at
8most once per ``FOUND_TTL``.
10A domain with no usable icon is remembered too (``MISSING_TTL``), so a
11missing icon costs one fetch a day rather than one per citation shown.
13Objects live in the knowledge bucket under ``favicons/``: ``favicons/<domain>``
14holds the image with its (sniffed) content type; ``favicons/<domain>.missing``
15is an empty marker.
16"""
18from __future__ import annotations
20import base64
21import logging
22import re
23from dataclasses import dataclass
24from datetime import timedelta
26from app.util.time import aware_utcnow
28logger = logging.getLogger(__name__)
30FOUND_TTL = timedelta(days=7)
31MISSING_TTL = timedelta(days=1)
32#: Must match svc-ai's knowledge/favicon.py — refused before any lookup.
33_DOMAIN = re.compile(
34 r"^(?=.{4,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$"
35)
36#: What svc-ai may return, and all this will ever serve.
37RASTER_TYPES = frozenset(
38 {"image/png", "image/x-icon", "image/gif", "image/jpeg", "image/webp"}
39)
40MAX_ICON_BYTES = 100 * 1024
43@dataclass(frozen=True)
44class Icon:
45 data: bytes
46 content_type: str
49def normalise_domain(raw: str) -> str | None:
50 """The cache key for a host name — lower-case, ``www.`` dropped — or None
51 for anything that is not a bare public host name."""
52 domain = (raw or "").strip().lower().rstrip(".")
53 if domain.startswith("www."):
54 domain = domain[4:]
55 return domain if _DOMAIN.match(domain) else None
58def _key(domain: str) -> str:
59 return f"favicons/{domain}"
62def _fresh(stat, ttl: timedelta) -> bool:
63 modified = getattr(stat, "last_modified", None)
64 if modified is None:
65 return False
66 if modified.tzinfo is None:
67 modified = modified.replace(tzinfo=aware_utcnow().tzinfo)
68 return aware_utcnow() - modified < ttl
71def get_icon(domain: str) -> Icon | None:
72 """The icon for ``domain`` (already normalised), or None if it has none."""
73 from app.services.ai_client import AIServiceError, fetch_favicon
74 from app.util import minio_client
76 key = _key(domain)
77 try:
78 stat = minio_client.stat_named(key)
79 if stat is not None and _fresh(stat, FOUND_TTL):
80 data = minio_client.read_named(key)
81 if data and stat.content_type in RASTER_TYPES:
82 return Icon(data, stat.content_type)
83 missing = minio_client.stat_named(f"{key}.missing")
84 if missing is not None and _fresh(missing, MISSING_TTL):
85 return None
86 except Exception:
87 logger.warning("Icon cache unavailable for %s", domain, exc_info=True)
89 try:
90 result = fetch_favicon(domain)
91 except AIServiceError:
92 logger.warning("Could not fetch icon for %s", domain, exc_info=True)
93 return None # not cached: an outage is not "this site has no icon"
95 icon = _verified(result)
96 try:
97 if icon is None:
98 minio_client.put_named(f"{key}.missing", b"", "text/plain")
99 else:
100 minio_client.put_named(key, icon.data, icon.content_type)
101 except Exception:
102 logger.warning("Could not cache icon for %s", domain, exc_info=True)
103 return icon
106def _verified(result: dict) -> Icon | None:
107 """svc-ai's answer, re-checked here: an allowed raster type, small, and
108 decodable. Nothing else is ever stored or served."""
109 if result.get("status") != "ok" or result.get("content_type") not in RASTER_TYPES:
110 return None
111 try:
112 data = base64.b64decode(result.get("data_b64") or "", validate=True)
113 except (ValueError, TypeError):
114 return None
115 if not data or len(data) > MAX_ICON_BYTES:
116 return None
117 return Icon(data, result["content_type"])