Coverage for app / knowledge / web.py: 85%

411 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2One page of a website knowledge source: fetched, checked against robots.txt, 

3reduced to markdown, and returned with the links that lead on from it — or, 

4when the URL is a sitemap or an RSS / Atom feed, the pages it lists. 

5 

6svc-core owns the crawl — which URLs are in scope, how many, how often, what 

7changed and what gets stored. This module owns the network: every fetch goes 

8through ``UrlFetcher``, so the SSRF guard the ``url_fetch`` tool relies on 

9(https only, every redirect hop re-resolved to a public address, a byte cap) 

10applies to crawling unchanged. svc-core is kept off the open internet for 

11exactly that reason. 

12 

13robots.txt is honoured per RFC 9309: a 4xx means no rules, a 5xx or an 

14unreachable file means "assume everything is disallowed" until it can be 

15read. Rules are cached per host for ``ROBOTS_TTL_S``. 

16""" 

17 

18from __future__ import annotations 

19 

20import asyncio 

21import hashlib 

22import logging 

23import re 

24import time 

25import urllib.parse 

26import urllib.robotparser 

27from dataclasses import asdict, dataclass, field 

28from datetime import datetime, timezone 

29from email.utils import parsedate_to_datetime 

30from typing import Literal 

31 

32from lxml import etree 

33 

34from app.common.settings import get_settings 

35from app.tools.web.fetch import ( 

36 FetchedResource, 

37 FetchError, 

38 FetchTooLarge, 

39 UnsafeUrlError, 

40 UrlFetcher, 

41 resource_to_page, 

42) 

43from app.knowledge.web_extract import ( 

44 PageLink, 

45 classify_link, 

46 extract_markdown, 

47 linked_markdown, 

48 strip_tracking, 

49) 

50from app.tools.web.policy import DomainPolicy 

51 

52logger = logging.getLogger(__name__) 

53 

54ROBOTS_TTL_S = 3600.0 

55#: Politeness ceiling: a robots ``Crawl-delay`` above this is clamped rather 

56#: than letting one site stall a crawl for minutes per page. 

57MAX_CRAWL_DELAY_S = 10.0 

58#: Links returned per page. A crawl caps pages anyway; this caps the payload. 

59MAX_LINKS = 500 

60MAX_SITEMAP_URLS = 2000 

61#: Entries read from one feed. Feeds carry their newest items; a crawl caps 

62#: pages anyway, this caps the payload. 

63MAX_FEED_ENTRIES = 200 

64#: Characters of an entry's own text kept (its ``content:encoded`` or 

65#: summary) — enough for a full press release, not a book. 

66MAX_ENTRY_CHARS = 20_000 

67 

68PageStatus = Literal[ 

69 "ok", 

70 "not_modified", 

71 "blocked_by_robots", 

72 "unsafe", 

73 "http_error", 

74 "unsupported", 

75 "auth_required", 

76 "error", 

77] 

78 

79 

80@dataclass 

81class PageResult: 

82 requested_url: str 

83 status: PageStatus 

84 url: str = "" 

85 http_status: int | None = None 

86 title: str | None = None 

87 published: str | None = None 

88 markdown: str = "" 

89 content_hash: str | None = None 

90 html: str | None = None 

91 content_type: str | None = None 

92 etag: str | None = None 

93 last_modified: str | None = None 

94 #: Each ``{url, text, category, in_content, external}`` — see 

95 #: web_extract.PageLink. The crawler decides what to follow from these. 

96 links: list[dict] = field(default_factory=list) 

97 sitemap_urls: list[str] = field(default_factory=list) 

98 #: When the URL is an RSS or Atom feed: its entries, newest first as the 

99 #: feed lists them — each ``{url, title, published, summary, author}`` 

100 #: (see :class:`FeedEntry`). svc-core decides whether to fetch the pages 

101 #: they link to or keep the entries themselves. 

102 feed_entries: list[dict] = field(default_factory=list) 

103 crawl_delay: float | None = None 

104 error: str | None = None 

105 

106 

107DocumentStatus = Literal[ 

108 "ok", 

109 "blocked_by_robots", 

110 "unsafe", 

111 "http_error", 

112 "too_large", 

113 "unsupported", 

114 "auth_required", 

115 "error", 

116] 

117 

118 

119@dataclass 

120class DocumentResult: 

121 """A document downloaded for a file source (:func:`fetch_document`).""" 

122 

123 requested_url: str 

124 status: DocumentStatus 

125 url: str = "" 

126 content: bytes | None = None 

127 mime_type: str | None = None 

128 filename: str | None = None 

129 last_modified: str | None = None 

130 http_status: int | None = None 

131 #: Safe to show: says which URL failed and why, never an exception's text. 

132 error: str | None = None 

133 

134 

135# --------------------------------------------------------------------------- 

136# URLs, links and sitemaps 

137# --------------------------------------------------------------------------- 

138 

139 

140def canonical_url(url: str) -> str | None: 

141 """The form a page is stored and compared under, or None if unusable. 

