spiderweb-sdk 0.2.0__tar.gz

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.
@@ -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,79 @@
1
+ # spiderweb-sdk
2
+
3
+ The Python SDK for the SpiderWeb job coordinator. It submits container jobs,
4
+ follows their logs, and runs Python functions as jobs inline from your code.
5
+ Install `spiderweb-sdk`; import `spiderweb`.
6
+
7
+ The SpiderWeb beta coordinator is `https://spiderweb-fallback.taileaa8f0.ts.net`,
8
+ available as `spiderweb.DEFAULT_COORDINATOR`.
9
+
10
+ The core package uses only the Python standard library (Python 3.9+).
11
+
12
+ ```
13
+ pip install spiderweb-sdk # client only, no dependencies
14
+ pip install 'spiderweb-sdk[remote]' # adds cloudpickle for closures and arbitrary arguments
15
+ ```
16
+
17
+ ## Jobs
18
+
19
+ ```python
20
+ from spiderweb import Client, DEFAULT_COORDINATOR
21
+
22
+ client = Client(DEFAULT_COORDINATOR, "spw_YOUR_API_KEY") # https://spiderweb-fallback.taileaa8f0.ts.net
23
+ job = client.run("alpine:3", ["echo", "hello"], job_class="cpu.m")
24
+ for chunk in client.logs(job.id):
25
+ print(chunk.text, end="")
26
+ print(client.wait(job.id).status)
27
+ ```
28
+
29
+ `spiderweb.aio.AsyncClient` has the same methods as coroutines.
30
+
31
+ ## Run a function remotely
32
+
33
+ ```python
34
+ from spiderweb import Client
35
+ from spiderweb.remote import configure, remote
36
+
37
+ configure(Client("https://spiderweb-fallback.taileaa8f0.ts.net", "spw_YOUR_API_KEY"))
38
+
39
+ @remote(cpu=2)
40
+ def total(values):
41
+ return sum(values)
42
+
43
+ print(total([1, 2, 3])) # runs as a job: 6
44
+ print(total.local([1, 2, 3])) # runs here
45
+ ```
46
+
47
+ - `spiderweb.remote.run(fn, *args)` runs an undecorated function the same way;
48
+ `await spiderweb.aio.run(fn, *args)` and `await total.aio(...)` are the async forms.
49
+ - Results are **JSON by default**. `@remote(result="pickle", trust_hosts=True)`
50
+ returns any picklable value. **This is unsafe**: unpickling runs code, and the
51
+ host that runs the job can return any pickle, so it gets code execution on your
52
+ machine. Without `trust_hosts=True` the call is refused
53
+ (`pickle_requires_trust_hosts`). The pickle carries a per-call HMAC, but the job
54
+ can read that key, so it only detects tampering in storage or transit, not by the host.
55
+ - If the wait times out or is interrupted, the job is cancelled and its key secret deleted.
56
+ - Without extras the function is shipped as source, so it must be a top-level `def`
57
+ that imports what it needs inside its body, with JSON arguments. With
58
+ `spiderweb[remote]`, closures and other arguments are shipped with cloudpickle
59
+ (use a job image that has cloudpickle installed).
60
+ - The job image defaults to `python:X.Y-slim` for your interpreter's version. A
61
+ mismatched Python minor version fails fast with `python_version_mismatch`.
62
+
63
+ **Your code and arguments run on third-party hosts.** Do not pass credentials as
64
+ arguments; store them as project secrets.
65
+
66
+ ## Errors
67
+
68
+ Every API error raises `spiderweb.SpiderWebError` with `status`, `code` and
69
+ `message`. Remote calls raise `spiderweb.remote.RemoteError` (a subclass), with codes
70
+ such as `remote_exception`, `result_not_json` and `python_version_mismatch`.
71
+
72
+ ## Marketplace tools
73
+
74
+ `spiderweb.toolkit` reads the context `spw <publisher.tool>` passes to an installed
75
+ tool: `toolkit.token()`, `toolkit.context()` and `toolkit.client()`.
76
+
77
+ ## License
78
+
79
+ Proprietary. See the license terms published with SpiderWeb.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "spiderweb-sdk"
7
+ version = "0.2.0"
8
+ description = "Python SDK for the SpiderWeb job coordinator: submit jobs and run Python functions remotely"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ # Stdlib only. Extras below are optional and imported lazily.
12
+ dependencies = []
13
+ license = { text = "Proprietary" }
14
+ authors = [{ name = "SpiderWeb" }]
15
+ keywords = ["spiderweb", "spiderweb-sdk", "jobs", "distributed", "compute", "remote"]
16
+ classifiers = [
17
+ "License :: Other/Proprietary License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Operating System :: OS Independent",
26
+ "Intended Audience :: Developers",
27
+ "Topic :: System :: Distributed Computing",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ # Ship closures and arbitrary arguments with spiderweb.remote.
32
+ remote = ["cloudpickle>=2.2"]
33
+
34
+ [tool.setuptools]
35
+ packages = ["spiderweb"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"
@@ -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"})
@@ -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
@@ -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", "")))