Repository navigation
Expand file tree
/
Copy pathallocyn_api.py
More file actions
133 lines (106 loc) · 8.92 KB
/
Copy pathallocyn_api.py
File metadata and controls
133 lines (106 loc) · 8.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# GENERATED by scripts/gen-python-client.mjs from the Allocyn API route table. Do not edit by hand.
"""Allocyn API client for Python. Standard library only, read-only.
from allocyn_api import AllocynApi
api = AllocynApi("https://your-project.vercel.app")
job = api.get_job("job-1")
Every method returns the `data` of the API's answer, or raises AllocynApiError with the API's error code.
It cannot write: writes are signed by the participant's own wallet with @allocyn/sdk.
"""
import json
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Optional
__version__ = "0.2.0"
class AllocynApiError(Exception):
"""The API answered with an error (or something that is not the Allocyn API)."""
def __init__(self, status: int, code: str, message: str, retryable: bool = False, field: Optional[str] = None):
super().__init__(f"{code}: {message}")
self.status, self.code, self.message, self.retryable, self.field = status, code, message, retryable, field
def _q(value: Any) -> str:
return urllib.parse.quote(str(value), safe="")
class AllocynApi:
def __init__(self, base_url: str, *, consistency: Optional[str] = None, timeout: float = 40.0):
parsed = urllib.parse.urlparse(base_url)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
raise ValueError(f"{base_url!r} is not a valid URL")
if parsed.scheme != "https" and parsed.hostname not in ("localhost", "127.0.0.1"):
raise ValueError("The API URL must use https (http is only accepted for localhost).")
if consistency not in (None, "latest", "final"):
raise ValueError('consistency must be "latest" or "final"')
self.base_url = base_url.rstrip("/")
self.consistency = consistency
self.timeout = timeout
def _get(self, path: str, query: Optional[dict] = None, raw: bool = False) -> Any:
params = {k: ("true" if v is True else "false" if v is False else v) for k, v in (query or {}).items() if v is not None}
if "consistency" in (query or {}) and params.get("consistency") is None and self.consistency:
params["consistency"] = self.consistency
url = self.base_url + path + ("?" + urllib.parse.urlencode(params) if params else "")
request = urllib.request.Request(url, headers={"Accept": "image/svg+xml" if raw else "application/json", "User-Agent": f"allocyn-api-python/{__version__}"})
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
status, body = response.status, response.read().decode("utf-8")
except urllib.error.HTTPError as e:
status, body = e.code, e.read().decode("utf-8", "replace")
except urllib.error.URLError as e:
raise AllocynApiError(0, "NETWORK_UNREACHABLE", f"Could not reach {self.base_url}: {e.reason}", retryable=True) from None
if raw and status == 200:
return body
try:
payload = json.loads(body)
except ValueError:
if raw:
raise AllocynApiError(status, f"HTTP_{status}", "The API answered with an error badge (the job may not exist).") from None
raise AllocynApiError(status, "NOT_ALLOCYN_API", f"The answer from {self.base_url} is not JSON. Is that the Allocyn API?") from None
if not isinstance(payload, dict) or payload.get("success") is not True:
err = (payload or {}).get("error", {}) if isinstance(payload, dict) else {}
raise AllocynApiError(status, err.get("code", f"HTTP_{status}"), err.get("message", "The API reported an error."), bool(err.get("retryable", False)), err.get("field"))
return payload["data"]
def get_health(self, *, deep: Optional[bool] = None) -> Any:
"""Liveness. Says the API process is up."""
return self._get(f"/v1/health", {"deep": deep})
def get_meta(self) -> Any:
"""Network, contract and API facts. Which network and contract this API reads, the contract profile it was built for, and the read consistency in use."""
return self._get(f"/v1/meta", {})
def get_limits(self) -> Any:
"""Input limits. The limits the contract reports right now (get_limits()), next to the copy this API was built for."""
return self._get(f"/v1/limits", {})
def list_jobs(self, *, consistency: Optional[str] = None, limit: Optional[int] = None, before: Optional[str] = None, status: Optional[str] = None, client: Optional[str] = None, q: Optional[str] = None, updated_since: Optional[str] = None, source: Optional[str] = None, worker: Optional[str] = None) -> Any:
"""List jobs. Jobs from newest to oldest, with an optional filter by status, client or worker."""
return self._get(f"/v1/jobs", {"consistency": consistency, "limit": limit, "before": before, "status": status, "client": client, "q": q, "updatedSince": updated_since, "source": source, "worker": worker})
def get_stats(self, *, client: Optional[str] = None, worker: Optional[str] = None) -> Any:
"""Counts and statistics. How many jobs there are in each status, and how many deliveries got each verdict, optionally for one client or one worker."""
return self._get(f"/v1/stats", {"client": client, "worker": worker})
def list_events(self, *, after: Optional[int] = None, limit: Optional[int] = None, job: Optional[str] = None, type: Optional[str] = None, worker: Optional[str] = None, client: Optional[str] = None, wait: Optional[int] = None) -> Any:
"""Feed of job events. What changed in the jobs, oldest first: a job was created or accepted, a delivery came in or got its verdict, a status moved."""
return self._get(f"/v1/events", {"after": after, "limit": limit, "job": job, "type": type, "worker": worker, "client": client, "wait": wait})
def get_address_record(self, address: str) -> Any:
"""What the copy holds about an address. For one wallet address: how many jobs it created (as client) and accepted (as worker) in each status, how many deliveries it made and the verdicts they got, and its five newest jobs on each side."""
return self._get(f"/v1/addresses/{_q(address)}", {})
def get_job(self, job_id: str, *, consistency: Optional[str] = None) -> Any:
"""Read a job. The job's terms, parties, status and receipt ids, read from the contract."""
return self._get(f"/v1/jobs/{_q(job_id)}", {"consistency": consistency})
def get_job_proof(self, job_id: str, *, consistency: Optional[str] = None) -> Any:
"""Proof pack of a job. A portable proof pack, safe to save and send as a file (format: "allocyn.proof", version 1)."""
return self._get(f"/v1/jobs/{_q(job_id)}/proof", {"consistency": consistency})
def get_job_badge(self, job_id: str, *, consistency: Optional[str] = None) -> str:
"""Status badge (SVG). A small SVG badge with the job's status, for a README or a portfolio: ."""
return self._get(f"/v1/jobs/{_q(job_id)}/badge.svg", {"consistency": consistency}, raw=True)
def wait_for_job(self, job_id: str, *, consistency: Optional[str] = None, since: Optional[str] = None, timeout: Optional[int] = None) -> Any:
"""Wait for a job to change. Long poll, instead of webhooks."""
return self._get(f"/v1/jobs/{_q(job_id)}/wait", {"consistency": consistency, "since": since, "timeout": timeout})
def prepare_action(self, job_id: str, *, consistency: Optional[str] = None, action: Optional[str] = None, delivery_url: Optional[str] = None, actor: Optional[str] = None) -> Any:
"""Prepare an action for the person to sign. Checks whether accepting, delivering or evaluating is possible on this job right now, and says exactly what the person would sign: the contract call, the SDK call and a link to the Allocyn app."""
return self._get(f"/v1/jobs/{_q(job_id)}/prepare", {"consistency": consistency, "action": action, "deliveryUrl": delivery_url, "actor": actor})
def list_job_receipts(self, job_id: str, *, consistency: Optional[str] = None) -> Any:
"""List a job's receipts. Every receipt of the job, in delivery order (delivery 1 first)."""
return self._get(f"/v1/jobs/{_q(job_id)}/receipts", {"consistency": consistency})
def get_job_receipt_by_index(self, job_id: str, delivery_index: int, *, consistency: Optional[str] = None) -> Any:
"""Read one receipt by delivery number. The receipt of delivery N of a job."""
return self._get(f"/v1/jobs/{_q(job_id)}/receipts/{_q(delivery_index)}", {"consistency": consistency})
def get_receipt(self, receipt_id: str, *, consistency: Optional[str] = None) -> Any:
"""Read a receipt by id. A receipt by its contract id."""
return self._get(f"/v1/receipts/{_q(receipt_id)}", {"consistency": consistency})
def get_transaction(self, tx_hash: str) -> Any:
"""Track a transaction. Where a transaction is in GenLayer consensus."""
return self._get(f"/v1/transactions/{_q(tx_hash)}", {})