diff --git a/README.md b/README.md index 0597c15..222d770 100644 --- a/README.md +++ b/README.md @@ -513,6 +513,30 @@ client.web_scraping_api.cancel_crawl(crawl_id) `get_crawl_status` returns `pending`, `done`, `faulted`, `cancelled` or `truncated`, with a `reason` when the crawl stopped early. +## Flows + +`client.web_scraping_api.flows` runs any product by the pattern the Decodo IR gives it, so an endpoint added to the IR works without a new SDK method. There are three patterns: `call` (one request), `job` (start, wait, read, cancel) and `batch` (one request that starts many jobs). Flows need an API key and IR 2.6.0 or newer. + +```python +flows = client.web_scraping_api.flows + +links = flows.call("map", {"url": "https://www.example.com"}) + +started = flows.start("crawl", {"url": "https://www.example.com", "limit": 10}) +crawl_id = started[flows.describe("crawl")["idField"]] +status = flows.wait("crawl", crawl_id, timeout=120) +if not flows.has_failed("crawl", status): + pages = flows.results("crawl", crawl_id) + +jobs = flows.start_batch("task_batch", {"target": "universal", "url": ["https://www.example.com", "https://www.example.org"]}) +``` + +`wait` returns the job's final status whether it succeeded or not, and raises `JobTimeoutError` (carrying `flow` and `job_id`) when `timeout` runs out; the job keeps running. It polls at the interval the IR gives the flow (`pollSeconds`) unless you pass `poll_interval`. `cancel` works for flows that have a cancel endpoint. `results` reads every page of a paged flow unless you pass `max_items`. `search`, `map`, `crawl` and the other typed methods are unchanged. + +`flows.check_key()` sends the request the IR gives for checking an API key: it returns when the key was accepted and raises `AuthenticationError` when it was rejected. `read_result(rule, response)` reads a response by a result rule from a surface, raising `ResultError` when the rule finds a failure inside a successful response. + +A schema also exposes `get_flow(name)`, `get_operation(name)` and `get_surface(client)`. A surface is how one client presents the APIs: its tools, shown fields, defaults and caps, keyed by the client's `x-integration` value. + ## Targets and parameter classes Every target in the `Target` enum has a matching parameter class. The name of the class is the enum member name followed by `Params`: @@ -693,6 +717,7 @@ The `["results"]["results"]` nesting above is the shape returned when `parse=Tru | `ValidationError` | The payload fails local schema validation, or the API returns `422` | `errors`, `status_code` | | `TimeoutError` | The request exceeds `timeout_ms` | none | | `CrawlTimeoutError` | `crawl()` exceeds its `timeout`. Subclass of `TimeoutError`; the crawl keeps running | `crawl_id` | +| `JobTimeoutError` | `flows.wait()` exceeds its `timeout`. Subclass of `TimeoutError`; the job keeps running | `flow`, `job_id` | | `CrawlError` | `crawl()` ends `faulted` or `cancelled`. Subclass of `DecodoError` | `crawl_id`, `status`, `reason` | | `DecodoError` | Any other unsuccessful response. Base class for the three errors above | `status_code`, `api_status` | diff --git a/src/decodo/__init__.py b/src/decodo/__init__.py index 0551cf8..9aaa197 100644 --- a/src/decodo/__init__.py +++ b/src/decodo/__init__.py @@ -1,3 +1,5 @@ +from .api.flows import Flows +from .api.results import check_result_rule, read_result from .api.web_scraping_api import WebScrapingApi, WebScrapingApiRoutes from .client import DecodoClient, DecodoConfig, WebScrapingApiConfig from .errors import ( @@ -6,13 +8,15 @@ CrawlInterruptedError, CrawlTimeoutError, DecodoError, + JobTimeoutError, RateLimitError, + ResultError, TimeoutError, ValidationError, ) from .schema.bundled_schema import BundledSchema from .schema.remote_schema import RemoteSchema -from .schema.types import DecodoSchema, RemoteSchemaLoadOptions +from .schema.types import DecodoSchema, FlowSchema, RemoteSchemaLoadOptions from .targets import Target, targets from .types.data_api import ( CrawlPage, @@ -111,6 +115,12 @@ def __getattr__(name: str) -> object: "CrawlError", "CrawlInterruptedError", "CrawlTimeoutError", + "JobTimeoutError", + "ResultError", + "read_result", + "check_result_rule", + "Flows", + "FlowSchema", ] __all__ += sorted(_CODEGEN_NAMES) diff --git a/src/decodo/api/flows.py b/src/decodo/api/flows.py new file mode 100644 index 0000000..f4b8089 --- /dev/null +++ b/src/decodo/api/flows.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import time +from collections.abc import Mapping +from typing import Any, cast +from urllib.parse import quote, urlencode, urlsplit + +import jsonschema + +import decodo.errors +from decodo.http import HttpClient +from decodo.schema.types import DecodoSchema, FlowSchema + +DEFAULT_POLL_INTERVAL = 5.0 + +Flow = dict[str, Any] + + +def _local_path(path: Any) -> str: + if not isinstance(path, str) or not path.startswith("/") or path.startswith("//") or "\\" in path: + raise ValueError("The schema gave a request path that is not a path on the API host.") + return path + + +class Flows: + def __init__(self, http: HttpClient, schema: DecodoSchema, *, available: bool) -> None: + self._http = http + self._schema = schema + self._available = available + + def describe(self, flow: str, pattern: str | None = None) -> Flow: + if not self._available: + raise ValueError("Flows require an API key. Configure web_scraping_api with api_key instead of token.") + if not isinstance(self._schema, FlowSchema): + raise ValueError("The schema in use has no flows; they need Decodo IR 2.6.0 or newer.") + found = self._schema.get_flow(flow) + if found is None: + raise ValueError(f"Unknown flow {flow!r}.") + if pattern is not None and found.get("pattern") != pattern: + raise ValueError(f"Flow {flow!r} is a {found.get('pattern')} flow, not a {pattern} flow.") + return found + + def check_key(self) -> None: + self.describe("scrape") + check = cast(FlowSchema, self._schema).get_key_check() + if not check or not isinstance(check.get("params"), Mapping): + raise ValueError("The schema in use has no key check; it needs Decodo IR 2.6.0 or newer.") + try: + self.call(check["flow"], check["params"]) + except (decodo.errors.AuthenticationError, decodo.errors.RateLimitError): + raise + except decodo.errors.DecodoError: + return + + def call(self, flow: str, params: Mapping[str, Any]) -> Any: + return self._send(self.describe(flow, "call")["run"], body=dict(params)) + + def start(self, flow: str, params: Mapping[str, Any]) -> dict[str, Any]: + return cast(dict[str, Any], self._send(self.describe(flow, "job")["start"], body=dict(params))) + + def start_batch(self, flow: str, params: Mapping[str, Any]) -> list[dict[str, Any]]: + described = self.describe(flow, "batch") + response = self._send(described["start"], body=dict(params)) + return list(response.get(described["itemsField"]) or []) + + def status(self, flow: str, job_id: str) -> dict[str, Any]: + return cast(dict[str, Any], self._send(self.describe(flow, "job")["status"], job_id=job_id)) + + def is_pending(self, flow: str, status: Mapping[str, Any]) -> bool: + described = self.describe(flow, "job") + return status.get(described["statusField"]) in described["pendingStatuses"] + + def has_failed(self, flow: str, status: Mapping[str, Any]) -> bool: + described = self.describe(flow, "job") + return status.get(described["statusField"]) in described["failedStatuses"] + + def wait( + self, + flow: str, + job_id: str, + *, + poll_interval: float | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: + if poll_interval is None: + poll_interval = self._poll_seconds(flow) + if poll_interval <= 0: + raise ValueError("poll_interval must be a positive number of seconds.") + started = time.monotonic() + + while True: + status = self.status(flow, job_id) + if not self.is_pending(flow, status): + return status + if timeout is None: + time.sleep(poll_interval) + continue + remaining = timeout - (time.monotonic() - started) + if remaining <= 0: + raise decodo.errors.JobTimeoutError(flow, job_id, timeout) + time.sleep(min(poll_interval, remaining)) + + def _poll_seconds(self, flow: str) -> float: + published = self.describe(flow, "job").get("pollSeconds") + if isinstance(published, (int, float)) and not isinstance(published, bool) and published > 0: + return float(published) + return DEFAULT_POLL_INTERVAL + + def results(self, flow: str, job_id: str, *, max_items: int | None = None) -> Any: + described = self.describe(flow, "job") + body = self._send(described["results"], job_id=job_id, query=described.get("resultsQuery")) + pagination = described.get("pagination") + if not pagination: + return body + + items: list[Any] = list((body or {}).get(pagination["itemsField"]) or []) + while max_items is None or len(items) < max_items: + next_url = (body or {}).get(pagination["nextUrlField"]) + if not next_url: + break + parts = urlsplit(next_url) + path = _local_path(parts.path) + body = self._http.get(f"{path}?{parts.query}" if parts.query else path) + items.extend((body or {}).get(pagination["itemsField"]) or []) + return items + + def cancel(self, flow: str, job_id: str) -> dict[str, Any]: + endpoint = self.describe(flow, "job").get("cancel") + if not endpoint: + raise ValueError(f"Flow {flow!r} cannot be cancelled.") + return cast(dict[str, Any], self._send(endpoint, job_id=job_id)) + + def _send( + self, + endpoint: str, + *, + body: dict[str, Any] | None = None, + job_id: str | None = None, + query: Mapping[str, str] | None = None, + ) -> Any: + described = cast(FlowSchema, self._schema).get_operation(endpoint) + if described is None: + raise ValueError(f"The schema has no operation {endpoint!r}.") + path = _local_path(described["path"]) + if job_id is not None: + before, _, rest = path.partition("{") + _, closed, after = rest.partition("}") + if not closed or not str(job_id): + raise ValueError(f"Operation {endpoint!r} needs a job id and a path with a place for it.") + path = before + quote(str(job_id), safe="") + after + if query: + path = f"{path}?{urlencode(query)}" + if body is not None: + self._validate(described, body) + return self._http.request(described["method"], path, body) + + def _validate(self, endpoint: Mapping[str, Any], body: dict[str, Any]) -> None: + schema = endpoint.get("requestSchema") + target = body.get("target") + if not (schema and "properties" in schema) and isinstance(target, str): + schema = self._schema.get_request_schema(target) or schema + if not schema: + return + try: + jsonschema.validate(body, schema) + except jsonschema.ValidationError as e: + raise decodo.errors.ValidationError(str(e)) from e diff --git a/src/decodo/api/results.py b/src/decodo/api/results.py new file mode 100644 index 0000000..e77f14d --- /dev/null +++ b/src/decodo/api/results.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from decodo.errors import ResultError + +_MISSING: Any = object() +_RETRYABLE_STATUS = 429 +_SERVER_ERROR = 500 + + +def _at(value: Any, path: str) -> Any: + segment, _, rest = path.partition(".") + if segment == "*": + if not isinstance(value, list): + return _MISSING + found = [_at(item, rest) if rest else item for item in value] + return [item for item in found if item is not _MISSING] + if segment.isdigit(): + index = int(segment) + step = value[index] if isinstance(value, list) and index < len(value) else _MISSING + else: + step = value.get(segment, _MISSING) if isinstance(value, Mapping) else _MISSING + return _at(step, rest) if rest and step is not _MISSING else step + + +def _is_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _raise_if_failed(failure: Mapping[str, Any], response: Any) -> None: + value = _at(response, failure["path"]) + if "equals" in failure: + failed = value is not _MISSING and value == failure["equals"] + else: + failed = _is_number(value) and value >= failure["atLeast"] + if not failed: + return + + code = _at(response, failure["code"]) if failure.get("code") else _MISSING + code = value if code is _MISSING or code is None else code + message = _at(response, failure["message"]) if failure.get("message") else _MISSING + retryable = bool(failure.get("retryable")) or ( + _is_number(code) and (code == _RETRYABLE_STATUS or code >= _SERVER_ERROR) + ) + text = message if isinstance(message, str) and message else f"Decodo reported a failure ({code})." + raise ResultError(text, str(code), retryable=retryable) + + +def _picked(item: Any, rule: Mapping[str, Any]) -> Any: + fields = rule.get("fields") + if fields: + found = {name: _at(item, path) for name, path in fields.items()} + picked = {name: value for name, value in found.items() if value is not _MISSING} + for name in rule.get("required") or (): + if picked.get(name) in (None, "", [], {}): + raise ResultError(f"Decodo returned a result with no {name}.", f"empty_{name}") + return picked + omit = rule.get("omit") + if omit and isinstance(item, Mapping): + return {name: value for name, value in item.items() if name not in omit} + return item + + +def read_result(rule: Mapping[str, Any] | None, response: Any) -> Any: + if not rule: + return response + for failure in rule.get("failures") or (): + _raise_if_failed(failure, response) + + result = _at(response, rule["from"]) if rule.get("from") else response + if result is _MISSING or result is None: + raise ResultError("Decodo returned no result.", "empty_response") + if isinstance(result, list): + return [_picked(item, rule) for item in result] + return _picked(result, rule) + + +def check_result_rule(rule: Any) -> None: + if not isinstance(rule, Mapping): + raise TypeError("the result rule is not an object") + failures = rule.get("failures") or [] + if not isinstance(failures, list): + raise TypeError("failures is not a list") + for failure in failures: + if not isinstance(failure, Mapping) or not isinstance(failure.get("path"), str): + raise TypeError("a failure has no path") + if ("equals" in failure) == ("atLeast" in failure) or not _is_number(failure.get("atLeast", 0)): + raise TypeError("a failure needs exactly one of equals and a numeric atLeast") + if not all(isinstance(failure.get(key, ""), str) for key in ("message", "code")): + raise TypeError("a failure's message or code is not a path") + if not isinstance(rule.get("from", ""), str): + raise TypeError("from is not a path") + fields = rule.get("fields") or {} + if not isinstance(fields, Mapping) or not all(isinstance(path, str) for path in fields.values()): + raise TypeError("fields is not an object of paths") + for key in ("omit", "required"): + names = rule.get(key) or [] + if not isinstance(names, list) or not all(isinstance(name, str) for name in names): + raise TypeError(f"{key} is not a list of names") diff --git a/src/decodo/api/web_scraping_api.py b/src/decodo/api/web_scraping_api.py index ace6289..b6c3d9e 100644 --- a/src/decodo/api/web_scraping_api.py +++ b/src/decodo/api/web_scraping_api.py @@ -10,6 +10,7 @@ from pydantic import BaseModel import decodo.errors +from decodo.api.flows import Flows from decodo.http import HttpClient if TYPE_CHECKING: @@ -77,6 +78,7 @@ def __init__( self._http = http self._schema = schema self._routes = routes + self.flows = Flows(http, schema, available=routes.search is not None) def _validate(self, payload: dict[str, Any]) -> None: if self._schema is None: diff --git a/src/decodo/errors.py b/src/decodo/errors.py index f562ac8..827d05e 100644 --- a/src/decodo/errors.py +++ b/src/decodo/errors.py @@ -36,6 +36,28 @@ def __init__(self, message: str = "The request timed out.") -> None: super().__init__(message) +class ResultError(Exception): + + code: str + retryable: bool + + def __init__(self, message: str, code: str, *, retryable: bool = False) -> None: + super().__init__(message) + self.code = code + self.retryable = retryable + + +class JobTimeoutError(TimeoutError): + + flow: str + job_id: str + + def __init__(self, flow: str, job_id: str, timeout: float) -> None: + super().__init__(f"The {flow} job {job_id} was still running after {timeout:g}s.") + self.flow = flow + self.job_id = job_id + + class CrawlError(DecodoError): """Raised by ``crawl()`` when the crawl ends ``faulted`` or ``cancelled``.""" diff --git a/src/decodo/schema/bundled_schema.py b/src/decodo/schema/bundled_schema.py index 6a1f9e0..ee0917f 100644 --- a/src/decodo/schema/bundled_schema.py +++ b/src/decodo/schema/bundled_schema.py @@ -9,7 +9,14 @@ from decodo.targets import targets from .build_target_meta import build_target_meta -from .types import DecodoSchema, RemoteIr, TargetMeta, build_endpoint_request_schemas +from .types import ( + DecodoSchema, + IrEndpoint, + RemoteIr, + TargetMeta, + build_endpoint_request_schemas, + ir_section, +) def _load_target_meta() -> dict[str, Any] | None: @@ -61,6 +68,11 @@ def __init__(self) -> None: } self._target_meta = _target_meta if _target_meta is not None else build_target_meta(api_targets) self._endpoint_schemas = build_endpoint_request_schemas(cast(RemoteIr, ir)) + self._operations = ir_section(ir, "operations") + self._flows = ir_section(ir, "flows") + self._surfaces = ir_section(ir, "surfaces") + key_check = ir.get("keyCheck") + self._key_check: dict[str, Any] | None = key_check if isinstance(key_check, dict) else None else: warnings.warn( "Decodo IR schema not found — payload validation is disabled. " @@ -72,6 +84,10 @@ def __init__(self) -> None: self._request_schemas = {} self._target_meta = _target_meta or {} self._endpoint_schemas = {} + self._operations = {} + self._flows = {} + self._surfaces = {} + self._key_check = None def get_request_schema(self, target: str) -> dict[str, Any] | None: return self._request_schemas.get(target) @@ -91,6 +107,18 @@ def get_shared_parameters(self) -> dict[str, Any]: def get_endpoint_request_schema(self, endpoint: str) -> dict[str, Any] | None: return self._endpoint_schemas.get(endpoint) + def get_flow(self, flow: str) -> dict[str, Any] | None: + return self._flows.get(flow) + + def get_operation(self, operation: str) -> IrEndpoint | None: + return cast(IrEndpoint | None, self._operations.get(operation)) + + def get_key_check(self) -> dict[str, Any] | None: + return self._key_check + + def get_surface(self, client: str) -> dict[str, Any] | None: + return self._surfaces.get(client) + @property def version(self) -> str | None: return None diff --git a/src/decodo/schema/remote_schema.py b/src/decodo/schema/remote_schema.py index 3083b45..f68af5d 100644 --- a/src/decodo/schema/remote_schema.py +++ b/src/decodo/schema/remote_schema.py @@ -1,23 +1,27 @@ from __future__ import annotations +import contextlib import json import os import time +import warnings from typing import Any, cast import httpx from .build_target_meta import build_target_meta -from .constants import DEFAULT_IR_CACHE_PATH +from .constants import DEFAULT_IR_BASE, DEFAULT_IR_CACHE_PATH, DEFAULT_IR_PREFIX from .expand_path import expand_path from .resolve_latest_ir import resolve_latest_ir from .types import ( CachedIr, DecodoSchema, + IrEndpoint, RemoteIr, RemoteSchemaLoadOptions, TargetMeta, build_endpoint_request_schemas, + ir_section, ) @@ -61,6 +65,33 @@ def _resolve_ir_url( def _load_ir(options: RemoteSchemaLoadOptions) -> RemoteIr: cache_path = expand_path(options.get("cache_path") or DEFAULT_IR_CACHE_PATH) cached = _read_cached_ir(cache_path) + ttl_ms = options.get("ttl_ms") + usable = cached if cached is not None and _is_cache_of(cached, options.get("url")) else None + + if usable is not None and ttl_ms is not None and _is_cache_fresh(usable, ttl_ms): + return usable["ir"] + + try: + return _refresh_ir(options, cache_path, cached) + except (httpx.HTTPError, RuntimeError, ValueError) as error: + if usable is None: + raise + warnings.warn( + f"Could not refresh the Decodo IR ({type(error).__name__}); using the cached copy.", + RuntimeWarning, + stacklevel=3, + ) + return usable["ir"] + + +def _is_cache_of(cached: CachedIr, url: str | None) -> bool: + resolved_url = cached.get("resolved_url") or "" + if url: + return resolved_url == url + return resolved_url.startswith(f"{DEFAULT_IR_BASE}/{DEFAULT_IR_PREFIX}") + + +def _refresh_ir(options: RemoteSchemaLoadOptions, cache_path: str, cached: CachedIr | None) -> RemoteIr: resolved_url, resolved_version = _resolve_ir_url(options) ttl_ms = options.get("ttl_ms") @@ -69,6 +100,8 @@ def _load_ir(options: RemoteSchemaLoadOptions) -> RemoteIr: return cached["ir"] if options.get("url") or cached["ir"].get("version") == resolved_version: + with contextlib.suppress(OSError): + _write_cached_ir(cache_path, CachedIr(**{**cached, "fetched_at": int(time.time() * 1000)})) return cached["ir"] ir = _fetch_ir(resolved_url) @@ -106,6 +139,11 @@ def __init__( self._shared_parameters: dict[str, Any] = ir["apis"]["webScrapingApi"].get("parameters") or {} self._target_keys = list(ir["apis"]["webScrapingApi"]["targets"].keys()) self._endpoint_schemas = build_endpoint_request_schemas(ir) + self._operations = ir_section(ir, "operations") + self._flows = ir_section(ir, "flows") + self._surfaces = ir_section(ir, "surfaces") + key_check = ir.get("keyCheck") + self._key_check: dict[str, Any] | None = key_check if isinstance(key_check, dict) else None @classmethod def load(cls, options: RemoteSchemaLoadOptions | None = None) -> RemoteSchema: @@ -132,6 +170,18 @@ def get_shared_parameters(self) -> dict[str, Any]: def get_endpoint_request_schema(self, endpoint: str) -> dict[str, Any] | None: return self._endpoint_schemas.get(endpoint) + def get_flow(self, flow: str) -> dict[str, Any] | None: + return self._flows.get(flow) + + def get_operation(self, operation: str) -> IrEndpoint | None: + return cast(IrEndpoint | None, self._operations.get(operation)) + + def get_key_check(self) -> dict[str, Any] | None: + return self._key_check + + def get_surface(self, client: str) -> dict[str, Any] | None: + return self._surfaces.get(client) + @property def version(self) -> str | None: return self._version diff --git a/src/decodo/schema/types.py b/src/decodo/schema/types.py index f428c5e..ede62a7 100644 --- a/src/decodo/schema/types.py +++ b/src/decodo/schema/types.py @@ -1,8 +1,8 @@ from __future__ import annotations -from typing import Any, Protocol +from typing import Any, Protocol, runtime_checkable -from typing_extensions import Required, TypedDict +from typing_extensions import NotRequired, Required, TypedDict class TargetMeta(TypedDict): @@ -20,6 +20,9 @@ class IrTarget(TypedDict): class RemoteIr(TypedDict): version: str apis: RemoteIrApis + operations: NotRequired[dict[str, IrEndpoint]] + flows: NotRequired[dict[str, dict[str, Any]]] + surfaces: NotRequired[dict[str, dict[str, Any]]] class RemoteIrApis(TypedDict, total=False): @@ -82,6 +85,29 @@ def get_endpoint_request_schema(self, endpoint: str) -> dict[str, Any] | None: def version(self) -> str | None: ... +@runtime_checkable +class FlowSchema(Protocol): + + def get_flow(self, flow: str) -> dict[str, Any] | None: + ... + + def get_operation(self, operation: str) -> IrEndpoint | None: + ... + + def get_key_check(self) -> dict[str, Any] | None: + ... + + def get_surface(self, client: str) -> dict[str, Any] | None: + ... + + +def ir_section(ir: Any, key: str) -> dict[str, Any]: + section = ir.get(key) + if not isinstance(section, dict): + return {} + return {name: value for name, value in section.items() if isinstance(value, dict)} + + def build_endpoint_request_schemas(ir: RemoteIr) -> dict[str, dict[str, Any]]: """Collect the request schemas of the IR's Data API endpoints, if the section exists.""" data_api = ir["apis"].get("dataApi") diff --git a/tests/schema/fixtures/flows_ir.json b/tests/schema/fixtures/flows_ir.json new file mode 100644 index 0000000..230a812 --- /dev/null +++ b/tests/schema/fixtures/flows_ir.json @@ -0,0 +1,1150 @@ +{ + "version": "2.6.0", + "apis": { + "webScrapingApi": { + "parameters": {}, + "targets": { + "universal": { + "group": "Universal", + "response_format": "html", + "parameter_schema": { + "type": "object", + "properties": { + "target": { + "const": "universal" + }, + "url": { + "type": "string", + "maxLength": 2056 + }, + "payload": { + "type": "string" + }, + "proxy_pool": { + "type": "string", + "enum": [ + "standard", + "premium" + ] + }, + "http_method": { + "type": "string" + }, + "headless": { + "type": "string", + "enum": [ + "html", + "png" + ] + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "device_type": { + "type": "string" + }, + "session_id": { + "type": "string" + }, + "successful_status_codes": { + "type": "array", + "items": { + "type": "number" + } + }, + "headers": { + "type": "object" + }, + "cookies": { + "type": "object" + }, + "force_headers": { + "type": "boolean" + }, + "force_cookies": { + "type": "boolean" + }, + "xhr": { + "type": "boolean" + }, + "markdown": { + "type": "boolean" + }, + "main_content": { + "type": "boolean" + }, + "callback_url": { + "type": "string" + } + }, + "required": [ + "target" + ], + "additionalProperties": false + } + } + } + }, + "dataApi": { + "endpoints": { + "runSearch": { + "method": "POST", + "path": "/v1/search", + "requestSchema": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1 + }, + "url": { + "type": "string", + "minLength": 1 + }, + "uule": { + "type": "string" + }, + "gl": { + "type": "string" + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "input_encoding": { + "type": "string" + }, + "page": { + "type": "number", + "minimum": 1 + } + } + } + }, + "mapSite": { + "method": "POST", + "path": "/v1/map", + "requestSchema": { + "type": "object", + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string" + }, + "limit": { + "type": "integer", + "default": 147700 + }, + "sitemap": { + "type": "string", + "enum": [ + "include", + "only", + "skip" + ], + "default": "include" + }, + "domain_filter": { + "type": "string", + "enum": [ + "domain", + "subdomain", + "all" + ], + "default": "domain" + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "JS_rendering": { + "type": "boolean", + "default": false + }, + "follow_redirects": { + "type": "boolean", + "default": true + }, + "select_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "exclude_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + } + } + }, + "listCrawls": { + "method": "GET", + "path": "/v1/crawl" + }, + "startCrawl": { + "method": "POST", + "path": "/v1/crawl", + "requestSchema": { + "type": "object", + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "default": 10 + }, + "max_depth": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "default": 5 + }, + "sitemap": { + "type": "string", + "enum": [ + "include", + "only", + "skip" + ], + "default": "include" + }, + "domain_filter": { + "type": "string", + "enum": [ + "domain", + "subdomain", + "all" + ], + "default": "domain" + }, + "output": { + "type": "string", + "enum": [ + "markdown", + "html" + ], + "default": "markdown" + }, + "geo": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z .'-]{0,58}[A-Za-z]$" + }, + "locale": { + "type": "string", + "pattern": "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$" + }, + "follow_redirects": { + "type": "boolean" + }, + "JS_retry": { + "type": "boolean" + }, + "max_duration": { + "type": "integer", + "minimum": 0, + "maximum": 14400, + "default": 3600 + }, + "callback_url": { + "type": "string" + }, + "passthrough": { + "type": "string", + "maxLength": 8192 + }, + "select_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "exclude_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + } + } + }, + "listCrawlPages": { + "method": "GET", + "path": "/v1/crawl/{id}" + }, + "getCrawlStatus": { + "method": "GET", + "path": "/v1/crawl/{id}/status" + }, + "cancelCrawl": { + "method": "POST", + "path": "/v1/crawl/{id}/cancel" + } + } + } + }, + "operations": { + "scrapePage": { + "method": "POST", + "path": "/v1/scrape", + "requestSchema": { + "allOf": [ + { + "type": "object", + "additionalProperties": true, + "properties": { + "target": { + "type": "string" + }, + "query": { + "type": "string", + "maxLength": 2048 + }, + "headless": { + "type": "string", + "enum": [ + "html", + "png" + ] + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "domain": { + "type": "string" + }, + "device_type": { + "type": "string" + }, + "parse": { + "type": "boolean" + }, + "markdown": { + "type": "boolean" + }, + "xhr": { + "type": "boolean" + }, + "http_method": { + "type": "string" + }, + "payload": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": true + }, + "cookies": { + "type": "array", + "items": { + "type": "object", + "required": [ + "key", + "value" + ], + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + }, + "force_headers": { + "type": "boolean" + }, + "force_cookies": { + "type": "boolean" + }, + "session_id": { + "type": "string" + }, + "proxy_pool": { + "type": "string", + "enum": [ + "standard", + "premium" + ] + }, + "successful_status_codes": { + "type": "array", + "items": { + "type": "integer" + } + }, + "page_count": { + "type": "integer" + }, + "browser_actions": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": true + } + }, + "custom_parsing": { + "type": "object", + "additionalProperties": true + }, + "output_schema": { + "type": "string" + }, + "callback_url": { + "type": "string", + "maxLength": 255 + }, + "passthrough": { + "type": "string", + "maxLength": 1024 + } + } + }, + { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 2056 + } + } + } + ] + } + }, + "runSearch": { + "method": "POST", + "path": "/v1/search", + "requestSchema": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1 + }, + "url": { + "type": "string", + "minLength": 1 + }, + "uule": { + "type": "string" + }, + "gl": { + "type": "string" + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "input_encoding": { + "type": "string" + }, + "page": { + "type": "number", + "minimum": 1 + } + } + } + }, + "mapSite": { + "method": "POST", + "path": "/v1/map", + "requestSchema": { + "type": "object", + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string" + }, + "limit": { + "type": "integer", + "default": 147700 + }, + "sitemap": { + "type": "string", + "enum": [ + "include", + "only", + "skip" + ], + "default": "include" + }, + "domain_filter": { + "type": "string", + "enum": [ + "domain", + "subdomain", + "all" + ], + "default": "domain" + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "JS_rendering": { + "type": "boolean", + "default": false + }, + "follow_redirects": { + "type": "boolean", + "default": true + }, + "select_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "exclude_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + } + } + }, + "queueTask": { + "method": "POST", + "path": "/v1/task", + "requestSchema": { + "allOf": [ + { + "type": "object", + "additionalProperties": true, + "properties": { + "target": { + "type": "string" + }, + "query": { + "type": "string", + "maxLength": 2048 + }, + "headless": { + "type": "string", + "enum": [ + "html", + "png" + ] + }, + "geo": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "domain": { + "type": "string" + }, + "device_type": { + "type": "string" + }, + "parse": { + "type": "boolean" + }, + "markdown": { + "type": "boolean" + }, + "xhr": { + "type": "boolean" + }, + "http_method": { + "type": "string" + }, + "payload": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": true + }, + "cookies": { + "type": "array", + "items": { + "type": "object", + "required": [ + "key", + "value" + ], + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + }, + "force_headers": { + "type": "boolean" + }, + "force_cookies": { + "type": "boolean" + }, + "session_id": { + "type": "string" + }, + "proxy_pool": { + "type": "string", + "enum": [ + "standard", + "premium" + ] + }, + "successful_status_codes": { + "type": "array", + "items": { + "type": "integer" + } + }, + "page_count": { + "type": "integer" + }, + "browser_actions": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": true + } + }, + "custom_parsing": { + "type": "object", + "additionalProperties": true + }, + "output_schema": { + "type": "string" + }, + "callback_url": { + "type": "string", + "maxLength": 255 + }, + "passthrough": { + "type": "string", + "maxLength": 1024 + } + } + }, + { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 2056 + } + } + } + ] + } + }, + "getTask": { + "method": "GET", + "path": "/v1/task/{id}" + }, + "getTaskResults": { + "method": "GET", + "path": "/v1/task/{id}/results" + }, + "startCrawl": { + "method": "POST", + "path": "/v1/crawl", + "requestSchema": { + "type": "object", + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "default": 10 + }, + "max_depth": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "default": 5 + }, + "sitemap": { + "type": "string", + "enum": [ + "include", + "only", + "skip" + ], + "default": "include" + }, + "domain_filter": { + "type": "string", + "enum": [ + "domain", + "subdomain", + "all" + ], + "default": "domain" + }, + "output": { + "type": "string", + "enum": [ + "markdown", + "html" + ], + "default": "markdown" + }, + "geo": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z .'-]{0,58}[A-Za-z]$" + }, + "locale": { + "type": "string", + "pattern": "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$" + }, + "follow_redirects": { + "type": "boolean" + }, + "JS_retry": { + "type": "boolean" + }, + "max_duration": { + "type": "integer", + "minimum": 0, + "maximum": 14400, + "default": 3600 + }, + "callback_url": { + "type": "string" + }, + "passthrough": { + "type": "string", + "maxLength": 8192 + }, + "select_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "exclude_paths": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + } + } + }, + "getCrawlStatus": { + "method": "GET", + "path": "/v1/crawl/{id}/status" + }, + "listCrawlPages": { + "method": "GET", + "path": "/v1/crawl/{id}" + }, + "cancelCrawl": { + "method": "POST", + "path": "/v1/crawl/{id}/cancel" + }, + "queueTaskBatch": { + "method": "POST", + "path": "/v1/task/batch", + "requestSchema": { + "type": "object", + "additionalProperties": true, + "properties": { + "target": { + "type": "string" + }, + "url": { + "type": "array", + "items": { + "type": "string", + "maxLength": 2056 + } + }, + "query": { + "type": "array", + "items": { + "type": "string" + } + }, + "prompt": { + "type": "array", + "items": { + "type": "string" + } + }, + "product_id": { + "type": "array", + "items": { + "type": "string" + } + }, + "callback_url": { + "type": "string", + "maxLength": 255 + }, + "passthrough": { + "type": "string" + } + } + } + } + }, + "flows": { + "scrape": { + "pattern": "call", + "run": "scrapePage" + }, + "search": { + "pattern": "call", + "run": "runSearch" + }, + "map": { + "pattern": "call", + "run": "mapSite" + }, + "task": { + "pattern": "job", + "start": "queueTask", + "status": "getTask", + "results": "getTaskResults", + "idField": "id", + "statusField": "status", + "pendingStatuses": [ + "pending" + ], + "failedStatuses": [ + "faulted" + ], + "pollSeconds": 5 + }, + "crawl": { + "pattern": "job", + "start": "startCrawl", + "status": "getCrawlStatus", + "results": "listCrawlPages", + "cancel": "cancelCrawl", + "idField": "crawl_id", + "statusField": "status", + "pendingStatuses": [ + "pending" + ], + "failedStatuses": [ + "faulted", + "cancelled" + ], + "resultsQuery": { + "type": "content" + }, + "pagination": { + "itemsField": "url", + "nextUrlField": "next" + }, + "pollSeconds": 5 + }, + "task_batch": { + "pattern": "batch", + "start": "queueTaskBatch", + "itemsField": "queries", + "job": "task" + } + }, + "keyCheck": { + "flow": "scrape", + "params": { + "target": "universal", + "url": "https://does-not-exist.decodo.com" + } + }, + "surfaces": { + "google-adk-python": { + "tools": [ + { + "name": "decodo_search", + "description": "Search the web and get ranked results with titles, links and snippets. Use it first to find pages on a topic; use decodo_scrape to read one of them.", + "flow": "search", + "result": { + "failures": [ + { + "path": "status", + "equals": "failed", + "message": "message", + "code": "status_code", + "retryable": true + } + ], + "omit": [ + "search_parameters" + ] + }, + "limits": { + "maxResultChars": 60000, + "maxTextChars": 40000, + "maxItems": 50, + "maxListValues": 500 + }, + "fields": [ + "query", + "geo", + "locale", + "page" + ], + "descriptions": { + "query": "The search query.", + "geo": "Country or city to search from, for example 'United States'.", + "locale": "Interface language of the results, for example 'en-us'.", + "page": "Results page number, a whole number starting at 1." + } + }, + { + "name": "decodo_scrape", + "description": "Read one web page and get its content as markdown. Use it when you already have the URL. To read many pages of one site, use decodo_crawl_start instead.", + "flow": "scrape", + "result": { + "failures": [ + { + "path": "status", + "equals": "failed", + "message": "message", + "code": "status_code", + "retryable": true + }, + { + "path": "results.0.status_code", + "atLeast": 400 + } + ], + "from": "results.0", + "fields": { + "url": "url", + "content": "content" + }, + "required": [ + "content" + ] + }, + "limits": { + "maxResultChars": 60000, + "maxTextChars": 40000, + "maxItems": 50, + "maxListValues": 500 + }, + "target": "universal", + "fields": [ + "url", + "geo", + "headless" + ], + "required": [ + "url" + ], + "fixed": { + "target": "universal", + "markdown": true + }, + "descriptions": { + "url": "Absolute http or https URL of the page.", + "geo": "Country to load the page from, for example 'Germany'.", + "headless": "Set to 'html' to render JavaScript when the page comes back empty without it." + } + }, + { + "name": "decodo_map", + "description": "List the URLs of a site without reading them. Use it to see what a site contains before choosing pages to scrape or a section to crawl.", + "flow": "map", + "result": { + "from": "results.0", + "fields": { + "url": "url", + "links": "content.links.*.url", + "warning": "warning" + } + }, + "limits": { + "maxResultChars": 60000, + "maxTextChars": 40000, + "maxItems": 50, + "maxListValues": 500 + }, + "fields": [ + "url", + "limit", + "sitemap", + "domain_filter" + ], + "defaults": { + "limit": 100 + }, + "minimums": { + "limit": 1 + }, + "maximums": { + "limit": 500 + }, + "descriptions": { + "url": "Absolute http or https URL of the site.", + "limit": "How many URLs to return, 100 unless set and 500 at most.", + "sitemap": "'include' reads the sitemap and the pages, 'only' reads just the sitemap, 'skip' ignores it.", + "domain_filter": "'domain' stays on the site, 'subdomain' adds its subdomains, 'all' follows any link." + } + }, + { + "name": "decodo_crawl_start", + "description": "Start reading many pages of one site, following its links. Returns a crawl_id at once; the pages come from decodo_crawl_results. Keep limit small: every page is billed.", + "flow": "crawl", + "step": "start", + "fields": [ + "url", + "limit", + "max_depth", + "domain_filter" + ], + "fixed": { + "output": "markdown" + }, + "defaults": { + "limit": 10 + }, + "maximums": { + "limit": 50 + }, + "descriptions": { + "url": "Absolute http or https URL to start from.", + "limit": "How many pages to read, 10 unless set and 50 at most. Every page is billed.", + "max_depth": "How many links away from the start URL the crawl may go.", + "domain_filter": "'domain' stays on the site, 'subdomain' adds its subdomains, 'all' follows any link." + } + }, + { + "name": "decodo_crawl_results", + "description": "Get the pages of a crawl as markdown. It waits inside the call while the crawl runs; if the crawl is still pending when it returns, call it again right away with the same crawl_id.", + "flow": "crawl", + "step": "results", + "result": { + "fields": { + "url": "url", + "status": "status", + "content": "content", + "content_error": "content_error" + } + }, + "limits": { + "maxResultChars": 60000, + "maxTextChars": 40000, + "maxItems": 50, + "maxListValues": 500, + "waitSeconds": 45 + }, + "descriptions": { + "crawl_id": "The crawl_id returned when the crawl was started." + } + }, + { + "name": "decodo_crawl_cancel", + "description": "Stop a running crawl. Pages already read stay available from decodo_crawl_results.", + "flow": "crawl", + "step": "cancel", + "descriptions": { + "crawl_id": "The crawl_id returned when the crawl was started." + } + } + ] + } + } +} diff --git a/tests/schema/test_remote_schema.py b/tests/schema/test_remote_schema.py index fcb68bd..18c927b 100644 --- a/tests/schema/test_remote_schema.py +++ b/tests/schema/test_remote_schema.py @@ -9,6 +9,9 @@ from typing import Any from unittest.mock import MagicMock, patch +import httpx +import pytest + from decodo.schema.constants import ( DEFAULT_IR_BASE, DEFAULT_IR_LIST_URL, @@ -221,3 +224,134 @@ def test_returns_none_when_the_ir_predates_the_data_api_section(self) -> None: schema = RemoteSchema(ir, {}) assert schema.get_endpoint_request_schema("runSearch") is None + + +def _latest_cache(version: str = "1.0.0", *, age_ms: int = 0) -> CachedIr: + import time + + return CachedIr( + fetched_at=int(time.time() * 1000) - age_ms, + resolved_url=f"{DEFAULT_IR_BASE}/{DEFAULT_IR_PREFIX}{version}.json", + ir=_clone_ir(version), + ) + + +class TestRemoteSchemaOffline: + def test_fresh_cache_of_the_latest_ir_is_used_without_any_request(self) -> None: + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache()) + + with patch("httpx.get", side_effect=AssertionError("no request expected")): + schema = RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + assert schema.version == "1.0.0" + + def test_stale_cache_is_used_when_the_versions_cannot_be_listed(self) -> None: + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache(age_ms=120_000)) + + with patch("httpx.get", side_effect=httpx.ConnectError("offline")): + schema = RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + assert schema.version == "1.0.0" + + def test_stale_cache_is_used_when_the_new_ir_cannot_be_fetched(self) -> None: + def fake_get(url: str, **kwargs: Any) -> MagicMock: + if url == DEFAULT_IR_LIST_URL: + return _make_response({"items": [{"name": f"{DEFAULT_IR_PREFIX}2.0.0.json"}]}) + return _make_response({}, status=503) + + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache(age_ms=120_000)) + + with patch("httpx.get", side_effect=fake_get): + schema = RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + assert schema.version == "1.0.0" + + def test_raises_when_offline_with_no_cache(self) -> None: + with _temp_cache_dir() as cache_path: + with patch("httpx.get", side_effect=httpx.ConnectError("offline")): + with pytest.raises(httpx.ConnectError): + RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path)) + + def test_cache_of_another_url_is_not_used_when_the_requested_url_fails(self) -> None: + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache()) + + with patch("httpx.get", side_effect=httpx.ConnectError("offline")): + with pytest.raises(httpx.ConnectError): + RemoteSchema.load(RemoteSchemaLoadOptions(url=IR_URL, cache_path=cache_path)) + + +class TestRemoteSchemaCacheOwnership: + def test_cache_of_a_pinned_url_is_not_served_as_the_latest_ir(self) -> None: + import time + + def fake_get(url: str, **kwargs: Any) -> MagicMock: + if url == DEFAULT_IR_LIST_URL: + return _make_response({"items": [{"name": f"{DEFAULT_IR_PREFIX}2.0.0.json"}]}) + return _make_response(_clone_ir("2.0.0")) + + with _temp_cache_dir() as cache_path: + pinned = CachedIr(fetched_at=int(time.time() * 1000), resolved_url=IR_URL, ir=_clone_ir("0.9.0")) + _write_cached_ir(cache_path, pinned) + + with patch("httpx.get", side_effect=fake_get): + schema = RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + assert schema.version == "2.0.0" + + def test_cache_of_a_pinned_url_is_not_used_offline_for_the_latest_ir(self) -> None: + import time + + with _temp_cache_dir() as cache_path: + pinned = CachedIr(fetched_at=int(time.time() * 1000), resolved_url=IR_URL, ir=_clone_ir("0.9.0")) + _write_cached_ir(cache_path, pinned) + + with patch("httpx.get", side_effect=httpx.ConnectError("offline")): + with pytest.raises(httpx.ConnectError): + RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + def test_a_stale_cache_confirmed_as_latest_is_fresh_again(self) -> None: + requests: list[str] = [] + + def fake_get(url: str, **kwargs: Any) -> MagicMock: + requests.append(url) + return _make_response({"items": [{"name": f"{DEFAULT_IR_PREFIX}1.0.0.json"}]}) + + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache(age_ms=120_000)) + options = RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000) + + with patch("httpx.get", side_effect=fake_get): + RemoteSchema.load(options) + RemoteSchema.load(options) + + assert requests == [DEFAULT_IR_LIST_URL] + + def test_a_stale_cache_confirmed_as_latest_loads_when_it_cannot_be_rewritten(self) -> None: + listing = _make_response({"items": [{"name": f"{DEFAULT_IR_PREFIX}1.0.0.json"}]}) + + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache(age_ms=120_000)) + + with ( + patch("httpx.get", return_value=listing), + patch("decodo.schema.remote_schema._write_cached_ir", side_effect=PermissionError("read-only")), + ): + schema = RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + assert schema.version == "1.0.0" + + def test_cached_copy_is_used_when_the_listing_is_not_json(self) -> None: + broken = _make_response(None) + broken.json.side_effect = ValueError("not json") + + with _temp_cache_dir() as cache_path: + _write_cached_ir(cache_path, _latest_cache(age_ms=120_000)) + + with patch("httpx.get", return_value=broken), pytest.warns(RuntimeWarning, match="cached copy"): + schema = RemoteSchema.load(RemoteSchemaLoadOptions(cache_path=cache_path, ttl_ms=60_000)) + + assert schema.version == "1.0.0" diff --git a/tests/test_flows.py b/tests/test_flows.py new file mode 100644 index 0000000..3a839d0 --- /dev/null +++ b/tests/test_flows.py @@ -0,0 +1,346 @@ +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, call, patch + +import pytest + +from decodo.api.web_scraping_api import DATA_API_ROUTES, SCRAPER_API_ROUTES, WebScrapingApi +from decodo.errors import ( + AuthenticationError, + DecodoError, + JobTimeoutError, + RateLimitError, + TimeoutError, + ValidationError, +) +from decodo.schema.bundled_schema import BundledSchema +from decodo.schema.remote_schema import RemoteSchema + +IR = json.loads((Path(__file__).parent / "schema" / "fixtures" / "flows_ir.json").read_text(encoding="utf-8")) + + +def _api(ir: dict[str, Any] = IR) -> tuple[WebScrapingApi, MagicMock]: + http = MagicMock() + targets = ir["apis"]["webScrapingApi"]["targets"] + parameter_schemas = {name: target["parameter_schema"] for name, target in targets.items()} + return WebScrapingApi(http, RemoteSchema(ir, parameter_schemas), DATA_API_ROUTES), http # type: ignore[arg-type] + + +class TestCallFlow: + @pytest.mark.parametrize( + ("flow", "path", "body"), + [ + ("search", "/v1/search", {"query": "decodo"}), + ("map", "/v1/map", {"url": "https://example.com"}), + ("scrape", "/v1/scrape", {"target": "universal", "url": "https://example.com"}), + ], + ) + def test_sends_the_request_the_ir_describes_and_returns_the_response( + self, flow: str, path: str, body: dict[str, Any] + ) -> None: + api, http = _api() + http.request.return_value = {"ok": True} + + assert api.flows.call(flow, body) == {"ok": True} + http.request.assert_called_once_with("POST", path, body) + + def test_a_body_the_endpoint_schema_refuses_is_not_sent(self) -> None: + api, http = _api() + + with pytest.raises(ValidationError): + api.flows.call("map", {"url": "https://example.com", "sitemap": "sometimes"}) + http.request.assert_not_called() + + def test_a_scrape_body_is_checked_against_its_target(self) -> None: + api, http = _api() + + with pytest.raises(ValidationError): + api.flows.call("scrape", {"target": "universal", "headless": "pdf"}) + http.request.assert_not_called() + + +class TestJobFlow: + def test_crawl_runs_from_start_to_paged_results(self) -> None: + api, http = _api() + http.request.side_effect = [ + {"crawl_id": "c1", "status": "pending"}, + {"crawl_id": "c1", "status": "pending"}, + {"crawl_id": "c1", "status": "truncated"}, + { + "crawl_id": "c1", + "url": [{"url": "https://example.com/1"}], + "next": "https://other.host/v1/crawl/c1?cursor=2", + }, + ] + http.get.return_value = {"crawl_id": "c1", "url": [{"url": "https://example.com/2"}]} + + with patch("decodo.api.flows.time") as fake_time: + fake_time.monotonic.side_effect = [0.0, 1.0] + started = api.flows.start("crawl", {"url": "https://example.com"}) + status = api.flows.wait("crawl", started["crawl_id"], poll_interval=4, timeout=60) + pages = api.flows.results("crawl", "c1") + + assert status["status"] == "truncated" + assert not api.flows.has_failed("crawl", status) + assert pages == [{"url": "https://example.com/1"}, {"url": "https://example.com/2"}] + assert http.request.call_args_list == [ + call("POST", "/v1/crawl", {"url": "https://example.com"}), + call("GET", "/v1/crawl/c1/status", None), + call("GET", "/v1/crawl/c1/status", None), + call("GET", "/v1/crawl/c1?type=content", None), + ] + http.get.assert_called_once_with("/v1/crawl/c1?cursor=2") + assert fake_time.sleep.call_args_list == [call(4)] + + def test_task_runs_from_start_to_results_with_its_own_fields(self) -> None: + api, http = _api() + results = {"results": [{"content": "", "status_code": 200}]} + http.request.side_effect = [{"id": "777", "status": "pending"}, {"id": "777", "status": "done"}, results] + + started = api.flows.start("task", {"target": "universal", "url": "https://example.com"}) + status = api.flows.wait("task", started["id"]) + + assert api.flows.results("task", "777") == results + assert status == {"id": "777", "status": "done"} + assert http.request.call_args_list == [ + call("POST", "/v1/task", {"target": "universal", "url": "https://example.com"}), + call("GET", "/v1/task/777", None), + call("GET", "/v1/task/777/results", None), + ] + + @pytest.mark.parametrize(("flow", "state"), [("crawl", "faulted"), ("crawl", "cancelled"), ("task", "faulted")]) + def test_a_failed_job_is_returned_and_recognised_not_raised(self, flow: str, state: str) -> None: + api, http = _api() + http.request.return_value = {"status": state} + + status = api.flows.wait(flow, "j1") + + assert api.flows.has_failed(flow, status) + assert not api.flows.is_pending(flow, status) + + def test_wait_raises_at_the_timeout_with_the_flow_and_job_id(self) -> None: + api, http = _api() + http.request.return_value = {"status": "pending"} + + with patch("decodo.api.flows.time") as fake_time: + fake_time.monotonic.side_effect = [0.0, 5.0, 10.0] + with pytest.raises(JobTimeoutError) as raised: + api.flows.wait("task", "777", poll_interval=5, timeout=10) + + assert (raised.value.flow, raised.value.job_id) == ("task", "777") + assert fake_time.sleep.call_args_list == [call(5)] + + @pytest.mark.parametrize(("published", "slept"), [(2, 2.0), (0, 5.0), ("fast", 5.0), (None, 5.0)]) + def test_wait_polls_at_the_interval_the_ir_gives_the_flow(self, published: Any, slept: float) -> None: + ir = copy.deepcopy(IR) + if published is None: + del ir["flows"]["task"]["pollSeconds"] + else: + ir["flows"]["task"]["pollSeconds"] = published + api, http = _api(ir) + http.request.side_effect = [{"status": "pending"}, {"status": "done"}] + + with patch("decodo.api.flows.time") as fake_time: + api.flows.wait("task", "777") + + assert fake_time.sleep.call_args_list == [call(slept)] + + def test_wait_rejects_a_non_positive_poll_interval(self) -> None: + api, _ = _api() + + with pytest.raises(ValueError): + api.flows.wait("crawl", "c1", poll_interval=0) + + def test_cancel_posts_to_the_cancel_endpoint(self) -> None: + api, http = _api() + http.request.return_value = {"crawl_id": "c1", "status": "cancelled"} + + assert api.flows.cancel("crawl", "c1")["status"] == "cancelled" + http.request.assert_called_once_with("POST", "/v1/crawl/c1/cancel", None) + + def test_a_flow_without_a_cancel_endpoint_cannot_be_cancelled(self) -> None: + api, http = _api() + + with pytest.raises(ValueError, match="cannot be cancelled"): + api.flows.cancel("task", "777") + http.request.assert_not_called() + + def test_a_start_body_the_schema_refuses_is_not_sent(self) -> None: + api, http = _api() + + with pytest.raises(ValidationError): + api.flows.start("crawl", {"url": "https://example.com", "output": "pdf"}) + http.request.assert_not_called() + + +class TestBatchFlow: + def test_returns_the_jobs_it_started_which_follow_the_task_flow(self) -> None: + api, http = _api() + body = {"target": "universal", "url": ["https://example.com/1", "https://example.com/2"]} + started = [{"id": "1", "status": "pending"}, {"id": "2", "status": "pending"}] + http.request.return_value = {"id": 9, "queries": started} + + jobs = api.flows.start_batch("task_batch", body) + + assert [job["id"] for job in jobs] == ["1", "2"] + assert all(api.flows.is_pending("task", job) for job in jobs) + http.request.assert_called_once_with("POST", "/v1/task/batch", body) + + def test_returns_nothing_when_no_job_was_accepted(self) -> None: + api, http = _api() + http.request.return_value = {"queries": []} + + assert api.flows.start_batch("task_batch", {"target": "universal", "url": []}) == [] + + +class TestFlowLookup: + def test_an_unknown_flow_is_an_error(self) -> None: + api, _ = _api() + + with pytest.raises(ValueError, match="Unknown flow 'nope'"): + api.flows.call("nope", {}) + + def test_a_flow_of_another_pattern_is_an_error(self) -> None: + api, _ = _api() + + with pytest.raises(ValueError, match="is a job flow, not a call flow"): + api.flows.call("crawl", {}) + + def test_an_ir_that_predates_flows_is_an_error(self) -> None: + api, _ = _api({key: value for key, value in IR.items() if key != "flows"}) + + with pytest.raises(ValueError, match="Unknown flow"): + api.flows.call("search", {"query": "q"}) + + def test_flows_need_an_api_key(self) -> None: + api = WebScrapingApi(MagicMock(), BundledSchema.shared, SCRAPER_API_ROUTES) + + with pytest.raises(ValueError, match="require an API key"): + api.flows.call("search", {"query": "q"}) + + +class TestSchemaAccess: + def test_exposes_flows_endpoints_and_surfaces(self) -> None: + api, _ = _api() + schema = api._schema + + assert schema.get_flow("crawl")["idField"] == "crawl_id" # type: ignore[attr-defined] + assert schema.get_operation("getTask") == {"method": "GET", "path": "/v1/task/{id}"} # type: ignore[attr-defined] + assert schema.get_surface("google-adk-python")["tools"][0]["flow"] == "search" # type: ignore[attr-defined] + assert schema.get_flow("nope") is None # type: ignore[attr-defined] + + +class TestRequestsStayOnTheApiHost: + @pytest.mark.parametrize("path", ["@evil.example/v1/x", "//evil.example/v1/x", "https://evil.example/x", ""]) + def test_a_path_that_could_name_another_host_is_refused(self, path: str) -> None: + ir = copy.deepcopy(IR) + ir["operations"]["runSearch"]["path"] = path + api, http = _api(ir) + + with pytest.raises(ValueError, match="not a path on the API host"): + api.flows.call("search", {"query": "q"}) + http.request.assert_not_called() + + @pytest.mark.parametrize( + ("job_id", "sent"), + [ + ("../task/batch?x=", "/v1/crawl/..%2Ftask%2Fbatch%3Fx%3D/cancel"), + ("c1/status", "/v1/crawl/c1%2Fstatus/cancel"), + (42, "/v1/crawl/42/cancel"), + ], + ) + def test_a_job_id_cannot_reach_another_endpoint(self, job_id: Any, sent: str) -> None: + api, http = _api() + http.request.return_value = {} + + api.flows.cancel("crawl", job_id) + + http.request.assert_called_once_with("POST", sent, None) + + def test_an_empty_job_id_is_refused(self) -> None: + api, http = _api() + + with pytest.raises(ValueError, match="needs a job id"): + api.flows.status("crawl", "") + http.request.assert_not_called() + + def test_a_job_operation_without_a_place_for_the_id_is_refused(self) -> None: + ir = copy.deepcopy(IR) + ir["operations"]["getCrawlStatus"]["path"] = "/v1/crawl/status" + api, http = _api(ir) + + with pytest.raises(ValueError, match="needs a job id"): + api.flows.status("crawl", "c1") + http.request.assert_not_called() + + def test_a_next_link_that_could_name_another_host_is_refused(self) -> None: + api, http = _api() + http.request.return_value = {"url": [], "next": "@evil.example/v1/crawl/c1"} + + with pytest.raises(ValueError, match="not a path on the API host"): + api.flows.results("crawl", "c1") + http.get.assert_not_called() + + +class TestResultsEdges: + def test_results_that_are_not_ready_come_back_empty(self) -> None: + api, http = _api() + http.request.return_value = None + + assert api.flows.results("task", "777") is None + assert api.flows.results("crawl", "c1") == [] + + def test_reading_stops_once_max_items_is_reached(self) -> None: + api, http = _api() + http.request.return_value = {"url": [{"url": "1"}, {"url": "2"}], "next": "/v1/crawl/c1?cursor=2"} + http.get.return_value = {"url": [{"url": "3"}], "next": "/v1/crawl/c1?cursor=3"} + + assert len(api.flows.results("crawl", "c1", max_items=3)) == 3 + http.get.assert_called_once_with("/v1/crawl/c1?cursor=2") + + +class TestIrPublishedLater: + @pytest.mark.parametrize("value", ["x", ["x"], 3, None, {"crawl": "x"}]) + def test_sections_of_the_wrong_type_are_dropped_not_fatal(self, value: Any) -> None: + ir = {**IR, "flows": value, "surfaces": value, "operations": value} + api, _ = _api(ir) + + assert api._schema.get_surface("google-adk-python") is None # type: ignore[attr-defined] + with pytest.raises(ValueError, match="Unknown flow"): + api.flows.call("search", {"query": "q"}) + + +class TestKeyCheck: + def test_sends_the_request_the_ir_gives(self) -> None: + api, http = _api() + + api.flows.check_key() + + http.request.assert_called_once_with( + "POST", "/v1/scrape", {"target": "universal", "url": "https://does-not-exist.decodo.com"} + ) + + @pytest.mark.parametrize("error", [DecodoError("target unreachable", 613), DecodoError("bad gateway", 502)]) + def test_another_answer_means_the_key_was_accepted(self, error: Exception) -> None: + api, http = _api() + http.request.side_effect = error + + api.flows.check_key() + + @pytest.mark.parametrize("error", [AuthenticationError(), RateLimitError(), TimeoutError()]) + def test_a_rejected_or_unproven_key_raises(self, error: Exception) -> None: + api, http = _api() + http.request.side_effect = error + + with pytest.raises(type(error)): + api.flows.check_key() + + def test_an_ir_without_a_key_check_is_an_error(self) -> None: + api, _ = _api({key: value for key, value in IR.items() if key != "keyCheck"}) + + with pytest.raises(ValueError, match="no key check"): + api.flows.check_key() diff --git a/tests/test_results.py b/tests/test_results.py new file mode 100644 index 0000000..76d75c0 --- /dev/null +++ b/tests/test_results.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from decodo.api.results import check_result_rule, read_result +from decodo.errors import ResultError + +IR = json.loads((Path(__file__).parent / "schema" / "fixtures" / "flows_ir.json").read_text(encoding="utf-8")) +RULES = {tool["name"]: tool.get("result") for tool in IR["surfaces"]["google-adk-python"]["tools"]} +SCRAPE, SEARCH, MAP, CRAWL = ( + RULES["decodo_scrape"], + RULES["decodo_search"], + RULES["decodo_map"], + RULES["decodo_crawl_results"], +) + + +def failure(rule: Any, response: Any) -> ResultError: + with pytest.raises(ResultError) as raised: + read_result(rule, response) + return raised.value + + +class TestPublishedRules: + def test_scrape_returns_the_page_url_and_content(self) -> None: + response = {"results": [{"status_code": 200, "url": "https://a.test", "content": "# Title", "task_id": "1"}]} + + assert read_result(SCRAPE, response) == {"url": "https://a.test", "content": "# Title"} + + @pytest.mark.parametrize( + ("response", "code", "retryable"), + [ + ({"status": "failed", "message": "target unreachable", "status_code": 612}, "612", True), + ({"status": "failed", "message": "target unreachable"}, "failed", True), + ({"results": [{"status_code": 613, "content": "blocked"}]}, "613", True), + ({"results": [{"status_code": 404, "content": "gone"}]}, "404", False), + ({"results": [{"status_code": 429, "content": "slow"}]}, "429", True), + ({"results": []}, "empty_response", False), + ({}, "empty_response", False), + ({"results": [{"status_code": 200, "content": ""}]}, "empty_content", False), + ({"results": [{"status_code": 200}]}, "empty_content", False), + ], + ) + def test_scrape_failures_inside_a_successful_response(self, response: Any, code: str, retryable: bool) -> None: + raised = failure(SCRAPE, response) + + assert (raised.code, raised.retryable) == (code, retryable) + + def test_a_failure_carries_the_message_decodo_gave(self) -> None: + assert str(failure(SCRAPE, {"status": "failed", "message": "target unreachable"})) == "target unreachable" + + def test_search_returns_everything_but_the_echoed_parameters(self) -> None: + response = {"organic": [{"rank": 1}], "search_parameters": {"query": "q"}, "url": "https://g.test"} + + assert read_result(SEARCH, response) == {"organic": [{"rank": 1}], "url": "https://g.test"} + + def test_search_failure(self) -> None: + assert failure(SEARCH, {"status": "failed", "message": "no luck"}).code == "failed" + + def test_map_returns_the_site_url_and_a_flat_list_of_links(self) -> None: + links = [{"url": "https://a.test/1"}, {"url": "https://a.test/2"}] + response = {"results": [{"status_code": 200, "url": "https://a.test", "content": {"links": links}}]} + + assert read_result(MAP, response) == { + "url": "https://a.test", + "links": ["https://a.test/1", "https://a.test/2"], + } + + def test_a_field_the_response_lacks_is_left_out_and_one_it_holds_is_kept(self) -> None: + with_warning = { + "results": [{"url": "https://a.test", "content": {"links": []}, "warning": "sitemap unreadable"}] + } + failed_page = [{"url": "https://a.test/1", "status": "done", "content_error": "expired"}] + + assert read_result(MAP, with_warning)["warning"] == "sitemap unreadable" + assert read_result(CRAWL, failed_page) == [ + {"url": "https://a.test/1", "status": "done", "content_error": "expired"} + ] + + def test_crawl_pages_keep_three_fields_each(self) -> None: + pages = [{"url": "https://a.test/1", "status": "done", "content": "one", "depth": 1, "task_id": "9"}] + + assert read_result(CRAWL, pages) == [{"url": "https://a.test/1", "status": "done", "content": "one"}] + + def test_every_published_rule_has_the_form_the_reader_understands(self) -> None: + for rule in RULES.values(): + if rule is not None: + check_result_rule(rule) + + +class TestReading: + def test_no_rule_returns_the_response_as_it_is(self) -> None: + assert read_result(None, {"a": 1}) == {"a": 1} + assert read_result({}, [1, 2]) == [1, 2] + + def test_a_missing_field_is_left_out_and_a_missing_item_field_is_skipped(self) -> None: + rule = {"fields": {"title": "meta.title", "tags": "tags.*.name"}} + + assert read_result(rule, {"tags": [{"name": "a"}, {"id": 2}]}) == {"tags": ["a"]} + + def test_a_response_of_an_unexpected_type_is_no_result_or_passes_through(self) -> None: + assert failure({"from": "results.0"}, ["x"]).code == "empty_response" + assert read_result({"omit": ["x"]}, "text") == "text" + + @pytest.mark.parametrize("value", [True, "400", None]) + def test_at_least_only_matches_numbers(self, value: Any) -> None: + rule = {"failures": [{"path": "status_code", "atLeast": 400}]} + + assert read_result(rule, {"status_code": value}) == {"status_code": value} + + +class TestRuleForm: + @pytest.mark.parametrize( + "rule", + [ + "x", + {"failures": "x"}, + {"failures": [{"equals": "failed"}]}, + {"failures": [{"path": "status"}]}, + {"failures": [{"path": "status", "equals": "x", "atLeast": 1}]}, + {"failures": [{"path": "status", "atLeast": "400"}]}, + {"failures": [{"path": "status", "equals": "x", "message": 3}]}, + {"from": 3}, + {"fields": ["url"]}, + {"fields": {"url": 1}}, + {"omit": "x"}, + {"required": [1]}, + ], + ) + def test_a_rule_of_another_form_is_refused(self, rule: Any) -> None: + with pytest.raises(TypeError): + check_result_rule(rule)