spiderweb-sdk 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- spiderweb/__init__.py +11 -0
- spiderweb/aio.py +81 -0
- spiderweb/client.py +207 -0
- spiderweb/models.py +80 -0
- spiderweb/remote.py +371 -0
- spiderweb/toolkit.py +50 -0
- spiderweb_sdk-0.2.0.dist-info/METADATA +102 -0
- spiderweb_sdk-0.2.0.dist-info/RECORD +10 -0
- spiderweb_sdk-0.2.0.dist-info/WHEEL +5 -0
- spiderweb_sdk-0.2.0.dist-info/top_level.txt +1 -0
spiderweb/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""SpiderWeb Python SDK."""
|
|
2
|
+
|
|
3
|
+
from .client import Client, SpiderWebError, WaitTimeout
|
|
4
|
+
from .models import Job, LogChunk, LogPage
|
|
5
|
+
|
|
6
|
+
# DEFAULT_COORDINATOR is the SpiderWeb beta coordinator (the spiderweb-fallback
|
|
7
|
+
# host on Tailscale). Pass your own URL to Client to use another coordinator.
|
|
8
|
+
DEFAULT_COORDINATOR = "https://spiderweb-fallback.taileaa8f0.ts.net"
|
|
9
|
+
|
|
10
|
+
__all__ = ["Client", "SpiderWebError", "WaitTimeout", "Job", "LogChunk", "LogPage", "DEFAULT_COORDINATOR"]
|
|
11
|
+
__version__ = "0.2.0"
|
spiderweb/aio.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Async variant. It runs the synchronous client in worker threads, so behaviour
|
|
2
|
+
(retries, error types, models) is identical and there is no second HTTP stack."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
from typing import Any, AsyncIterator, List, Sequence
|
|
8
|
+
|
|
9
|
+
from .client import Client, WaitTimeout
|
|
10
|
+
from .models import Job, LogChunk, LogPage
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AsyncClient:
|
|
14
|
+
def __init__(self, base_url: str, token: str, **kwargs: Any):
|
|
15
|
+
self._c = Client(base_url, token, **kwargs)
|
|
16
|
+
|
|
17
|
+
async def run(self, image: str, command: Sequence[str], **options: Any) -> Job:
|
|
18
|
+
return await asyncio.to_thread(self._c.run, image, command, **options)
|
|
19
|
+
|
|
20
|
+
async def get(self, job_id: str) -> Job:
|
|
21
|
+
return await asyncio.to_thread(self._c.get, job_id)
|
|
22
|
+
|
|
23
|
+
async def cancel(self, job_id: str) -> None:
|
|
24
|
+
await asyncio.to_thread(self._c.cancel, job_id)
|
|
25
|
+
|
|
26
|
+
async def list(self, *, limit: int = 50) -> List[Job]:
|
|
27
|
+
return await asyncio.to_thread(self._c.list, limit=limit)
|
|
28
|
+
|
|
29
|
+
async def wait(self, job_id: str, *, timeout: float = 600.0, poll: float = 1.0, backoff: float = 1.5,
|
|
30
|
+
max_poll: float = 15.0) -> Job:
|
|
31
|
+
loop = asyncio.get_running_loop()
|
|
32
|
+
deadline = loop.time() + timeout
|
|
33
|
+
while True:
|
|
34
|
+
job = await self.get(job_id)
|
|
35
|
+
if job.done:
|
|
36
|
+
return job
|
|
37
|
+
if loop.time() >= deadline:
|
|
38
|
+
raise WaitTimeout(job_id, job.status)
|
|
39
|
+
await asyncio.sleep(min(poll, max(0.0, deadline - loop.time())))
|
|
40
|
+
poll = min(max_poll, poll * backoff)
|
|
41
|
+
|
|
42
|
+
async def logs(self, job_id: str, *, after_seq: int = 0, limit: int = 500) -> AsyncIterator[LogChunk]:
|
|
43
|
+
# Page by page so a long log does not block the event loop for its whole length.
|
|
44
|
+
while True:
|
|
45
|
+
raw = await asyncio.to_thread(
|
|
46
|
+
self._c._request, "GET", f"/jobs/{job_id}/logs", None, {"after_seq": after_seq, "limit": limit}
|
|
47
|
+
)
|
|
48
|
+
page = LogPage.from_api(raw)
|
|
49
|
+
if not page.chunks:
|
|
50
|
+
return
|
|
51
|
+
for chunk in page.chunks:
|
|
52
|
+
yield chunk
|
|
53
|
+
after_seq = max(page.next_seq, page.chunks[-1].seq)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def run_remote(fn, args, kwargs, opts) -> Any:
|
|
57
|
+
"""The async path of spiderweb.remote: blocking HTTP runs in worker threads and
|
|
58
|
+
the wait polls with asyncio.sleep, so the event loop is never blocked."""
|
|
59
|
+
from .remote import _Call, _resolve
|
|
60
|
+
client, project_id = await asyncio.to_thread(_resolve, opts)
|
|
61
|
+
call = await asyncio.to_thread(_Call, client, project_id, fn, args, kwargs, opts)
|
|
62
|
+
try:
|
|
63
|
+
job_id = await asyncio.to_thread(call.start)
|
|
64
|
+
ac = AsyncClient.__new__(AsyncClient)
|
|
65
|
+
ac._c = client
|
|
66
|
+
try:
|
|
67
|
+
job = await ac.wait(job_id, timeout=call.timeout)
|
|
68
|
+
except BaseException:
|
|
69
|
+
await asyncio.shield(asyncio.to_thread(call.abort))
|
|
70
|
+
raise
|
|
71
|
+
return await asyncio.to_thread(call.finish, job)
|
|
72
|
+
finally:
|
|
73
|
+
await asyncio.to_thread(call.cleanup)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def run(fn, *args: Any, **kwargs: Any) -> Any:
|
|
77
|
+
"""Async `spiderweb.remote.run`: `await aio.run(fn, *args)`."""
|
|
78
|
+
from .remote import RemoteFunction
|
|
79
|
+
if isinstance(fn, RemoteFunction):
|
|
80
|
+
return await run_remote(fn.__wrapped__, args, kwargs, fn.options)
|
|
81
|
+
return await run_remote(fn, args, kwargs, {"result": "json", "serializer": "auto"})
|
spiderweb/client.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Synchronous HTTP client for the SpiderWeb coordinator (standard library only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import random
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
from typing import Any, Dict, Iterator, List, Optional, Sequence
|
|
13
|
+
|
|
14
|
+
from .models import Job, LogChunk, LogPage
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SpiderWebError(Exception):
|
|
18
|
+
"""The coordinator returned an error envelope or an unexpected response."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, status: int, code: str, message: str, details: Optional[dict] = None):
|
|
21
|
+
super().__init__(f"{status} {code}: {message}")
|
|
22
|
+
self.status = status
|
|
23
|
+
self.code = code
|
|
24
|
+
self.message = message
|
|
25
|
+
# Keep structured server diagnostics available without making them part
|
|
26
|
+
# of customer-facing resource models (which must not expose node data).
|
|
27
|
+
self.details = dict(details or {})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class WaitTimeout(SpiderWebError):
|
|
31
|
+
def __init__(self, job_id: str, last_status: str):
|
|
32
|
+
super().__init__(0, "wait_timeout", f"job {job_id} still {last_status}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
RETRY_STATUSES = frozenset({429, 502, 503, 504})
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Client:
|
|
39
|
+
"""`max_retries` extra attempts on 429/502/503/504 and connection errors, with
|
|
40
|
+
exponential backoff (`retry_base` doubling, capped at `retry_max`, Retry-After
|
|
41
|
+
honored). Submitting a job is retried only on 429 (the server refused it), never
|
|
42
|
+
on an ambiguous failure, so a retry cannot create a duplicate job."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, base_url: str, token: str, *, timeout: float = 30.0, max_retries: int = 3,
|
|
45
|
+
retry_base: float = 0.5, retry_max: float = 10.0, sleep=time.sleep):
|
|
46
|
+
self.base_url = base_url.rstrip("/")
|
|
47
|
+
self._token = token
|
|
48
|
+
self.timeout = timeout
|
|
49
|
+
self.max_retries = max_retries
|
|
50
|
+
self.retry_base = retry_base
|
|
51
|
+
self.retry_max = retry_max
|
|
52
|
+
self._sleep = sleep
|
|
53
|
+
|
|
54
|
+
# -- transport ---------------------------------------------------------
|
|
55
|
+
def _request(self, method: str, path: str, body: Optional[dict] = None, query: Optional[dict] = None) -> Any:
|
|
56
|
+
url = self.base_url + "/v1" + path
|
|
57
|
+
if query:
|
|
58
|
+
url += "?" + urllib.parse.urlencode(query)
|
|
59
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
60
|
+
req = urllib.request.Request(url, data=data, method=method)
|
|
61
|
+
req.add_header("Authorization", "Bearer " + self._token)
|
|
62
|
+
req.add_header("Accept", "application/json")
|
|
63
|
+
if data is not None:
|
|
64
|
+
req.add_header("Content-Type", "application/json")
|
|
65
|
+
safe = method == "GET"
|
|
66
|
+
attempt = 0
|
|
67
|
+
while True:
|
|
68
|
+
retry_after = None
|
|
69
|
+
try:
|
|
70
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
71
|
+
raw = resp.read()
|
|
72
|
+
return json.loads(raw) if raw else None
|
|
73
|
+
except urllib.error.HTTPError as e:
|
|
74
|
+
err = _error_from(e.code, e.read())
|
|
75
|
+
e.close()
|
|
76
|
+
retryable = e.code in RETRY_STATUSES and (safe or e.code == 429)
|
|
77
|
+
retry_after = _retry_after(e.headers.get("Retry-After"))
|
|
78
|
+
except (urllib.error.URLError, ConnectionError, TimeoutError) as e:
|
|
79
|
+
if not safe:
|
|
80
|
+
raise SpiderWebError(0, "connection", str(e)) from None
|
|
81
|
+
err, retryable = SpiderWebError(0, "connection", str(e)), True
|
|
82
|
+
if not retryable or attempt >= self.max_retries:
|
|
83
|
+
raise err
|
|
84
|
+
delay = min(self.retry_max, self.retry_base * (2 ** attempt))
|
|
85
|
+
self._sleep(max(delay, retry_after) if retry_after is not None else delay * random.uniform(0.5, 1.0))
|
|
86
|
+
attempt += 1
|
|
87
|
+
|
|
88
|
+
# -- jobs --------------------------------------------------------------
|
|
89
|
+
def run(self, image: str, command: Sequence[str], **options: Any) -> Job:
|
|
90
|
+
"""Submit a job. `options` are SubmitJobRequest fields (env, class, cpu, ...).
|
|
91
|
+
|
|
92
|
+
Use `job_class=` for the wire field `class`.
|
|
93
|
+
"""
|
|
94
|
+
body: Dict[str, Any] = {"image": image, "command": list(command)}
|
|
95
|
+
if "job_class" in options:
|
|
96
|
+
options["class"] = options.pop("job_class")
|
|
97
|
+
body.update(options)
|
|
98
|
+
return Job.from_api(self._request("POST", "/jobs", body))
|
|
99
|
+
|
|
100
|
+
def get(self, job_id: str) -> Job:
|
|
101
|
+
return Job.from_api(self._request("GET", f"/jobs/{job_id}"))
|
|
102
|
+
|
|
103
|
+
def cancel(self, job_id: str) -> None:
|
|
104
|
+
self._request("POST", f"/jobs/{job_id}/cancel")
|
|
105
|
+
|
|
106
|
+
def list(self, *, limit: int = 50) -> List[Job]:
|
|
107
|
+
"""The newest `limit` jobs. The API has no cursor for /jobs; see openapi.yaml."""
|
|
108
|
+
data = self._request("GET", "/jobs", query={"limit": limit})
|
|
109
|
+
return [Job.from_api(j) for j in data.get("jobs") or []]
|
|
110
|
+
|
|
111
|
+
def wait(self, job_id: str, *, timeout: float = 600.0, poll: float = 1.0, backoff: float = 1.5,
|
|
112
|
+
max_poll: float = 15.0) -> Job:
|
|
113
|
+
"""Poll until the job is terminal. The poll interval grows by `backoff` up to `max_poll`."""
|
|
114
|
+
deadline = time.monotonic() + timeout
|
|
115
|
+
while True:
|
|
116
|
+
job = self.get(job_id)
|
|
117
|
+
if job.done:
|
|
118
|
+
return job
|
|
119
|
+
if time.monotonic() >= deadline:
|
|
120
|
+
raise WaitTimeout(job_id, job.status)
|
|
121
|
+
self._sleep(min(poll, max(0.0, deadline - time.monotonic())))
|
|
122
|
+
poll = min(max_poll, poll * backoff)
|
|
123
|
+
|
|
124
|
+
def logs(self, job_id: str, *, after_seq: int = 0, limit: int = 500) -> Iterator[LogChunk]:
|
|
125
|
+
"""Yield every stored log chunk after `after_seq`, following pages."""
|
|
126
|
+
while True:
|
|
127
|
+
page = LogPage.from_api(
|
|
128
|
+
self._request("GET", f"/jobs/{job_id}/logs", query={"after_seq": after_seq, "limit": limit})
|
|
129
|
+
)
|
|
130
|
+
if not page.chunks:
|
|
131
|
+
return
|
|
132
|
+
for chunk in page.chunks:
|
|
133
|
+
yield chunk
|
|
134
|
+
after_seq = max(page.next_seq, page.chunks[-1].seq)
|
|
135
|
+
|
|
136
|
+
# -- projects, artifacts and secrets (used by spiderweb.remote) --------
|
|
137
|
+
def default_project_id(self) -> str:
|
|
138
|
+
"""The org's project named "default", else its first project (as `spw artifact` does)."""
|
|
139
|
+
projects = (self._request("GET", "/projects") or {}).get("projects") or []
|
|
140
|
+
for p in projects:
|
|
141
|
+
if p.get("name") == "default":
|
|
142
|
+
return str(p["id"])
|
|
143
|
+
if projects:
|
|
144
|
+
return str(projects[0]["id"])
|
|
145
|
+
raise SpiderWebError(0, "no_project", "no project found; the org should have a default project")
|
|
146
|
+
|
|
147
|
+
def upload_artifact(self, project_id: str, name: str, data: bytes, *, version: str = "v1") -> str:
|
|
148
|
+
"""Create name@version, PUT `data` to its presigned URL, complete it, and return its id."""
|
|
149
|
+
created = self._request("POST", "/artifacts", {"project_id": project_id, "name": name, "version": version})
|
|
150
|
+
req = urllib.request.Request(created["put_url"], data=data, method="PUT")
|
|
151
|
+
for k, v in (created.get("headers") or {}).items():
|
|
152
|
+
req.add_header(k, v)
|
|
153
|
+
self._raw(req)
|
|
154
|
+
digest = "sha256:" + hashlib.sha256(data).hexdigest()
|
|
155
|
+
self._request("POST", f"/artifacts/{created['id']}/complete", {"digest": digest, "size_bytes": len(data)})
|
|
156
|
+
return str(created["id"])
|
|
157
|
+
|
|
158
|
+
def find_artifact(self, project_id: str, name: str, *, version: str = "v1") -> Optional[str]:
|
|
159
|
+
"""The id of name@version in `project_id`, or None."""
|
|
160
|
+
for a in (self._request("GET", "/artifacts") or {}).get("artifacts") or []:
|
|
161
|
+
if a.get("name") == name and a.get("version", "v1") == version and \
|
|
162
|
+
str(a.get("project_id", project_id)) == str(project_id):
|
|
163
|
+
return str(a["id"])
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
def download_artifact(self, artifact_id: str) -> bytes:
|
|
167
|
+
"""The bytes of an artifact, fetched through its presigned GET URL."""
|
|
168
|
+
url = self._request("GET", f"/artifacts/{artifact_id}/get")["url"]
|
|
169
|
+
return self._raw(urllib.request.Request(url, method="GET"))
|
|
170
|
+
|
|
171
|
+
def put_secret(self, project_id: str, name: str, value: str) -> None:
|
|
172
|
+
self._request("PUT", f"/projects/{project_id}/secrets/{urllib.parse.quote(name)}", {"value": value})
|
|
173
|
+
|
|
174
|
+
def delete_secret(self, project_id: str, name: str) -> None:
|
|
175
|
+
self._request("DELETE", f"/projects/{project_id}/secrets/{urllib.parse.quote(name)}")
|
|
176
|
+
|
|
177
|
+
def _raw(self, req: urllib.request.Request) -> bytes:
|
|
178
|
+
# Presigned URLs carry their own authorization: never send the API token there.
|
|
179
|
+
try:
|
|
180
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
181
|
+
return resp.read()
|
|
182
|
+
except urllib.error.HTTPError as e:
|
|
183
|
+
body = e.read(); e.close()
|
|
184
|
+
raise SpiderWebError(e.code, "storage", body[:200].decode("utf-8", "replace")) from None
|
|
185
|
+
except (urllib.error.URLError, ConnectionError, TimeoutError) as e:
|
|
186
|
+
raise SpiderWebError(0, "connection", str(e)) from None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _error_from(status: int, raw: bytes) -> SpiderWebError:
|
|
190
|
+
try:
|
|
191
|
+
err = json.loads(raw)["error"]
|
|
192
|
+
details = err.get("details")
|
|
193
|
+
return SpiderWebError(
|
|
194
|
+
status,
|
|
195
|
+
str(err.get("code", "")),
|
|
196
|
+
str(err.get("message", "")),
|
|
197
|
+
details if isinstance(details, dict) else {},
|
|
198
|
+
)
|
|
199
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
200
|
+
return SpiderWebError(status, "unknown", raw[:200].decode("utf-8", "replace"))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _retry_after(value: Optional[str]) -> Optional[float]:
|
|
204
|
+
try:
|
|
205
|
+
return max(0.0, float(value)) if value is not None else None
|
|
206
|
+
except ValueError:
|
|
207
|
+
return None
|
spiderweb/models.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Customer-facing models. They mirror schemas/openapi.yaml `Job` and `LogsResponse`.
|
|
2
|
+
|
|
3
|
+
There is deliberately no node, host, provider, or IP field: customer surfaces never
|
|
4
|
+
expose node identity. Unknown keys in a server response are dropped, so a field
|
|
5
|
+
added to the wire format cannot leak into these models by accident.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
13
|
+
|
|
14
|
+
# These are the terminal states exposed by the customer API. In particular,
|
|
15
|
+
# lost and preempted are terminal too: callers must not poll forever when a node
|
|
16
|
+
# disappears or the scheduler reclaims a job.
|
|
17
|
+
TERMINAL_STATUSES = frozenset({
|
|
18
|
+
"succeeded", "failed", "cancelled", "lost", "preempted",
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _pick(cls: type, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
23
|
+
names = {f.name for f in dataclasses.fields(cls)}
|
|
24
|
+
return {k: v for k, v in data.items() if k in names}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Job:
|
|
29
|
+
id: str
|
|
30
|
+
status: str
|
|
31
|
+
image: str
|
|
32
|
+
# class is a Python keyword; the wire name is "class".
|
|
33
|
+
job_class: str = ""
|
|
34
|
+
image_digest: Optional[str] = None
|
|
35
|
+
cpu: int = 0
|
|
36
|
+
ram_mb: int = 0
|
|
37
|
+
arch: Optional[str] = None
|
|
38
|
+
region: Optional[str] = None
|
|
39
|
+
network: str = "none"
|
|
40
|
+
timeout_s: int = 0
|
|
41
|
+
priority: str = "normal"
|
|
42
|
+
trust: str = ""
|
|
43
|
+
attempt: int = 0
|
|
44
|
+
emulated: bool = False
|
|
45
|
+
exit_code: Optional[int] = None
|
|
46
|
+
failure_reason: Optional[str] = None
|
|
47
|
+
estimated_cost_micros: int = 0
|
|
48
|
+
running_cost_micros: int = 0
|
|
49
|
+
created_at: Optional[str] = None
|
|
50
|
+
started_at: Optional[str] = None
|
|
51
|
+
finished_at: Optional[str] = None
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_api(cls, data: Dict[str, Any]) -> "Job":
|
|
55
|
+
d = dict(data)
|
|
56
|
+
if "class" in d:
|
|
57
|
+
d["job_class"] = d.pop("class")
|
|
58
|
+
return cls(**_pick(cls, d))
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def done(self) -> bool:
|
|
62
|
+
return self.status in TERMINAL_STATUSES
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class LogChunk:
|
|
67
|
+
seq: int
|
|
68
|
+
text: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class LogPage:
|
|
73
|
+
chunks: List[LogChunk] = field(default_factory=list)
|
|
74
|
+
next_seq: int = 0
|
|
75
|
+
status: str = ""
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def from_api(cls, data: Dict[str, Any]) -> "LogPage":
|
|
79
|
+
chunks = [LogChunk(seq=int(c.get("seq", 0)), text=str(c.get("text", ""))) for c in data.get("chunks") or []]
|
|
80
|
+
return cls(chunks=chunks, next_seq=int(data.get("next_seq", 0)), status=str(data.get("status", "")))
|
spiderweb/remote.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Run Python functions as SpiderWeb jobs, inline from your code.
|
|
2
|
+
|
|
3
|
+
from spiderweb import Client
|
|
4
|
+
from spiderweb.remote import configure, remote
|
|
5
|
+
|
|
6
|
+
configure(Client("https://spw.example", "spw_..."))
|
|
7
|
+
|
|
8
|
+
@remote(cpu=2)
|
|
9
|
+
def square(x):
|
|
10
|
+
return x * x
|
|
11
|
+
|
|
12
|
+
square(7) # runs as a job, returns 49
|
|
13
|
+
square.local(7) # runs here
|
|
14
|
+
|
|
15
|
+
How it works: the function and its arguments are uploaded as a job input
|
|
16
|
+
artifact, a small bootstrap runs them in a `python:X.Y-slim` image matching
|
|
17
|
+
your interpreter, and the result comes back as an output artifact.
|
|
18
|
+
|
|
19
|
+
* Results are JSON by default (tuples come back as lists). `result="pickle"`
|
|
20
|
+
returns any picklable value, but ONLY with `trust_hosts=True`: unpickling
|
|
21
|
+
runs code, and the host that runs the job can write any pickle it likes, so
|
|
22
|
+
a pickle result gives that host code execution on YOUR machine. The pickle
|
|
23
|
+
is HMAC-SHA256 signed with a per-call key passed to the job as a project
|
|
24
|
+
secret; the job (and so the host) can read that key, so the signature only
|
|
25
|
+
protects against tampering in storage or transit, never against the host.
|
|
26
|
+
The secret is deleted when the call finishes.
|
|
27
|
+
* Without extras, the function is shipped as source: it must be a plain
|
|
28
|
+
top-level function that does its imports inside its body, and its arguments
|
|
29
|
+
must be JSON. `pip install 'spiderweb-sdk[remote]'` adds cloudpickle, which ships
|
|
30
|
+
closures and arbitrary arguments (the job image then needs cloudpickle too).
|
|
31
|
+
* The job's Python minor version must match yours, or the call fails fast with
|
|
32
|
+
`python_version_mismatch`.
|
|
33
|
+
|
|
34
|
+
WARNING: your code and arguments run on third-party hosts. Never pass secrets
|
|
35
|
+
as arguments; use project secrets.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import ast
|
|
41
|
+
import base64
|
|
42
|
+
import functools
|
|
43
|
+
import hashlib
|
|
44
|
+
import hmac
|
|
45
|
+
import inspect
|
|
46
|
+
import json
|
|
47
|
+
import pickle
|
|
48
|
+
import re
|
|
49
|
+
import secrets
|
|
50
|
+
import sys
|
|
51
|
+
import textwrap
|
|
52
|
+
from typing import Any, Callable, Dict, Optional
|
|
53
|
+
|
|
54
|
+
from .client import Client, SpiderWebError
|
|
55
|
+
|
|
56
|
+
__all__ = ["RemoteError", "RemoteFunction", "configure", "remote", "run", "python_version", "PAYLOAD_VERSION"]
|
|
57
|
+
|
|
58
|
+
PAYLOAD_VERSION = 1
|
|
59
|
+
INPUT_PATH = "/work/in/payload.json"
|
|
60
|
+
OUTPUT_PATH = "/work/out/result.json"
|
|
61
|
+
RESULT_MODES = ("json", "pickle")
|
|
62
|
+
SERIALIZERS = ("auto", "source", "cloudpickle")
|
|
63
|
+
|
|
64
|
+
# The bootstrap always exits 0 after writing a result so the output is uploaded;
|
|
65
|
+
# the result envelope says whether the call worked.
|
|
66
|
+
BOOTSTRAP = r'''
|
|
67
|
+
import base64, hmac, json, os, pickle, sys, traceback
|
|
68
|
+
P = json.load(open(%r))
|
|
69
|
+
def emit(o):
|
|
70
|
+
os.makedirs(os.path.dirname(%r), exist_ok=True)
|
|
71
|
+
with open(%r, "w") as f:
|
|
72
|
+
json.dump(o, f)
|
|
73
|
+
have = "%%d.%%d" %% sys.version_info[:2]
|
|
74
|
+
if P.get("v") != %d:
|
|
75
|
+
emit({"ok": False, "error": {"code": "payload_version_unsupported", "message": "payload version %%r" %% P.get("v")}}); sys.exit(0)
|
|
76
|
+
if P["python"] != have:
|
|
77
|
+
emit({"ok": False, "error": {"code": "python_version_mismatch", "message": "the job runs Python %%s but the caller uses Python %%s" %% (have, P["python"])}}); sys.exit(0)
|
|
78
|
+
try:
|
|
79
|
+
if P["mode"] == "source":
|
|
80
|
+
g = {"__name__": "__spw_remote__"}
|
|
81
|
+
exec(compile(P["source"], "<spw-remote>", "exec"), g)
|
|
82
|
+
f, a, k = g[P["name"]], P["args"], P["kwargs"]
|
|
83
|
+
else:
|
|
84
|
+
import cloudpickle
|
|
85
|
+
f, a, k = pickle.loads(base64.b64decode(P["pickled"]))
|
|
86
|
+
v = f(*a, **k)
|
|
87
|
+
except BaseException as e:
|
|
88
|
+
emit({"ok": False, "error": {"code": "remote_exception", "type": type(e).__name__, "message": str(e)[:4000], "traceback": traceback.format_exc()[-8000:]}}); sys.exit(0)
|
|
89
|
+
if P["result"] == "pickle":
|
|
90
|
+
raw = pickle.dumps(v)
|
|
91
|
+
key = os.environ.get(P["key_env"], "").encode()
|
|
92
|
+
emit({"ok": True, "pickle": base64.b64encode(raw).decode(), "mac": hmac.new(key, raw, "sha256").hexdigest()})
|
|
93
|
+
else:
|
|
94
|
+
try:
|
|
95
|
+
emit({"ok": True, "value": json.loads(json.dumps(v))})
|
|
96
|
+
except (TypeError, ValueError) as e:
|
|
97
|
+
emit({"ok": False, "error": {"code": "result_not_json", "message": "the result is not JSON (%%s); use result=\"pickle\"" %% e}})
|
|
98
|
+
''' % (INPUT_PATH, OUTPUT_PATH, OUTPUT_PATH, PAYLOAD_VERSION)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class RemoteError(SpiderWebError):
|
|
102
|
+
"""A remote call failed. `code` is one of python_version_mismatch, remote_exception,
|
|
103
|
+
result_not_json, result_missing, result_mac_invalid, remote_unsupported_function,
|
|
104
|
+
cloudpickle_missing, not_configured, job_failed, payload_version_unsupported."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, code: str, message: str, details: Optional[dict] = None):
|
|
107
|
+
super().__init__(0, code, message, details)
|
|
108
|
+
self.remote_type = (details or {}).get("type", "")
|
|
109
|
+
self.remote_traceback = (details or {}).get("traceback", "")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def python_version() -> str:
|
|
113
|
+
return "%d.%d" % sys.version_info[:2]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
_defaults: Dict[str, Any] = {"client": None, "project_id": None}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def configure(client: Optional[Client] = None, *, project_id: Optional[str] = None) -> None:
|
|
120
|
+
"""Set the Client (and optionally the project) remote calls use by default."""
|
|
121
|
+
_defaults["client"] = client
|
|
122
|
+
_defaults["project_id"] = project_id
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _cloudpickle():
|
|
126
|
+
try:
|
|
127
|
+
import cloudpickle # noqa: F401 (optional extra)
|
|
128
|
+
except ImportError:
|
|
129
|
+
raise RemoteError("cloudpickle_missing",
|
|
130
|
+
"this function needs cloudpickle: pip install 'spiderweb-sdk[remote]'") from None
|
|
131
|
+
return cloudpickle
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _function_source(fn: Callable) -> str:
|
|
135
|
+
"""Top-level function source with its decorators removed."""
|
|
136
|
+
try:
|
|
137
|
+
src = textwrap.dedent(inspect.getsource(fn))
|
|
138
|
+
except (OSError, TypeError) as e:
|
|
139
|
+
raise RemoteError("remote_unsupported_function", f"cannot read the source of {fn!r}: {e}") from None
|
|
140
|
+
tree = ast.parse(src)
|
|
141
|
+
node = tree.body[0] if tree.body else None
|
|
142
|
+
if not isinstance(node, ast.FunctionDef) or node.name != fn.__name__:
|
|
143
|
+
raise RemoteError("remote_unsupported_function", f"{fn.__qualname__} is not a plain def")
|
|
144
|
+
node.decorator_list = []
|
|
145
|
+
return ast.unparse(node) + "\n"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _source_supported(fn: Callable) -> Optional[str]:
|
|
149
|
+
if not inspect.isfunction(fn) or fn.__name__ == "<lambda>":
|
|
150
|
+
return "only plain def functions can be shipped as source"
|
|
151
|
+
if fn.__code__.co_freevars:
|
|
152
|
+
return "closures cannot be shipped as source"
|
|
153
|
+
if "<locals>" in fn.__qualname__:
|
|
154
|
+
return "nested functions cannot be shipped as source"
|
|
155
|
+
if inspect.iscoroutinefunction(fn) or inspect.isgeneratorfunction(fn):
|
|
156
|
+
return "async and generator functions cannot run remotely"
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def build_payload(fn: Callable, args: tuple, kwargs: dict, *, result: str = "json",
|
|
161
|
+
serializer: str = "auto", key_env: str = "") -> bytes:
|
|
162
|
+
"""The job input for one call. Exposed for tests and for inspecting what is uploaded."""
|
|
163
|
+
if result not in RESULT_MODES:
|
|
164
|
+
raise ValueError(f"result must be one of {RESULT_MODES}")
|
|
165
|
+
if serializer not in SERIALIZERS:
|
|
166
|
+
raise ValueError(f"serializer must be one of {SERIALIZERS}")
|
|
167
|
+
fn = getattr(fn, "__wrapped__", fn)
|
|
168
|
+
body: Dict[str, Any] = {"v": PAYLOAD_VERSION, "python": python_version(), "result": result, "key_env": key_env}
|
|
169
|
+
problem = _source_supported(fn)
|
|
170
|
+
use_source = serializer == "source" or (serializer == "auto" and problem is None)
|
|
171
|
+
if use_source:
|
|
172
|
+
if problem:
|
|
173
|
+
raise RemoteError("remote_unsupported_function", f"{problem}; install 'spiderweb[remote]' and use serializer=\"cloudpickle\"")
|
|
174
|
+
try:
|
|
175
|
+
json_args = json.loads(json.dumps([list(args), kwargs]))
|
|
176
|
+
except (TypeError, ValueError):
|
|
177
|
+
if serializer == "source":
|
|
178
|
+
raise RemoteError("remote_unsupported_function", "arguments must be JSON when shipped as source") from None
|
|
179
|
+
use_source = False
|
|
180
|
+
else:
|
|
181
|
+
body.update(mode="source", name=fn.__name__, source=_function_source(fn), args=json_args[0], kwargs=json_args[1])
|
|
182
|
+
if not use_source:
|
|
183
|
+
cp = _cloudpickle()
|
|
184
|
+
body.update(mode="cloudpickle", pickled=base64.b64encode(cp.dumps((fn, tuple(args), dict(kwargs)))).decode())
|
|
185
|
+
return json.dumps(body).encode()
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def check_image(image: str) -> None:
|
|
189
|
+
"""Fail before submitting when a python:X.Y image cannot match this interpreter."""
|
|
190
|
+
m = re.match(r"^(?:.*/)?python:(\d+\.\d+)(?:[.\-:@]|$)", image)
|
|
191
|
+
if m and m.group(1) != python_version():
|
|
192
|
+
raise RemoteError("python_version_mismatch",
|
|
193
|
+
f"image {image} runs Python {m.group(1)} but this interpreter is Python {python_version()}")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def decode_result(raw: bytes, *, result: str, key: str = "", trust_hosts: bool = False) -> Any:
|
|
197
|
+
"""Verify and decode a result envelope written by the bootstrap. A pickle
|
|
198
|
+
result is refused unless trust_hosts=True (unpickling host output runs code)."""
|
|
199
|
+
try:
|
|
200
|
+
env = json.loads(raw)
|
|
201
|
+
except ValueError:
|
|
202
|
+
raise RemoteError("result_missing", "the job wrote an unreadable result") from None
|
|
203
|
+
if not isinstance(env, dict):
|
|
204
|
+
raise RemoteError("result_missing", "the job wrote an unreadable result")
|
|
205
|
+
if not env.get("ok"):
|
|
206
|
+
err = env.get("error") if isinstance(env.get("error"), dict) else {}
|
|
207
|
+
code = str(err.get("code") or "remote_exception")
|
|
208
|
+
msg = str(err.get("message") or "the remote call failed")
|
|
209
|
+
if err.get("type"):
|
|
210
|
+
msg = f"{err['type']}: {msg}"
|
|
211
|
+
raise RemoteError(code, msg, err)
|
|
212
|
+
if result == "pickle":
|
|
213
|
+
if not trust_hosts:
|
|
214
|
+
raise RemoteError("pickle_requires_trust_hosts",
|
|
215
|
+
"refusing to unpickle a host-produced result; pass trust_hosts=True only if you trust every host")
|
|
216
|
+
try:
|
|
217
|
+
data = base64.b64decode(env["pickle"], validate=True)
|
|
218
|
+
mac = str(env["mac"])
|
|
219
|
+
except (KeyError, ValueError, TypeError):
|
|
220
|
+
raise RemoteError("result_mac_invalid", "the pickled result is malformed") from None
|
|
221
|
+
want = hmac.new(key.encode(), data, hashlib.sha256).hexdigest()
|
|
222
|
+
# The job can read the key, so this MAC only rules out storage/transit
|
|
223
|
+
# tampering; the executing host is trusted because trust_hosts=True.
|
|
224
|
+
if not key or not hmac.compare_digest(want, mac):
|
|
225
|
+
raise RemoteError("result_mac_invalid", "the pickled result failed HMAC verification")
|
|
226
|
+
return pickle.loads(data) # noqa: S301 - caller opted in with trust_hosts=True
|
|
227
|
+
if "value" not in env:
|
|
228
|
+
raise RemoteError("result_missing", "the result has no value")
|
|
229
|
+
return env["value"]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class _Call:
|
|
233
|
+
"""One remote call's plan. Shared by the sync and async paths."""
|
|
234
|
+
|
|
235
|
+
def __init__(self, client: Client, project_id: str, fn: Callable, args: tuple, kwargs: dict, opts: Dict[str, Any]):
|
|
236
|
+
self.client, self.project_id = client, project_id
|
|
237
|
+
self.result = opts.get("result", "json")
|
|
238
|
+
self.trust_hosts = bool(opts.get("trust_hosts", False))
|
|
239
|
+
check_result_mode(self.result, self.trust_hosts)
|
|
240
|
+
self.tag = secrets.token_hex(8)
|
|
241
|
+
self.key = secrets.token_hex(32) if self.result == "pickle" else ""
|
|
242
|
+
self.key_env = f"SPW_REMOTE_KEY_{self.tag.upper()}" if self.key else ""
|
|
243
|
+
self.payload = build_payload(fn, args, kwargs, result=self.result,
|
|
244
|
+
serializer=opts.get("serializer", "auto"), key_env=self.key_env)
|
|
245
|
+
self.image = opts.get("image") or f"python:{python_version()}-slim"
|
|
246
|
+
check_image(self.image)
|
|
247
|
+
self.timeout = float(opts.get("timeout", 600.0))
|
|
248
|
+
self.job_options = {k: v for k, v in opts.items()
|
|
249
|
+
if k not in ("result", "serializer", "image", "timeout", "client", "project_id", "trust_hosts")
|
|
250
|
+
and v is not None}
|
|
251
|
+
self.in_name = f"spw-remote-{self.tag}"
|
|
252
|
+
self.out_name = f"spw-remote-{self.tag}-result"
|
|
253
|
+
self.job_id = ""
|
|
254
|
+
|
|
255
|
+
def start(self) -> str:
|
|
256
|
+
self.client.upload_artifact(self.project_id, self.in_name, self.payload)
|
|
257
|
+
body = dict(self.job_options)
|
|
258
|
+
body.update(project_id=self.project_id,
|
|
259
|
+
inputs=[{"artifact": self.in_name, "path": INPUT_PATH}],
|
|
260
|
+
outputs=[{"path": OUTPUT_PATH, "artifact": self.out_name}])
|
|
261
|
+
if self.key:
|
|
262
|
+
self.client.put_secret(self.project_id, self.key_env, self.key)
|
|
263
|
+
body["secrets"] = list(body.get("secrets") or []) + [self.key_env]
|
|
264
|
+
self.job_id = self.client.run(self.image, ["python", "-c", BOOTSTRAP], **body).id
|
|
265
|
+
return self.job_id
|
|
266
|
+
|
|
267
|
+
def finish(self, job) -> Any:
|
|
268
|
+
art = self.client.find_artifact(self.project_id, self.out_name)
|
|
269
|
+
if art is None:
|
|
270
|
+
if job.status != "succeeded":
|
|
271
|
+
raise RemoteError("job_failed", f"job {job.id} ended {job.status}"
|
|
272
|
+
+ (f": {job.failure_reason}" if job.failure_reason else ""),
|
|
273
|
+
{"job_id": job.id, "status": job.status})
|
|
274
|
+
raise RemoteError("result_missing", f"job {job.id} wrote no result", {"job_id": job.id})
|
|
275
|
+
return decode_result(self.client.download_artifact(art), result=self.result, key=self.key,
|
|
276
|
+
trust_hosts=self.trust_hosts)
|
|
277
|
+
|
|
278
|
+
def abort(self) -> None:
|
|
279
|
+
"""Cancel the job after a timeout or interrupt so it stops running and billing."""
|
|
280
|
+
if self.job_id:
|
|
281
|
+
try:
|
|
282
|
+
self.client.cancel(self.job_id)
|
|
283
|
+
except SpiderWebError:
|
|
284
|
+
pass
|
|
285
|
+
|
|
286
|
+
def cleanup(self) -> None:
|
|
287
|
+
if self.key:
|
|
288
|
+
try:
|
|
289
|
+
self.client.delete_secret(self.project_id, self.key_env)
|
|
290
|
+
except SpiderWebError:
|
|
291
|
+
pass
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def check_result_mode(result: str, trust_hosts: bool) -> None:
|
|
295
|
+
if result not in RESULT_MODES:
|
|
296
|
+
raise ValueError(f"result must be one of {RESULT_MODES}")
|
|
297
|
+
if result == "pickle" and not trust_hosts:
|
|
298
|
+
raise RemoteError("pickle_requires_trust_hosts",
|
|
299
|
+
'result="pickle" lets the host run code on this machine; '
|
|
300
|
+
"pass trust_hosts=True only if you trust every host")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _resolve(opts: Dict[str, Any]):
|
|
304
|
+
client = opts.get("client") or _defaults["client"]
|
|
305
|
+
if client is None:
|
|
306
|
+
raise RemoteError("not_configured", "call spiderweb.remote.configure(Client(...)) or pass client=")
|
|
307
|
+
inner = getattr(client, "_c", client) # accept an AsyncClient too
|
|
308
|
+
project_id = opts.get("project_id") or _defaults["project_id"] or inner.default_project_id()
|
|
309
|
+
return inner, project_id
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _run_with(fn: Callable, args: tuple, kwargs: dict, opts: Dict[str, Any]) -> Any:
|
|
313
|
+
client, project_id = _resolve(opts)
|
|
314
|
+
call = _Call(client, project_id, fn, args, kwargs, opts)
|
|
315
|
+
try:
|
|
316
|
+
try:
|
|
317
|
+
job = client.wait(call.start(), timeout=call.timeout)
|
|
318
|
+
except BaseException:
|
|
319
|
+
call.abort()
|
|
320
|
+
raise
|
|
321
|
+
return call.finish(job)
|
|
322
|
+
finally:
|
|
323
|
+
call.cleanup()
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class RemoteFunction:
|
|
327
|
+
"""A function wrapped by @remote. Calling it runs it as a job; `.local` runs it here."""
|
|
328
|
+
|
|
329
|
+
def __init__(self, fn: Callable, opts: Dict[str, Any]):
|
|
330
|
+
functools.update_wrapper(self, fn)
|
|
331
|
+
self.__wrapped__ = fn
|
|
332
|
+
self.options = dict(opts)
|
|
333
|
+
|
|
334
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
335
|
+
return _run_with(self.__wrapped__, args, kwargs, self.options)
|
|
336
|
+
|
|
337
|
+
def local(self, *args: Any, **kwargs: Any) -> Any:
|
|
338
|
+
return self.__wrapped__(*args, **kwargs)
|
|
339
|
+
|
|
340
|
+
async def aio(self, *args: Any, **kwargs: Any) -> Any:
|
|
341
|
+
from .aio import run_remote
|
|
342
|
+
return await run_remote(self.__wrapped__, args, kwargs, self.options)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def remote(fn: Optional[Callable] = None, *, cpu: Optional[int] = None, job_class: Optional[str] = None,
|
|
346
|
+
ram_mb: Optional[int] = None, image: Optional[str] = None, result: str = "json",
|
|
347
|
+
serializer: str = "auto", timeout: float = 600.0, client: Optional[Client] = None,
|
|
348
|
+
project_id: Optional[str] = None, trust_hosts: bool = False, **job_options: Any):
|
|
349
|
+
"""Decorator: `@remote` or `@remote(cpu=2, job_class=..., result="pickle", trust_hosts=True)`.
|
|
350
|
+
Extra keyword arguments are SubmitJobRequest fields (env, network, ...).
|
|
351
|
+
UNSAFE: result="pickle" requires trust_hosts=True, because the host that
|
|
352
|
+
runs the job can make the unpickle run arbitrary code on this machine."""
|
|
353
|
+
check_result_mode(result, trust_hosts)
|
|
354
|
+
if serializer not in SERIALIZERS:
|
|
355
|
+
raise ValueError(f"serializer must be one of {SERIALIZERS}")
|
|
356
|
+
if cpu is not None and job_class is not None:
|
|
357
|
+
raise ValueError("pass cpu or job_class, not both")
|
|
358
|
+
opts = dict(job_options, cpu=cpu, job_class=job_class, ram_mb=ram_mb, image=image, result=result,
|
|
359
|
+
serializer=serializer, timeout=timeout, client=client, project_id=project_id,
|
|
360
|
+
trust_hosts=trust_hosts)
|
|
361
|
+
if fn is not None:
|
|
362
|
+
return RemoteFunction(fn, opts)
|
|
363
|
+
return lambda f: RemoteFunction(f, opts)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def run(fn: Callable, *args: Any, **kwargs: Any) -> Any:
|
|
367
|
+
"""Run `fn(*args, **kwargs)` as a job and return its result. A @remote function
|
|
368
|
+
keeps its options; a plain function runs with the defaults."""
|
|
369
|
+
if isinstance(fn, RemoteFunction):
|
|
370
|
+
return fn(*args, **kwargs)
|
|
371
|
+
return _run_with(fn, args, kwargs, {"result": "json", "serializer": "auto"})
|
spiderweb/toolkit.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Helpers for marketplace tools written in Python.
|
|
2
|
+
|
|
3
|
+
`spw <publisher.tool>` runs an installed tool with its context in the
|
|
4
|
+
environment. These helpers read it; they mirror the helper `spw tool init
|
|
5
|
+
--template python` vendors, so a tool can use either.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
12
|
+
|
|
13
|
+
from .client import Client
|
|
14
|
+
|
|
15
|
+
__all__ = ["token", "context", "permissions", "client"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def token(env: Optional[Mapping[str, str]] = None) -> Optional[str]:
|
|
19
|
+
"""This run's SpiderWeb token, or None when the tool has no SpiderWeb permission."""
|
|
20
|
+
env = os.environ if env is None else env
|
|
21
|
+
return env.get("SPW_TOOL_TOKEN") or None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def permissions(env: Optional[Mapping[str, str]] = None) -> List[str]:
|
|
25
|
+
"""The permissions the user consented to at install time."""
|
|
26
|
+
env = os.environ if env is None else env
|
|
27
|
+
return [p for p in env.get("SPW_TOOL_PERMISSIONS", "").split(",") if p]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def context(env: Optional[Mapping[str, str]] = None) -> Dict[str, Any]:
|
|
31
|
+
"""Name, version, install dir, server URL and permissions of the running tool."""
|
|
32
|
+
env = os.environ if env is None else env
|
|
33
|
+
return {
|
|
34
|
+
"name": env.get("SPW_TOOL_NAME", ""),
|
|
35
|
+
"version": env.get("SPW_TOOL_VERSION", ""),
|
|
36
|
+
"dir": env.get("SPW_TOOL_DIR", ""),
|
|
37
|
+
"server": env.get("SPW_SERVER", ""),
|
|
38
|
+
"permissions": permissions(env),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def client(env: Optional[Mapping[str, str]] = None, **kwargs: Any) -> Client:
|
|
43
|
+
"""A Client for the tool's server and token. It raises when the tool was not
|
|
44
|
+
granted a SpiderWeb permission, since then there is no token to use."""
|
|
45
|
+
env = os.environ if env is None else env
|
|
46
|
+
tok, server = token(env), env.get("SPW_SERVER", "")
|
|
47
|
+
if not tok or not server:
|
|
48
|
+
raise RuntimeError("this tool has no SpiderWeb token: add jobs:write to its manifest permissions "
|
|
49
|
+
"and reinstall with --accept-permissions")
|
|
50
|
+
return Client(server, tok, **kwargs)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: spiderweb-sdk
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Python SDK for the SpiderWeb job coordinator: submit jobs and run Python functions remotely
|
|
5
|
+
Author: SpiderWeb
|
|
6
|
+
License: Proprietary
|
|
7
|
+
Keywords: spiderweb,spiderweb-sdk,jobs,distributed,compute,remote
|
|
8
|
+
Classifier: License :: Other/Proprietary License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Provides-Extra: remote
|
|
22
|
+
Requires-Dist: cloudpickle>=2.2; extra == "remote"
|
|
23
|
+
|
|
24
|
+
# spiderweb-sdk
|
|
25
|
+
|
|
26
|
+
The Python SDK for the SpiderWeb job coordinator. It submits container jobs,
|
|
27
|
+
follows their logs, and runs Python functions as jobs inline from your code.
|
|
28
|
+
Install `spiderweb-sdk`; import `spiderweb`.
|
|
29
|
+
|
|
30
|
+
The SpiderWeb beta coordinator is `https://spiderweb-fallback.taileaa8f0.ts.net`,
|
|
31
|
+
available as `spiderweb.DEFAULT_COORDINATOR`.
|
|
32
|
+
|
|
33
|
+
The core package uses only the Python standard library (Python 3.9+).
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
pip install spiderweb-sdk # client only, no dependencies
|
|
37
|
+
pip install 'spiderweb-sdk[remote]' # adds cloudpickle for closures and arbitrary arguments
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Jobs
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from spiderweb import Client, DEFAULT_COORDINATOR
|
|
44
|
+
|
|
45
|
+
client = Client(DEFAULT_COORDINATOR, "spw_YOUR_API_KEY") # https://spiderweb-fallback.taileaa8f0.ts.net
|
|
46
|
+
job = client.run("alpine:3", ["echo", "hello"], job_class="cpu.m")
|
|
47
|
+
for chunk in client.logs(job.id):
|
|
48
|
+
print(chunk.text, end="")
|
|
49
|
+
print(client.wait(job.id).status)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`spiderweb.aio.AsyncClient` has the same methods as coroutines.
|
|
53
|
+
|
|
54
|
+
## Run a function remotely
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from spiderweb import Client
|
|
58
|
+
from spiderweb.remote import configure, remote
|
|
59
|
+
|
|
60
|
+
configure(Client("https://spiderweb-fallback.taileaa8f0.ts.net", "spw_YOUR_API_KEY"))
|
|
61
|
+
|
|
62
|
+
@remote(cpu=2)
|
|
63
|
+
def total(values):
|
|
64
|
+
return sum(values)
|
|
65
|
+
|
|
66
|
+
print(total([1, 2, 3])) # runs as a job: 6
|
|
67
|
+
print(total.local([1, 2, 3])) # runs here
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- `spiderweb.remote.run(fn, *args)` runs an undecorated function the same way;
|
|
71
|
+
`await spiderweb.aio.run(fn, *args)` and `await total.aio(...)` are the async forms.
|
|
72
|
+
- Results are **JSON by default**. `@remote(result="pickle", trust_hosts=True)`
|
|
73
|
+
returns any picklable value. **This is unsafe**: unpickling runs code, and the
|
|
74
|
+
host that runs the job can return any pickle, so it gets code execution on your
|
|
75
|
+
machine. Without `trust_hosts=True` the call is refused
|
|
76
|
+
(`pickle_requires_trust_hosts`). The pickle carries a per-call HMAC, but the job
|
|
77
|
+
can read that key, so it only detects tampering in storage or transit, not by the host.
|
|
78
|
+
- If the wait times out or is interrupted, the job is cancelled and its key secret deleted.
|
|
79
|
+
- Without extras the function is shipped as source, so it must be a top-level `def`
|
|
80
|
+
that imports what it needs inside its body, with JSON arguments. With
|
|
81
|
+
`spiderweb[remote]`, closures and other arguments are shipped with cloudpickle
|
|
82
|
+
(use a job image that has cloudpickle installed).
|
|
83
|
+
- The job image defaults to `python:X.Y-slim` for your interpreter's version. A
|
|
84
|
+
mismatched Python minor version fails fast with `python_version_mismatch`.
|
|
85
|
+
|
|
86
|
+
**Your code and arguments run on third-party hosts.** Do not pass credentials as
|
|
87
|
+
arguments; store them as project secrets.
|
|
88
|
+
|
|
89
|
+
## Errors
|
|
90
|
+
|
|
91
|
+
Every API error raises `spiderweb.SpiderWebError` with `status`, `code` and
|
|
92
|
+
`message`. Remote calls raise `spiderweb.remote.RemoteError` (a subclass), with codes
|
|
93
|
+
such as `remote_exception`, `result_not_json` and `python_version_mismatch`.
|
|
94
|
+
|
|
95
|
+
## Marketplace tools
|
|
96
|
+
|
|
97
|
+
`spiderweb.toolkit` reads the context `spw <publisher.tool>` passes to an installed
|
|
98
|
+
tool: `toolkit.token()`, `toolkit.context()` and `toolkit.client()`.
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
Proprietary. See the license terms published with SpiderWeb.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
spiderweb/__init__.py,sha256=YJQtzkb5fVyYd8t0B0lZfvPx_4l5AS8lc11i8h8tc3I,486
|
|
2
|
+
spiderweb/aio.py,sha256=ePsi6xnmwVdySBitEsek085PHCAp2OU72un8ZmDuf-g,3385
|
|
3
|
+
spiderweb/client.py,sha256=L3lE-628X_K_6bildRtMDPZyr7RnaZTaUyw6eViRDQA,9571
|
|
4
|
+
spiderweb/models.py,sha256=dcaVkIohWYOlA-Q64uqOEHgFxG37rF77cHOw61gwgrU,2450
|
|
5
|
+
spiderweb/remote.py,sha256=eLY0ZxnGa-ZwciLYBV7-C2VU7Tc1KkZkbWGiM4eNP70,17223
|
|
6
|
+
spiderweb/toolkit.py,sha256=PgD1QqyygSt826TVLMm3OmRhshAqu6hxYSLRwm9h3hs,1988
|
|
7
|
+
spiderweb_sdk-0.2.0.dist-info/METADATA,sha256=0S3MQ-ZBi632tKJdQRQmwktXjGJyq06HNWz1bIvEbz4,4108
|
|
8
|
+
spiderweb_sdk-0.2.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
9
|
+
spiderweb_sdk-0.2.0.dist-info/top_level.txt,sha256=wrn1tKO8PIfkcMSGH674ygh0H0FmfFffQ8qRFHmbe1Y,10
|
|
10
|
+
spiderweb_sdk-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
spiderweb
|