Skip to content

Commit c7db4c5

Browse files
committed
Add versioned crawl result contract
1 parent 9a829a5 commit c7db4c5

9 files changed

Lines changed: 335 additions & 1 deletion

‎docs/CRAWL_RESULT.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Shared crawl-result contract
2+
3+
TorBot exposes a versioned, machine-readable crawl result through
4+
`LinkTree.to_crawl_result()`. It is an integration contract, not a replacement
5+
for the existing tree JSON saved by `--save json`; that legacy format remains
6+
available through the 4.x series. Consumers must feature-detect
7+
`schemaVersion` and reject versions they do not understand.
8+
9+
## Version 1
10+
11+
The top-level object contains `schemaVersion`, a unique `runId`, `engine` and
12+
`engineVersion`, normalized `target`, effective `settings`, terminal status,
13+
timestamps, `durationMs`, `pages`, and privacy-safe `diagnostics`.
14+
15+
Each page records `url`, `parentUrl`, `depth`, `outcome`, HTTP `status`,
16+
`skippedReason`, bounded `errorCategory`, extracted `links`, and `contacts`.
17+
`outcome` is `fetched` or `failed`; failures expose one of `cancelled`,
18+
`invalid_input`, `network`, `parse`, or `unknown`, never an exception message.
19+
Links and contacts include their source (`anchor`, `mailto`, or `tel`). Raw
20+
HTML, headers, cookies, credentials, and arbitrary exception strings are not
21+
part of the contract.
22+
23+
GoTor's versioned report is the compatibility baseline: both projects use
24+
`schemaVersion: 1`, `engine`, `target`, depth/settings, timestamps, duration,
25+
and per-page URL/parent/depth/status/link information. TorBot's fields are
26+
additive where GoTor's current report has no equivalent (`runId`, terminal
27+
state, provenance, bounded errors, and diagnostics). Consumers should retain
28+
unknown fields and branch only on the schema version, not on engine-specific
29+
internals.
30+
31+
## Deprecation path
32+
33+
No existing CLI output changes in this issue. A future major release may mark
34+
the legacy tree JSON as deprecated only after the shared result is available
35+
from an explicit CLI/API surface and downstream consumers have migrated.

‎src/torbot/crawl_result.py‎

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
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+
}

‎src/torbot/modules/linktree.py‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import json
66
import logging
77
import os
8+
from datetime import datetime, timezone
9+
from time import monotonic
810
from urllib import parse
911

1012
import httpx
@@ -50,8 +52,11 @@ def __init__(self, url: str, depth: int, client: httpx.Client) -> None:
5052
self._url = url
5153
self._depth = depth
5254
self._client = client
55+
self.crawl_failures: list[dict] = []
5356

5457
def load(self) -> None:
58+
self.crawl_started_at = datetime.now(timezone.utc)
59+
self.crawl_started_monotonic = monotonic()
5560
self._append_node(id=self._url, parent_id=None)
5661
self._build_tree(url=self._url, depth=self._depth)
5762

@@ -102,9 +107,29 @@ def _build_tree(self, url: str, depth: int) -> None:
102107
try:
103108
self._append_node(id=child, parent_id=url)
104109
self._build_tree(url=child, depth=depth)
105-
except RequestError:
110+
except RequestError as exc:
111+
from torbot.crawl_result import failed_page
112+
113+
parent_depth = self.depth(url)
114+
self.crawl_failures.append(
115+
failed_page(child, url, parent_depth + 1, exc)
116+
)
106117
continue
107118

119+
def to_crawl_result(
120+
self, *, uses_tor: bool, terminal_status: str = "completed"
121+
) -> dict:
122+
"""Return the shared versioned crawl-result representation.
123+
124+
This is additive: ``saveJSON`` and the human-readable CLI views retain
125+
their existing legacy behavior.
126+
"""
127+
from torbot.crawl_result import CrawlResultAdapter
128+
129+
return CrawlResultAdapter(self, uses_tor=uses_tor).result(
130+
terminal_status=terminal_status
131+
)
132+
108133
def _get_tree_file_name(self) -> str:
109134
root_id = self.root
110135
root_node = self.get_node(root_id)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"schemaVersion": 1,
3+
"engine": "gotor",
4+
"target": "https://example.com/",
5+
"maxDepth": 1,
6+
"usesTor": false,
7+
"startedAt": "2026-08-21T12:00:00Z",
8+
"durationMs": 15,
9+
"pages": [
10+
{"parentUrl": "", "depth": 0, "links": ["https://example.com/child"], "metadata": {"url": "https://example.com/", "status": 200}}
11+
],
12+
"errors": []
13+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"schemaVersion":1,"terminalStatus":"cancelled","cancelled":true,"pages":[{"outcome":"fetched","status":200}]}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"schemaVersion":1,"terminalStatus":"invalid","cancelled":false,"pages":[{"outcome":"failed","status":null,"errorCategory":"invalid_input"}]}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"schemaVersion":1,"terminalStatus":"completed","cancelled":false,"pages":[{"outcome":"fetched","status":200},{"outcome":"failed","status":null,"errorCategory":"network"}]}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"schemaVersion":1,"terminalStatus":"completed","cancelled":false,"pages":[{"outcome":"skipped","status":200,"skippedReason":"non_html"}]}