142 

143 Fragment dropped (it never reaches the server), scheme and host 

144 lower-cased, default port and an empty path normalised. The query is 

145 kept — ``?id=`` pages are different pages — less tracking parameters 

146 (``utm_*``, ``fbclid``…), which only say how somebody arrived. 

147 """ 

148 try: 

149 parts = urllib.parse.urlsplit(url.strip()) 

150 except ValueError: 

151 return None 

152 if parts.scheme.lower() not in ("http", "https") or not parts.hostname: 

153 return None 

154 netloc = parts.hostname.lower() 

155 try: 

156 port = parts.port 

157 except ValueError: 

158 return None 

159 if port and port not in (80, 443): 

160 netloc = f"{netloc}:{port}" 

161 return urllib.parse.urlunsplit( 

162 ( 

163 parts.scheme.lower(), 

164 netloc, 

165 parts.path or "/", 

166 strip_tracking(parts.query), 

167 "", 

168 ) 

169 ) 

170 

171 

172def extract_links(html: str, base_url: str) -> list[PageLink]: 

173 """Every link on a page, classified, de-duplicated, in page order. 

174 

175 ``rel=nofollow`` links are dropped: a site marking a link that way is 

176 asking crawlers not to follow it. 

177 """ 

178 _, _, links = linked_markdown(html, base_url) 

179 seen: set[str] = set() 

180 out: list[PageLink] = [] 

181 for link in links: 

182 if link.url in seen: 

183 continue 

184 seen.add(link.url) 

185 out.append(link) 

186 if len(out) >= MAX_LINKS: 

187 break 

188 return out 

189 

190 

191_SITEMAP_ROOT = re.compile(rb"<(?:\w+:)?(urlset|sitemapindex)\b", re.IGNORECASE) 

192_LOC = re.compile(r"<(?:\w+:)?loc>\s*(.*?)\s*</(?:\w+:)?loc>", re.IGNORECASE | re.S) 

193 

194 

195def sitemap_urls(body: bytes) -> list[str] | None: 

196 """The URLs a sitemap (or sitemap index) lists, or None if it is not one. 

197 

198 Read with a pattern rather than an XML parser: ``<loc>`` is all that is 

199 needed, and a regex has no entity expansion to abuse. 

200 """ 

201 if not _SITEMAP_ROOT.search(body[:4096]): 

202 return None 

203 text = body.decode("utf-8", errors="replace") 

204 urls: list[str] = [] 

205 for raw in _LOC.findall(text): 

206 url = canonical_url( 

207 raw.replace("&amp;", "&").replace("<![CDATA[", "").replace("]]>", "") 

208 ) 

209 if url: 

210 urls.append(url) 

211 if len(urls) >= MAX_SITEMAP_URLS: 

212 break 

213 return urls 

214 

215 

216# --------------------------------------------------------------------------- 

217# RSS and Atom feeds 

218# --------------------------------------------------------------------------- 

219 

220_FEED_ROOT = re.compile(rb"<(?:[\w-]+:)?(rss|feed|RDF)\b", re.IGNORECASE) 

221 

222 

223@dataclass 

224class FeedEntry: 

225 """One item of a feed: the page it points at, and what the feed says of it. 

226 

227 ``published`` is ISO 8601 when the feed's date could be read, else None. 

