From 8e0a6fb985f8a88e3ee1ceddf1690874e3f72c69 Mon Sep 17 00:00:00 2001 From: kasparasizi1 <132673909+kasparasizi1@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:00:40 +0200 Subject: [PATCH] SCR-652: async requests and webhooks in the Python SDK (0.80.0) - requests.submit (Prefer / X-Callback-URL / Idempotency-Key), requests.wait (honours Retry-After, raises AsyncRequestTimeoutError), requests.callback_status. AsyncRequest gains status, headers, body and replayed; running, data, credits_used and result_id are kept, and requests.get keeps its locked signature. - account.webhook_secret, rotate_webhook_secret and webhook_deliveries with typed models; 403 full_access_required maps to PermissionDeniedError. - scrapebadger.webhooks: verify_signature (constant time, optional sent_at tolerance) and parse_event -> WebhookEvent. - BaseClient._send: the shared retry loop with per-call headers. A submit without an idempotency key retries only transport errors raised before sending; an idempotent replay and a wait() poll never retry an error status. - account/client.py: the handwritten methods sit above the generated block, so sdk/codegen/facade rewrites only that block instead of the whole module. - Version 0.80.0 in pyproject, SDK_VERSION, __version__ (was stale at 0.77.0) and uv.lock; CHANGELOG and a README "Async requests and webhooks" section. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 + README.md | 80 ++- pyproject.toml | 2 +- src/scrapebadger/__init__.py | 16 +- src/scrapebadger/_internal/client.py | 197 ++++--- src/scrapebadger/_internal/exceptions.py | 36 ++ src/scrapebadger/account/__init__.py | 3 +- src/scrapebadger/account/client.py | 78 ++- src/scrapebadger/account/models.py | 76 +++ src/scrapebadger/agent/__init__.py | 4 +- src/scrapebadger/agent/client.py | 315 +++++++++-- src/scrapebadger/agent/models.py | 87 +++- src/scrapebadger/webhooks.py | 163 ++++++ tests/test_async_requests.py | 632 +++++++++++++++++++++++ uv.lock | 2 +- 15 files changed, 1579 insertions(+), 126 deletions(-) create mode 100644 src/scrapebadger/account/models.py create mode 100644 src/scrapebadger/webhooks.py create mode 100644 tests/test_async_requests.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7142e8b..786a039 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [0.80.0] - 2026-11-18 + +- **Async requests and webhooks.** Run any slow call asynchronously and get the result by polling or by a signed webhook. Submitting and polling are free; the call is billed once, when it completes. (SCR-652) + - `requests.submit(path, *, method="GET", params=None, json=None, callback_url=None, wait=None, idempotency_key=None)` sends the call with `Prefer: respond-async[, wait=N]`, `X-Callback-URL` and `Idempotency-Key`. It returns an `AsyncRequest`: running (202, with `request_id`) or completed (the result within `wait` seconds). `wait` (0-120) defaults to 0 with a `callback_url`, otherwise to the API's default. + - `idempotency_key` (1-200 visible ASCII characters): re-submitting the same call with the same key returns the first call's state with `replayed=True` (`Idempotent-Replayed: true`) and does not run or bill it again. The same key with a different call raises `ScrapeBadgerError` 409 `idempotency_key_reused`. The SDK retries a submit whose answer was lost in transit (a read timeout) only when it has a key; connection errors raised before anything was sent are always retried. + - `requests.wait(request_id, *, timeout=600.0)` polls until the call completes, sleeping `Retry-After` between polls. It raises the new `AsyncRequestTimeoutError` (a `ScrapeBadgerError` and a `TimeoutError`) when time runs out. A completed call with an error status is raised as the matching exception without retrying: a stored result can't change. + - `requests.callback_status(request_id)` returns a `CallbackStatus`: the webhook's `state`, `attempts`, `last_status`, `last_error`, `next_attempt_at`, `delivered_at` and `callback_host`. + - `account.webhook_secret()`, `account.rotate_webhook_secret()` (`WebhookSecret`) and `account.webhook_deliveries(limit=50)` (`WebhookDeliveries` of `WebhookDelivery`). A key limited to some APIs now raises `PermissionDeniedError` (403 `full_access_required`). The generated `get_the_webhook_signing_secret` / `rotate_the_webhook_signing_secret` (raw dicts) are kept. + - New `scrapebadger.webhooks` module: `verify_signature(secret, raw_body, signature, *, sent_at=None, tolerance_s=300)` checks `X-ScrapeBadger-Signature` in constant time and rejects a `sent_at` outside the tolerance. `parse_event(raw_body)` returns a `WebhookEvent` (the `request.completed` payload). + - `AsyncRequest` gains `status` (`"running"` / `"completed"`), `headers`, `body` (decoded JSON for a JSON response, else the text) and `replayed`. `running`, `data`, `credits_used` and `result_id` are unchanged. `requests.get` keeps its signature; a non-JSON result now comes back as text instead of `{}`. + - Idempotency keys, `callback_status` and `webhook_deliveries` need the API's SCR-652 release. Against an older API, an `Idempotency-Key` is ignored. +- `scrapebadger.__version__` reported 0.77.0 since 0.78.0; it now matches the package version. +- Also ships the generated `rufus` client merged after 0.79.0 (#103). + ## [0.79.0] - 2026-11-14 - **Grok API.** Adds the generated `grok` client for real Grok answers with web citations, X post references, multi-turn conversations, assistant modes, and brand-visibility analysis. Includes GET and POST ask/brand methods, conversation history, and models. (SCR-623) diff --git a/README.md b/README.md index 1ab7306..49782b7 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ The official Python SDK for [ScrapeBadger](https://scrapebadger.com) - async web - **Type-safe** - Full type hints and Pydantic models for all responses - **Automatic pagination** - Iterator methods with smart rate limit handling - **Resilient retries** - Exponential backoff on transient errors +- **Async requests and webhooks** - Submit any slow call, poll or `wait` for it, or take a signed webhook; idempotency keys make re-submits safe - **37+ Twitter endpoints** - Tweets, users, lists, communities, trends, geo, real-time streams - **20 Google product APIs** - Search (with optional deferred AI Overview follow-up), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (+ merchant URL enrichment), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, **Local Pack**, **Shorts**, **Flights**, Products, **Ads Transparency Center** - **Vinted scraping** - Search items, item details, user profiles, brands, colors, markets @@ -135,7 +136,7 @@ Etsy and AliExpress category navigation is separate from search: their search me | **ChatGPT** | Prompt the real chatgpt.com anonymously — structured answer with citations anchored to character offsets, the full retrieved search trail, and AEO/GEO brand-visibility analysis | [ChatGPT Guide](docs/chatgpt.md) | | **Gemini** | Prompt the real gemini.google.com anonymously — structured answer with cited web sources, the full retrieved search trail, and AEO/GEO brand-visibility analysis | [Gemini Docs](https://docs.scrapebadger.com/gemini/overview) | -## Quotes, feedback and async polling +## Quotes and feedback These calls are free and never billed. @@ -145,22 +146,83 @@ async with ScrapeBadger(api_key="your-api-key") as client: quote = await client.agent.quote("GET", "/v1/google/search", params={"q": "coffee"}) print(quote.valid, quote.errors, quote.credits.max, quote.usd, quote.latency) - # Poll a call made with `Prefer: respond-async` (202 + request_id). - state = await client.requests.get(request_id) - if not state.running: - print(state.status_code, state.credits_used, state.data) - # Report a bug or send feedback (pass the failing call's X-Request-ID). await client.agent.report_bug("Empty results for a valid query", request_id=request_id) await client.agent.feedback("Need a Google Maps photos endpoint") ``` -ScrapeBadger does not cache or store responses: every call is fetched fresh and billed, and `results.get` (the old free re-read) is deprecated because `GET /v1/results/{id}` was removed on 2026-11-09. To reshape a result, re-run the call with the `jq`, `fields` or `max_items` view parameters. `requests.get` returns `running=True` while the call is in progress — wait `retry_after_seconds` and poll again; never re-submit the call. Once finished it returns the original body, or raises the original call's error. - -The SDK's own methods never send `Prefer: respond-async`; `requests.get` polls a request ID obtained elsewhere (raw HTTP, the CLI or MCP server). +ScrapeBadger does not cache or store responses: every call is fetched fresh and billed, and `results.get` (the old free re-read) is deprecated because `GET /v1/results/{id}` was removed on 2026-11-09. To reshape a result, re-run the call with the `jq`, `fields` or `max_items` view parameters. For an agent trial key, `await client.account.get_account_info()` carries an `agent_trial` block; parse it with `AgentTrial.model_validate(info["agent_trial"])` for `credits_remaining`, `expires_at` and `claim_url`. +## Async requests and webhooks + +Slow calls can run asynchronously: AI asks such as Perplexity, ChatGPT or Gemini take 15–40 s, sometimes over a minute. `client.requests.submit` sends any `/v1` call with `Prefer: respond-async`. You get a `request_id` at once and the result later, by polling (free) or by a signed webhook. The call is billed once, when it completes; a call that never completes is not billed. Results are kept for about 15 minutes. + +```python +from scrapebadger import ScrapeBadger + +async with ScrapeBadger(api_key="your-api-key") as client: + req = await client.requests.submit( + "/v1/perplexity/ask", + params={"prompt": "best crm for startups", "country": "us"}, + callback_url="https://example.com/hooks/scrapebadger", + idempotency_key="crm-question-42", # a re-submit with this key never runs or bills twice + ) + print(req.request_id, req.status) # "running": the result goes to the callback URL + + # Or, without a webhook, wait for it here (polls are free and honour Retry-After): + done = await client.requests.wait(req.request_id, timeout=300) + print(done.status_code, done.body["answer"]) +``` + +- `submit(path, *, method="GET", params=None, json=None, callback_url=None, wait=None, idempotency_key=None)` returns an `AsyncRequest`. That is `status="running"` with `request_id` and `retry_after_seconds`, or `status="completed"` with `status_code`, `headers` and `body` when the call finished within `wait` seconds (0–120). `wait` defaults to 0 with a `callback_url` (answer at once), otherwise to the API's default (25 s). +- `idempotency_key` (1–200 visible ASCII characters) makes a re-submit safe. The same call with the same key within 15 minutes returns the first call's state with `replayed=True` instead of running it again. The same key with a different call raises `ScrapeBadgerError` 409 `idempotency_key_reused`. The SDK retries a submit whose answer was lost in transit only when it has a key. +- `requests.get(request_id)` polls once. `requests.wait(request_id, timeout=600)` polls until the call is done and raises `AsyncRequestTimeoutError` (also a `TimeoutError`) if it is still running. The call keeps running either way: poll again, never re-submit. A finished call with an error status is raised as the matching exception (for example `ServerError` for a 502), as for a synchronous call. +- `requests.callback_status(request_id)` reports the webhook delivery: `state` (`pending`, `delivering`, `delivered` or `failed`), `attempts`, `last_status`, `last_error`, `next_attempt_at` and `delivered_at`. `account.webhook_deliveries(limit=50)` lists the account's deliveries of the last 24 hours. +- `requests.batch([...], callback_url=...)` submits up to 100 GET reads in one call. + +### Receive the webhook + +When the call completes, ScrapeBadger POSTs a `request.completed` event to the callback URL. It is signed with your account's secret: `(await client.account.webhook_secret()).secret`. Rotate it with `account.rotate_webhook_secret()`; both need a full-access key. + +- Verify the signature on the **raw** body before you trust it, and reject stale deliveries with `sent_at`. +- Answer with a `2xx` within 10 s, and do slow work afterwards. +- Failed deliveries are retried after 10 s, 60 s and 5 min, so deduplicate on `request_id`. + +```python +import os + +from fastapi import FastAPI, HTTPException, Request +from scrapebadger.webhooks import parse_event, verify_signature + +app = FastAPI() +SECRET = os.environ["SCRAPEBADGER_WEBHOOK_SECRET"] +seen: set[str] = set() # use your database in production + + +@app.post("/hooks/scrapebadger") +async def scrapebadger_hook(request: Request) -> dict[str, bool]: + raw = await request.body() # the raw bytes, before any JSON parsing + try: + event = parse_event(raw) + except ValueError: + raise HTTPException(400) from None + signature = request.headers.get("X-ScrapeBadger-Signature", "") + if not verify_signature(SECRET, raw, signature, sent_at=event.sent_at): + raise HTTPException(401) + if event.request_id not in seen: + seen.add(event.request_id) + # event.status and event.body are the call's own, errors included. A body over + # 1 MB is left out (event.body_omitted): fetch it from event.result_url. + print(event.status, event.body) + return {"ok": True} +``` + +`verify_signature(secret, raw_body, signature, *, sent_at=None, tolerance_s=300)` compares in constant time and never raises. It returns `False` for a wrong, missing or malformed signature, or for a `sent_at` more than `tolerance_s` seconds away. Pass the `sent_at` from the parsed body: the body is what is signed. `parse_event(raw_body)` returns a `WebhookEvent` with `event`, `request_id`, `batch_id`, `status`, `headers`, `body`, `body_omitted`, `body_size`, `result_url`, `result_expires_at`, `attempt` and `sent_at`. It raises `ValueError` for a body that is not such an event. + +See [Async requests and webhooks](https://docs.scrapebadger.com/long-running-requests) in the docs. + ## Error Handling ```python diff --git a/pyproject.toml b/pyproject.toml index 41ebf09..d7b0117 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "scrapebadger" -version = "0.79.0" +version = "0.80.0" description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more" readme = "README.md" license = { text = "MIT" } diff --git a/src/scrapebadger/__init__.py b/src/scrapebadger/__init__.py index ba3cdd1..3e2116d 100644 --- a/src/scrapebadger/__init__.py +++ b/src/scrapebadger/__init__.py @@ -29,8 +29,10 @@ async def main(): For more information, see https://docs.scrapebadger.com """ +from scrapebadger import webhooks from scrapebadger._internal.config import ClientConfig from scrapebadger._internal.exceptions import ( + AsyncRequestTimeoutError, AuthenticationError, BlockedError, InsufficientCreditsError, @@ -44,12 +46,14 @@ async def main(): WebSocketStreamError, ) from scrapebadger._internal.pagination import PaginatedResponse +from scrapebadger.account import WebhookDeliveries, WebhookDelivery, WebhookSecret from scrapebadger.agent import ( AgentClient, AgentTrial, AsyncRequest, BatchItemResult, BatchSubmission, + CallbackStatus, FeedbackReceipt, Quote, QuoteCredits, @@ -1052,6 +1056,7 @@ async def main(): Warranty as WalmartWarranty, ) from scrapebadger.web.models import DetectResult, ExtractResult, ScrapeResult, ScreenshotResult +from scrapebadger.webhooks import WebhookEvent, parse_event, verify_signature from scrapebadger.yahoo.client import YahooClient from scrapebadger.yahoo.models import Ad as YahooAd from scrapebadger.yahoo.models import AutocompleteResponse as YahooAutocompleteResponse @@ -1351,7 +1356,7 @@ async def main(): ZestimateHistoryPoint as ZillowZestimateHistoryPoint, ) -__version__ = "0.77.0" +__version__ = "0.80.0" __all__ = [ # TikTok core models @@ -1384,6 +1389,7 @@ async def main(): "ApartmentsSearchResult", "ApartmentsUnit", "AsyncRequest", + "AsyncRequestTimeoutError", "AuthenticationError", # Baidu "BaiduAutocompleteResponse", @@ -1418,6 +1424,7 @@ async def main(): "BlockedError", # Vinted response envelopes "BrandsResponse", + "CallbackStatus", "CategoriesResponse", "CategoryResponse", # ChatGPT @@ -1846,6 +1853,10 @@ async def main(): "WalmartWarranty", # Stream exceptions "WebSocketStreamError", + "WebhookDeliveries", + "WebhookDelivery", + "WebhookEvent", + "WebhookSecret", # Yahoo "YahooAd", "YahooAutocompleteResponse", @@ -1961,4 +1972,7 @@ async def main(): "ZillowZestimateHistoryPoint", # Version "__version__", + "parse_event", + "verify_signature", + "webhooks", ] diff --git a/src/scrapebadger/_internal/client.py b/src/scrapebadger/_internal/client.py index 2f9c028..3258932 100644 --- a/src/scrapebadger/_internal/client.py +++ b/src/scrapebadger/_internal/client.py @@ -38,6 +38,15 @@ httpx.ProxyError, ) +# The subset raised before the request reached the server: safe to retry even for a +# call that must not run twice (an async submit without an Idempotency-Key). +UNSENT_TRANSPORT_ERRORS = ( + httpx.ConnectError, + httpx.ConnectTimeout, + httpx.PoolTimeout, + httpx.ProxyError, +) + if TYPE_CHECKING: from collections.abc import Mapping from types import TracebackType @@ -47,7 +56,7 @@ T = TypeVar("T") # User agent for SDK requests -SDK_VERSION = "0.79.0" +SDK_VERSION = "0.80.0" USER_AGENT = f"scrapebadger-python/{SDK_VERSION}" @@ -182,7 +191,12 @@ def _handle_error_response( if status_code == 403 and data.get("error") == "ip_not_allowed": raise IPNotAllowedError(message, status_code, data) - if status_code == 403 and data.get("error") == "insufficient_scope": + # full_access_required: the webhook secret and deliveries need a key that may + # call every API, not one limited to a few. + if status_code == 403 and data.get("error") in ( + "insufficient_scope", + "full_access_required", + ): raise PermissionDeniedError(message, status_code, data) if status_code == 404: @@ -217,7 +231,8 @@ async def _execute_request( path: str, *, params: Mapping[str, Any] | None = None, - json: dict[str, Any] | None = None, + json: Any = None, + headers: Mapping[str, str] | None = None, ) -> httpx.Response: """Execute a single HTTP request without any retry logic. @@ -226,6 +241,7 @@ async def _execute_request( path: API endpoint path. params: Query parameters. json: JSON body for POST/PUT requests. + headers: Extra request headers for this call only. Returns: The raw httpx.Response. @@ -236,57 +252,42 @@ async def _execute_request( url=path, params=params, json=json, + headers=headers, ) - async def _request_with_retry( + async def _send( self, method: str, path: str, *, params: Mapping[str, Any] | None = None, - json: dict[str, Any] | None = None, - ) -> tuple[dict[str, Any], dict[str, str]]: - """Make an HTTP request with retry logic, returning data and headers. - - Args: - method: HTTP method (GET, POST, etc.). - path: API endpoint path. - params: Query parameters. - json: JSON body for POST/PUT requests. - - Returns: - A (data, headers) tuple where data is the parsed JSON response and - headers is a dict of response header name → value strings. - - Raises: - ScrapeBadgerError: For API errors. - httpx.RequestError: For network errors after retries exhausted. - """ - data, headers, _ = await self._request_with_status(method, path, params=params, json=json) - return data, headers - - async def _request_with_status( - self, - method: str, - path: str, - *, - params: Mapping[str, Any] | None = None, - json: dict[str, Any] | None = None, - ) -> tuple[dict[str, Any], dict[str, str], int]: - """Make an HTTP request with retry logic, returning data, headers and status. + json: Any = None, + headers: Mapping[str, str] | None = None, + retry_status: bool = True, + retry_transport: tuple[type[Exception], ...] = RETRYABLE_TRANSPORT_ERRORS, + ) -> httpx.Response: + """Send a request with the retry policy and error mapping; return the raw response. - For endpoints whose 2xx status carries meaning — ``/v1/requests/{id}`` - answers 202 while the call is still running and the original status - once it finished. + The shared retry loop behind every call. A 4xx/5xx response raises the + matching ``ScrapeBadgerError`` subclass; anything below 400 is returned + undecoded. Args: method: HTTP method (GET, POST, etc.). path: API endpoint path. - params: Query parameters. - json: JSON body for POST/PUT requests. + params: Query parameters (None values are dropped). + json: JSON body. + headers: Extra request headers for this call only. + retry_status: Retry the configured ``retry_on_status`` codes. Off for + reads of a stored result, whose status can't change. An + idempotent replay (``Idempotent-Replayed: true``) is a stored + result too and is never retried. + retry_transport: Transport errors to retry. ``UNSENT_TRANSPORT_ERRORS`` + for a call that would run (and bill) a second time if the first + attempt got through. Returns: - A (data, headers, status_code) tuple. + The raw httpx.Response (status below 400). Raises: ScrapeBadgerError: For API errors. @@ -299,21 +300,28 @@ async def _request_with_status( last_exception: Exception | None = None for attempt in range(self._config.max_retries + 1): try: - response = await self._execute_request(method, path, params=params, json=json) - - # Parse response body - try: - data: dict[str, Any] = response.json() - except Exception: - data = {} - - # Build a plain dict of headers for the caller - headers: dict[str, str] = dict(response.headers) + response = await self._execute_request( + method, path, params=params, json=json, headers=headers + ) # Check for errors if response.status_code >= 400: + try: + data: Any = response.json() + except Exception: + data = {} + if not isinstance(data, dict): + data = {} + + replayed = ( + response.headers.get("Idempotent-Replayed", "").strip().lower() == "true" + ) # Don't retry client errors (except specific status codes) - if response.status_code not in self._config.retry_on_status: + if ( + not retry_status + or replayed + or response.status_code not in self._config.retry_on_status + ): self._handle_error_response(response, data) # Retry on configured status codes @@ -332,20 +340,11 @@ async def _request_with_status( self._handle_error_response(response, data) - # Check for application-level errors in response - # (bare JSON array bodies, e.g. /markets, have no .get) - if isinstance(data, dict) and data.get("error"): - raise ScrapeBadgerError( - data["error"], - response.status_code, - data, - ) - - return data, headers, response.status_code + return response except RETRYABLE_TRANSPORT_ERRORS as e: last_exception = e - if attempt < self._config.max_retries: + if isinstance(e, retry_transport) and attempt < self._config.max_retries: delay = 2**attempt error_type = type(e).__name__ logger.warning( @@ -365,6 +364,80 @@ async def _request_with_status( msg = "Request failed after retries" raise ScrapeBadgerError(msg) + async def _request_with_retry( + self, + method: str, + path: str, + *, + params: Mapping[str, Any] | None = None, + json: dict[str, Any] | None = None, + ) -> tuple[dict[str, Any], dict[str, str]]: + """Make an HTTP request with retry logic, returning data and headers. + + Args: + method: HTTP method (GET, POST, etc.). + path: API endpoint path. + params: Query parameters. + json: JSON body for POST/PUT requests. + + Returns: + A (data, headers) tuple where data is the parsed JSON response and + headers is a dict of response header name → value strings. + + Raises: + ScrapeBadgerError: For API errors. + httpx.RequestError: For network errors after retries exhausted. + """ + data, headers, _ = await self._request_with_status(method, path, params=params, json=json) + return data, headers + + async def _request_with_status( + self, + method: str, + path: str, + *, + params: Mapping[str, Any] | None = None, + json: dict[str, Any] | None = None, + ) -> tuple[dict[str, Any], dict[str, str], int]: + """Make an HTTP request with retry logic, returning data, headers and status. + + For endpoints whose 2xx status carries meaning — ``/v1/requests/{id}`` + answers 202 while the call is still running and the original status + once it finished. + + Args: + method: HTTP method (GET, POST, etc.). + path: API endpoint path. + params: Query parameters. + json: JSON body for POST/PUT requests. + + Returns: + A (data, headers, status_code) tuple. + + Raises: + ScrapeBadgerError: For API errors. + httpx.RequestError: For network errors after retries exhausted. + """ + response = await self._send(method, path, params=params, json=json) + + # Parse response body + try: + data: dict[str, Any] = response.json() + except Exception: + data = {} + + # Check for application-level errors in response + # (bare JSON array bodies, e.g. /markets, have no .get) + if isinstance(data, dict) and data.get("error"): + raise ScrapeBadgerError( + data["error"], + response.status_code, + data, + ) + + # Build a plain dict of headers for the caller + return data, dict(response.headers), response.status_code + async def _request( self, method: str, diff --git a/src/scrapebadger/_internal/exceptions.py b/src/scrapebadger/_internal/exceptions.py index 57ddfef..0063289 100644 --- a/src/scrapebadger/_internal/exceptions.py +++ b/src/scrapebadger/_internal/exceptions.py @@ -323,6 +323,42 @@ def __init__( super().__init__(message, status_code, response_data) +class AsyncRequestTimeoutError(ScrapeBadgerError, TimeoutError): + """Raised when ``requests.wait`` gives up before the call completed. + + The call itself keeps running and is billed once when it completes: keep + polling ``request_id`` (free) or wait for its webhook. Never re-submit it. + Also a ``TimeoutError``, so ``except TimeoutError`` catches it. + + Attributes: + request_id: The request that was still running. + timeout: The ``timeout`` that ran out, in seconds. + + Example: + ```python + from scrapebadger import AsyncRequestTimeoutError + + try: + done = await client.requests.wait(request_id, timeout=120) + except AsyncRequestTimeoutError as e: + print(f"{e.request_id} still running; poll it again later") + ``` + """ + + def __init__( + self, + message: str = "The async request is still running", + status_code: int | None = None, + response_data: dict[str, Any] | None = None, + *, + request_id: str = "", + timeout: float | None = None, + ) -> None: + super().__init__(message, status_code, response_data) + self.request_id = request_id + self.timeout = timeout + + class WebSocketStreamError(ScrapeBadgerError): """Raised when the WebSocket stream connection fails or is terminated. diff --git a/src/scrapebadger/account/__init__.py b/src/scrapebadger/account/__init__.py index a1c1764..5f24ed3 100644 --- a/src/scrapebadger/account/__init__.py +++ b/src/scrapebadger/account/__init__.py @@ -1,5 +1,6 @@ """account API client.""" from scrapebadger.account.client import AccountClient +from scrapebadger.account.models import WebhookDeliveries, WebhookDelivery, WebhookSecret -__all__ = ["AccountClient"] +__all__ = ["AccountClient", "WebhookDeliveries", "WebhookDelivery", "WebhookSecret"] diff --git a/src/scrapebadger/account/client.py b/src/scrapebadger/account/client.py index d8a0c37..5d171a1 100644 --- a/src/scrapebadger/account/client.py +++ b/src/scrapebadger/account/client.py @@ -1,19 +1,91 @@ -"""Account API client. # --- BEGIN generated by sdk/codegen/facade — do not edit ---""" +"""Account API client: account info, the webhook signing secret and deliveries. + +The typed methods above the generated block are handwritten (SCR-652). The block +at the end of the class is kept in sync with the OpenAPI spec by +sdk/codegen/facade, which rewrites only that block. +""" from __future__ import annotations from typing import TYPE_CHECKING, Any +from scrapebadger.account.models import WebhookDeliveries, WebhookSecret + if TYPE_CHECKING: from scrapebadger._internal.client import BaseClient class AccountClient: - """Client for all Account API operations. (Generated from the OpenAPI spec.)""" + """Client for the Account API. + + Example: + ```python + async with ScrapeBadger(api_key="your-key") as client: + secret = await client.account.webhook_secret() + recent = await client.account.webhook_deliveries(limit=20) + for d in recent.deliveries: + print(d.request_id, d.state, d.attempts, d.last_status) + ``` + + Note: + This client is not instantiated directly. Instead, access it through + the `account` property of the main `ScrapeBadger` client. + """ def __init__(self, client: BaseClient) -> None: self._client = client + async def webhook_secret(self) -> WebhookSecret: + """Get the secret that signs this account's webhooks. Free. + + Created on first read. Verify each delivery with + ``scrapebadger.webhooks.verify_signature(secret.secret, raw_body, signature)``. + + Returns: + WebhookSecret with ``secret``. + + Raises: + PermissionDeniedError: The key is limited to some APIs (403 + ``full_access_required``); the secret needs a full-access key. + """ + response = await self._client.get("/v1/account/webhook-secret") + return WebhookSecret.model_validate(response) + + async def rotate_webhook_secret(self) -> WebhookSecret: + """Replace the webhook signing secret. Free. + + Deliveries that start from now on are signed with the new secret; + retries of a delivery already under way keep the old one, so accept + both for a few minutes after rotating. + + Returns: + WebhookSecret with the new ``secret``. + + Raises: + PermissionDeniedError: The key is limited to some APIs (403 + ``full_access_required``). + """ + response = await self._client.post("/v1/account/webhook-secret/rotate") + return WebhookSecret.model_validate(response) + + async def webhook_deliveries(self, limit: int = 50) -> WebhookDeliveries: + """List the account's webhook deliveries of the last 24 hours, newest first. Free. + + Args: + limit: How many to return (1-200, default 50). + + Returns: + WebhookDeliveries with ``deliveries`` and ``window_hours``. + + Raises: + PermissionDeniedError: The key is limited to some APIs (403 + ``full_access_required``). + """ + response = await self._client.get("/v1/account/webhook-deliveries", params={"limit": limit}) + return WebhookDeliveries.model_validate(response) + + # --- BEGIN generated by sdk/codegen/facade — do not edit --- + async def get_account_info(self) -> dict[str, Any]: """Get account info. @@ -38,3 +110,5 @@ async def rotate_the_webhook_signing_secret( return await self._client.post( "/v1/account/webhook-secret/rotate", params=params, json=payload ) + + # --- END generated by sdk/codegen/facade --- diff --git a/src/scrapebadger/account/models.py b/src/scrapebadger/account/models.py new file mode 100644 index 0000000..3b46b62 --- /dev/null +++ b/src/scrapebadger/account/models.py @@ -0,0 +1,76 @@ +"""Pydantic models for the account endpoints: webhook secret and deliveries. + +All models are immutable (frozen) and ignore unknown fields for forward +compatibility. +""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, Field + + +class _BaseModel(BaseModel): + """Base model with common configuration.""" + + model_config = ConfigDict( + frozen=True, + populate_by_name=True, + extra="ignore", + ) + + +class WebhookSecret(_BaseModel): + """The secret that signs every webhook of the account. + + Pass ``secret`` to ``scrapebadger.webhooks.verify_signature``. + + Attributes: + secret: The signing secret (``whsec_...``). Treat it like a password. + signature_header: Header that carries the signature. + algorithm: How the signature is made. + """ + + secret: str + signature_header: str = "X-ScrapeBadger-Signature" + algorithm: str = "sha256=" + + +class WebhookDelivery(_BaseModel): + """One webhook delivery of the last 24 hours. + + Only metadata is kept: the endpoint path (never its query) and the + callback host (never its path or query), statuses, attempts and times. + + Attributes: + request_id: The request the webhook is for. + endpoint: Path of the call, e.g. "/v1/perplexity/ask". + state: "pending", "delivering", "delivered" or "failed". + attempts: Attempts made so far. + last_status: HTTP status your endpoint answered on the last attempt. + last_error: Short error class of the last attempt. + created_at: Unix time the delivery was scheduled. + delivered_at: Unix time it was delivered, or None. + callback_host: Host of the callback URL. + """ + + request_id: str + endpoint: str | None = None + state: str = "pending" + attempts: int = 0 + last_status: int | None = None + last_error: str | None = None + created_at: int | float | None = None + delivered_at: int | float | None = None + callback_host: str | None = None + + +class WebhookDeliveries(_BaseModel): + """The account's webhook deliveries, newest first. + + Attributes: + deliveries: The deliveries. + window_hours: How far back the list goes (24). + """ + + deliveries: list[WebhookDelivery] = Field(default_factory=list) + window_hours: int = 24 diff --git a/src/scrapebadger/agent/__init__.py b/src/scrapebadger/agent/__init__.py index 173fbfc..754bcdb 100644 --- a/src/scrapebadger/agent/__init__.py +++ b/src/scrapebadger/agent/__init__.py @@ -1,4 +1,4 @@ -"""Agent platform API: quotes, feedback, async request polling and batches.""" +"""Agent platform API: quotes, feedback, async requests and batches.""" from scrapebadger.agent.client import AgentClient, RequestsClient, ResultsClient from scrapebadger.agent.models import ( @@ -6,6 +6,7 @@ AsyncRequest, BatchItemResult, BatchSubmission, + CallbackStatus, FeedbackReceipt, Quote, QuoteCredits, @@ -20,6 +21,7 @@ "AsyncRequest", "BatchItemResult", "BatchSubmission", + "CallbackStatus", "FeedbackReceipt", "Quote", "QuoteCredits", diff --git a/src/scrapebadger/agent/client.py b/src/scrapebadger/agent/client.py index 5a3e613..d23f501 100644 --- a/src/scrapebadger/agent/client.py +++ b/src/scrapebadger/agent/client.py @@ -1,21 +1,48 @@ """Agent platform API clients. Free helpers around the scraper APIs: quote a call before making it, report a -bug, and poll a call made with ``Prefer: respond-async``. None of these calls is -ever billed. (``results.get`` is deprecated: the API stopped storing results on -2026-11-09.) +bug, and run any call asynchronously (submit, poll, wait, webhook status). None +of the helper calls is ever billed; an async call is billed once, like any +call, when it completes. (``results.get`` is deprecated: the API stopped storing +results on 2026-11-09.) """ from __future__ import annotations +import asyncio import warnings +from time import monotonic from typing import TYPE_CHECKING, Any, Literal - -from scrapebadger.agent.models import AsyncRequest, BatchSubmission, FeedbackReceipt, Quote +from urllib.parse import quote + +from scrapebadger._internal.client import ( + RETRYABLE_TRANSPORT_ERRORS, + UNSENT_TRANSPORT_ERRORS, + _retry_after_seconds, +) +from scrapebadger._internal.exceptions import AsyncRequestTimeoutError, ScrapeBadgerError +from scrapebadger.agent.models import ( + AsyncRequest, + BatchSubmission, + CallbackStatus, + FeedbackReceipt, + Quote, +) if TYPE_CHECKING: + from collections.abc import Mapping + + import httpx + from scrapebadger._internal.client import BaseClient +# Prefer: respond-async, wait=N accepts 0..120 seconds. +MAX_ASYNC_WAIT_S = 120 +# Poll interval when a 202 names none (the API sends 5). +_DEFAULT_POLL_S = 5 +# Never poll faster than this, whatever Retry-After says. +_MIN_POLL_S = 1.0 + class AgentClient: """Client for quoting calls and sending feedback. @@ -224,12 +251,97 @@ async def get( return await self._client.get(f"/v1/results/{result_id}", params=params) +def _api_path(path: str) -> str: + """Normalise "perplexity/ask", "/perplexity/ask" or "/v1/perplexity/ask".""" + p = path.strip() + if not p or "://" in p: + msg = f"Pass the API path, e.g. '/v1/perplexity/ask', not {path!r}" + raise ValueError(msg) + p = "/" + p.lstrip("/") + return p if p.startswith("/v1/") else "/v1" + p + + +def _request_path(request_id: str) -> str: + if not request_id: + msg = "request_id is required" + raise ValueError(msg) + return "/v1/requests/" + quote(request_id, safe="") + + +def _decode_body(response: httpx.Response) -> Any: + """Decoded JSON for a JSON response, else the text (as the webhook does). + + A body without a Content-Type is tried as JSON too, as earlier releases did. + """ + content_type = response.headers.get("content-type", "").lower() + if "json" in content_type or not content_type: + try: + return response.json() + except ValueError: + pass + return response.text + + +def _to_async_request(response: httpx.Response, request_id: str | None = None) -> AsyncRequest: + """Build an AsyncRequest from a submit or poll response (status below 400).""" + replayed = response.headers.get("Idempotent-Replayed", "").strip().lower() == "true" + data = _decode_body(response) + fields = data if isinstance(data, dict) else {} + if response.status_code == 202: + retry_after = fields.get("retry_after_seconds") + if not isinstance(retry_after, int) or isinstance(retry_after, bool): + retry_after = ( + _retry_after_seconds(response, default=_DEFAULT_POLL_S) + if "Retry-After" in response.headers + else None + ) + polled_id = str(fields.get("request_id") or response.headers.get("X-Request-ID", "")) + return AsyncRequest( + request_id=request_id or polled_id, + status="running", + running=True, + status_code=202, + retry_after_seconds=retry_after, + replayed=replayed, + data=data, + ) + # Application-level error in a 2xx body: raised like on every other call. + if fields.get("error"): + raise ScrapeBadgerError(fields["error"], response.status_code, fields) + credits_used = response.headers.get("X-Credits-Used", "") + return AsyncRequest( + request_id=request_id or response.headers.get("X-Request-ID", ""), + status="completed", + running=False, + status_code=response.status_code, + headers=dict(response.headers), + body=data, + replayed=replayed, + credits_used=int(credits_used) if credits_used.isdigit() else None, + data=data, + ) + + class RequestsClient: - """Client for polling calls made with ``Prefer: respond-async``. + """Run any call asynchronously: submit it, then poll, wait, or take its webhook. - A read sent with ``Prefer: respond-async, wait=25`` that doesn't finish - within ``wait`` seconds answers 202 with a ``request_id``; poll it here - until it is done. Never re-submit the original call. + ``submit`` sends a call with ``Prefer: respond-async``. If it finishes within + ``wait`` seconds you get the result at once (``status == "completed"``); + otherwise a ``request_id`` to poll with ``get`` or ``wait`` (free), or to + match against its webhook. Never re-submit a running call: that starts, and + bills, a second one. Results are kept for about 15 minutes. + + Example: + ```python + async with ScrapeBadger(api_key="your-key") as client: + req = await client.requests.submit( + "/v1/perplexity/ask", + params={"prompt": "best crm for startups"}, + idempotency_key="crm-question-2026-11-18", + ) + done = await client.requests.wait(req.request_id, timeout=300) + print(done.status_code, done.body) + ``` Note: This client is not instantiated directly. Instead, access it through @@ -244,15 +356,105 @@ def __init__(self, client: BaseClient) -> None: """ self._client = client + async def submit( + self, + path: str, + *, + method: str = "GET", + params: Mapping[str, Any] | None = None, + json: Any = None, + callback_url: str | None = None, + wait: int | None = None, + idempotency_key: str | None = None, + ) -> AsyncRequest: + """Submit any API call asynchronously. Submitting is free; the call is billed + once, when it completes. + + Example: + ```python + req = await client.requests.submit( + "/v1/perplexity/ask", + params={"prompt": "best crm for startups"}, + callback_url="https://example.com/hooks/scrapebadger", + idempotency_key=f"crm-{row_id}", + ) + # req.status == "running": the result arrives at the callback URL. + ``` + + Args: + path: The call's path, e.g. "/v1/perplexity/ask" (the "/v1" prefix is + optional). + method: HTTP method of the call ("GET", "POST", ...). + params: The call's query parameters (None values are dropped). + json: The call's JSON body (POST endpoints). + callback_url: https URL that gets a signed ``request.completed`` + webhook when the call completes (``X-Callback-URL``). Verify it + with ``scrapebadger.webhooks.verify_signature``. + wait: Seconds (0-120) to wait for the result before answering 202 + (``Prefer: respond-async, wait=N``). Default: 0 with a + ``callback_url`` (answer at once), otherwise the API's default (25). + idempotency_key: 1-200 visible ASCII characters (``Idempotency-Key``). + Re-submitting the same call with the same key within 15 minutes + does not run or bill it again: you get the first call's state + (``replayed=True``). The same key with a different call raises + ``ScrapeBadgerError`` 409 ``idempotency_key_reused``. With a key, + the SDK also retries a submit whose answer was lost in transit. + + Returns: + AsyncRequest: ``status="running"`` with ``request_id`` and + ``retry_after_seconds``, or ``status="completed"`` with + ``status_code``, ``headers`` and ``body`` when the call finished + within ``wait``. + + Raises: + ValueError: ``wait`` outside 0-120, an invalid ``idempotency_key`` or + ``path``. + ScrapeBadgerError: The call was refused (400 ``invalid_callback_url``, + ``async_not_supported``, 409 ``idempotency_key_reused``, 402, 429...) + or finished within ``wait`` with an error status (raised as the + matching subclass). A refused call is not billed. + """ + if wait is None and callback_url is not None: + wait = 0 + if wait is not None and ( + isinstance(wait, bool) or not isinstance(wait, int) or not 0 <= wait <= MAX_ASYNC_WAIT_S + ): + msg = f"wait must be an int from 0 to {MAX_ASYNC_WAIT_S} seconds, got {wait!r}" + raise ValueError(msg) + headers = {"Prefer": "respond-async" if wait is None else f"respond-async, wait={wait}"} + if callback_url is not None: + headers["X-Callback-URL"] = callback_url + if idempotency_key is not None: + if not 1 <= len(idempotency_key) <= 200 or not all( + "!" <= c <= "~" for c in idempotency_key + ): + msg = "idempotency_key must be 1-200 visible ASCII characters (no spaces)" + raise ValueError(msg) + headers["Idempotency-Key"] = idempotency_key + response = await self._client._send( + method.upper(), + _api_path(path), + params=params, + json=json, + headers=headers, + # Without a key, a retry after the request got through would start and + # bill a second call: only retry errors raised before it was sent. + retry_transport=( + RETRYABLE_TRANSPORT_ERRORS if idempotency_key else UNSENT_TRANSPORT_ERRORS + ), + ) + return _to_async_request(response) + async def get(self, request_id: str) -> AsyncRequest: """Poll an async request. Free. Args: - request_id: ``request_id`` from the 202 response. + request_id: ``request_id`` from ``submit`` or the 202 response. Returns: - AsyncRequest. ``running`` is True while the call is in progress; - once done, ``data`` holds the original response body. + AsyncRequest. ``status == "running"`` (``running`` is True) while the + call is in progress; once done, ``status == "completed"`` with the + original ``status_code``, ``headers`` and ``body``. Raises: NotFoundError: Unknown or expired request. A request that never @@ -260,24 +462,73 @@ async def get(self, request_id: str) -> AsyncRequest: ScrapeBadgerError: The original call finished with an error status (raised as the matching subclass). """ - data, headers, status_code = await self._client._request_with_status( - "GET", f"/v1/requests/{request_id}" - ) - lower = {k.lower(): v for k, v in headers.items()} - running = status_code == 202 - retry_after = ( - data.get("retry_after_seconds") if running and isinstance(data, dict) else None - ) - credits_used = lower.get("x-credits-used") - return AsyncRequest( - request_id=request_id, - running=running, - status_code=status_code, - retry_after_seconds=retry_after, - result_id=None, # deprecated: the API no longer sends X-Result-ID - credits_used=int(credits_used) if credits_used and credits_used.isdigit() else None, - data=data, - ) + response = await self._client._send("GET", _request_path(request_id)) + return _to_async_request(response, request_id) + + async def wait(self, request_id: str, *, timeout: float = 600.0) -> AsyncRequest: + """Poll until the request completes, sleeping ``Retry-After`` between polls. Free. + + Args: + request_id: ``request_id`` from ``submit``. + timeout: Give up after this many seconds (default 600). Results are + kept for about 15 minutes after the call completes. + + Returns: + The completed AsyncRequest (``status_code``, ``headers``, ``body``). + + Raises: + AsyncRequestTimeoutError: Still running after ``timeout``. The call + keeps running: poll it again or wait for its webhook; never + re-submit it. Also a ``TimeoutError``. + NotFoundError: Unknown or expired request. + ScrapeBadgerError: The original call finished with an error status + (raised as the matching subclass). A stored result can't change, + so error statuses are raised at once, not retried. + """ + if timeout < 0: + msg = "timeout must be >= 0" + raise ValueError(msg) + path = _request_path(request_id) + deadline = monotonic() + timeout + while True: + response = await self._client._send("GET", path, retry_status=False) + state = _to_async_request(response, request_id) + if state.status == "completed": + return state + remaining = deadline - monotonic() + if remaining <= 0: + msg = ( + f"Request {request_id} is still running after {timeout:g} s. Poll it " + "again (free) or wait for its webhook; do not re-submit it." + ) + raise AsyncRequestTimeoutError( + msg, + 202, + state.data if isinstance(state.data, dict) else None, + request_id=request_id, + timeout=timeout, + ) + delay = state.retry_after_seconds + if delay is None: + delay = _DEFAULT_POLL_S + await asyncio.sleep(min(max(float(delay), _MIN_POLL_S), remaining)) + + async def callback_status(self, request_id: str) -> CallbackStatus: + """Read the delivery state of a request's webhook. Free. + + Args: + request_id: A request submitted with a ``callback_url``. + + Returns: + CallbackStatus with ``state``, ``attempts``, ``last_status``, + ``last_error``, ``next_attempt_at`` and ``delivered_at``. + + Raises: + NotFoundError: The request has no callback (404 + ``callback_not_found``), or its delivery record (kept 24 h) expired. + """ + response = await self._client.get(f"{_request_path(request_id)}/callback") + return CallbackStatus.model_validate(response) async def batch( self, @@ -303,8 +554,8 @@ async def batch( requests: Items ``{"path": "/v1/...", "query": {...}}`` (``method`` defaults to "GET"). callback_url: https URL that gets one signed webhook per item when - it completes. Verify it with ``verify_webhook_signature`` and the - secret from ``GET /v1/account/webhook-secret``. + it completes. Verify it with ``scrapebadger.webhooks.verify_signature`` + and the secret from ``client.account.webhook_secret()``. Returns: BatchSubmission with a request_id (or the refusal) for every item. diff --git a/src/scrapebadger/agent/models.py b/src/scrapebadger/agent/models.py index 2c1b0dc..cfb4562 100644 --- a/src/scrapebadger/agent/models.py +++ b/src/scrapebadger/agent/models.py @@ -1,16 +1,16 @@ """Pydantic models for the agent platform endpoints. -Quote, feedback and async-request polling — the account-level helpers an -agent uses around the scraper APIs. None of these calls is ever billed. All -models are immutable (frozen) and ignore unknown fields for forward -compatibility. +Quote, feedback and async requests — the account-level helpers an agent uses +around the scraper APIs. None of these calls is ever billed (an async call is +billed once, like any call, when it completes). All models are immutable +(frozen) and ignore unknown fields for forward compatibility. """ from __future__ import annotations -from typing import Any +from typing import Any, Literal -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, model_validator class _BaseModel(BaseModel): @@ -149,30 +149,85 @@ class FeedbackReceipt(_BaseModel): class AsyncRequest(_BaseModel): - """State of a call made with ``Prefer: respond-async``. + """State of an async call: submitted with ``requests.submit`` (or + ``Prefer: respond-async``) and read back with ``requests.get`` / ``wait``. Attributes: - request_id: The request polled. - running: True while the call is still in progress (HTTP 202). Poll - again after ``retry_after_seconds``; never re-submit the call. - status_code: HTTP status of this poll: 202 while running, otherwise - the original call's status. + request_id: The request's id (``X-Request-ID``). + status: "running" while the call is in progress (HTTP 202), then + "completed". Never re-submit a running call: poll it, or wait for + its webhook. + running: ``status == "running"`` (kept from earlier releases). + status_code: 202 while running, then the original call's HTTP status. retry_after_seconds: Suggested wait before the next poll (running only). + headers: The original call's response headers, lower-cased names + (completed only), e.g. ``x-credits-used``. + body: The original call's response body (completed only): decoded JSON + for a JSON response, else the text. + replayed: True when the API answered from an earlier call with the same + ``Idempotency-Key`` (``Idempotent-Replayed: true``) instead of + running it again. Nothing was billed for the replay. + credits_used: ``X-Credits-Used`` of the finished call. result_id: Deprecated, always None. The API stopped sending ``X-Result-ID`` (and storing results for re-reads) on 2026-11-09. - credits_used: ``X-Credits-Used`` of the finished call. - data: The original call's response body once finished (any JSON - value), or the 202 status body while running. + data: The response body as earlier releases returned it: ``body`` once + completed, the 202 status body while running. """ request_id: str + status: Literal["running", "completed"] running: bool status_code: int retry_after_seconds: int | None = None - result_id: str | None = None + headers: dict[str, str] = Field(default_factory=dict) + body: Any = None + replayed: bool = False credits_used: int | None = None + result_id: str | None = None data: Any = None + @model_validator(mode="before") + @classmethod + def _status_and_running(cls, values: Any) -> Any: + """Accept either ``status`` or ``running`` and derive the other.""" + if isinstance(values, dict): + if "status" not in values and "running" in values: + values = {**values, "status": "running" if values["running"] else "completed"} + elif "running" not in values and "status" in values: + values = {**values, "running": values["status"] == "running"} + return values + + +class CallbackStatus(_BaseModel): + """Delivery state of a request's webhook (``requests.callback_status``). + + Only requests submitted with a ``callback_url`` have one. The delivery + metadata is kept for 24 hours; it holds the callback host only, never its + path or query. + + Attributes: + request_id: The request the webhook is for. + state: "pending" (not sent yet, or waiting for a retry), "delivering", + "delivered" or "failed" (all attempts used, or a final status). + attempts: Attempts made so far (at most 4: retries after 10 s, 60 s + and 5 min). + last_status: HTTP status your endpoint answered on the last attempt, + or None (no answer, e.g. a timeout). + last_error: Short error class of the last attempt, or None. + next_attempt_at: Unix time of the next retry, or None. + delivered_at: Unix time of the successful delivery, or None. + callback_host: Host of the callback URL. + """ + + request_id: str + state: str = "pending" + attempts: int = 0 + last_status: int | None = None + last_error: str | None = None + next_attempt_at: int | float | None = None + delivered_at: int | float | None = None + callback_host: str | None = None + class BatchItemResult(_BaseModel): """One item of a ``requests.batch`` submission. diff --git a/src/scrapebadger/webhooks.py b/src/scrapebadger/webhooks.py new file mode 100644 index 0000000..eeb38f7 --- /dev/null +++ b/src/scrapebadger/webhooks.py @@ -0,0 +1,163 @@ +"""Receive ScrapeBadger async-request webhooks: verify the signature, parse the event. + +A call submitted with a ``callback_url`` (``client.requests.submit(..., +callback_url=...)``, ``X-Callback-URL``, or a batch's ``callback_url``) gets one +``request.completed`` POST when it completes. Each delivery is signed with the +account's webhook secret (``client.account.webhook_secret()``): +``X-ScrapeBadger-Signature: sha256=``. + +Example (FastAPI): + ```python + from fastapi import FastAPI, HTTPException, Request + from scrapebadger.webhooks import parse_event, verify_signature + + app = FastAPI() + + @app.post("/hooks/scrapebadger") + async def hook(request: Request) -> dict[str, bool]: + raw = await request.body() # the raw bytes, before any JSON parsing + event = parse_event(raw) + if not verify_signature( + SECRET, + raw, + request.headers.get("X-ScrapeBadger-Signature", ""), + sent_at=event.sent_at, + ): + raise HTTPException(401) + # Deliveries can repeat: deduplicate on event.request_id. + return {"ok": True} + ``` +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import math +import time +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +__all__ = ["SIGNATURE_HEADER", "WebhookEvent", "parse_event", "verify_signature"] + +#: Header that carries the signature of a delivery. +SIGNATURE_HEADER = "X-ScrapeBadger-Signature" + +_PREFIX = "sha256=" + + +class WebhookEvent(BaseModel): + """A ``request.completed`` webhook delivery. + + Attributes: + event: Always "request.completed" today. + request_id: The request that completed. Deliveries can repeat (retries), + so deduplicate on it. + batch_id: The batch the request belongs to, or None. + status: The call's own HTTP status, errors included. + headers: The call's response headers, lower-cased names. + body: The call's response body: decoded JSON for a JSON response, else + the text. None when ``body_omitted``. + body_omitted: True when the body was over 1 MB and left out: fetch it + from ``result_url`` before ``result_expires_at``. + body_size: Size of the body in bytes. + result_url: Where to read the result (``GET``, free) while it is kept. + result_expires_at: Unix time the result stops being kept (about 15 min). + attempt: Delivery attempt, 1 to 4. + sent_at: Unix time this attempt was signed and sent. It is part of the + signed body: pass it to ``verify_signature(..., sent_at=...)`` to + reject replays. + """ + + model_config = ConfigDict(frozen=True, populate_by_name=True, extra="ignore") + + event: str = "request.completed" + request_id: str + batch_id: str | None = None + status: int + headers: dict[str, str] = Field(default_factory=dict) + body: Any = None + body_omitted: bool = False + body_size: int | None = None + result_url: str | None = None + result_expires_at: int | None = None + attempt: int = 1 + sent_at: int | None = None + + +def _as_bytes(value: bytes | bytearray | memoryview | str) -> bytes: + if isinstance(value, str): + return value.encode("utf-8") + return bytes(value) + + +def verify_signature( + secret: str, + raw_body: bytes | bytearray | memoryview | str, + signature: str | None, + *, + sent_at: float | str | None = None, + tolerance_s: float = 300, +) -> bool: + """Check that a webhook delivery is genuine (and, with ``sent_at``, fresh). + + Compares in constant time. Never raises on bad input: a missing or + malformed signature, or an unreadable ``sent_at``, is simply invalid. + + Args: + secret: The account's webhook secret (``client.account.webhook_secret()``). + raw_body: The request body exactly as received. Re-serialised JSON will + not match. + signature: The ``X-ScrapeBadger-Signature`` header (``sha256=``). + sent_at: The delivery's ``sent_at`` (Unix seconds). When given, a + delivery older than ``tolerance_s`` (or that far in the future) is + rejected. Take it from the parsed body (``parse_event(raw).sent_at``): + the body is what is signed. The ``X-ScrapeBadger-Timestamp`` header + carries the same value but is not itself signed. + tolerance_s: Accepted age of ``sent_at`` in seconds (default 300). + + Returns: + True when the signature matches (and ``sent_at`` is within tolerance). + """ + if not secret or not signature: + return False + try: + given = signature.strip().encode("ascii") + except (AttributeError, UnicodeEncodeError): + return False + digest = hmac.new(secret.encode("utf-8"), _as_bytes(raw_body), hashlib.sha256).hexdigest() + expected = (_PREFIX + digest).encode("ascii") + if not hmac.compare_digest(expected, given): + return False + if sent_at is None: + return True + try: + sent = float(sent_at) + except (TypeError, ValueError): + return False + return math.isfinite(sent) and abs(time.time() - sent) <= tolerance_s + + +def parse_event(raw_body: bytes | bytearray | memoryview | str) -> WebhookEvent: + """Parse a webhook delivery body into a ``WebhookEvent``. + + Parsing does not check authenticity: call ``verify_signature`` on the same + raw body before acting on the event. + + Args: + raw_body: The request body as received. + + Returns: + The event. + + Raises: + ValueError: The body is not JSON or not a ``request.completed`` payload + (``pydantic.ValidationError`` is a ``ValueError``). + """ + data = json.loads(_as_bytes(raw_body)) + if not isinstance(data, dict): + msg = "A webhook body is a JSON object" + raise ValueError(msg) + return WebhookEvent.model_validate(data) diff --git a/tests/test_async_requests.py b/tests/test_async_requests.py new file mode 100644 index 0000000..9565dad --- /dev/null +++ b/tests/test_async_requests.py @@ -0,0 +1,632 @@ +"""Tests for async requests (submit/get/wait/callback_status), the account webhook +methods and the scrapebadger.webhooks helpers (SCR-652).""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import time +from typing import TYPE_CHECKING +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +import respx + +import scrapebadger +from scrapebadger import ( + AsyncRequest, + AsyncRequestTimeoutError, + CallbackStatus, + NotFoundError, + PermissionDeniedError, + ScrapeBadger, + ScrapeBadgerError, + ServerError, + WebhookDeliveries, + WebhookEvent, + WebhookSecret, + webhooks, +) + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator + +BASE = "https://api.test.scrapebadger.com" +ASK = f"{BASE}/v1/perplexity/ask" + + +@pytest.fixture +async def sb() -> AsyncGenerator[ScrapeBadger, None]: + async with ScrapeBadger(api_key="test_key", base_url=BASE, max_retries=0) as client: + yield client + + +@pytest.fixture +async def sb_retry() -> AsyncGenerator[ScrapeBadger, None]: + async with ScrapeBadger(api_key="test_key", base_url=BASE, max_retries=2) as client: + yield client + + +@pytest.fixture +def no_sleep(): + # Poll waits and the shared retry backoff both await asyncio.sleep. + with patch("scrapebadger.agent.client.asyncio.sleep", new_callable=AsyncMock) as sleep: + yield sleep + + +def accepted(request_id: str = "req-1", retry_after: int = 5, **headers: str) -> httpx.Response: + return httpx.Response( + 202, + headers={ + "Location": f"/v1/requests/{request_id}", + "Retry-After": str(retry_after), + **headers, + }, + json={ + "request_id": request_id, + "status": "running", + "retry_after_seconds": retry_after, + "next_action": {"method": "GET", "url": f"/v1/requests/{request_id}"}, + }, + ) + + +ANSWER = {"answer": "HubSpot, Pipedrive", "sources": ["https://example.com"]} + + +def completed(status: int = 200, body: object = ANSWER, **headers: str) -> httpx.Response: + return httpx.Response( + status, + headers={"X-Request-ID": "req-1", "X-Credits-Used": "20", **headers}, + json=body, + ) + + +# ============================================================================= +# submit +# ============================================================================= + + +class TestSubmit: + @respx.mock + async def test_202_is_running_and_sends_async_headers(self, sb: ScrapeBadger) -> None: + route = respx.get(ASK).mock(return_value=accepted()) + req = await sb.requests.submit( + "/v1/perplexity/ask", + params={"prompt": "best crm", "country": None}, + callback_url="https://example.com/hook", + idempotency_key="crm-1", + ) + + assert isinstance(req, AsyncRequest) + assert req.status == "running" + assert req.running is True + assert req.request_id == "req-1" + assert req.status_code == 202 + assert req.retry_after_seconds == 5 + assert req.body is None + assert req.replayed is False + + sent = route.calls.last.request + assert sent.headers["Prefer"] == "respond-async, wait=0" # callback: answer at once + assert sent.headers["X-Callback-URL"] == "https://example.com/hook" + assert sent.headers["Idempotency-Key"] == "crm-1" + assert dict(sent.url.params) == {"prompt": "best crm"} + + @respx.mock + async def test_200_inline_is_completed(self, sb: ScrapeBadger) -> None: + route = respx.get(ASK).mock(return_value=completed()) + req = await sb.requests.submit("perplexity/ask", params={"prompt": "x"}, wait=30) + + assert req.status == "completed" + assert req.running is False + assert req.request_id == "req-1" + assert req.status_code == 200 + assert req.body == ANSWER + assert req.data == ANSWER + assert req.headers["x-credits-used"] == "20" + assert req.credits_used == 20 + assert req.retry_after_seconds is None + + sent = route.calls.last.request + assert sent.headers["Prefer"] == "respond-async, wait=30" + assert "X-Callback-URL" not in sent.headers + assert "Idempotency-Key" not in sent.headers + + @respx.mock + async def test_without_wait_or_callback_uses_api_default(self, sb: ScrapeBadger) -> None: + route = respx.get(ASK).mock(return_value=accepted()) + await sb.requests.submit("/v1/perplexity/ask", params={"prompt": "x"}) + assert route.calls.last.request.headers["Prefer"] == "respond-async" + + @respx.mock + async def test_post_with_json_body(self, sb: ScrapeBadger) -> None: + route = respx.post(f"{BASE}/v1/chatgpt/ask").mock(return_value=accepted("req-2")) + req = await sb.requests.submit( + "/v1/chatgpt/ask", method="post", json={"prompt": "x"}, wait=0 + ) + + assert req.request_id == "req-2" + assert json.loads(route.calls.last.request.content) == {"prompt": "x"} + + @respx.mock + async def test_idempotent_replay_sets_replayed(self, sb: ScrapeBadger) -> None: + respx.get(ASK).mock(return_value=completed(**{"Idempotent-Replayed": "true"})) + req = await sb.requests.submit("/v1/perplexity/ask", idempotency_key="crm-1") + + assert req.replayed is True + assert req.status == "completed" + assert req.body == ANSWER + + @respx.mock + async def test_idempotent_replay_of_running_call(self, sb: ScrapeBadger) -> None: + respx.get(ASK).mock(return_value=accepted(**{"Idempotent-Replayed": "true"})) + req = await sb.requests.submit("/v1/perplexity/ask", idempotency_key="crm-1") + + assert req.replayed is True + assert req.status == "running" + + @respx.mock + async def test_key_reused_for_another_call_raises_409(self, sb: ScrapeBadger) -> None: + respx.get(ASK).mock( + return_value=httpx.Response( + 409, json={"error": "idempotency_key_reused", "detail": "different call"} + ) + ) + with pytest.raises(ScrapeBadgerError) as exc: + await sb.requests.submit("/v1/perplexity/ask", idempotency_key="crm-1") + assert exc.value.status_code == 409 + assert exc.value.response_data["error"] == "idempotency_key_reused" + + @respx.mock + async def test_invalid_callback_url_raises_400(self, sb: ScrapeBadger) -> None: + respx.get(ASK).mock( + return_value=httpx.Response( + 400, json={"error": "invalid_callback_url", "detail": "must be https"} + ) + ) + with pytest.raises(ScrapeBadgerError) as exc: + await sb.requests.submit("/v1/perplexity/ask", callback_url="http://x") + assert exc.value.status_code == 400 + + @pytest.mark.parametrize("wait", [-1, 121, 2.5, True]) + async def test_rejects_bad_wait(self, sb: ScrapeBadger, wait: object) -> None: + with pytest.raises(ValueError, match="wait"): + await sb.requests.submit("/v1/perplexity/ask", wait=wait) # type: ignore[arg-type] + + @pytest.mark.parametrize("key", ["", "has space", "é", "x" * 201]) + async def test_rejects_bad_idempotency_key(self, sb: ScrapeBadger, key: str) -> None: + with pytest.raises(ValueError, match="idempotency_key"): + await sb.requests.submit("/v1/perplexity/ask", idempotency_key=key) + + @pytest.mark.parametrize("path", ["", "https://scrapebadger.com/v1/perplexity/ask"]) + async def test_rejects_bad_path(self, sb: ScrapeBadger, path: str) -> None: + with pytest.raises(ValueError, match="path"): + await sb.requests.submit(path) + + @respx.mock + async def test_lost_answer_is_not_resent_without_key( + self, sb_retry: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(ASK).mock(side_effect=httpx.ReadTimeout("lost")) + with pytest.raises(httpx.ReadTimeout): + await sb_retry.requests.submit("/v1/perplexity/ask") + assert route.call_count == 1 # a resend could start (and bill) a second call + + @respx.mock + async def test_unsent_request_is_retried_without_key( + self, sb_retry: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(ASK).mock(side_effect=[httpx.ConnectError("refused"), accepted()]) + req = await sb_retry.requests.submit("/v1/perplexity/ask") + assert req.status == "running" + assert route.call_count == 2 + + @respx.mock + async def test_lost_answer_is_resent_with_key( + self, sb_retry: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(ASK).mock( + side_effect=[ + httpx.ReadTimeout("lost"), + accepted(**{"Idempotent-Replayed": "true"}), + ] + ) + req = await sb_retry.requests.submit("/v1/perplexity/ask", idempotency_key="k-1") + assert route.call_count == 2 + assert req.replayed is True + + @respx.mock + async def test_replayed_error_is_not_retried( + self, sb_retry: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(ASK).mock( + return_value=httpx.Response( + 502, headers={"Idempotent-Replayed": "true"}, json={"detail": "no answer"} + ) + ) + with pytest.raises(ServerError): + await sb_retry.requests.submit("/v1/perplexity/ask", idempotency_key="k-1") + assert route.call_count == 1 # a stored result can't change + + +# ============================================================================= +# get / wait / callback_status +# ============================================================================= + + +POLL = f"{BASE}/v1/requests/req-1" + + +class TestGet: + @respx.mock + async def test_completed_has_status_code_headers_and_body(self, sb: ScrapeBadger) -> None: + respx.get(POLL).mock( + return_value=completed(201, {"created": True}, **{"X-Callback-Status": "delivered"}) + ) + state = await sb.requests.get("req-1") + + assert state.status == "completed" + assert state.status_code == 201 + assert state.body == {"created": True} + assert state.headers["x-callback-status"] == "delivered" + assert state.credits_used == 20 + assert state.replayed is False + + @respx.mock + async def test_running(self, sb: ScrapeBadger) -> None: + respx.get(POLL).mock(return_value=accepted(retry_after=3)) + state = await sb.requests.get("req-1") + + assert state.status == "running" + assert state.retry_after_seconds == 3 + assert state.headers == {} + assert state.data["next_action"]["url"] == "/v1/requests/req-1" + + @respx.mock + async def test_text_body_is_returned_as_text(self, sb: ScrapeBadger) -> None: + respx.get(POLL).mock( + return_value=httpx.Response( + 200, headers={"Content-Type": "text/html; charset=utf-8"}, text="ok" + ) + ) + state = await sb.requests.get("req-1") + assert state.body == "ok" + + @respx.mock + async def test_request_id_is_path_quoted(self, sb: ScrapeBadger) -> None: + route = respx.get(f"{BASE}/v1/requests/a%2Fb").mock(return_value=completed()) + await sb.requests.get("a/b") + assert route.called + + +class TestWait: + @respx.mock + async def test_polls_until_done_honouring_retry_after( + self, sb: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(POLL).mock( + side_effect=[accepted(retry_after=5), accepted(retry_after=2), completed()] + ) + done = await sb.requests.wait("req-1", timeout=60) + + assert done.status == "completed" + assert done.body == ANSWER + assert route.call_count == 3 + assert [c.args[0] for c in no_sleep.await_args_list] == [5, 2] + + @respx.mock + async def test_uses_retry_after_header_without_body_hint( + self, sb: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + respx.get(POLL).mock( + side_effect=[ + httpx.Response(202, headers={"Retry-After": "7"}, json={"status": "running"}), + completed(), + ] + ) + await sb.requests.wait("req-1") + assert no_sleep.await_args_list[0].args[0] == 7 + + @respx.mock + async def test_timeout_raises_and_keeps_request_id( + self, sb: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(POLL).mock(return_value=accepted(retry_after=5)) + with ( + patch("scrapebadger.agent.client.monotonic", side_effect=[0.0, 0.0, 5.0, 10.0]), + pytest.raises(AsyncRequestTimeoutError) as exc, + ): + await sb.requests.wait("req-1", timeout=7) + + assert isinstance(exc.value, TimeoutError) + assert exc.value.request_id == "req-1" + assert exc.value.timeout == 7 + assert route.call_count == 3 + # The last sleep is cut to what is left of the timeout. + assert [c.args[0] for c in no_sleep.await_args_list] == [5, 2] + + @respx.mock + async def test_zero_timeout_polls_once(self, sb: ScrapeBadger, no_sleep: AsyncMock) -> None: + route = respx.get(POLL).mock(return_value=accepted()) + with pytest.raises(AsyncRequestTimeoutError): + await sb.requests.wait("req-1", timeout=0) + assert route.call_count == 1 + no_sleep.assert_not_awaited() + + @respx.mock + async def test_error_result_is_raised_without_retry( + self, sb_retry: ScrapeBadger, no_sleep: AsyncMock + ) -> None: + route = respx.get(POLL).mock( + return_value=httpx.Response(502, json={"detail": "no usable answer"}) + ) + with pytest.raises(ServerError): + await sb_retry.requests.wait("req-1") + assert route.call_count == 1 + no_sleep.assert_not_awaited() + + @respx.mock + async def test_expired_request_raises_not_found(self, sb: ScrapeBadger) -> None: + respx.get(POLL).mock(return_value=httpx.Response(404, json={"error": "request_not_found"})) + with pytest.raises(NotFoundError): + await sb.requests.wait("req-1") + + +class TestCallbackStatus: + @respx.mock + async def test_parses_delivery_state(self, sb: ScrapeBadger) -> None: + respx.get(f"{POLL}/callback").mock( + return_value=httpx.Response( + 200, + json={ + "request_id": "req-1", + "state": "pending", + "attempts": 2, + "last_status": 503, + "last_error": "HTTPStatusError", + "next_attempt_at": 1793139000, + "delivered_at": None, + "callback_host": "example.com", + }, + ) + ) + cb = await sb.requests.callback_status("req-1") + + assert isinstance(cb, CallbackStatus) + assert cb.state == "pending" + assert cb.attempts == 2 + assert cb.last_status == 503 + assert cb.next_attempt_at == 1793139000 + assert cb.delivered_at is None + assert cb.callback_host == "example.com" + + @respx.mock + async def test_no_callback_raises_not_found(self, sb: ScrapeBadger) -> None: + respx.get(f"{POLL}/callback").mock( + return_value=httpx.Response(404, json={"error": "callback_not_found"}) + ) + with pytest.raises(NotFoundError): + await sb.requests.callback_status("req-1") + + +def test_async_request_keeps_the_old_constructor() -> None: + old = AsyncRequest(request_id="r", running=True, status_code=202) + assert old.status == "running" + new = AsyncRequest(request_id="r", status="completed", status_code=200) + assert new.running is False + + +# ============================================================================= +# account +# ============================================================================= + + +SECRET = { + "secret": "whsec_test", + "signature_header": "X-ScrapeBadger-Signature", + "algorithm": "sha256=", +} + + +class TestAccount: + @respx.mock + async def test_webhook_secret_and_rotate(self, sb: ScrapeBadger) -> None: + respx.get(f"{BASE}/v1/account/webhook-secret").mock( + return_value=httpx.Response(200, json=SECRET) + ) + rotate = respx.post(f"{BASE}/v1/account/webhook-secret/rotate").mock( + return_value=httpx.Response(200, json={**SECRET, "secret": "whsec_new"}) + ) + + secret = await sb.account.webhook_secret() + assert isinstance(secret, WebhookSecret) + assert secret.secret == "whsec_test" + assert (await sb.account.rotate_webhook_secret()).secret == "whsec_new" + assert rotate.called + + @respx.mock + async def test_webhook_deliveries(self, sb: ScrapeBadger) -> None: + route = respx.get(f"{BASE}/v1/account/webhook-deliveries").mock( + return_value=httpx.Response( + 200, + json={ + "deliveries": [ + { + "request_id": "req-1", + "endpoint": "/v1/perplexity/ask", + "state": "delivered", + "attempts": 1, + "last_status": 200, + "last_error": None, + "created_at": 1793138851, + "delivered_at": 1793138852, + "callback_host": "example.com", + } + ], + "window_hours": 24, + }, + ) + ) + result = await sb.account.webhook_deliveries(limit=10) + + assert route.calls.last.request.url.params["limit"] == "10" + assert isinstance(result, WebhookDeliveries) + assert result.window_hours == 24 + assert result.deliveries[0].state == "delivered" + assert result.deliveries[0].endpoint == "/v1/perplexity/ask" + + @respx.mock + async def test_restricted_key_raises_permission_denied(self, sb: ScrapeBadger) -> None: + respx.get(f"{BASE}/v1/account/webhook-deliveries").mock( + return_value=httpx.Response( + 403, json={"error": "full_access_required", "detail": "needs a full key"} + ) + ) + with pytest.raises(PermissionDeniedError): + await sb.account.webhook_deliveries() + + def test_generated_methods_are_kept(self, sb: ScrapeBadger) -> None: + for name in ( + "get_account_info", + "get_the_webhook_signing_secret", + "rotate_the_webhook_signing_secret", + ): + assert callable(getattr(sb.account, name)) + + +# ============================================================================= +# webhooks +# ============================================================================= + + +def sign(secret: str, body: bytes) -> str: + return "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest() + + +EVENT = { + "event": "request.completed", + "request_id": "6ca4ab7a-1", + "batch_id": None, + "status": 200, + "headers": {"content-type": "application/json", "x-credits-used": "20"}, + "body": {"answer": "…", "sources": ["…"]}, + "body_size": 4812, + "result_url": "https://scrapebadger.com/v1/requests/6ca4ab7a-1", + "result_expires_at": 1793139751, + "attempt": 1, + "sent_at": 1793138851, +} +RAW = json.dumps(EVENT).encode() + + +class TestVerifySignature: + def test_valid(self) -> None: + assert webhooks.verify_signature("whsec_test", RAW, sign("whsec_test", RAW)) + + def test_str_body_and_padded_header(self) -> None: + sig = sign("whsec_test", RAW) + assert webhooks.verify_signature("whsec_test", RAW.decode(), f" {sig} ") + + @pytest.mark.parametrize( + "signature", + [ + sign("whsec_other", RAW), # wrong secret + sign("whsec_test", RAW + b" "), # tampered body + sign("whsec_test", RAW).removeprefix("sha256="), # no scheme + sign("whsec_test", RAW).upper(), + "sha256=é", + "", + None, + ], + ) + def test_invalid(self, signature: str | None) -> None: + assert not webhooks.verify_signature("whsec_test", RAW, signature) + + def test_empty_secret_never_verifies(self) -> None: + assert not webhooks.verify_signature("", RAW, sign("", RAW)) + + def test_fresh_sent_at(self) -> None: + now = time.time() + sig = sign("whsec_test", RAW) + assert webhooks.verify_signature("whsec_test", RAW, sig, sent_at=int(now) - 10) + assert webhooks.verify_signature("whsec_test", RAW, sig, sent_at=str(int(now))) + + def test_stale_or_future_sent_at(self) -> None: + now = time.time() + sig = sign("whsec_test", RAW) + assert not webhooks.verify_signature("whsec_test", RAW, sig, sent_at=now - 301) + assert not webhooks.verify_signature("whsec_test", RAW, sig, sent_at=now + 301) + assert webhooks.verify_signature( + "whsec_test", RAW, sig, sent_at=now - 3000, tolerance_s=3600 + ) + + @pytest.mark.parametrize("sent_at", ["soon", "nan", "inf"]) + def test_unreadable_sent_at(self, sent_at: str) -> None: + assert not webhooks.verify_signature( + "whsec_test", RAW, sign("whsec_test", RAW), sent_at=sent_at + ) + + def test_uses_constant_time_compare(self) -> None: + with patch("scrapebadger.webhooks.hmac.compare_digest", return_value=True) as cmp: + assert webhooks.verify_signature("whsec_test", RAW, "sha256=00") + cmp.assert_called_once() + + +class TestParseEvent: + def test_parses_payload(self) -> None: + event = webhooks.parse_event(RAW) + + assert isinstance(event, WebhookEvent) + assert event.event == "request.completed" + assert event.request_id == "6ca4ab7a-1" + assert event.batch_id is None + assert event.status == 200 + assert event.headers["x-credits-used"] == "20" + assert event.body == {"answer": "…", "sources": ["…"]} + assert event.body_omitted is False + assert event.body_size == 4812 + assert event.result_url.endswith("/v1/requests/6ca4ab7a-1") + assert event.result_expires_at == 1793139751 + assert event.attempt == 1 + assert event.sent_at == 1793138851 + + def test_omitted_body(self) -> None: + raw = json.dumps({**EVENT, "body": None, "body_omitted": True, "batch_id": "b-1"}) + event = webhooks.parse_event(raw) + assert event.body is None + assert event.body_omitted is True + assert event.batch_id == "b-1" + + @pytest.mark.parametrize("raw", [b"not json", b"[]", b'{"event": "request.completed"}']) + def test_invalid_raises_value_error(self, raw: bytes) -> None: + with pytest.raises(ValueError): + webhooks.parse_event(raw) + + def test_verify_with_parsed_sent_at(self) -> None: + raw = json.dumps({**EVENT, "sent_at": int(time.time())}).encode() + event = webhooks.parse_event(raw) + assert webhooks.verify_signature( + "whsec_test", raw, sign("whsec_test", raw), sent_at=event.sent_at + ) + + +def test_public_exports() -> None: + assert scrapebadger.webhooks is webhooks + assert scrapebadger.verify_signature is webhooks.verify_signature + assert scrapebadger.parse_event is webhooks.parse_event + for name in ( + "AsyncRequestTimeoutError", + "CallbackStatus", + "WebhookDeliveries", + "WebhookDelivery", + "WebhookEvent", + "WebhookSecret", + "verify_signature", + "parse_event", + "webhooks", + ): + assert name in scrapebadger.__all__ + assert scrapebadger.__version__ == "0.80.0" diff --git a/uv.lock b/uv.lock index 694f452..1314146 100644 --- a/uv.lock +++ b/uv.lock @@ -930,7 +930,7 @@ wheels = [ [[package]] name = "scrapebadger" -version = "0.79.0" +version = "0.80.0" source = { editable = "." } dependencies = [ { name = "httpx" },