|
| 1 | +"""Versioned, integration-safe crawl results. |
| 2 | +
|
| 3 | +This module intentionally contains only data adaptation. It does not import |
| 4 | +GoTor or expose either crawler's implementation details. |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from datetime import datetime, timezone |
| 9 | +from importlib import metadata |
| 10 | +from time import monotonic |
| 11 | +from typing import Any |
| 12 | +from urllib.parse import urlsplit, urlunsplit |
| 13 | +from uuid import uuid4 |
| 14 | + |
| 15 | + |
| 16 | +SCHEMA_VERSION = 1 |
| 17 | +ENGINE = "torbot" |
| 18 | + |
| 19 | + |
| 20 | +def _version() -> str: |
| 21 | + try: |
| 22 | + return metadata.version("torbot") |
| 23 | + except metadata.PackageNotFoundError: |
| 24 | + return "unknown" |
| 25 | + |
| 26 | + |
| 27 | +def normalize_target(value: str) -> str: |
| 28 | + """Normalize a target without removing its meaningful path or query.""" |
| 29 | + parsed = urlsplit(value.strip()) |
| 30 | + if parsed.scheme not in {"http", "https"} or not parsed.hostname: |
| 31 | + raise ValueError("target must be an absolute HTTP(S) URL") |
| 32 | + host = parsed.hostname.lower() |
| 33 | + try: |
| 34 | + port = parsed.port |
| 35 | + except ValueError as exc: |
| 36 | + raise ValueError("target has an invalid port") from exc |
| 37 | + if ":" in host: |
| 38 | + host = f"[{host}]" |
| 39 | + if port: |
| 40 | + host = f"{host}:{port}" |
| 41 | + return urlunsplit((parsed.scheme.lower(), host, parsed.path or "/", parsed.query, "")) |
| 42 | + |
| 43 | + |
| 44 | +def error_category(error: BaseException | str | None) -> str: |
| 45 | + """Return a bounded category; never serialize an arbitrary exception message.""" |
| 46 | + if error is None: |
| 47 | + return "unknown" |
| 48 | + value = str(error).lower() |
| 49 | + if "cancel" in value: |
| 50 | + return "cancelled" |
| 51 | + if "invalid" in value or "url" in value: |
| 52 | + return "invalid_input" |
| 53 | + if any(token in value for token in ("timeout", "connect", "network", "proxy", "request")): |
| 54 | + return "network" |
| 55 | + if any(token in value for token in ("parse", "html", "empty response")): |
| 56 | + return "parse" |
| 57 | + return "unknown" |
| 58 | + |
| 59 | + |
| 60 | +class CrawlResultAdapter: |
| 61 | + """Adapt a completed :class:`LinkTree` to the shared crawl-result v1 shape.""" |
| 62 | + |
| 63 | + def __init__(self, tree: Any, *, uses_tor: bool, started_at: datetime | None = None): |
| 64 | + self.tree = tree |
| 65 | + self.uses_tor = uses_tor |
| 66 | + self.started_at = ( |
| 67 | + started_at |
| 68 | + or getattr(tree, "crawl_started_at", None) |
| 69 | + or datetime.now(timezone.utc) |
| 70 | + ) |
| 71 | + self._started_monotonic = getattr(tree, "crawl_started_monotonic", monotonic()) |
| 72 | + |
| 73 | + def result( |
| 74 | + self, |
| 75 | + *, |
| 76 | + terminal_status: str = "completed", |
| 77 | + run_id: str | None = None, |
| 78 | + diagnostics: dict[str, str] | None = None, |
| 79 | + ) -> dict[str, Any]: |
| 80 | + if terminal_status not in {"completed", "cancelled", "failed", "invalid"}: |
| 81 | + raise ValueError("unsupported terminal status") |
| 82 | + ended_at = datetime.now(timezone.utc) |
| 83 | + pages = [self._page(node) for node in self.tree.all_nodes_itr()] |
| 84 | + pages.extend(getattr(self.tree, "crawl_failures", [])) |
| 85 | + pages.sort(key=lambda page: (page["depth"], page["url"])) |
| 86 | + result = { |
| 87 | + "schemaVersion": SCHEMA_VERSION, |
| 88 | + "runId": run_id or str(uuid4()), |
| 89 | + "engine": ENGINE, |
| 90 | + "engineVersion": _version(), |
| 91 | + "target": normalize_target(self.tree._url), |
| 92 | + "settings": {"maxDepth": self.tree._depth, "usesTor": self.uses_tor}, |
| 93 | + "terminalStatus": terminal_status, |
| 94 | + "cancelled": terminal_status == "cancelled", |
| 95 | + "startedAt": self.started_at.isoformat().replace("+00:00", "Z"), |
| 96 | + "endedAt": ended_at.isoformat().replace("+00:00", "Z"), |
| 97 | + "durationMs": int((monotonic() - self._started_monotonic) * 1000), |
| 98 | + "pages": pages, |
| 99 | + "diagnostics": _safe_diagnostics(diagnostics or {}), |
| 100 | + } |
| 101 | + return result |
| 102 | + |
| 103 | + def _page(self, node: Any) -> dict[str, Any]: |
| 104 | + parent = self.tree.parent(node.identifier) |
| 105 | + depth = self.tree.depth(node.identifier) |
| 106 | + links = [] |
| 107 | + for child in self.tree.children(node.identifier): |
| 108 | + links.append({"url": child.identifier, "source": "anchor"}) |
| 109 | + contacts = [] |
| 110 | + contacts.extend( |
| 111 | + {"value": email, "source": "mailto"} for email in sorted(node.data.emails) |
| 112 | + ) |
| 113 | + contacts.extend( |
| 114 | + {"value": phone, "source": "tel"} for phone in sorted(node.data.numbers) |
| 115 | + ) |
| 116 | + return { |
| 117 | + "url": node.identifier, |
| 118 | + "parentUrl": parent.identifier if parent else None, |
| 119 | + "depth": depth, |
| 120 | + "outcome": "fetched", |
| 121 | + "status": node.data.status, |
| 122 | + "skippedReason": None, |
| 123 | + "errorCategory": None, |
| 124 | + "links": links, |
| 125 | + "contacts": contacts, |
| 126 | + } |
| 127 | + |
| 128 | + |
| 129 | +def failed_page( |
| 130 | + url: str, parent_url: str | None, depth: int, error: BaseException | str |
| 131 | +) -> dict[str, Any]: |
| 132 | + """Create a privacy-safe per-page failure record.""" |
| 133 | + return { |
| 134 | + "url": url, |
| 135 | + "parentUrl": parent_url, |
| 136 | + "depth": depth, |
| 137 | + "outcome": "failed", |
| 138 | + "status": None, |
| 139 | + "skippedReason": None, |
| 140 | + "errorCategory": error_category(error), |
| 141 | + "links": [], |
| 142 | + "contacts": [], |
| 143 | + } |
| 144 | + |
| 145 | + |
| 146 | +def invalid_result(target: str, *, run_id: str | None = None) -> dict[str, Any]: |
| 147 | + """Return a terminal v1 result for invalid input without echoing it in diagnostics.""" |
| 148 | + now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 149 | + return { |
| 150 | + "schemaVersion": SCHEMA_VERSION, |
| 151 | + "runId": run_id or str(uuid4()), |
| 152 | + "engine": ENGINE, |
| 153 | + "engineVersion": _version(), |
| 154 | + "target": target, |
| 155 | + "settings": {}, |
| 156 | + "terminalStatus": "invalid", |
| 157 | + "cancelled": False, |
| 158 | + "startedAt": now, |
| 159 | + "endedAt": now, |
| 160 | + "durationMs": 0, |
| 161 | + "pages": [failed_page(target, None, 0, "invalid input")], |
| 162 | + "diagnostics": {}, |
| 163 | + } |
| 164 | + |
| 165 | + |
| 166 | +def _safe_diagnostics(diagnostics: dict[str, str]) -> dict[str, str]: |
| 167 | + """Allow only caller-selected, scalar diagnostics and omit secret-like keys.""" |
| 168 | + blocked = ("cookie", "token", "secret", "password", "authorization", "credential") |
| 169 | + return { |
| 170 | + key: str(value) |
| 171 | + for key, value in diagnostics.items() |
| 172 | + if isinstance(key, str) and isinstance(value, (str, int, float, bool)) |
| 173 | + and not any(word in key.lower() for word in blocked) |
| 174 | + } |
0 commit comments