228 ``summary`` is the entry's own text as markdown with its links — the 

229 full ``content:encoded`` when the feed carries it, else its description. 

230 """ 

231 

232 url: str 

233 title: str | None = None 

234 published: str | None = None 

235 summary: str = "" 

236 author: str | None = None 

237 

238 

239def _local(tag: object) -> str: 

240 return etree.QName(tag).localname.lower() if isinstance(tag, str) else "" 

241 

242 

243def _children(node: etree._Element, *names: str) -> list[etree._Element]: 

244 wanted = {n.lower() for n in names} 

245 return [c for c in node if _local(c.tag) in wanted] 

246 

247 

248def _first_text(node: etree._Element, *names: str) -> str: 

249 """The text of the first child named any of ``names``, in that order.""" 

250 for name in names: 

251 for child in _children(node, name): 

252 text = "".join(child.itertext()).strip() 

253 if text: 

254 return text 

255 return "" 

256 

257 

258def _entry_link(node: etree._Element) -> str: 

259 # Atom: <link rel="alternate" href>, else the first <link href>. 

260 atom = [c for c in _children(node, "link") if c.get("href")] 

261 for link in atom: 

262 if (link.get("rel") or "alternate") == "alternate": 

263 return link.get("href", "") 

264 if atom: 

265 return atom[0].get("href", "") 

266 # RSS: <link>text</link>, else a permalink <guid>. 

267 text = _first_text(node, "link") 

268 if text: 

269 return text 

270 for guid in _children(node, "guid"): 

271 if (guid.get("isPermaLink") or "true").lower() == "true": 

272 return (guid.text or "").strip() 

273 return "" 

274 

275 

276def _iso_date(raw: str) -> str | None: 

277 """A feed date (RFC 822 in RSS, RFC 3339 in Atom) as ISO 8601 UTC.""" 

278 raw = raw.strip() 

279 if not raw: 

280 return None 

281 parsed: datetime | None = None 

282 try: 

283 parsed = parsedate_to_datetime(raw) 

284 except (TypeError, ValueError, IndexError): 

285 try: 

286 parsed = datetime.fromisoformat(raw.replace("Z", "+00:00")) 

287 except ValueError: 

288 return None 

289 if parsed.tzinfo is None: 

290 parsed = parsed.replace(tzinfo=timezone.utc) 

291 return parsed.astimezone(timezone.utc).isoformat() 

292 

293 

294def _entry_text(node: etree._Element, base_url: str) -> str: 

295 """The entry's own text as markdown: full content if carried, else its 

296 summary. Feeds put HTML (escaped or CDATA) in these fields.""" 

297 raw = _first_text(node, "encoded", "content", "description", "summary") 

298 if not raw: 

299 return "" 

300 if "<" in raw: 

301 markdown, _, _ = linked_markdown(raw, base_url) 

302 else: 

303 markdown = raw 

304 return re.sub(r"\n{3,}", "\n\n", markdown).strip()[:MAX_ENTRY_CHARS] 

305 

306 

307def feed_entries(body: bytes, base_url: str = "") -> list[FeedEntry] | None: 

308 """The entries an RSS (0.9x, 1.0, 2.0) or Atom feed lists, or None if 

309 the body is not a feed. 

310 

311 Parsed with entity resolution, DTD loading and network access off, so a 

312 hostile feed cannot expand entities or reach anything — the same care 

313 :func:`sitemap_urls` takes by not parsing XML at all. 

