返回 last30days-skill
robots.py
1 """A site's robots.txt: whether a path is disallowed, and the sitemaps it lists.
2
3 The jobs lane reads a company's job listing whatever the site's robots.txt
4 says, by the owner's decision (SECURITY.md). ``LAST30DAYS_JOBS_RESPECT_ROBOTS=1``
5 turns that off: a listing the ``*`` group disallows is then not read, and the
6 lane falls to the site's job sitemap. The sitemaps a robots.txt lists are
7 read either way: they are what the site publishes for crawlers.
8
9 Only the ``User-agent: *`` group is read, with the ``*`` and ``$`` wildcards
10 and the longest-match rule (an ``Allow`` wins a tie).
11 """
12
13 from __future__ import annotations
14
15 import os
16 import threading
17 from typing import Any
18 from urllib.parse import urlparse
19
20 from .. import http
21 from . import detect
22
23 RESPECT_ROBOTS_VAR = "LAST30DAYS_JOBS_RESPECT_ROBOTS"
24 TIMEOUT_SECONDS = 5
25 MAX_ROBOTS_CHARS = 512 * 1024
26 MAX_ROBOTS_BYTES = 1024 * 1024
27 MAX_LINES = 10_000
28 MAX_LINE_LENGTH = 4096
29 MAX_RULES = 2_000
30 MAX_PATHS = 2_000
31 MAX_SITEMAPS = 200
32
33 _cache: dict[str, "Rules"] = {}
34 _lock = threading.Lock()
35
36
37 def respect_robots(environ: Any = None) -> bool:
38 """True when ``LAST30DAYS_JOBS_RESPECT_ROBOTS`` asks the lane to skip a
39 job listing its site's robots.txt disallows."""
40 source = os.environ if environ is None else environ
41 return str(source.get(RESPECT_ROBOTS_VAR) or "").strip().lower() in {"1", "true", "yes", "on"}
42
43
44 class Rules:
45 """The ``*`` group's rules and the file's sitemaps. ``paths`` is every
46 ``Allow`` and ``Disallow`` path in the file, whatever group it is in."""
47
48 def __init__(self, text: str = "") -> None:
49 self.rules: list[tuple[bool, str]] = []
50 self.sitemaps: list[str] = []
51 self.paths: list[str] = []
52 agents: list[str] = []
53 in_rules = False
54 applies = False
55 raw_text = text or ""
56 if len(raw_text) > MAX_ROBOTS_CHARS:
57 bounded = raw_text[:MAX_ROBOTS_CHARS]
58 if (
59 bounded
60 and bounded[-1] not in ("\n", "\r")
61 and raw_text[MAX_ROBOTS_CHARS] not in ("\n", "\r")
62 ):
63 # Discard a trailing line cut mid-rule by MAX_ROBOTS_CHARS so a
64 # shortened Allow/Disallow prefix never takes effect.
65 last_nl = max(bounded.rfind("\n"), bounded.rfind("\r"))
66 bounded = bounded[:last_nl] if last_nl != -1 else ""
67 else:
68 bounded = raw_text
69 for line_count, raw in enumerate(bounded.splitlines()):
70 if line_count >= MAX_LINES:
71 break
72 line = raw.split("#", 1)[0].strip()
73 if len(line) > MAX_LINE_LENGTH or ":" not in line:
74 continue
75 field, value = (part.strip() for part in line.split(":", 1))
76 field = field.lower()
77 if field == "sitemap":
78 if value and len(self.sitemaps) < MAX_SITEMAPS:
79 self.sitemaps.append(value)
80 continue
81 if field == "user-agent":
82 if in_rules:
83 agents, in_rules = [], False
84 agents.append(value.lower())
85 applies = "*" in agents
86 continue
87 if field in ("allow", "disallow"):
88 in_rules = True
89 if value and len(self.paths) < MAX_PATHS:
90 self.paths.append(value)
91 if applies and value and len(self.rules) < MAX_RULES:
92 self.rules.append((field == "allow", value))
93
94 def allows(self, path: str) -> bool:
95 best: tuple[int, bool] | None = None
96 for allow, pattern in self.rules:
97 if _matches(pattern, path):
98 rank = (len(pattern), allow)
99 if best is None or rank > best:
100 best = rank
101 return True if best is None else best[1]
102
103
104 def _matches(pattern: str, path: str) -> bool:
105 anchored = pattern.endswith("$")
106 body = pattern[:-1] if anchored else pattern
107 parts = body.split("*")
108 if len(parts) == 1:
109 return path == parts[0] if anchored else path.startswith(parts[0])
110 first = parts[0]
111 if not path.startswith(first):
112 return False
113 pos = len(first)
114 middle = parts[1:-1] if anchored else parts[1:]
115 for part in middle:
116 if not part:
117 continue
118 idx = path.find(part, pos)
119 if idx == -1:
120 return False
121 pos = idx + len(part)
122 if not anchored:
123 return True
124 last = parts[-1]
125 if not last:
126 return True
127 return path.endswith(last) and len(path) - len(last) >= pos
128
129
130 def rules_for(host: str, *, deadline_monotonic: float | None = None) -> Rules:
131 """The robots.txt rules of ``host``, fetched once per run. A file that is
132 missing or does not answer has no rules."""
133 clean_host = (host or "").strip().rstrip(".").lower()
134 robots_url = f"https://{clean_host}/robots.txt"
135 if (
136 not clean_host
137 or not detect.is_safe_public_url(robots_url)
138 or detect.page_host(robots_url) != clean_host
139 ):
140 return Rules("")
141 with _lock:
142 if clean_host in _cache:
143 return _cache[clean_host]
144 bounds: dict[str, Any] = {}
145 if deadline_monotonic is not None:
146 bounds["deadline_monotonic"] = deadline_monotonic
147 try:
148 with http.capture_failures():
149 text = http.get_text(
150 robots_url, accept="text/plain", timeout=TIMEOUT_SECONDS,
151 retries=1, retry_dns=False, public_only=True,
152 redirect_guard=detect.same_site_redirect_guard(robots_url),
153 max_bytes=MAX_ROBOTS_BYTES, **bounds,
154 )
155 except UnicodeDecodeError:
156 text = None
157 found = Rules(text or "")
158 with _lock:
159 _cache[clean_host] = found
160 return found
161
162
163 def disallowed(url: str, *, deadline_monotonic: float | None = None) -> bool:
164 """Whether ``LAST30DAYS_JOBS_RESPECT_ROBOTS`` is on and the site's robots.txt
165 disallows ``url``. Always False with the setting off: no request is made."""
166 if not respect_robots():
167 return False
168 host = detect.page_host(url)
169 if not host:
170 return False
171 parsed = urlparse(url)
172 path = parsed.path or "/"
173 if parsed.query:
174 path += "?" + parsed.query
175 return not rules_for(host, deadline_monotonic=deadline_monotonic).allows(path)
176
177
178 def clear_cache() -> None:
179 with _lock:
180 _cache.clear()
181
181 lines PYTHON