Coverage for app / services / knowledge / web_config.py: 94%
156 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"""
2What a website knowledge source is told to crawl.
4Stored as the source's ``source_config`` and validated here on every create
5and edit, so the crawler only ever reads a shape it understands. The same
6model reads two older shapes without complaint:
8* ``{"urls": [...], "depth": n}`` — what fe-core's form wrote before crawling
9 existed; ``depth`` becomes ``max_depth``.
10* ``{}`` — a source with no URLs yet (one generative setup found nothing
11 for). It validates, and simply has nothing to crawl until the user adds
12 some.
14A URL may be an RSS or Atom feed. Its entries are the pages it lists —
15newest first — and ``feed_content`` decides whether each is read from the
16feed itself or fetched from the site (see :class:`FeedContent`).
17"""
19from __future__ import annotations
21import fnmatch
22from enum import Enum
23from typing import Any
24from urllib.parse import urlsplit, urlunsplit
26from app.util import knowledge_categories, vocab
27from app.util.knowledge_categories import KnowledgeCategory
28from pydantic import (
29 BaseModel,
30 ConfigDict,
31 Field,
32 ValidationError,
33 field_validator,
34 model_validator,
35)
37MAX_URLS = 20
38MAX_PAGES_CEILING = 200
39MAX_DEPTH_CEILING = 5
40MAX_PATTERNS = 20
41MAX_EXTERNAL_CEILING = 100
42MAX_AGE_DAYS_CEILING = 3650
43MAX_ATTRIBUTION_CHARS = 500
46class CrawlScope(str, Enum):
47 """How far a crawl may wander from the URLs it was given."""
49 #: Only the listed URLs (a listed sitemap is still expanded).
50 page = "page"
51 #: The listed pages and anything beneath their path on the same host —
52 #: ``/docs/start`` reaches ``/docs/*``.
53 section = "section"
54 #: Anything on the same host.
55 site = "site"
58class RefreshCadence(str, Enum):
59 manual = "manual"
60 #: For news: a feed read hourly, which only fetches entries it has not
61 #: seen (or that the feed says changed).
62 hourly = "hourly"
63 daily = "daily"
64 weekly = "weekly"
66 @property
67 def interval_seconds(self) -> int | None:
68 return {"hourly": 3_600, "daily": 86_400, "weekly": 604_800}.get(self.value)
71class FeedContent(str, Enum):
72 """How the entries of an RSS or Atom feed become pages.
74 A feed carries each entry's title, date, link and some of its text —
75 sometimes all of it, sometimes a sentence.
76 """
78 #: The feed's own text when it carries the whole item; otherwise the
79 #: linked page, fetched as an article. When the page has no readable
80 #: text (it renders in the browser, or refuses automated readers), the
81 #: entry is kept instead.
82 auto = "auto"
83 #: Only what the feed says — the linked pages are never fetched. For a
84 #: publisher whose feed is offered for syndication but whose pages are
85 #: not, or that serves its pages to browsers only.
86 entry = "entry"
87 #: Always the linked page. Entries on other sites are skipped.
88 article = "article"
91def normalise_seed_url(raw: str) -> str:
92 """A seed URL as stored: https, no credentials, no fragment.
94 https only, because svc-ai's fetcher refuses anything else — a seed it
95 will always refuse is better rejected where the user typed it.
96 """
97 value = raw.strip()
98 if "://" not in value:
99 value = f"https://{value}"
100 try:
101 parts = urlsplit(value)
102 port = parts.port
103 except ValueError as exc:
104 raise ValueError(f"'{raw}' is not a URL.") from exc
105 if parts.scheme.lower() != "https":
106 raise ValueError(f"'{raw}' must be an https:// URL.")
107 if parts.username or parts.password:
108 raise ValueError(f"'{raw}' must not embed credentials.")
109 if not parts.hostname or "." not in parts.hostname:
110 raise ValueError(f"'{raw}' has no public host name.")
111 if len(value) > 2048:
112 raise ValueError("URLs are limited to 2048 characters.")
113 netloc = parts.hostname.lower() + (f":{port}" if port and port != 443 else "")
114 return urlunsplit(("https", netloc, parts.path or "/", parts.query, ""))
117class WebSourceConfig(BaseModel):
118 model_config = ConfigDict(extra="ignore")
120 urls: list[str] = Field(default_factory=list, max_length=MAX_URLS)
121 scope: CrawlScope = CrawlScope.section
122 max_pages: int = Field(default=25, ge=1, le=MAX_PAGES_CEILING)
123 max_depth: int = Field(default=2, ge=0, le=MAX_DEPTH_CEILING)
124 #: Path globs (``/blog/*``). With any include pattern set, only matching
125 #: pages beyond the listed URLs are crawled; an exclude always wins.
126 include: list[str] = Field(default_factory=list, max_length=MAX_PATTERNS)
127 exclude: list[str] = Field(default_factory=list, max_length=MAX_PATTERNS)
128 refresh: RefreshCadence = RefreshCadence.weekly
129 #: Also read the host's ``/sitemap.xml`` when crawling beyond single pages.
130 use_sitemap: bool = True
131 #: Skip links that are never knowledge: actions (vote, hide, share, log
132 #: out), account pages (login, profiles, settings), assets and feeds —
133 #: as svc-ai classifies them (knowledge/web_extract.py). Also stops
134 #: fetching a URL template that keeps coming back empty or login-walled.
135 skip_low_value: bool = True
136 #: Also read the pages on *other* sites that crawled pages link to — the
137 #: articles an aggregator lists, the sources a post cites. One hop only:
138 #: a linked page's own links are never followed. Each such page is stored
139 #: with the page(s) that linked it, which is what a deep citation shows.
140 follow_external: bool = False
141 #: Cap on linked pages per crawl, separate from ``max_pages``.
142 max_external_pages: int = Field(default=20, ge=0, le=MAX_EXTERNAL_CEILING)
143 #: How a feed's entries become pages (only matters when a URL is a feed).
144 feed_content: FeedContent = FeedContent.auto
145 #: A rolling window: pages published (or, undated, first stored) more
146 #: than this many days ago are removed — index, snapshots and all — at
147 #: the end of each crawl. None keeps every page and its history, the
148 #: default for a source kept as a record rather than as news.
149 max_age_days: int | None = Field(default=None, ge=1, le=MAX_AGE_DAYS_CEILING)
150 #: The credit every passage from this source carries into a citation —
151 #: what the publisher's licence asks for ("Contains public sector
152 #: information licensed under the Open Government Licence v3.0.").
153 attribution: str | None = Field(default=None, max_length=MAX_ATTRIBUTION_CHARS)
154 #: Where the licence is, linked beside the attribution.
155 licence_url: str | None = Field(default=None, max_length=2048)
157 @model_validator(mode="before")
158 @classmethod
159 def _legacy_depth(cls, data: Any) -> Any:
160 if isinstance(data, dict) and "depth" in data and "max_depth" not in data:
161 data = {**data, "max_depth": data["depth"]}
162 return data
164 @field_validator("urls", mode="before")
165 @classmethod
166 def _split_urls(cls, value: Any) -> Any:
167 if isinstance(value, str):
168 value = value.splitlines()
169 return value
171 @field_validator("urls")
172 @classmethod
173 def _normalise_urls(cls, value: list[str]) -> list[str]:
174 seen: list[str] = []
175 for raw in value:
176 if not str(raw).strip():
177 continue
178 url = normalise_seed_url(str(raw))
179 if url not in seen:
180 seen.append(url)
181 return seen
183 @field_validator("include", "exclude")
184 @classmethod
185 def _clean_patterns(cls, value: list[str]) -> list[str]:
186 cleaned = []
187 for raw in value:
188 pattern = str(raw).strip()
189 if not pattern:
190 continue
191 if len(pattern) > 256:
192 raise ValueError("Patterns are limited to 256 characters.")
193 cleaned.append(pattern if pattern.startswith("/") else f"/{pattern}")
194 return cleaned
196 @field_validator("attribution")
197 @classmethod
198 def _clean_attribution(cls, value: str | None) -> str | None:
199 text = " ".join((value or "").split())
200 return text or None
202 @field_validator("licence_url")
203 @classmethod
204 def _licence_url(cls, value: str | None) -> str | None:
205 """An https link, kept as written — a fragment (``#105``) can be the
206 part of a statute page that is the licence."""
207 text = (value or "").strip()
208 if not text:
209 return None
210 parts = urlsplit(text)
211 if parts.scheme.lower() != "https" or not parts.hostname:
212 raise ValueError("The licence link must be an https:// URL.")
213 if parts.username or parts.password:
214 raise ValueError("The licence link must not embed credentials.")
215 return text
217 def path_allowed(self, path: str) -> bool:
218 """Whether a discovered page's path passes include / exclude."""
219 if any(fnmatch.fnmatchcase(path, p) for p in self.exclude):
220 return False
221 return not self.include or any(
222 fnmatch.fnmatchcase(path, p) for p in self.include
223 )
226def parse_web_config(raw: dict | None) -> WebSourceConfig:
227 """The typed config, as the crawler reads it. Raises ``ValueError``."""
228 try:
229 return WebSourceConfig.model_validate(raw or {})
230 except ValidationError as exc:
231 messages = "; ".join(
232 str(err.get("msg", "")).removeprefix("Value error, ")
233 for err in exc.errors()
234 )
235 raise ValueError(messages or "Invalid website configuration.") from exc
238def validate_web_config(raw: dict | None) -> dict:
239 """The stored form of a website source's config. Raises ``ValueError``."""
240 return parse_web_config(raw).model_dump(mode="json")
243# ---------------------------------------------------------------------------
244# A website source generative setup designs
245# ---------------------------------------------------------------------------
247#: What each scope does, as the knowledge designer is told — checked against
248#: :class:`CrawlScope` at import, and sent to svc-ai with the request.
249SCOPE_GUIDE: dict[str, str] = {
250 "page": "only the pages chosen — for a page that is itself the material",
251 "section": (
252 "the pages chosen and those beneath them on the same site — for a "
253 "guidance hub or a programme's pages (the usual choice)"
254 ),
255 "site": "anything on the same site — for a small site entirely on the topic",
256}
257#: How often each cadence crawls again.
258REFRESH_GUIDE: dict[str, str] = {
259 "manual": "only when the person asks — for material that does not change",
260 "hourly": "every hour — for news",
261 "daily": "every day — for material updated often",
262 "weekly": "every week — for guidance and reference pages (the usual choice)",
263}
264vocab.check(SCOPE_GUIDE, CrawlScope)
265vocab.check(REFRESH_GUIDE, RefreshCadence)
267#: How much of a site a generated source crawls at most: the defaults, kept
268#: modest — a person widens a source they find useful.
269GENERATED_MAX_PAGES = 25
270GENERATED_MAX_DEPTH = 2
272#: How long a generated temporal source keeps its pages: dated knowledge is
273#: read for what is current, and the built-in News keeps as long.
274TEMPORAL_MAX_AGE_DAYS = 30
276#: How often a generated website source of each kind of knowledge is read
277#: when nobody chose (``app/util/knowledge_categories.py``): reference pages
278#: weekly, dated knowledge daily, a framework only when asked.
279CATEGORY_REFRESH: dict[str, RefreshCadence] = {
280 KnowledgeCategory.domain: RefreshCadence.weekly,
281 KnowledgeCategory.temporal: RefreshCadence.daily,
282 KnowledgeCategory.reasoning: RefreshCadence.manual,
283}
284#: The cadences dated knowledge may keep: anything slower would leave it out
285#: of date, so it is read daily instead.
286TEMPORAL_REFRESH = frozenset({RefreshCadence.hourly.value, RefreshCadence.daily.value})
287if set(CATEGORY_REFRESH) != set(KnowledgeCategory):
288 raise RuntimeError("Every knowledge category needs a default refresh")
291def refresh_for(category: object, chosen: str | None = None) -> str:
292 """How often a generated website source of ``category`` is read: the
293 cadence chosen (by the designer or the person), else its kind's — and
294 for dated knowledge never less often than daily."""
295 kind = knowledge_categories.of(category)
296 if kind is KnowledgeCategory.temporal:
297 return chosen if chosen in TEMPORAL_REFRESH else CATEGORY_REFRESH[kind].value
298 return chosen if chosen in REFRESH_GUIDE else CATEGORY_REFRESH[kind].value
301def catalogue_scopes() -> list[dict[str, str]]:
302 return [{"key": key, "description": text} for key, text in SCOPE_GUIDE.items()]
305def catalogue_refresh() -> list[dict[str, str]]:
306 return [{"key": key, "description": text} for key, text in REFRESH_GUIDE.items()]
309def generated_config(
310 urls: list[str],
311 scope: str | None = None,
312 refresh: str | None = None,
313 *,
314 category: object = None,
315) -> dict:
316 """A generated website source's stored config: its checked URLs, the
317 scope and cadence the designer chose (else the defaults), and modest
318 caps. Validated as a hand-written one is. Raises ``ValueError``.
320 ``category`` is the kind of knowledge it is made for, which the server
321 holds it to whatever the designer chose: dated knowledge is read at
322 least daily and keeps its pages ``TEMPORAL_MAX_AGE_DAYS``
323 (:func:`refresh_for`)."""
324 config: dict[str, Any] = {
325 "urls": urls,
326 "scope": scope if scope in SCOPE_GUIDE else CrawlScope.section.value,
327 "refresh": refresh_for(category, refresh),
328 "max_pages": GENERATED_MAX_PAGES,
329 "max_depth": GENERATED_MAX_DEPTH,
330 }
331 if knowledge_categories.of(category) is KnowledgeCategory.temporal:
332 config["max_age_days"] = TEMPORAL_MAX_AGE_DAYS
333 return validate_web_config(config)