314 """ 

315 if not _FEED_ROOT.search(body[:4096]): 

316 return None 

317 parser = etree.XMLParser( 

318 resolve_entities=False, 

319 no_network=True, 

320 load_dtd=False, 

321 huge_tree=False, 

322 recover=True, 

323 ) 

324 try: 

325 root = etree.fromstring(body, parser) 

326 except (etree.XMLSyntaxError, ValueError): 

327 return None 

328 if root is None or _local(root.tag) not in ("rss", "feed", "rdf"): 

329 return None 

330 items = [el for el in root.iter() if _local(el.tag) in ("item", "entry")] 

331 entries: list[FeedEntry] = [] 

332 seen: set[str] = set() 

333 for item in items: 

334 link = _entry_link(item).strip() 

335 if not link: 

336 continue # joined onto the base it would become the feed itself 

337 url = canonical_url(urllib.parse.urljoin(base_url, link)) 

338 if url is None or url in seen: 

339 continue 

340 seen.add(url) 

341 author = _first_text(item, "creator", "author") 

342 entries.append( 

343 FeedEntry( 

344 url=url, 

345 title=_first_text(item, "title") or None, 

346 published=_iso_date( 

347 _first_text(item, "pubDate", "published", "date", "updated") 

348 ), 

349 summary=_entry_text(item, url), 

350 author=author[:200] or None, 

351 ) 

352 ) 

353 if len(entries) >= MAX_FEED_ENTRIES: 

354 break 

355 return entries 

356 

357 

358def content_hash(markdown: str) -> str: 

359 """What "the page changed" means: its extracted text, not its bytes. 

360 

361 Hashing the markdown rather than the HTML means a rotated CSRF token, 

362 ad slot or build id does not count as a new version of the page. 

363 """ 

364 normalised = "\n".join(line.rstrip() for line in markdown.strip().splitlines()) 

365 return hashlib.sha256(normalised.encode("utf-8")).hexdigest() 

366 

367 

368# --------------------------------------------------------------------------- 

369# robots.txt 

370# --------------------------------------------------------------------------- 

371 

372 

373@dataclass 

374class _Robots: 

375 parser: urllib.robotparser.RobotFileParser | None # None: disallow all 

376 fetched_at: float 

377 

378 

379class RobotsCache: 

380 """robots.txt rules per origin, fetched through the same SSRF guard.""" 

381 

382 def __init__(self, fetcher: UrlFetcher, token: str) -> None: 

383 self._fetcher = fetcher 

384 self._token = token 

385 self._cache: dict[str, _Robots] = {} 

386 

387 async def _load(self, origin: str) -> _Robots: 

388 cached = self._cache.get(origin) 

389 if cached and time.monotonic() - cached.fetched_at < ROBOTS_TTL_S: 

390 return cached 

391 parser: urllib.robotparser.RobotFileParser | None 

392 try: 

393 res = await self._fetcher.fetch(f"{origin}/robots.txt") 

394 parser = urllib.robotparser.RobotFileParser() 

395 parser.parse(res.body.decode("utf-8", errors="replace").splitlines()) 

396 except FetchError as exc: 

397 if exc.status is not None and 400 <= exc.status < 500: 

398 parser = urllib.robotparser.RobotFileParser() 

399 parser.parse([]) # no file: everything allowed 

400 else: 

401 parser = None # 5xx / unreachable: RFC 9309 says disallow all 

402 except (UnsafeUrlError, OSError): 

403 parser = None 

404 entry = _Robots(parser=parser, fetched_at=time.monotonic()) 

405 self._cache[origin] = entry 

406 return entry 

407 

408 async def check(self, url: str) -> tuple[bool, float | None]: 

409 """``(allowed, crawl_delay)`` for *url*.""" 

410 parts = urllib.parse.urlsplit(url) 

411 robots = await self._load(f"{parts.scheme}://{parts.netloc}") 

412 if robots.parser is None: 

413 return False, None 

414 allowed = robots.parser.can_fetch(self._token, url) 

415 delay = robots.parser.crawl_delay(self._token) 

416 return allowed, (min(float(delay), MAX_CRAWL_DELAY_S) if delay else None) 

417 

418 

419# --------------------------------------------------------------------------- 

420# One page 

421# --------------------------------------------------------------------------- 

422 

423_fetcher: UrlFetcher | None = None 

424_robots: RobotsCache | None = None 

425 

426 

427def _defaults() -> tuple[UrlFetcher, RobotsCache]: 

428 global _fetcher, _robots 

429 if _fetcher is None or _robots is None: 

430 settings = get_settings() 

431 # No operator allowlist here — the user chose these sites — but the 

432 # safety blocklists (shorteners, disposable TLDs) still apply. 

433 policy = DomainPolicy( 

434 allowed_domains=[], blocked_domains=[], require_https=True 

435 ) 

436 _fetcher = UrlFetcher( 

437 policy, 

438 max_bytes=settings.url_fetch_max_bytes, 

439 user_agent=settings.url_fetch_user_agent, 

440 ) 

441 _robots = RobotsCache(_fetcher, settings.web_knowledge_robots_token) 

442 return _fetcher, _robots 

443 

444 

445async def fetch_page( 

446 url: str, 

447 *, 

448 etag: str | None = None, 

449 last_modified: str | None = None, 

450 article: bool = False, 

451 fetcher: UrlFetcher | None = None, 

452 robots: RobotsCache | None = None, 

453) -> PageResult: 

454 """Fetch one page for a website knowledge source. Never raises. 

