perucompras-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- perucompras_cli-0.1.0.dist-info/METADATA +429 -0
- perucompras_cli-0.1.0.dist-info/RECORD +50 -0
- perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
- perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
- perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
- piloto_ai_cli/__init__.py +51 -0
- piloto_ai_cli/__main__.py +5 -0
- piloto_ai_cli/api.py +394 -0
- piloto_ai_cli/attribute_text.py +106 -0
- piloto_ai_cli/attributes_service.py +250 -0
- piloto_ai_cli/auto_tag.py +65 -0
- piloto_ai_cli/backoff.py +25 -0
- piloto_ai_cli/cards.py +871 -0
- piloto_ai_cli/cli.py +602 -0
- piloto_ai_cli/connectors.py +106 -0
- piloto_ai_cli/database.py +491 -0
- piloto_ai_cli/enrichment.py +557 -0
- piloto_ai_cli/errors.py +92 -0
- piloto_ai_cli/excel.py +186 -0
- piloto_ai_cli/extraction.py +1316 -0
- piloto_ai_cli/health.py +398 -0
- piloto_ai_cli/health_workflow.py +1060 -0
- piloto_ai_cli/http_client.py +610 -0
- piloto_ai_cli/llm_client.py +259 -0
- piloto_ai_cli/llm_extraction.py +444 -0
- piloto_ai_cli/llm_output.py +90 -0
- piloto_ai_cli/pane.py +303 -0
- piloto_ai_cli/parsers.py +477 -0
- piloto_ai_cli/payload_store.py +227 -0
- piloto_ai_cli/pdf_parser.py +12 -0
- piloto_ai_cli/py.typed +0 -0
- piloto_ai_cli/query_compiler.py +1112 -0
- piloto_ai_cli/query_result.py +175 -0
- piloto_ai_cli/query_service.py +199 -0
- piloto_ai_cli/reextract.py +129 -0
- piloto_ai_cli/review.py +217 -0
- piloto_ai_cli/rules.py +67 -0
- piloto_ai_cli/run_log.py +230 -0
- piloto_ai_cli/schema/__init__.py +25 -0
- piloto_ai_cli/schema/contract-v1.schema.json +261 -0
- piloto_ai_cli/schema/contract.py +257 -0
- piloto_ai_cli/schema/migration_filters.py +59 -0
- piloto_ai_cli/schema/models.py +747 -0
- piloto_ai_cli/schema/snowflake_autogen.py +134 -0
- piloto_ai_cli/search_form.py +82 -0
- piloto_ai_cli/settings.py +174 -0
- piloto_ai_cli/snowflake_url.py +90 -0
- piloto_ai_cli/stamp_service.py +53 -0
- piloto_ai_cli/sync.py +1157 -0
- piloto_ai_cli/unit_converter.py +81 -0
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
"""Polite asynchronous HTTP client for external requests."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import contextlib
|
|
5
|
+
import math
|
|
6
|
+
import random
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Iterator, Mapping
|
|
11
|
+
from contextvars import ContextVar
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from email.utils import parsedate_to_datetime
|
|
14
|
+
from html.parser import HTMLParser
|
|
15
|
+
from types import TracebackType
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import httpx2
|
|
19
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
20
|
+
|
|
21
|
+
from piloto_ai_cli.database import upsert
|
|
22
|
+
from piloto_ai_cli.payload_store import PayloadStore
|
|
23
|
+
from piloto_ai_cli.schema.models import Payload, RequestLog
|
|
24
|
+
from piloto_ai_cli.settings import MAX_PAGES_IN_FLIGHT, Settings
|
|
25
|
+
|
|
26
|
+
_PROCESS_IN_FLIGHT_LIMIT = threading.BoundedSemaphore(MAX_PAGES_IN_FLIGHT)
|
|
27
|
+
# Statuses the client retries with backoff: temporary by definition.
|
|
28
|
+
RETRYABLE_STATUSES = frozenset({429, 502, 503})
|
|
29
|
+
_DOWNLOAD_PATH = "/search/download"
|
|
30
|
+
_ANTIFORGERY_FIELD = "__RequestVerificationToken"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _AntiforgeryTokenParser(HTMLParser):
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
super().__init__()
|
|
36
|
+
self.token: str | None = None
|
|
37
|
+
|
|
38
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
39
|
+
if tag != "input" or self.token is not None:
|
|
40
|
+
return
|
|
41
|
+
attributes = dict(attrs)
|
|
42
|
+
if attributes.get("name") == _ANTIFORGERY_FIELD:
|
|
43
|
+
self.token = attributes.get("value")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _ErrorPageParser(HTMLParser):
|
|
47
|
+
def __init__(self) -> None:
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.headings: list[tuple[str, str]] = []
|
|
50
|
+
self._heading_tag: str | None = None
|
|
51
|
+
self._heading_parts: list[str] = []
|
|
52
|
+
|
|
53
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
54
|
+
if tag in {"h1", "h2"} and self._heading_tag is None:
|
|
55
|
+
self._heading_tag = tag
|
|
56
|
+
|
|
57
|
+
def handle_data(self, data: str) -> None:
|
|
58
|
+
if self._heading_tag is not None:
|
|
59
|
+
self._heading_parts.append(data)
|
|
60
|
+
|
|
61
|
+
def handle_endtag(self, tag: str) -> None:
|
|
62
|
+
if tag == self._heading_tag:
|
|
63
|
+
heading = " ".join("".join(self._heading_parts).split()).casefold()
|
|
64
|
+
self.headings.append((tag, heading))
|
|
65
|
+
self._heading_tag = None
|
|
66
|
+
self._heading_parts = []
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_error_page(html: str) -> bool:
|
|
70
|
+
"""Return whether HTML contains the site's generic ASP.NET error headings."""
|
|
71
|
+
parser = _ErrorPageParser()
|
|
72
|
+
parser.feed(html)
|
|
73
|
+
return ("h1", "error.") in parser.headings and (
|
|
74
|
+
"h2",
|
|
75
|
+
"an error occurred while processing your request.",
|
|
76
|
+
) in parser.headings
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _is_secret_name(name: str) -> bool:
|
|
80
|
+
return (
|
|
81
|
+
name.casefold()
|
|
82
|
+
.replace("_", "")
|
|
83
|
+
.replace("-", "")
|
|
84
|
+
.endswith(("token", "password", "secret", "apikey", "authorization"))
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def sanitize_request_form(form: Mapping[str, Any] | None) -> dict[str, Any] | None:
|
|
89
|
+
"""Return a request form safe to store in a request log."""
|
|
90
|
+
if form is None:
|
|
91
|
+
return None
|
|
92
|
+
return {
|
|
93
|
+
key: _sanitize_request_value(value)
|
|
94
|
+
for key, value in form.items()
|
|
95
|
+
if not _is_secret_name(key)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _sanitize_request_value(value: Any) -> Any:
|
|
100
|
+
if isinstance(value, Mapping):
|
|
101
|
+
return {
|
|
102
|
+
key: _sanitize_request_value(item)
|
|
103
|
+
for key, item in value.items()
|
|
104
|
+
if not _is_secret_name(key)
|
|
105
|
+
}
|
|
106
|
+
if isinstance(value, (list, tuple)):
|
|
107
|
+
return [_sanitize_request_value(item) for item in value]
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _partial_response(
|
|
112
|
+
response: httpx2.Response | None, raw_chunks: list[bytes]
|
|
113
|
+
) -> httpx2.Response | None:
|
|
114
|
+
"""The response with the raw bytes received so far, or None if none arrived.
|
|
115
|
+
|
|
116
|
+
The bytes are kept exactly as they came off the wire (still compressed if the
|
|
117
|
+
response has a Content-Encoding): a partial or malformed body may not decode,
|
|
118
|
+
and the raw bytes are what is worth keeping.
|
|
119
|
+
"""
|
|
120
|
+
if response is None:
|
|
121
|
+
return None
|
|
122
|
+
response._content = b"".join(raw_chunks)
|
|
123
|
+
response.extensions["raw_body"] = True
|
|
124
|
+
return response
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _loggable_url(url: httpx2.URL) -> str:
|
|
128
|
+
"""The request URL as sent, minus user:password and secret query parameters."""
|
|
129
|
+
if url.userinfo:
|
|
130
|
+
url = url.copy_with(userinfo=b"")
|
|
131
|
+
if any(_is_secret_name(name) for name in url.params):
|
|
132
|
+
url = url.copy_with(
|
|
133
|
+
params=[
|
|
134
|
+
(name, value)
|
|
135
|
+
for name, value in url.params.multi_items()
|
|
136
|
+
if not _is_secret_name(name)
|
|
137
|
+
]
|
|
138
|
+
)
|
|
139
|
+
return str(url)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _decode_body(response: httpx2.Response, raw: bytes) -> bytes:
|
|
143
|
+
"""Undo the response's Content-Encoding, as ``aread()`` would."""
|
|
144
|
+
decoder = response._get_content_decoder()
|
|
145
|
+
# ``httpx2`` decoders yield the decoded bytes in bounded pieces.
|
|
146
|
+
return b"".join([*decoder.decode(raw), *decoder.flush()])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_REQUEST_ID_ATTRIBUTE = "request_id"
|
|
150
|
+
|
|
151
|
+
# Per-call collector of request-log IDs (see ``collect_logged_request_ids()``).
|
|
152
|
+
_LOGGED_REQUEST_IDS: ContextVar[list[str] | None] = ContextVar("_logged_request_ids", default=None)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@contextlib.contextmanager
|
|
156
|
+
def collect_logged_request_ids() -> Iterator[list[str]]:
|
|
157
|
+
"""Collect the IDs of every request logged inside the block, in order.
|
|
158
|
+
|
|
159
|
+
Lets a caller that cancels a call (e.g. on a deadline) still point at the
|
|
160
|
+
last logged request, which a cancellation cannot carry on an error.
|
|
161
|
+
"""
|
|
162
|
+
request_ids: list[str] = []
|
|
163
|
+
token = _LOGGED_REQUEST_IDS.set(request_ids)
|
|
164
|
+
try:
|
|
165
|
+
yield request_ids
|
|
166
|
+
finally:
|
|
167
|
+
_LOGGED_REQUEST_IDS.reset(token)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def logged_request_id(error: BaseException) -> str | None:
|
|
171
|
+
"""Return the request-log ID that ``write_request()`` attached to a terminal failure."""
|
|
172
|
+
request_id = getattr(error, _REQUEST_ID_ATTRIBUTE, None)
|
|
173
|
+
return request_id if isinstance(request_id, str) else None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def set_logged_request_id(error: BaseException, request_id: str) -> None:
|
|
177
|
+
"""Attach a request-log ID to an error so ``logged_request_id()`` can read it back."""
|
|
178
|
+
setattr(error, _REQUEST_ID_ATTRIBUTE, request_id)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class _RequestFailure(Exception):
|
|
182
|
+
def __init__(
|
|
183
|
+
self,
|
|
184
|
+
error: httpx2.TransportError | httpx2.DecodingError,
|
|
185
|
+
body_produced: bool,
|
|
186
|
+
partial_response: httpx2.Response | None = None,
|
|
187
|
+
) -> None:
|
|
188
|
+
self.error = error
|
|
189
|
+
self.body_produced = body_produced
|
|
190
|
+
# Status, headers and the bytes received before the failure, if the
|
|
191
|
+
# server answered at all; logged with the error.
|
|
192
|
+
self.partial_response = partial_response
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class HttpClient:
|
|
196
|
+
"""HTTP client that applies identity, timeouts, retry, and concurrency rules."""
|
|
197
|
+
|
|
198
|
+
def __init__(
|
|
199
|
+
self,
|
|
200
|
+
settings: Settings,
|
|
201
|
+
*,
|
|
202
|
+
session_factory: sessionmaker[Session],
|
|
203
|
+
payload_store: PayloadStore,
|
|
204
|
+
run_id: str,
|
|
205
|
+
transport: httpx2.AsyncBaseTransport | None = None,
|
|
206
|
+
max_retries: int = 3,
|
|
207
|
+
backoff_base_seconds: float = 0.5,
|
|
208
|
+
max_backoff_seconds: float = 30.0,
|
|
209
|
+
) -> None:
|
|
210
|
+
if max_retries < 0:
|
|
211
|
+
raise ValueError("max_retries cannot be negative")
|
|
212
|
+
if backoff_base_seconds <= 0 or max_backoff_seconds <= 0:
|
|
213
|
+
raise ValueError("backoff values must be positive")
|
|
214
|
+
|
|
215
|
+
self._settings = settings
|
|
216
|
+
self._session_factory = session_factory
|
|
217
|
+
self._payload_store = payload_store
|
|
218
|
+
self._run_id = run_id
|
|
219
|
+
self._max_retries = max_retries
|
|
220
|
+
self._backoff_base_seconds = backoff_base_seconds
|
|
221
|
+
self._max_backoff_seconds = max_backoff_seconds
|
|
222
|
+
self._token: str | None = None
|
|
223
|
+
self._in_flight = asyncio.Semaphore(settings.per_call_in_flight_limit)
|
|
224
|
+
self._client = httpx2.AsyncClient(
|
|
225
|
+
headers={"User-Agent": settings.http_user_agent},
|
|
226
|
+
transport=transport,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def token(self) -> str | None:
|
|
231
|
+
"""The antiforgery token from the most recent successful bootstrap."""
|
|
232
|
+
return self._token
|
|
233
|
+
|
|
234
|
+
async def bootstrap(self, url: str) -> str:
|
|
235
|
+
"""Load the site's form token; the client's cookie jar keeps response cookies."""
|
|
236
|
+
_, token = await self._bootstrap(url)
|
|
237
|
+
if token is None:
|
|
238
|
+
raise AssertionError("a successful bootstrap must return an antiforgery token")
|
|
239
|
+
return token
|
|
240
|
+
|
|
241
|
+
async def bootstrap_response(
|
|
242
|
+
self, url: str, *, allow_error_page: bool = False
|
|
243
|
+
) -> httpx2.Response:
|
|
244
|
+
"""Load the site's form token and return its logged bootstrap response."""
|
|
245
|
+
response, _ = await self._bootstrap(url, allow_error_page=allow_error_page)
|
|
246
|
+
return response
|
|
247
|
+
|
|
248
|
+
async def _bootstrap(
|
|
249
|
+
self, url: str, *, allow_error_page: bool = False
|
|
250
|
+
) -> tuple[httpx2.Response, str | None]:
|
|
251
|
+
self._token = None
|
|
252
|
+
response = await self.write_request("GET", url, endpoint="get_home")
|
|
253
|
+
response.raise_for_status()
|
|
254
|
+
if response.extensions["is_error_page"]:
|
|
255
|
+
if not allow_error_page:
|
|
256
|
+
raise ValueError("bootstrap returned the site's error page")
|
|
257
|
+
return response, None
|
|
258
|
+
|
|
259
|
+
parser = _AntiforgeryTokenParser()
|
|
260
|
+
parser.feed(response.text)
|
|
261
|
+
if not parser.token:
|
|
262
|
+
raise ValueError(f"{_ANTIFORGERY_FIELD} was not found in the bootstrap response")
|
|
263
|
+
|
|
264
|
+
token = parser.token
|
|
265
|
+
self._token = token
|
|
266
|
+
return response, token
|
|
267
|
+
|
|
268
|
+
async def __aenter__(self) -> HttpClient:
|
|
269
|
+
return self
|
|
270
|
+
|
|
271
|
+
async def __aexit__(
|
|
272
|
+
self,
|
|
273
|
+
exc_type: type[BaseException] | None,
|
|
274
|
+
exc: BaseException | None,
|
|
275
|
+
traceback: TracebackType | None,
|
|
276
|
+
) -> None:
|
|
277
|
+
await self.aclose()
|
|
278
|
+
|
|
279
|
+
async def aclose(self) -> None:
|
|
280
|
+
await self._client.aclose()
|
|
281
|
+
|
|
282
|
+
async def write_request(
|
|
283
|
+
self,
|
|
284
|
+
method: str,
|
|
285
|
+
url: str,
|
|
286
|
+
*,
|
|
287
|
+
endpoint: str | None = None,
|
|
288
|
+
log_data: Mapping[str, Any] | None = None,
|
|
289
|
+
excel_download: bool = False,
|
|
290
|
+
timeout: httpx2.Timeout | float | None = None,
|
|
291
|
+
**kwargs: Any,
|
|
292
|
+
) -> httpx2.Response:
|
|
293
|
+
"""Send a request with the configured identity, limits, and retry policy."""
|
|
294
|
+
if kwargs.get("follow_redirects") or kwargs.get("auth") is not None:
|
|
295
|
+
raise ValueError("automatic redirects and authentication flows are not supported")
|
|
296
|
+
headers = httpx2.Headers(kwargs.pop("headers", None))
|
|
297
|
+
headers["User-Agent"] = self._settings.http_user_agent
|
|
298
|
+
form = kwargs.get("data")
|
|
299
|
+
if form is not None and log_data is not None:
|
|
300
|
+
raise ValueError("request form and log_data cannot both be provided")
|
|
301
|
+
if form is not None and not isinstance(form, Mapping):
|
|
302
|
+
raise TypeError("request form must be a mapping")
|
|
303
|
+
request_form = sanitize_request_form(log_data if log_data is not None else form)
|
|
304
|
+
# The URL as it is sent, including any ``params=`` and client defaults.
|
|
305
|
+
logged_url = _loggable_url(
|
|
306
|
+
self._client.build_request(method, url, params=kwargs.get("params")).url
|
|
307
|
+
)
|
|
308
|
+
endpoint = endpoint or httpx2.URL(url).path or "/"
|
|
309
|
+
is_download = (
|
|
310
|
+
method.upper() == "POST" and httpx2.URL(url).path.rstrip("/").lower() == _DOWNLOAD_PATH
|
|
311
|
+
)
|
|
312
|
+
request_timeout = (
|
|
313
|
+
timeout
|
|
314
|
+
if timeout is not None
|
|
315
|
+
else self._timeout(excel_download=excel_download or is_download)
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
for retry_number in range(self._max_retries + 1):
|
|
319
|
+
try:
|
|
320
|
+
async with self._in_flight:
|
|
321
|
+
await self._acquire_process_slot()
|
|
322
|
+
try:
|
|
323
|
+
requested_at = datetime.now(UTC)
|
|
324
|
+
started = time.monotonic()
|
|
325
|
+
try:
|
|
326
|
+
response = await self._request_once(
|
|
327
|
+
method,
|
|
328
|
+
url,
|
|
329
|
+
headers=headers,
|
|
330
|
+
timeout=request_timeout,
|
|
331
|
+
**kwargs,
|
|
332
|
+
)
|
|
333
|
+
except asyncio.CancelledError as cancelled:
|
|
334
|
+
# The request may already have been sent: commit
|
|
335
|
+
# what is known before the cancellation propagates.
|
|
336
|
+
with contextlib.suppress(Exception, asyncio.CancelledError):
|
|
337
|
+
await self._commit_log(
|
|
338
|
+
endpoint,
|
|
339
|
+
method,
|
|
340
|
+
logged_url,
|
|
341
|
+
request_form,
|
|
342
|
+
requested_at,
|
|
343
|
+
max(0, int((time.monotonic() - started) * 1000)),
|
|
344
|
+
response=getattr(cancelled, "partial_response", None),
|
|
345
|
+
error=cancelled,
|
|
346
|
+
)
|
|
347
|
+
raise
|
|
348
|
+
finally:
|
|
349
|
+
_PROCESS_IN_FLIGHT_LIMIT.release()
|
|
350
|
+
except _RequestFailure as failure:
|
|
351
|
+
failed_id = await self._commit_log(
|
|
352
|
+
endpoint,
|
|
353
|
+
method,
|
|
354
|
+
logged_url,
|
|
355
|
+
request_form,
|
|
356
|
+
requested_at,
|
|
357
|
+
max(0, int((time.monotonic() - started) * 1000)),
|
|
358
|
+
response=failure.partial_response,
|
|
359
|
+
error=failure.error,
|
|
360
|
+
)
|
|
361
|
+
if (
|
|
362
|
+
retry_number >= self._max_retries
|
|
363
|
+
or (is_download and failure.body_produced)
|
|
364
|
+
or isinstance(failure.error, httpx2.DecodingError)
|
|
365
|
+
):
|
|
366
|
+
# Keep the terminal attempt's log ID so callers can point at it.
|
|
367
|
+
set_logged_request_id(failure.error, failed_id)
|
|
368
|
+
raise failure.error from None
|
|
369
|
+
await asyncio.sleep(self._backoff_delay(retry_number))
|
|
370
|
+
continue
|
|
371
|
+
|
|
372
|
+
response.extensions["request_id"] = await self._commit_log(
|
|
373
|
+
endpoint,
|
|
374
|
+
method,
|
|
375
|
+
logged_url,
|
|
376
|
+
request_form,
|
|
377
|
+
requested_at,
|
|
378
|
+
max(0, int((time.monotonic() - started) * 1000)),
|
|
379
|
+
response=response,
|
|
380
|
+
)
|
|
381
|
+
if (
|
|
382
|
+
response.status_code not in RETRYABLE_STATUSES
|
|
383
|
+
or retry_number >= self._max_retries
|
|
384
|
+
or (is_download and response.content)
|
|
385
|
+
):
|
|
386
|
+
return response
|
|
387
|
+
|
|
388
|
+
retry_after = _retry_after_seconds(response.headers.get("Retry-After"))
|
|
389
|
+
await asyncio.sleep(self._backoff_delay(retry_number, retry_after))
|
|
390
|
+
|
|
391
|
+
raise AssertionError("unreachable")
|
|
392
|
+
|
|
393
|
+
async def _commit_log(
|
|
394
|
+
self,
|
|
395
|
+
endpoint: str,
|
|
396
|
+
method: str,
|
|
397
|
+
url: str,
|
|
398
|
+
form: dict[str, Any] | None,
|
|
399
|
+
requested_at: datetime,
|
|
400
|
+
duration_ms: int,
|
|
401
|
+
*,
|
|
402
|
+
response: httpx2.Response | None = None,
|
|
403
|
+
error: BaseException | None = None,
|
|
404
|
+
) -> str:
|
|
405
|
+
"""Run ``_log_request`` off the event loop and wait until it has committed.
|
|
406
|
+
|
|
407
|
+
Off the loop so that other coroutines (e.g. one holding a SQLite write)
|
|
408
|
+
keep running; shielded so that a cancellation, whether the job is still
|
|
409
|
+
queued or already running, neither drops the log nor reaches the caller
|
|
410
|
+
before the commit. A cancellation received meanwhile is re-raised once
|
|
411
|
+
the log is committed (or has failed).
|
|
412
|
+
"""
|
|
413
|
+
log = asyncio.ensure_future(
|
|
414
|
+
asyncio.to_thread(
|
|
415
|
+
self._log_request,
|
|
416
|
+
endpoint,
|
|
417
|
+
method,
|
|
418
|
+
url,
|
|
419
|
+
form,
|
|
420
|
+
requested_at,
|
|
421
|
+
duration_ms,
|
|
422
|
+
response=response,
|
|
423
|
+
error=error,
|
|
424
|
+
)
|
|
425
|
+
)
|
|
426
|
+
cancelled = False
|
|
427
|
+
while not log.done():
|
|
428
|
+
try:
|
|
429
|
+
await asyncio.shield(log)
|
|
430
|
+
except asyncio.CancelledError:
|
|
431
|
+
cancelled = True
|
|
432
|
+
except Exception:
|
|
433
|
+
break
|
|
434
|
+
if cancelled:
|
|
435
|
+
if not log.cancelled():
|
|
436
|
+
log.exception() # mark a logging failure as retrieved
|
|
437
|
+
raise asyncio.CancelledError
|
|
438
|
+
return log.result()
|
|
439
|
+
|
|
440
|
+
def _log_request(
|
|
441
|
+
self,
|
|
442
|
+
endpoint: str,
|
|
443
|
+
method: str,
|
|
444
|
+
url: str,
|
|
445
|
+
form: dict[str, Any] | None,
|
|
446
|
+
requested_at: datetime,
|
|
447
|
+
duration_ms: int,
|
|
448
|
+
*,
|
|
449
|
+
response: httpx2.Response | None = None,
|
|
450
|
+
error: BaseException | None = None,
|
|
451
|
+
) -> str:
|
|
452
|
+
request_id = str(uuid.uuid4())
|
|
453
|
+
payload_row: dict[str, Any] | None = None
|
|
454
|
+
payload_sha256 = None
|
|
455
|
+
error_page = False
|
|
456
|
+
if response is not None:
|
|
457
|
+
# Every response body is stored, whatever the status or outcome: raw
|
|
458
|
+
# sources are what extraction is improved against. A body that could
|
|
459
|
+
# not be (fully) decoded is stored as received, and its content type
|
|
460
|
+
# says which encoding is still applied.
|
|
461
|
+
body = response.content
|
|
462
|
+
content_type = response.headers.get("content-type", "application/octet-stream")
|
|
463
|
+
content_encoding = response.headers.get("content-encoding")
|
|
464
|
+
if response.extensions.get("raw_body") and content_encoding:
|
|
465
|
+
content_type = f"{content_type}; content-encoding={content_encoding}"
|
|
466
|
+
payload_sha256 = self._payload_store.put(body, content_type)
|
|
467
|
+
payload_row = {
|
|
468
|
+
"payload_sha256": payload_sha256,
|
|
469
|
+
"content_type": content_type,
|
|
470
|
+
"size_bytes": len(body),
|
|
471
|
+
"storage_uri": self._payload_store.storage_uri(payload_sha256),
|
|
472
|
+
"stored_at": datetime.now(UTC),
|
|
473
|
+
}
|
|
474
|
+
if (
|
|
475
|
+
error is None
|
|
476
|
+
and response.status_code == 200
|
|
477
|
+
and ("html" in content_type.lower() or body.lstrip().startswith(b"<"))
|
|
478
|
+
):
|
|
479
|
+
error_page = is_error_page(response.text)
|
|
480
|
+
|
|
481
|
+
with self._session_factory.begin() as session:
|
|
482
|
+
if payload_row is not None:
|
|
483
|
+
upsert(session, Payload, [payload_row])
|
|
484
|
+
upsert(
|
|
485
|
+
session,
|
|
486
|
+
RequestLog,
|
|
487
|
+
[
|
|
488
|
+
{
|
|
489
|
+
"request_id": request_id,
|
|
490
|
+
"run_id": self._run_id,
|
|
491
|
+
"endpoint": endpoint,
|
|
492
|
+
"url": url,
|
|
493
|
+
"http_method": method.upper(),
|
|
494
|
+
"request_form": form,
|
|
495
|
+
"requested_at": requested_at,
|
|
496
|
+
"duration_ms": duration_ms,
|
|
497
|
+
"http_status": response.status_code if response is not None else None,
|
|
498
|
+
"is_error_page": error_page,
|
|
499
|
+
"error": (
|
|
500
|
+
(
|
|
501
|
+
"Request cancelled"
|
|
502
|
+
if isinstance(error, asyncio.CancelledError)
|
|
503
|
+
else str(error) or type(error).__name__
|
|
504
|
+
)
|
|
505
|
+
if error is not None
|
|
506
|
+
else f"HTTP {response.status_code}"
|
|
507
|
+
if response is not None and response.status_code >= 400
|
|
508
|
+
else "Site error page"
|
|
509
|
+
if error_page
|
|
510
|
+
else None
|
|
511
|
+
),
|
|
512
|
+
"payload_sha256": payload_sha256,
|
|
513
|
+
}
|
|
514
|
+
],
|
|
515
|
+
)
|
|
516
|
+
if response is not None:
|
|
517
|
+
response.extensions["is_error_page"] = error_page
|
|
518
|
+
collector = _LOGGED_REQUEST_IDS.get()
|
|
519
|
+
if collector is not None:
|
|
520
|
+
collector.append(request_id)
|
|
521
|
+
return request_id
|
|
522
|
+
|
|
523
|
+
async def _request_once(
|
|
524
|
+
self,
|
|
525
|
+
method: str,
|
|
526
|
+
url: str,
|
|
527
|
+
*,
|
|
528
|
+
headers: httpx2.Headers,
|
|
529
|
+
timeout: httpx2.Timeout | float,
|
|
530
|
+
**kwargs: Any,
|
|
531
|
+
) -> httpx2.Response:
|
|
532
|
+
response: httpx2.Response | None = None
|
|
533
|
+
raw_chunks: list[bytes] = []
|
|
534
|
+
try:
|
|
535
|
+
async with self._client.stream(
|
|
536
|
+
method,
|
|
537
|
+
url,
|
|
538
|
+
headers=headers,
|
|
539
|
+
timeout=timeout,
|
|
540
|
+
**kwargs,
|
|
541
|
+
) as response:
|
|
542
|
+
# Read the raw bytes chunk by chunk so that what was received
|
|
543
|
+
# before a failure, or a body that does not decode, can still
|
|
544
|
+
# be logged as it came off the wire.
|
|
545
|
+
if response.is_stream_consumed:
|
|
546
|
+
# Already read when it was built (an in-memory transport):
|
|
547
|
+
# its decoded content is all there is.
|
|
548
|
+
return response
|
|
549
|
+
async for chunk in response.aiter_raw():
|
|
550
|
+
raw_chunks.append(chunk)
|
|
551
|
+
response._content = _decode_body(response, b"".join(raw_chunks))
|
|
552
|
+
return response
|
|
553
|
+
except (httpx2.TransportError, httpx2.DecodingError) as error:
|
|
554
|
+
# A decoding error (malformed gzip/deflate) is not a TransportError
|
|
555
|
+
# but still follows a received response, so it is logged too.
|
|
556
|
+
raise _RequestFailure(
|
|
557
|
+
error,
|
|
558
|
+
response is not None and response.num_bytes_downloaded > 0,
|
|
559
|
+
_partial_response(response, raw_chunks),
|
|
560
|
+
) from error
|
|
561
|
+
except asyncio.CancelledError as cancelled:
|
|
562
|
+
cancelled.partial_response = _partial_response( # type: ignore[attr-defined]
|
|
563
|
+
response, raw_chunks
|
|
564
|
+
)
|
|
565
|
+
raise
|
|
566
|
+
|
|
567
|
+
async def _acquire_process_slot(self) -> None:
|
|
568
|
+
while not _PROCESS_IN_FLIGHT_LIMIT.acquire(blocking=False):
|
|
569
|
+
await asyncio.sleep(0.01)
|
|
570
|
+
|
|
571
|
+
def _timeout(self, *, excel_download: bool) -> httpx2.Timeout:
|
|
572
|
+
read_timeout = (
|
|
573
|
+
self._settings.http_excel_read_timeout_seconds
|
|
574
|
+
if excel_download
|
|
575
|
+
else self._settings.http_read_timeout_seconds
|
|
576
|
+
)
|
|
577
|
+
return httpx2.Timeout(
|
|
578
|
+
connect=self._settings.http_connect_timeout_seconds,
|
|
579
|
+
read=read_timeout,
|
|
580
|
+
write=read_timeout,
|
|
581
|
+
pool=self._settings.http_connect_timeout_seconds,
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
def _backoff_delay(self, retry_number: int, retry_after: float | None = None) -> float:
|
|
585
|
+
ceiling = min(
|
|
586
|
+
self._max_backoff_seconds,
|
|
587
|
+
self._backoff_base_seconds * (2**retry_number),
|
|
588
|
+
)
|
|
589
|
+
delay = random.uniform(0, ceiling)
|
|
590
|
+
return max(delay, retry_after or 0)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _retry_after_seconds(value: str | None) -> float | None:
|
|
594
|
+
if value is None:
|
|
595
|
+
return None
|
|
596
|
+
|
|
597
|
+
try:
|
|
598
|
+
seconds = float(value)
|
|
599
|
+
except ValueError:
|
|
600
|
+
try:
|
|
601
|
+
retry_at = parsedate_to_datetime(value)
|
|
602
|
+
except TypeError, ValueError, OverflowError:
|
|
603
|
+
return None
|
|
604
|
+
if retry_at.tzinfo is None:
|
|
605
|
+
retry_at = retry_at.replace(tzinfo=UTC)
|
|
606
|
+
seconds = (retry_at - datetime.now(UTC)).total_seconds()
|
|
607
|
+
|
|
608
|
+
if not math.isfinite(seconds):
|
|
609
|
+
return None
|
|
610
|
+
return max(0.0, seconds)
|