Debian Codegraph @

scripts/dcs_client.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Shared Debian Code Search (v1 API) client for the offline codesearch aids.
18
19 Used by both rank-license-usage-codesearch.py and verify-anchors-codesearch.py
20 so the politeness and caching behaviour cannot drift between them. Politeness:
21 one request at a time, a sleep between live requests, an on-disk response cache,
22 a caller-supplied User-Agent, honouring HTTP 429 / Retry-After, and retrying a
23 stalled connection. The v1 API needs an `x-dcs-apikey` header (key via
24 `$DCS_API_KEY` or a `--key-file`; see load_key).
25
26 These are offline curation aids - NOT part of the test suite's network path and
27 never run in CI. This module imports only the stdlib, so it stays a leaf that
28 both scripts can depend on.
29 """
30
31 from __future__ import annotations
32
33 import enum
34 import hashlib
35 import json
36 import os
37 import sys
38 import time
39 import urllib.error
40 import urllib.parse
41 import urllib.request
42 from dataclasses import dataclass, field
43 from http import HTTPStatus
44 from pathlib import Path
45
46 API_URL = "https://codesearch.debian.net/api/v1/search"
47 DEFAULT_SLEEP = 1.3 # seconds between LIVE requests (>= 1 req/s with margin)
48 # Above this a result set is broad-by-design; do not download it (may be GBs),
49 # just treat the candidate as clearly over threshold.
50 MAX_RESPONSE_BYTES = 25_000_000
51 MAX_ATTEMPTS = 4 # tries per query before giving up on it
52 BACKOFF_STEP = 2.0 # seconds; multiplied by the attempt number
53 REQUEST_TIMEOUT = 120 # seconds for a single urlopen
54 ERROR_BODY_CHARS = 120 # of a fatal error's body to include in the message
55 CACHE_KEY_LEN = 20 # hex chars of the query digest used as the cache filename
56
57
58 class SearchState(enum.Enum):
59 HITS = "hits" # a normal result set (see SearchOutcome.hits)
60 BROAD = "broad" # too many results to download; treated as clearly popular
61 PENDING = "pending" # offline and nothing cached yet; not queried
62
63
64 @dataclass(frozen=True)
65 class SearchOutcome:
66 state: SearchState
67 hits: list[dict] = field(default_factory=list)
68
69
70 class SearchError(Exception):
71 """A single query failed after exhausting its retries.
72
73 Recoverable at the batch level - the caller skips the candidate and keeps
74 going. Distinct from a fatal error (bad key, malformed query), which raises
75 SystemExit and aborts the whole run.
76 """
77
78
79 def load_key(path: Path | None) -> str:
80 """API key from $DCS_API_KEY, else the given --key-file, else abort."""
81 env = os.environ.get("DCS_API_KEY")
82 if env:
83 return env.strip()
84 if path is not None:
85 return path.read_text(encoding="utf-8").strip()
86 msg = (
87 "No API key: set $DCS_API_KEY or pass --key-file PATH "
88 "(get one at https://codesearch.debian.net/apikeys/)."
89 )
90 raise SystemExit(msg)
91
92
93 def _http_should_retry(code: int) -> bool:
94 """Whether an HTTP status warrants a retry (rate-limit or server error)."""
95 return (
96 code == HTTPStatus.TOO_MANY_REQUESTS or code >= HTTPStatus.INTERNAL_SERVER_ERROR
97 )
98
99
100 def _retry_after(exc: urllib.error.HTTPError, attempt: int) -> float:
101 """Seconds to wait: the server's Retry-After if given, else linear backoff."""
102 retry_after = exc.headers.get("Retry-After")
103 if retry_after:
104 return float(retry_after)
105 return BACKOFF_STEP * (attempt + 1)
106
107
108 def _backoff(seconds: float, label: str) -> None:
109 print(f" {label}; backing off {seconds:.0f}s", file=sys.stderr)
110 time.sleep(seconds)
111
112
113 @dataclass
114 class DcsConfig:
115 """Connection, cache and politeness settings for a DcsClient.
116
117 ``cache_prefix`` namespaces the cache key so two scripts sharing a cache
118 directory never collide (e.g. "rank" vs the empty default).
119 """
120
121 key: str
122 user_agent: str
123 cache_dir: Path
124 sleep: float = DEFAULT_SLEEP
125 refresh: bool = False
126 cache_prefix: str = ""
127
128
129 class DcsClient:
130 def __init__(self, config: DcsConfig) -> None:
131 self.key = config.key
132 self.user_agent = config.user_agent
133 self.cache_dir = config.cache_dir
134 self.sleep = config.sleep
135 self.refresh = config.refresh
136 self.cache_prefix = config.cache_prefix
137 self._last_live = 0.0
138 config.cache_dir.mkdir(parents=True, exist_ok=True)
139
140 def _cache_path(self, query: str, match_mode: str) -> Path:
141 parts = [match_mode, query]
142 if self.cache_prefix:
143 parts.insert(0, self.cache_prefix)
144 digest = hashlib.sha256("\x00".join(parts).encode()).hexdigest()
145 return self.cache_dir / f"{digest[:CACHE_KEY_LEN]}.json"
146
147 def _read_cache(self, path: Path) -> SearchOutcome | None:
148 """Cached outcome, or None on miss/refresh/corruption (a corrupt file is
149 deleted so the next call refetches). The on-disk shape is unchanged:
150 a JSON list is HITS; the legacy ``{"broad": true}`` object is BROAD."""
151 if self.refresh or not path.exists():
152 return None
153 try:
154 data = json.loads(path.read_text(encoding="utf-8"))
155 except json.JSONDecodeError:
156 path.unlink(missing_ok=True)
157 return None
158 if isinstance(data, dict):
159 return SearchOutcome(SearchState.BROAD)
160 return SearchOutcome(SearchState.HITS, data)
161
162 def _write_cache(self, path: Path, outcome: SearchOutcome) -> None:
163 # Keep the legacy on-disk shape so existing cache files stay valid.
164 data: list[dict] | dict = (
165 {"broad": True}
166 if outcome.state is SearchState.BROAD
167 else list(outcome.hits)
168 )
169 tmp = path.with_name(path.name + ".tmp")
170 tmp.write_text(json.dumps(data), encoding="utf-8")
171 tmp.replace(path) # atomic; a killed run cannot leave a half file
172
173 def _build_request(self, query: str, match_mode: str) -> urllib.request.Request:
174 params = urllib.parse.urlencode({"query": query, "match_mode": match_mode})
175 return urllib.request.Request( # noqa: S310
176 f"{API_URL}?{params}",
177 headers={"User-Agent": self.user_agent, "x-dcs-apikey": self.key},
178 )
179
180 def search_cached(self, query: str, match_mode: str) -> SearchOutcome:
181 """Cached outcome, or PENDING when nothing is cached. No network, no key."""
182 cached = self._read_cache(self._cache_path(query, match_mode))
183 return cached if cached is not None else SearchOutcome(SearchState.PENDING)
184
185 def search_live(self, query: str, match_mode: str) -> SearchOutcome:
186 """Cached outcome, or a fresh fetch that is then cached."""
187 path = self._cache_path(query, match_mode)
188 cached = self._read_cache(path)
189 if cached is not None:
190 return cached
191 outcome = self._fetch(self._build_request(query, match_mode))
192 self._write_cache(path, outcome)
193 return outcome
194
195 def _throttle(self) -> None:
196 wait = self.sleep - (time.monotonic() - self._last_live)
197 if wait > 0:
198 time.sleep(wait)
199
200 def _read(self, req: urllib.request.Request) -> SearchOutcome:
201 with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: # noqa: S310
202 raw = resp.read(MAX_RESPONSE_BYTES + 1)
203 self._last_live = time.monotonic()
204 if len(raw) > MAX_RESPONSE_BYTES:
205 return SearchOutcome(SearchState.BROAD)
206 return SearchOutcome(SearchState.HITS, json.loads(raw.decode()))
207
208 def _fetch(self, req: urllib.request.Request) -> SearchOutcome:
209 """Fetch with retries; SearchError on exhaustion, SystemExit if fatal.
210
211 A rate-limit/server error or a stalled connection is retried; any
212 other HTTP error (bad key, malformed query) is fatal and aborts.
213 """
214 for attempt in range(MAX_ATTEMPTS):
215 self._throttle()
216 try:
217 return self._read(req)
218 except urllib.error.HTTPError as exc:
219 self._last_live = time.monotonic()
220 if not _http_should_retry(exc.code):
221 body = exc.read().decode(errors="replace")[:ERROR_BODY_CHARS]
222 msg = f"HTTP {exc.code} from Code Search: {body}"
223 raise SystemExit(msg) from exc
224 _backoff(_retry_after(exc, attempt), f"HTTP {exc.code}")
225 except (TimeoutError, urllib.error.URLError) as exc:
226 # A stalled/reset connection carries no HTTP status to branch
227 # on: back off and retry the same way as a 429/5xx.
228 self._last_live = time.monotonic()
229 _backoff(BACKOFF_STEP * (attempt + 1), repr(exc))
230 msg = "Code Search kept failing after retries; aborting."
231 raise SearchError(msg)