455 

456 ``article``: the page is known to be one article (a feed listed it), so 

457 its article text is preferred over the whole page — see 

458 ``web_extract.extract_markdown``. 

459 """ 

460 if fetcher is None or robots is None: 

461 fetcher, robots = _defaults() 

462 canonical = canonical_url(url) 

463 if canonical is None: 

464 return PageResult(url, "unsafe", error="not an http(s) URL") 

465 result = PageResult(requested_url=url, status="error", url=canonical) 

466 

467 try: 

468 allowed, delay = await robots.check(canonical) 

469 except Exception as exc: # noqa: BLE001 — never let robots take down a crawl 

470 logger.warning("[web] robots check failed for %s: %s", canonical, exc) 

471 allowed, delay = False, None 

472 result.crawl_delay = delay 

473 if not allowed: 

474 result.status = "blocked_by_robots" 

475 result.error = "robots.txt disallows this page for CHAINR's crawler" 

476 return result 

477 

478 conditional = {} 

479 if etag: 

480 conditional["If-None-Match"] = etag 

481 if last_modified: 

482 conditional["If-Modified-Since"] = last_modified 

483 

484 try: 

485 res: FetchedResource = await fetcher.fetch(canonical, headers=conditional) 

486 except UnsafeUrlError as exc: 

487 result.status, result.error = "unsafe", str(exc) 

488 return result 

489 except FetchError as exc: 

490 result.status, result.error = "http_error", str(exc) 

491 result.http_status = exc.status 

492 return result 

493 except Exception as exc: # noqa: BLE001 — network failures are page results 

494 result.status, result.error = "error", f"{type(exc).__name__}: {exc}" 

495 return result 

496 

497 result.url = canonical_url(res.url) or canonical 

498 result.http_status = res.status 

499 if result.url != canonical and classify_link(result.url, canonical) in ( 

500 "account", 

501 "action", 

502 ): 

503 # Redirected to a login or an action: the page is behind an account, 

504 # and what came back is the sign-in form, not the page. 

505 result.status = "auth_required" 

506 result.error = "The page redirects to a login" 

507 return result 

508 result.etag, result.last_modified = res.etag, res.last_modified 

509 if res.not_modified: 

510 result.status = "not_modified" 

511 return result 

512 

513 mime = res.content_type.split(";", 1)[0].strip() 

514 result.content_type = mime or None 

515 listed = sitemap_urls(res.body) 

516 if listed is not None: 

517 result.status, result.sitemap_urls = "ok", listed 

518 return result 

519 if "html" not in mime: 

520 entries = feed_entries(res.body, result.url) 

521 if entries is not None: 

522 result.status = "ok" 

523 result.feed_entries = [asdict(entry) for entry in entries] 

524 return result 

525 

526 is_html = mime in ("text/html", "application/xhtml+xml") or ( 

527 not mime and b"<html" in res.body[:2048].lower() 

528 ) 

529 if is_html: 

530 # Knowledge pages keep their links (web_extract.extract_markdown); 

531 # url_fetch's extraction drops them to save an agent's tokens. 

532 result.html = res.body.decode(res.encoding or "utf-8", errors="replace") 

533 markdown, title, published = await asyncio.to_thread( 

534 extract_markdown, result.html, result.url, prefer_article=article 

535 ) 

536 result.title, result.published = title, published 

537 result.markdown = markdown.strip() 

538 result.links = [asdict(link) for link in extract_links(result.html, result.url)] 

539 else: 

540 try: 

541 page = await resource_to_page(res) 

542 except FetchError as exc: 

543 result.status, result.error = "unsupported", str(exc) 

544 return result 

545 result.title, result.published = page.title, page.published 

546 result.markdown = page.text.strip() 

547 result.status = "ok" 

548 result.content_hash = content_hash(result.markdown) if result.markdown else None 

549 return result 

550 

551 

552# --------------------------------------------------------------------------- 

553# One document, for a file source 

554# --------------------------------------------------------------------------- 

555 

556#: The office formats, by their container: OOXML is a zip, the older ones an 

557#: OLE compound file — their bytes say which family, the label which member. 

558_OOXML = { 

559 "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", 

560 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx", 

561 "application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx", 

562} 

563_OLE = { 

564 "application/msword": ".doc", 

565 "application/vnd.ms-excel": ".xls", 

566 "application/vnd.ms-powerpoint": ".ppt", 

567} 

568#: Text documents a file source may hold. Not HTML: a page is a website 

569#: source's, crawled and kept current. 

570_TEXT_DOCUMENTS = { 

571 "text/plain", 

572 "text/csv", 

573 "text/markdown", 

574 "application/json", 

575 "application/xml", 

576 "text/xml", 

577} 

578#: Every type :func:`fetch_document` hands back (svc-core's 

579#: ``file_types.IMPORT_MIME_EXTENSIONS`` maps each to its extension). 

580DOCUMENT_IMPORT_MIMES = frozenset({"application/pdf", *_OOXML, *_OLE, *_TEXT_DOCUMENTS}) 

581 

582_document_fetcher: UrlFetcher | None = None 

583 

584#: How long one document may take, all told — svc-core waits a little longer. 

585DOCUMENT_BUDGET_S = 120.0 

586 

587 

588def _textual(head: bytes) -> bool: 

589 if b"\x00" in head: 

590 return False 

591 try: 

592 head.decode("utf-8") 

593 except UnicodeDecodeError as exc: 

594 return exc.start >= len(head) - 3 

595 return True 

596 

597 

598def sniff_mime(head: bytes, declared: str, filename: str = "") -> str | None: 

599 """The document type the bytes are, checked against the label — or None 

