Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER7# File : sdk/python/spider_sdk/_client.py8# Module : Sdk9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Asynchronous client of the SPIDER API (httpx)."""42from __future__ import annotations4344import asyncio45import hashlib46import json as jsonlib47import random48import time49import uuid50from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence51from dataclasses import dataclass, field52from typing import Any, Literal, Self53from urllib.parse import quote, urlsplit5455import httpx5657from . import requests as rq58from ._routes import MONITOR_ACTIONS, ROUTES, TERMINAL_JOB_STATES59from ._version import __version__60from .errors import (61 APIError,62 ArtifactIntegrityError,63 JobTimeoutError,64 QuotaExceededError,65 TransportError,66 error_from_response,67)6869USER_AGENT = f"spider-sdk-python/{__version__}"70JSON = dict[str, Any]71ExportFormat = Literal["jsonl", "csv", "markdown", "html", "zip"]72RETRY_STATUSES = (502, 503, 504)737475@dataclass(frozen=True)76class Event:77 """One server-sent event of a job. ``data`` is the decoded JSON payload."""78 type: str79 data: Any80 id: str | None = None818283@dataclass(frozen=True)84class JobResult:85 """A finished job with every result page collected."""86 job: JSON87 results: list[JSON]88 not_collected: list[JSON] = field(default_factory=list)8990 @property91 def status(self) -> str:92 return str(self.job.get("status"))9394 @property95 def succeeded(self) -> bool:96 return self.job.get("status") == "succeeded"979899def new_idempotency_key() -> str:100 return str(uuid.uuid4())101102103def is_terminal(job: Mapping[str, Any]) -> bool:104 return job.get("status") in TERMINAL_JOB_STATES105106107class SSEParser:108 """Incremental parser of a text/event-stream body, fed line by line."""109110 def __init__(self) -> None:111 self._type, self._data, self._id = "", [], None112 self.last_event_id: str | None = None113114 def feed(self, line: str) -> Event | None:115 line = line.rstrip("\r\n")116 if line == "":117 raw = "\n".join(self._data)118 if not raw and not self._type:119 self._data = []120 return None # keep-alive, a bare id or an empty data field: nothing to dispatch121 try:122 data = jsonlib.loads(raw) if raw else None123 except ValueError:124 data = raw125 ev = Event(self._type or "message", data, self._id)126 self._type, self._data = "", []127 return ev128 if line.startswith(":"):129 return None130 name, _, value = line.partition(":")131 value = value.removeprefix(" ")132 if name == "event":133 self._type = value134 elif name == "data":135 self._data.append(value)136 elif name == "id" and "\0" not in value:137 self._id = self.last_event_id = value138 return None139140141class AsyncSpider:142 """Asynchronous SPIDER client.143144 The API key travels only in the ``Authorization`` header: never in a URL, never in ``repr`` and145 never in an error message. Redirects are not followed, so the key is never sent to another origin.146147 Retries (at most ``max_retries``, exponential backoff with jitter, ``Retry-After`` honoured):148 connection errors, 429 and 502/503/504 only. A job submission is retried because the SDK sends an149 ``Idempotency-Key`` (generated once per call, reused by every retry of that call): a submission150 whose answer was lost is replayed by the server, not duplicated. No other 4xx is ever retried.151 """152153 def __init__(self, base_url: str, api_key: str, *, timeout: float = 30.0, connect_timeout: float = 10.0,154 max_retries: int = 3, backoff_base: float = 0.5, backoff_max: float = 20.0,155 max_retry_after: float = 120.0, user_agent: str | None = None,156 transport: httpx.AsyncBaseTransport | None = None,157 sleep: Callable[[float], Awaitable[None]] | None = None) -> None:158 parts = urlsplit(base_url)159 if parts.scheme not in ("http", "https") or not parts.netloc:160 raise ValueError("base_url must be an http(s) URL")161 if parts.username or parts.password or parts.query or parts.fragment:162 raise ValueError("base_url must not carry credentials, a query string or a fragment")163 if not api_key or any(c.isspace() for c in api_key):164 raise ValueError("api_key is required")165 self.base_url = base_url.rstrip("/")166 self.max_retries = max(0, int(max_retries))167 self.backoff_base, self.backoff_max, self.max_retry_after = backoff_base, backoff_max, max_retry_after168 self._timeout = httpx.Timeout(timeout, connect=connect_timeout)169 self._sleep = sleep or asyncio.sleep170 ua = USER_AGENT if not user_agent else f"{USER_AGENT} {user_agent}"171 self._http = httpx.AsyncClient(172 base_url=self.base_url, timeout=self._timeout, transport=transport, follow_redirects=False,173 headers={"Authorization": f"Bearer {api_key}", "User-Agent": ua, "Accept": "application/json"})174175 def __repr__(self) -> str:176 return f"{type(self).__name__}(base_url={self.base_url!r}, api_key='***')"177178 async def __aenter__(self) -> Self:179 return self180181 async def __aexit__(self, *exc: object) -> None:182 await self.aclose()183184 async def aclose(self) -> None:185 await self._http.aclose()186187 # ------------------------------------------------------------------ transport188 def _delay(self, attempt: int, retry_after: float | None) -> float:189 if retry_after is not None:190 return retry_after191 return min(self.backoff_max, self.backoff_base * (2 ** attempt)) * (0.5 + random.random() / 2)192193 async def _send(self, method: str, path: str, *, params: Mapping[str, Any] | None = None, json: Any = None,194 headers: Mapping[str, str] | None = None, retry: str = "safe", stream: bool = False,195 timeout: httpx.Timeout | None = None) -> httpx.Response:196 """Send with the retry policy; returns a 2xx/3xx response or raises a typed error."""197 params = {k: v for k, v in (params or {}).items() if v is not None}198 attempt = 0199 while True:200 error: Exception201 retry_after: float | None = None202 try:203 req = self._http.build_request(method, path, params=params or None, json=json, headers=headers,204 timeout=timeout or self._timeout)205 resp = await self._http.send(req, stream=stream)206 except (httpx.ConnectError, httpx.ConnectTimeout) as e: # nothing reached the application207 error, retryable = TransportError(f"{type(e).__name__}: {method} {path}"), True208 except httpx.TransportError as e: # the request may have been processed209 error, retryable = TransportError(f"{type(e).__name__}: {method} {path}"), retry != "unsafe"210 else:211 if resp.status_code < 400:212 return resp213 try:214 raw = await resp.aread()215 finally:216 await resp.aclose()217 try:218 body = jsonlib.loads(raw)219 except ValueError:220 body = None221 error = error_from_response(resp.status_code, body, resp.headers, raw[:300].decode("utf-8", "replace"))222 retry_after = error.retry_after223 if resp.status_code == 429: # refused before any processing: always safe to repeat224 retryable = not (isinstance(error, QuotaExceededError) and retry_after is None)225 else:226 retryable = resp.status_code in RETRY_STATUSES and retry != "unsafe"227 if not retryable or attempt >= self.max_retries or (retry_after or 0) > self.max_retry_after:228 raise error229 await self._sleep(self._delay(attempt, retry_after))230 attempt += 1231232 @staticmethod233 def _path(route: str, **path_params: str) -> tuple[str, str, str]:234 r = ROUTES[route]235 return r.method, r.path.format(**{k: quote(str(v), safe="") for k, v in path_params.items()}), r.retry236237 async def _call(self, route: str, *, params: Mapping[str, Any] | None = None, json: Any = None,238 idempotency_key: str | None = None, **path_params: str) -> Any:239 method, path, retry = self._path(route, **path_params)240 headers = None241 if retry == "keyed":242 headers = {"Idempotency-Key": idempotency_key or new_idempotency_key()}243 resp = await self._send(method, path, params=params, json=json, headers=headers, retry=retry)244 return resp.json()245246 async def request(self, method: str, path: str, *, json: Any = None, params: Mapping[str, Any] | None = None,247 headers: Mapping[str, str] | None = None, idempotency_key: str | None = None) -> Any:248 """Low-level escape hatch: any endpoint, same authentication, errors and retry policy.249250 The body is sent as given (no typed builder, no local check). GET, HEAD, PUT and DELETE are251 retried as safe requests; a POST is retried on 5xx/transport errors only if ``idempotency_key``252 is given. Returns the decoded JSON body, or the raw bytes when the answer is not JSON.253 """254 method = method.upper()255 hdrs = dict(headers or {})256 if idempotency_key:257 hdrs["Idempotency-Key"] = idempotency_key258 has_key = any(k.lower() == "idempotency-key" for k in hdrs)259 retry = "safe" if method in ("GET", "HEAD", "PUT", "DELETE") else ("keyed" if has_key else "unsafe")260 resp = await self._send(method, path, params=params, json=json, headers=hdrs or None, retry=retry)261 if "json" in resp.headers.get("content-type", ""):262 return resp.json()263 return resp.content264265 # ------------------------------------------------------------------ job submissions266 async def scrape(self, url: str, *, render: rq.Render | None = None, capture: rq.CaptureLike | None = None,267 extract: rq.ExtractLike | None = None, policy: rq.PolicyLike | None = None,268 webhook: rq.WebhookLike | None = None, priority: int | None = None,269 metadata: Mapping[str, str] | None = None, timeout_s: int | None = None,270 idempotency_key: str | None = None) -> JSON:271 """Collect one page. Returns the accepted job (``job_id``, ``status_url``, ``results_url``, ``events_url``)."""272 body = rq.scrape_request(url, render=render, capture=capture, extract=extract, policy=policy,273 webhook=webhook, priority=priority, metadata=metadata, timeout_s=timeout_s)274 return await self._call("scrape", json=body, idempotency_key=idempotency_key)275276 async def crawl(self, url: str | None = None, *, urls: Sequence[str] | None = None, sitemap: str | None = None,277 strategy: Literal["bfs", "dfs", "priority"] | None = None, render: rq.Render | None = None,278 max_depth: int | None = None, max_pages: int | None = None,279 max_states_per_page: int | None = None, budgets: rq.BudgetsLike | None = None,280 capture: rq.CaptureLike | None = None, extract: rq.ExtractLike | None = None,281 use_sitemaps: bool | None = None, policy: rq.PolicyLike | None = None,282 webhook: rq.WebhookLike | None = None, priority: int | None = None,283 metadata: Mapping[str, str] | None = None, idempotency_key: str | None = None) -> JSON:284 """Multi-page exploration from a URL, a list of URLs or a sitemap, bounded by budgets."""285 body = rq.crawl_request(url, urls=urls, sitemap=sitemap, strategy=strategy, render=render,286 max_depth=max_depth, max_pages=max_pages, max_states_per_page=max_states_per_page,287 budgets=budgets, capture=capture, extract=extract, use_sitemaps=use_sitemaps,288 policy=policy, webhook=webhook, priority=priority, metadata=metadata)289 return await self._call("crawl", json=body, idempotency_key=idempotency_key)290291 async def map(self, url: str, *, budgets: rq.BudgetsLike | None = None, use_sitemaps: bool | None = None,292 render: Literal["http", "browser"] | None = None, policy: rq.PolicyLike | None = None,293 webhook: rq.WebhookLike | None = None, priority: int | None = None,294 metadata: Mapping[str, str] | None = None, idempotency_key: str | None = None) -> JSON:295 """Discover the URL graph of a site without storing page content."""296 body = rq.map_request(url, budgets=budgets, use_sitemaps=use_sitemaps, render=render, policy=policy,297 webhook=webhook, priority=priority, metadata=metadata)298 return await self._call("map", json=body, idempotency_key=idempotency_key)299300 async def screenshot(self, url: str, *, capture: rq.CaptureLike | None = None,301 policy: rq.PolicyLike | None = None, webhook: rq.WebhookLike | None = None,302 priority: int | None = None, metadata: Mapping[str, str] | None = None,303 timeout_s: int | None = None, idempotency_key: str | None = None) -> JSON:304 """Targeted capture (viewport, full page, tiles, elements)."""305 body = rq.screenshot_request(url, capture=capture, policy=policy, webhook=webhook, priority=priority,306 metadata=metadata, timeout_s=timeout_s)307 return await self._call("screenshot", json=body, idempotency_key=idempotency_key)308309 async def deep_capture(self, url: str, *, capture: rq.CaptureLike | None = None,310 budgets: rq.BudgetsLike | None = None, extract: rq.ExtractLike | None = None,311 policy: rq.PolicyLike | None = None, webhook: rq.WebhookLike | None = None,312 priority: int | None = None, metadata: Mapping[str, str] | None = None,313 timeout_s: int | None = None, idempotency_key: str | None = None) -> JSON:314 """Tiled capture and exploration of interactive states."""315 body = rq.deep_capture_request(url, capture=capture, budgets=budgets, extract=extract, policy=policy,316 webhook=webhook, priority=priority, metadata=metadata, timeout_s=timeout_s)317 return await self._call("deep_capture", json=body, idempotency_key=idempotency_key)318319 async def extract(self, url: str, extract: rq.ExtractLike, *, render: rq.Render | None = None,320 policy: rq.PolicyLike | None = None, webhook: rq.WebhookLike | None = None,321 priority: int | None = None, metadata: Mapping[str, str] | None = None,322 idempotency_key: str | None = None) -> JSON:323 """Schema-driven extraction with per-field evidence."""324 body = rq.extract_request(url, extract, render=render, policy=policy, webhook=webhook, priority=priority,325 metadata=metadata)326 return await self._call("extract", json=body, idempotency_key=idempotency_key)327328 async def ocr(self, artifact_id: str, *, languages: Sequence[str] | None = None, fast: bool | None = None,329 idempotency_key: str | None = None) -> JSON:330 """OCR of a stored image artifact."""331 return await self._call("ocr", json=rq.ocr_request(artifact_id, languages=languages, fast=fast),332 idempotency_key=idempotency_key)333334 async def vision(self, artifact_ids: Sequence[str], *, task: Literal["describe", "fields"] | None = None,335 json_schema: Mapping[str, Any] | None = None, model: str | None = None,336 idempotency_key: str | None = None) -> JSON:337 """Local multimodal analysis of stored image artifacts."""338 body = rq.vision_request(artifact_ids, task=task, json_schema=json_schema, model=model)339 return await self._call("vision", json=body, idempotency_key=idempotency_key)340341 async def batch(self, items: Sequence[rq.BatchItem | Mapping[str, Any]], *,342 idempotency_key: str | None = None) -> JSON:343 """Submit independent jobs at once. Returns ``{items: [{index, job_id | error}], accepted, rejected}``."""344 return await self._call("batch", json=rq.batch_request(items), idempotency_key=idempotency_key)345346 # ------------------------------------------------------------------ watch and search347 async def create_monitor(self, name: str, request: Mapping[str, Any], *, interval_s: int | None = None,348 watch: Sequence[rq.WatchKind] | None = None,349 ignore_selectors: Sequence[str] | None = None, cooldown_s: int | None = None,350 enabled: bool | None = None) -> JSON:351 """Create a recurring watch. ``request`` is a scrape body (``requests.scrape_request``).352353 The API takes no idempotency key here, so this call is not retried after an ambiguous failure.354 """355 body = rq.monitor_request(name, request, interval_s=interval_s, watch=watch,356 ignore_selectors=ignore_selectors, cooldown_s=cooldown_s, enabled=enabled)357 return await self._call("create_monitor", json=body)358359 async def diff(self, snapshot_a: str, snapshot_b: str, *, visual: bool | None = None,360 ignore_selectors: Sequence[str] | None = None) -> JSON:361 """Compare two snapshots (text, layout, fields, pixels)."""362 body = rq.diff_request(snapshot_a, snapshot_b, visual=visual, ignore_selectors=ignore_selectors)363 return await self._call("diff", json=body)364365 async def search(self, query: str, *, site_id: str | None = None, domain: str | None = None,366 since: str | None = None, until: str | None = None, limit: int | None = None,367 cursor: str | None = None) -> JSON:368 """One page of full-text search in the tenant's own corpus (``items``, ``next_cursor``)."""369 body = rq.search_request(query, site_id=site_id, domain=domain, since=since, until=until, limit=limit,370 cursor=cursor)371 return await self._call("search", json=body)372373 async def iter_search(self, query: str, *, site_id: str | None = None, domain: str | None = None,374 since: str | None = None, until: str | None = None, page_size: int | None = None375 ) -> AsyncIterator[JSON]:376 """Every search hit, following ``next_cursor``."""377 cursor: str | None = None378 while True:379 page = await self.search(query, site_id=site_id, domain=domain, since=since, until=until,380 limit=page_size, cursor=cursor)381 for item in page.get("items", []):382 yield item383 cursor = page.get("next_cursor")384 if not cursor:385 return386387 # ------------------------------------------------------------------ jobs388 async def get_job(self, job_id: str) -> JSON:389 return await self._call("get_job", job_id=job_id)390391 async def list_jobs(self, *, status: str | None = None, kind: str | None = None, limit: int | None = None,392 cursor: str | None = None) -> JSON:393 """One page of jobs, newest first (``items``, ``next_cursor``)."""394 return await self._call("list_jobs", params={"status": status, "kind": kind, "limit": limit,395 "cursor": cursor})396397 async def iter_jobs(self, *, status: str | None = None, kind: str | None = None, page_size: int | None = None398 ) -> AsyncIterator[JSON]:399 """Every job, following ``next_cursor``."""400 cursor: str | None = None401 while True:402 page = await self.list_jobs(status=status, kind=kind, limit=page_size, cursor=cursor)403 for item in page.get("items", []):404 yield item405 cursor = page.get("next_cursor")406 if not cursor:407 return408409 async def cancel_job(self, job_id: str) -> JSON:410 return await self._call("cancel_job", job_id=job_id)411412 async def pause_job(self, job_id: str) -> JSON:413 return await self._call("pause_job", job_id=job_id)414415 async def resume_job(self, job_id: str) -> JSON:416 return await self._call("pause_job", job_id=job_id, params={"resume": True})417418 async def retry_job(self, job_id: str) -> JSON:419 """Re-queue the failed URLs of a finished job as a new job (never retried automatically)."""420 return await self._call("retry_job", job_id=job_id)421422 async def get_results(self, job_id: str, *, limit: int | None = None, cursor: str | None = None,423 include_evidence: bool | None = None, include_content: bool | None = None,424 mask_pii: bool = False) -> JSON:425 """One page of results (``items``, ``not_collected``, ``complete``, ``next_cursor``)."""426 return await self._call("get_results", job_id=job_id, params={427 "limit": limit, "cursor": cursor, "include_evidence": include_evidence,428 "include_content": include_content, "mask": "pii" if mask_pii else None})429430 async def iter_results(self, job_id: str, *, page_size: int | None = None,431 include_evidence: bool | None = None, include_content: bool | None = None,432 mask_pii: bool = False) -> AsyncIterator[JSON]:433 """Every result of a job, page after page, following ``next_cursor``."""434 cursor: str | None = None435 while True:436 page = await self.get_results(job_id, limit=page_size, cursor=cursor, include_evidence=include_evidence,437 include_content=include_content, mask_pii=mask_pii)438 for item in page.get("items", []):439 yield item440 cursor = page.get("next_cursor")441 if not cursor:442 return443444 async def stream_events(self, job_id: str, *, last_event_id: str | None = None, reconnect: bool = True445 ) -> AsyncIterator[Event]:446 """Server-sent events of a job, ending after ``job.finished``.447448 A dropped stream is resumed with ``Last-Event-ID`` (at most ``max_retries`` consecutive449 failed reconnections), so no event is lost or repeated.450 """451 method, path, _ = self._path("stream_events", job_id=job_id)452 timeout = httpx.Timeout(self._timeout.connect, read=max(60.0, self._timeout.read or 0.0))453 failures = 0454 while True:455 headers = {"Accept": "text/event-stream"}456 if last_event_id:457 headers["Last-Event-ID"] = last_event_id458 resp = await self._send(method, path, headers=headers, stream=True, timeout=timeout)459 parser, got = SSEParser(), False460 try:461 async for line in resp.aiter_lines():462 ev = parser.feed(line)463 if ev is None:464 continue465 got = True466 last_event_id = ev.id or last_event_id467 yield ev468 if ev.type == "job.finished":469 return470 except httpx.TransportError as e:471 if not reconnect:472 raise TransportError(f"{type(e).__name__}: event stream of job {job_id}") from None473 finally:474 await resp.aclose()475 if not reconnect:476 return477 failures = 0 if got else failures + 1478 if failures > self.max_retries:479 raise TransportError(f"event stream of job {job_id} ended {failures} times without an event")480 await self._sleep(self._delay(failures, None))481482 async def wait_for_job(self, job_id: str, *, timeout: float = 300.0, poll_interval: float = 0.5,483 max_poll_interval: float = 5.0, use_events: bool = False) -> JSON:484 """Wait until the job is terminal (partial, succeeded, failed, cancelled, blocked) and return it.485486 Polls ``GET /v1/jobs/{id}`` with a growing interval, or follows the event stream when487 ``use_events`` is set. Raises :class:`JobTimeoutError` after ``timeout`` seconds; the job is488 not cancelled.489 """490 deadline = time.monotonic() + timeout491 last: str | None = None492 if use_events:493 async def follow() -> None:494 async for _ in self.stream_events(job_id):495 pass496 try:497 await asyncio.wait_for(follow(), timeout)498 except TimeoutError:499 raise JobTimeoutError(job_id, last, timeout) from None500 delay = poll_interval501 while True:502 job = await self.get_job(job_id)503 if is_terminal(job):504 return job505 last = job.get("status")506 remaining = deadline - time.monotonic()507 if remaining <= 0:508 raise JobTimeoutError(job_id, last, timeout)509 await self._sleep(min(delay, remaining))510 delay = min(max_poll_interval, delay * 1.5)511512 async def collect(self, job: str | Mapping[str, Any], *, wait_timeout: float = 300.0, use_events: bool = False,513 page_size: int | None = None) -> JobResult:514 """Wait for a job (id or accepted job), then gather every result page."""515 job_id = job if isinstance(job, str) else str(job["job_id"])516 final = await self.wait_for_job(job_id, timeout=wait_timeout, use_events=use_events)517 items: list[JSON] = []518 not_collected: list[JSON] = []519 cursor: str | None = None520 while True:521 page = await self.get_results(job_id, limit=page_size, cursor=cursor)522 items += page.get("items", [])523 not_collected += page.get("not_collected", [])524 cursor = page.get("next_cursor")525 if not cursor:526 return JobResult(final, items, not_collected)527528 async def scrape_and_wait(self, url: str, *, wait_timeout: float = 300.0, use_events: bool = False,529 **options: Any) -> JobResult:530 """``scrape`` + ``collect``. ``options`` are those of :meth:`scrape`."""531 return await self.collect(await self.scrape(url, **options), wait_timeout=wait_timeout, use_events=use_events)532533 async def crawl_and_wait(self, url: str | None = None, *, wait_timeout: float = 900.0, use_events: bool = False,534 page_size: int | None = None, **options: Any) -> JobResult:535 """``crawl`` + ``collect``. ``options`` are those of :meth:`crawl`."""536 return await self.collect(await self.crawl(url, **options), wait_timeout=wait_timeout,537 use_events=use_events, page_size=page_size)538539 async def extract_and_wait(self, url: str, extract: rq.ExtractLike, *, wait_timeout: float = 300.0,540 use_events: bool = False, **options: Any) -> JobResult:541 """``extract`` + ``collect``. ``options`` are those of :meth:`extract`."""542 return await self.collect(await self.extract(url, extract, **options), wait_timeout=wait_timeout,543 use_events=use_events)544545 async def export(self, job_id: str, *, format: ExportFormat = "jsonl", mask_pii: bool = False) -> bytes:546 """Export the results of a job as bytes (jsonl, csv, markdown, html or zip)."""547 method, path, retry = self._path("export", job_id=job_id)548 resp = await self._send(method, path, params={"format": format, "mask": "pii" if mask_pii else None},549 headers={"Accept": "*/*"}, retry=retry)550 return resp.content551552 # ------------------------------------------------------------------ artifacts and snapshots553 async def get_artifact(self, artifact_id: str, *, expected_sha256: str | None = None) -> bytes:554 """Download an artifact and verify it against the ``X-Spider-Sha256`` response header.555556 Raises :class:`ArtifactIntegrityError` when the header is missing or does not match the bytes557 (or ``expected_sha256``, e.g. the ``sha256`` listed in a result item, when given).558 """559 method, path, retry = self._path("get_artifact", artifact_id=artifact_id)560 resp = await self._send(method, path, headers={"Accept": "*/*"}, retry=retry)561 data = resp.content562 actual = hashlib.sha256(data).hexdigest()563 announced = (resp.headers.get("x-spider-sha256") or "").strip().lower() or None564 if announced != actual:565 raise ArtifactIntegrityError(artifact_id, announced, actual)566 if expected_sha256 is not None and expected_sha256.lower() != actual:567 raise ArtifactIntegrityError(artifact_id, expected_sha256, actual)568 return data569570 async def get_snapshot(self, snapshot_id: str) -> JSON:571 return await self._call("get_snapshot", snapshot_id=snapshot_id)572573 async def snapshot_history(self, url: str, *, limit: int | None = None) -> JSON:574 """Snapshots of a URL, newest first (``url``, ``items``)."""575 return await self._call("snapshot_history", params={"url": url, "limit": limit})576577 # ------------------------------------------------------------------ sites578 async def list_sites(self) -> JSON:579 return await self._call("list_sites")580581 async def site_graph(self, site_id: str, *, job_id: str | None = None, limit: int | None = None,582 cursor: str | None = None) -> JSON:583 """One page of the URL graph (``nodes``, ``edges``, ``next_cursor``)."""584 return await self._call("site_graph", site_id=site_id, params={"job_id": job_id, "limit": limit,585 "cursor": cursor})586587 async def site_coverage(self, site_id: str, *, job_id: str | None = None) -> JSON:588 return await self._call("site_coverage", site_id=site_id, params={"job_id": job_id})589590 # ------------------------------------------------------------------ system and admin helpers591 async def health(self) -> JSON:592 return await self._call("health")593594 async def me(self) -> JSON:595 return await self._call("me")596597 async def list_monitors(self) -> JSON:598 return await self._call("list_monitors")599600 async def monitor_action(self, schedule_id: str, action: Literal["enable", "disable", "run-now", "delete"]601 ) -> JSON:602 if action not in MONITOR_ACTIONS:603 raise ValueError(f"action must be one of {', '.join(MONITOR_ACTIONS)}")604 return await self._call("monitor_action", schedule_id=schedule_id, action=action)605606 async def list_changes(self, *, schedule_id: str | None = None, limit: int | None = None) -> JSON:607 """Change events detected by monitors, newest first."""608 return await self._call("list_changes", params={"schedule_id": schedule_id, "limit": limit})609610 async def webhook_secret(self) -> str:611 """The tenant's webhook signing secret (admin scope). Treat it as a credential."""612 return str((await self._call("webhook_secret"))["secret"])613614615__all__ = [616 "USER_AGENT",617 "APIError",618 "AsyncSpider",619 "Event",620 "JobResult",621 "SSEParser",622 "is_terminal",623 "new_idempotency_key",624]625