Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down Expand Up @@ -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` |

Expand Down
12 changes: 11 additions & 1 deletion src/decodo/__init__.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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,
Expand Down Expand Up @@ -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)
167 changes: 167 additions & 0 deletions src/decodo/api/flows.py
Original file line number Diff line number Diff line change
@@ -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
101 changes: 101 additions & 0 deletions src/decodo/api/results.py
Original file line number Diff line number Diff line change
@@ -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")
2 changes: 2 additions & 0 deletions src/decodo/api/web_scraping_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
22 changes: 22 additions & 0 deletions src/decodo/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``."""

Expand Down
Loading