600 when it is no document a file source may hold (a web page, an image, a 

601 label its bytes contradict).""" 

602 base = (declared or "").split(";", 1)[0].strip().lower() 

603 ext = filename.lower().rpartition(".")[2] if "." in filename else "" 

604 if head.startswith(b"%PDF-"): 

605 return "application/pdf" 

606 if head.startswith(b"PK\x03\x04"): 

607 if base in _OOXML: 

608 return base 

609 by_ext = {v.lstrip("."): k for k, v in _OOXML.items()} 

610 return by_ext.get(ext) 

611 if head.startswith(b"\xd0\xcf\x11\xe0"): 

612 if base in _OLE: 

613 return base 

614 by_ext = {v.lstrip("."): k for k, v in _OLE.items()} 

615 return by_ext.get(ext) 

616 if base in _TEXT_DOCUMENTS and _textual(head[:8192]): 

617 return base 

618 return None 

619 

620 

621def filename_from(disposition: str | None, url: str) -> str: 

622 """The name a server gives a download, else its URL's last segment.""" 

623 if disposition: 

624 star = re.search(r"filename\*\s*=\s*(?:UTF-8'')?([^;]+)", disposition, re.I) 

625 plain = re.search(r'filename\s*=\s*"?([^";]+)"?', disposition, re.I) 

626 found = star or plain 

627 if found: 

628 name = urllib.parse.unquote(found.group(1).strip().strip('"')) 

629 if name: 

630 return name.rsplit("/", 1)[-1] 

631 segment = urllib.parse.urlsplit(url).path.rstrip("/").rsplit("/", 1)[-1] 

632 return urllib.parse.unquote(segment) or "document" 

633 

634 

635def _document_defaults() -> tuple[UrlFetcher, RobotsCache]: 

636 global _document_fetcher 

637 _, robots = _defaults() 

638 if _document_fetcher is None: 