‎tests/test_crawl_result.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import json
2+
from pathlib import Path
3+
4+
from torbot.crawl_result import CrawlResultAdapter, invalid_result
5+
from torbot.modules.linktree import LinkNode, LinkTree
6+
7+
8+
class EmptyClient:
9+
pass
10+
11+
12+
def make_tree() -> LinkTree:
13+
tree = LinkTree("https://EXAMPLE.com", depth=1, client=EmptyClient())
14+
root = LinkNode("Root", "https://example.com/", 200, "", 0.0, [], [])
15+
child = LinkNode(
16+
"Child", "https://example.com/child", 200, "", 0.0,
17+
["+14155551234"], ["info@example.com"],
18+
)
19+
tree.create_node(root.tag, root.identifier, data=root)
20+
tree.create_node(child.tag, child.identifier, parent=root.identifier, data=child)
21+
return tree
22+
23+
24+
def test_shared_contract_matches_gotor_baseline_fixture():
25+
gotor = json.loads(
26+
(Path(__file__).parent / "fixtures" / "gotor-v1-success.json").read_text()
27+
)
28+
result = CrawlResultAdapter(make_tree(), uses_tor=False).result(run_id="run-1")
29+
30+
assert result["schemaVersion"] == gotor["schemaVersion"]
31+
assert result["target"] == gotor["target"]
32+
assert result["settings"]["maxDepth"] == gotor["maxDepth"]
33+
assert result["settings"]["usesTor"] == gotor["usesTor"]
34+
assert result["pages"][0]["url"] == gotor["pages"][0]["metadata"]["url"]
35+
assert result["pages"][0]["status"] == gotor["pages"][0]["metadata"]["status"]
36+
assert result["pages"][0]["links"] == [
37+
{"url": "https://example.com/child", "source": "anchor"}
38+
]
39+
40+
41+
def test_result_records_failures_and_filters_secret_diagnostics():
42+
tree = make_tree()
43+
tree.crawl_failures.append({
44+
"url": "https://example.com/unavailable", "parentUrl": "https://example.com/",
45+
"depth": 1, "outcome": "failed", "status": None, "skippedReason": None,
46+
"errorCategory": "network", "links": [], "contacts": [],
47+
})
48+
result = CrawlResultAdapter(tree, uses_tor=True).result(
49+
diagnostics={"proxy": "configured", "cookie": "do-not-store", "token": "do-not-store"}
50+
)
51+
52+
assert result["terminalStatus"] == "completed"
53+
assert result["diagnostics"] == {"proxy": "configured"}
54+
assert result["pages"][-1]["errorCategory"] == "network"
55+
56+
57+
def test_cancelled_and_invalid_input_fixtures_are_terminal_and_safe():
58+
cancelled = CrawlResultAdapter(make_tree(), uses_tor=False).result(
59+
terminal_status="cancelled"
60+
)
61+
invalid = invalid_result("not-a-url", run_id="invalid-run")
62+
63+
assert cancelled["cancelled"] is True
64+
assert cancelled["terminalStatus"] == "cancelled"
65+
assert invalid["terminalStatus"] == "invalid"
66+
assert invalid["pages"] == [{
67+
"url": "not-a-url", "parentUrl": None, "depth": 0, "outcome": "failed",
68+
"status": None, "skippedReason": None, "errorCategory": "invalid_input",
69+
"links": [], "contacts": [],
70+
}]
71+
72+
73+
def test_contract_fixtures_cover_terminal_and_page_outcomes():
74+
fixture_directory = Path(__file__).parent / "fixtures"
75+
fixtures = [
76+
json.loads(path.read_text())
77+
for path in fixture_directory.glob("torbot-v1-*.json")
78+
]
79+
assert {fixture["terminalStatus"] for fixture in fixtures} == {
80+
"completed", "cancelled", "invalid"
81+
}
82+
outcomes = {page["outcome"] for fixture in fixtures for page in fixture["pages"]}
83+
assert {"fetched", "failed", "skipped"} <= outcomes

0 commit comments

Comments
 (0)