639 settings = get_settings() 

640 _document_fetcher = UrlFetcher( 

641 DomainPolicy(allowed_domains=[], blocked_domains=[], require_https=True), 

642 max_bytes=settings.knowledge_import_max_bytes, 

643 user_agent=settings.url_fetch_user_agent, 

644 timeout_s=30.0, 

645 ) 

646 return _document_fetcher, robots 

647 

648 

649async def fetch_document( 

650 url: str, 

651 *, 

652 fetcher: UrlFetcher | None = None, 

653 robots: RobotsCache | None = None, 

654) -> DocumentResult: 

655 """Download one document for a file knowledge source. Never raises. 

656 

657 Under the crawler's rules — robots.txt for CHAINR's crawler, the public 

658 https guard on every hop, a login redirect refused — and only a document 

659 whose bytes are one (``sniff_mime``): a page is a website source's. 

660 """ 

661 if fetcher is None or robots is None: 

662 fetcher, robots = _document_defaults() 

663 canonical = canonical_url(url) 

664 if canonical is None: 

665 return DocumentResult(url, "unsafe", error="Not an https URL.") 

666 try: 

667 return await asyncio.wait_for( 

668 _fetch_document(canonical, url, fetcher, robots), DOCUMENT_BUDGET_S 

669 ) 

670 except TimeoutError: 

671 return DocumentResult( 

672 url, "error", url=canonical, error="The download took too long." 

673 ) 

674 

675 

676async def _fetch_document( 

677 canonical: str, requested: str, fetcher: UrlFetcher, robots: RobotsCache 

678) -> DocumentResult: 

679 result = DocumentResult(requested_url=requested, status="error", url=canonical) 

680 try: 

681 await fetcher.check(canonical) 

682 except UnsafeUrlError: 

683 result.status, result.error = ( 

684 "unsafe", 

685 "The address is not a public https site.", 

686 ) 

687 return result 

688 try: 

689 allowed, _ = await robots.check(canonical) 

690 except Exception: # noqa: BLE001 — a robots failure refuses, never raises 

691 allowed = False 

692 if not allowed: 

693 result.status = "blocked_by_robots" 

694 result.error = "The site's robots.txt does not allow CHAINR's crawler here." 

695 return result 

696 try: 

697 res = await fetcher.fetch(canonical) 

698 except UnsafeUrlError: 

699 result.status, result.error = ( 

700 "unsafe", 

701 "The address is not a public https site.", 

702 ) 

703 return result 

704 except FetchTooLarge: 

705 limit = get_settings().knowledge_import_max_bytes // (1024 * 1024) 

706 result.status = "too_large" 

707 result.error = f"The document is larger than {limit} MB." 

708 return result 

709 except FetchError as exc: 

710 result.status, result.http_status = "http_error", exc.status 

711 result.error = ( 

712 f"The site answered HTTP {exc.status}." 

713 if exc.status 

714 else "The site could not be reached." 

715 ) 

716 return result 

717 except Exception as exc: # noqa: BLE001 — network failures are results 

718 logger.warning("[web] document fetch failed: %s", type(exc).__name__) 

719 result.error = "The site could not be reached." 

720 return result 

721 

722 result.url = canonical_url(res.url) or canonical 

723 result.http_status = res.status 

724 if result.url != canonical and classify_link(result.url, canonical) in ( 

725 "account", 

726 "action", 

727 ): 

728 result.status = "auth_required" 

729 result.error = "The link redirects to a login." 

730 return result 

731 filename = filename_from(res.disposition, result.url) 

732 mime = sniff_mime(res.body[:8192], res.content_type, filename) 

733 if mime is None: 

734 declared = res.content_type.split(";", 1)[0].strip() or "unknown" 

735 result.status = "unsupported" 

736 result.error = ( 

737 "The link is a web page, not a document — add it to a website source." 

738 if "html" in declared 

739 else f"The link is not a document a file source can hold ({declared})." 

740 ) 

741 return result 

742 result.status = "ok" 

743 result.content = res.body 

744 result.mime_type = mime 

745 result.filename = filename 

746 result.last_modified = res.last_modified 

747 return result