scraperack 0.1.0a1__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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: scraperack
3
+ Version: 0.1.0a1
4
+ Summary: Python SDK for self-hosted ScrapeRack clusters
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/damadjan/scraperack
7
+ Project-URL: Issues, https://github.com/damadjan/scraperack/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: cloudpickle>=3
13
+ Requires-Dist: httpx>=0.27
14
+ Dynamic: license-file
15
+
16
+ # ScrapeRack SDK
17
+
18
+ Python client for submitting trusted Python functions to a self-hosted ScrapeRack cluster.
19
+
20
+ > ScrapeRack is alpha software. Use it on trusted infrastructure and expect breaking changes.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pip install scraperack
26
+ ```
27
+
28
+ ## Run a function
29
+
30
+ The environment must already exist on the cluster.
31
+
32
+ ```python
33
+ from scraperack import Cluster
34
+
35
+
36
+ def add(a, b):
37
+ return a + b
38
+
39
+
40
+ cluster = Cluster("http://controller:7070")
41
+ try:
42
+ execution = cluster.run("python", add, (2, 3))
43
+ result = cluster.wait(execution["id"])
44
+ print(result["result"]["value"]["data"])
45
+ finally:
46
+ cluster.close()
47
+ ```
48
+
49
+ Installation, cluster setup, and source code are available at [github.com/damadjan/scraperack](https://github.com/damadjan/scraperack).
@@ -0,0 +1,34 @@
1
+ # ScrapeRack SDK
2
+
3
+ Python client for submitting trusted Python functions to a self-hosted ScrapeRack cluster.
4
+
5
+ > ScrapeRack is alpha software. Use it on trusted infrastructure and expect breaking changes.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install scraperack
11
+ ```
12
+
13
+ ## Run a function
14
+
15
+ The environment must already exist on the cluster.
16
+
17
+ ```python
18
+ from scraperack import Cluster
19
+
20
+
21
+ def add(a, b):
22
+ return a + b
23
+
24
+
25
+ cluster = Cluster("http://controller:7070")
26
+ try:
27
+ execution = cluster.run("python", add, (2, 3))
28
+ result = cluster.wait(execution["id"])
29
+ print(result["result"]["value"]["data"])
30
+ finally:
31
+ cluster.close()
32
+ ```
33
+
34
+ Installation, cluster setup, and source code are available at [github.com/damadjan/scraperack](https://github.com/damadjan/scraperack).
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scraperack"
7
+ version = "0.1.0a1"
8
+ description = "Python SDK for self-hosted ScrapeRack clusters"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["cloudpickle>=3", "httpx>=0.27"]
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+ classifiers = ["Development Status :: 3 - Alpha"]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/damadjan/scraperack"
18
+ Issues = "https://github.com/damadjan/scraperack/issues"
19
+
20
+ [tool.setuptools.package-data]
21
+ scraperack = ["py.typed"]
@@ -0,0 +1,36 @@
1
+ from .client import AsyncCluster, Cluster
2
+ from .types import (
3
+ EncodedValue,
4
+ Environment,
5
+ Execution,
6
+ ExecutionOutput,
7
+ ExecutionStatus,
8
+ Image,
9
+ ImageView,
10
+ MicroVM,
11
+ Node,
12
+ NodeStatus,
13
+ Pool,
14
+ PortProtocol,
15
+ PortSpec,
16
+ PublishedPort,
17
+ )
18
+
19
+ __all__ = [
20
+ "AsyncCluster",
21
+ "Cluster",
22
+ "EncodedValue",
23
+ "Environment",
24
+ "Execution",
25
+ "ExecutionOutput",
26
+ "ExecutionStatus",
27
+ "Image",
28
+ "ImageView",
29
+ "MicroVM",
30
+ "Node",
31
+ "NodeStatus",
32
+ "Pool",
33
+ "PortProtocol",
34
+ "PortSpec",
35
+ "PublishedPort",
36
+ ]
@@ -0,0 +1,425 @@
1
+ import base64
2
+ import hashlib
3
+ from pathlib import Path
4
+ from typing import Any, Callable, Mapping, Sequence
5
+
6
+ import cloudpickle
7
+ import httpx
8
+
9
+ from .types import Environment, Execution, Image, ImageView, MicroVM, Node, Pool, PortSpec
10
+
11
+
12
+ def _payload(
13
+ function: Callable[..., Any], params: Sequence[Any]
14
+ ) -> dict[str, Any]:
15
+ data = cloudpickle.dumps(function)
16
+ return {
17
+ "encoding": "python-function",
18
+ "hash": hashlib.sha256(data).hexdigest(),
19
+ "function": base64.b64encode(data).decode(),
20
+ "params": base64.b64encode(cloudpickle.dumps(tuple(params))).decode(),
21
+ }
22
+
23
+
24
+ def _files(files: Mapping[str, str | Path]) -> dict[str, str]:
25
+ return {
26
+ name: base64.b64encode(Path(path).read_bytes()).decode()
27
+ for name, path in files.items()
28
+ }
29
+
30
+
31
+ class Cluster:
32
+ """Synchronous client for a Scraperack controller."""
33
+
34
+ def __init__(self, url: str = "http://127.0.0.1:7070") -> None:
35
+ """Connect to the controller at ``url``."""
36
+ self.client = httpx.Client(base_url=url.rstrip("/"))
37
+
38
+ def close(self) -> None:
39
+ """Close the underlying HTTP client."""
40
+ self.client.close()
41
+
42
+ def import_image(
43
+ self,
44
+ name: str,
45
+ reference: str,
46
+ username: str | None = None,
47
+ password: str | None = None,
48
+ kind: str | None = None,
49
+ ) -> Image:
50
+ """Import and convert a Docker image from a registry."""
51
+ return self._post("/v1/images/import", {
52
+ "name": name,
53
+ "reference": reference,
54
+ "username": username,
55
+ "password": password,
56
+ "kind": kind,
57
+ })
58
+
59
+ def images(self) -> list[ImageView]:
60
+ """Return all golden images and their distribution state."""
61
+ return self._get("/v1/images")
62
+
63
+ def delete_image(self, image: str) -> None:
64
+ """Delete an image by ID."""
65
+ self._delete(f"/v1/images/{image}")
66
+
67
+ def create_pool(
68
+ self,
69
+ name: str,
70
+ image: str,
71
+ cpu: int | float = 1,
72
+ memory_mib: int = 512,
73
+ disk_mib: int = 1024,
74
+ timeout: int = 300,
75
+ warm: int = 0,
76
+ max_instances: int | None = None,
77
+ idle_timeout: int = 30,
78
+ reuse: bool = True,
79
+ network: bool = False,
80
+ ports: Sequence[PortSpec] = (),
81
+ ) -> Pool:
82
+ """Create a pool with execution, concurrency, and idle-VM settings."""
83
+ return self._post("/v1/pools", {
84
+ "name": name,
85
+ "image": image,
86
+ "warm_instances": warm,
87
+ "max_instances": max_instances,
88
+ "cpu_millis": round(cpu * 1000),
89
+ "memory_mib": memory_mib,
90
+ "disk_mib": disk_mib,
91
+ "timeout_secs": timeout,
92
+ "idle_timeout_secs": idle_timeout,
93
+ "reuse": reuse,
94
+ "network": network,
95
+ "ports": ports,
96
+ })
97
+
98
+ def create_environment(
99
+ self,
100
+ name: str,
101
+ image: str,
102
+ packages: Sequence[str] = (),
103
+ cpu: int | float = 1,
104
+ memory_mib: int = 512,
105
+ disk_mib: int = 1024,
106
+ timeout: int = 300,
107
+ warm: int = 0,
108
+ max_instances: int | None = None,
109
+ idle_timeout: int = 30,
110
+ reuse: bool = True,
111
+ network: bool = True,
112
+ preload: Sequence[str] = (),
113
+ ) -> Environment:
114
+ """Create a cached Python execution environment."""
115
+ return self._post("/v1/environments", {
116
+ "name": name,
117
+ "image": image,
118
+ "packages": list(packages),
119
+ "preload": list(preload),
120
+ "warm_instances": warm,
121
+ "max_instances": max_instances,
122
+ "cpu_millis": round(cpu * 1000),
123
+ "memory_mib": memory_mib,
124
+ "disk_mib": disk_mib,
125
+ "timeout_secs": timeout,
126
+ "idle_timeout_secs": idle_timeout,
127
+ "reuse": reuse,
128
+ "network": network,
129
+ })
130
+
131
+ def environments(self) -> list[Environment]:
132
+ """Return Python execution environments and cache state."""
133
+ return self._get("/v1/environments")
134
+
135
+ def delete_environment(self, environment: str) -> None:
136
+ """Delete an inactive execution environment."""
137
+ self._delete(f"/v1/environments/{environment}")
138
+
139
+ def run(
140
+ self,
141
+ environment: str,
142
+ function: Callable[..., Any],
143
+ params: Sequence[Any] = (),
144
+ queue: bool = True,
145
+ ) -> Execution:
146
+ """Submit a Python function and its positional arguments."""
147
+ return self.submit(environment, _payload(function, params), queue)
148
+
149
+ def delete_pool(self, name: str) -> None:
150
+ """Delete an inactive pool."""
151
+ self._delete(f"/v1/pools/{name}")
152
+
153
+ def run_json(self, environment: str, payload: Any, queue: bool = True) -> Execution:
154
+ """Submit a JSON-compatible value as the execution payload."""
155
+ return self.submit(environment, {"encoding": "json", "data": payload}, queue)
156
+
157
+ def run_source(
158
+ self,
159
+ environment: str,
160
+ source: str,
161
+ params: Sequence[Any] = (),
162
+ queue: bool = True,
163
+ ) -> Execution:
164
+ """Submit Python source that defines ``main(...)``."""
165
+ return self.submit(environment, {
166
+ "encoding": "python-source",
167
+ "source": source,
168
+ "params": params,
169
+ }, queue)
170
+
171
+ def run_files(
172
+ self,
173
+ environment: str,
174
+ files: Mapping[str, str | Path],
175
+ command: str | Sequence[str],
176
+ queue: bool = True,
177
+ ) -> Execution:
178
+ """Upload files and run a command inside a temporary directory."""
179
+ return self.submit(environment, {
180
+ "encoding": "files",
181
+ "files": _files(files),
182
+ "command": command,
183
+ }, queue)
184
+
185
+ def submit(
186
+ self, environment: str, payload: Mapping[str, Any], queue: bool = True
187
+ ) -> Execution:
188
+ """Submit a raw execution payload."""
189
+ return self._post(
190
+ "/v1/executions",
191
+ {"environment": environment, "payload": payload, "queue": queue},
192
+ )
193
+
194
+ def execution(self, execution_id: str) -> Execution:
195
+ """Return one execution by ID."""
196
+ return self._get(f"/v1/executions/{execution_id}")
197
+
198
+ def wait(self, execution_id: str, interval: float = 0.1) -> Execution:
199
+ """Wait until an execution succeeds, fails, or times out."""
200
+ while True:
201
+ response = self.client.get(f"/v1/executions/{execution_id}/wait", timeout=None)
202
+ response.raise_for_status()
203
+ execution = response.json()
204
+ if execution["status"] in {"succeeded", "failed", "timed_out"}:
205
+ return execution
206
+
207
+ def nodes(self) -> list[Node]:
208
+ """Return all registered worker nodes."""
209
+ return self._get("/v1/nodes")
210
+
211
+ def vms(self) -> list[MicroVM]:
212
+ """Return live microVMs and their published ports."""
213
+ return self._get("/v1/vms")
214
+
215
+ def executions(self) -> list[Execution]:
216
+ """Return all executions."""
217
+ return self._get("/v1/executions")
218
+
219
+ def _get(self, path: str) -> Any:
220
+ response = self.client.get(path)
221
+ response.raise_for_status()
222
+ return response.json()
223
+
224
+ def _post(self, path: str, data: Mapping[str, Any]) -> Any:
225
+ response = self.client.post(path, json=data)
226
+ response.raise_for_status()
227
+ return response.json()
228
+
229
+ def _delete(self, path: str) -> None:
230
+ response = self.client.delete(path)
231
+ response.raise_for_status()
232
+
233
+
234
+ class AsyncCluster:
235
+ """Asynchronous client for a Scraperack controller."""
236
+
237
+ def __init__(self, url: str = "http://127.0.0.1:7070") -> None:
238
+ """Connect to the controller at ``url``."""
239
+ self.client = httpx.AsyncClient(base_url=url.rstrip("/"))
240
+
241
+ async def close(self) -> None:
242
+ """Close the underlying HTTP client."""
243
+ await self.client.aclose()
244
+
245
+ async def import_image(
246
+ self,
247
+ name: str,
248
+ reference: str,
249
+ username: str | None = None,
250
+ password: str | None = None,
251
+ kind: str | None = None,
252
+ ) -> Image:
253
+ """Import and convert a Docker image from a registry."""
254
+ return await self._post("/v1/images/import", {
255
+ "name": name,
256
+ "reference": reference,
257
+ "username": username,
258
+ "password": password,
259
+ "kind": kind,
260
+ })
261
+
262
+ async def create_pool(
263
+ self,
264
+ name: str,
265
+ image: str,
266
+ cpu: int | float = 1,
267
+ memory_mib: int = 512,
268
+ disk_mib: int = 1024,
269
+ timeout: int = 300,
270
+ warm: int = 0,
271
+ max_instances: int | None = None,
272
+ idle_timeout: int = 30,
273
+ reuse: bool = True,
274
+ network: bool = False,
275
+ ports: Sequence[PortSpec] = (),
276
+ ) -> Pool:
277
+ """Create a pool with execution, concurrency, and idle-VM settings."""
278
+ return await self._post("/v1/pools", {
279
+ "name": name,
280
+ "image": image,
281
+ "warm_instances": warm,
282
+ "max_instances": max_instances,
283
+ "cpu_millis": round(cpu * 1000),
284
+ "memory_mib": memory_mib,
285
+ "disk_mib": disk_mib,
286
+ "timeout_secs": timeout,
287
+ "idle_timeout_secs": idle_timeout,
288
+ "reuse": reuse,
289
+ "network": network,
290
+ "ports": ports,
291
+ })
292
+
293
+ async def create_environment(
294
+ self,
295
+ name: str,
296
+ image: str,
297
+ packages: Sequence[str] = (),
298
+ cpu: int | float = 1,
299
+ memory_mib: int = 512,
300
+ disk_mib: int = 1024,
301
+ timeout: int = 300,
302
+ warm: int = 0,
303
+ max_instances: int | None = None,
304
+ idle_timeout: int = 30,
305
+ reuse: bool = True,
306
+ network: bool = True,
307
+ preload: Sequence[str] = (),
308
+ ) -> Environment:
309
+ """Create a cached Python execution environment."""
310
+ return await self._post("/v1/environments", {
311
+ "name": name,
312
+ "image": image,
313
+ "packages": list(packages),
314
+ "preload": list(preload),
315
+ "warm_instances": warm,
316
+ "max_instances": max_instances,
317
+ "cpu_millis": round(cpu * 1000),
318
+ "memory_mib": memory_mib,
319
+ "disk_mib": disk_mib,
320
+ "timeout_secs": timeout,
321
+ "idle_timeout_secs": idle_timeout,
322
+ "reuse": reuse,
323
+ "network": network,
324
+ })
325
+
326
+ async def environments(self) -> list[Environment]:
327
+ """Return Python execution environments and cache state."""
328
+ return await self._get("/v1/environments")
329
+
330
+ async def delete_environment(self, environment: str) -> None:
331
+ """Delete an inactive execution environment."""
332
+ await self._delete(f"/v1/environments/{environment}")
333
+
334
+ async def delete_image(self, image: str) -> None:
335
+ """Delete an image by ID."""
336
+ await self._delete(f"/v1/images/{image}")
337
+
338
+ async def delete_pool(self, name: str) -> None:
339
+ """Delete an inactive pool."""
340
+ await self._delete(f"/v1/pools/{name}")
341
+
342
+ async def run(
343
+ self,
344
+ environment: str,
345
+ function: Callable[..., Any],
346
+ params: Sequence[Any] = (),
347
+ queue: bool = True,
348
+ ) -> Execution:
349
+ """Submit a Python function and its positional arguments."""
350
+ return await self.submit(environment, _payload(function, params), queue)
351
+
352
+ async def run_json(
353
+ self, environment: str, payload: Any, queue: bool = True
354
+ ) -> Execution:
355
+ """Submit a JSON-compatible value as the execution payload."""
356
+ return await self.submit(environment, {"encoding": "json", "data": payload}, queue)
357
+
358
+ async def run_source(
359
+ self,
360
+ environment: str,
361
+ source: str,
362
+ params: Sequence[Any] = (),
363
+ queue: bool = True,
364
+ ) -> Execution:
365
+ """Submit Python source that defines ``main(...)``."""
366
+ return await self.submit(environment, {
367
+ "encoding": "python-source",
368
+ "source": source,
369
+ "params": params,
370
+ }, queue)
371
+
372
+ async def run_files(
373
+ self,
374
+ environment: str,
375
+ files: Mapping[str, str | Path],
376
+ command: str | Sequence[str],
377
+ queue: bool = True,
378
+ ) -> Execution:
379
+ """Upload files and run a command inside a temporary directory."""
380
+ return await self.submit(environment, {
381
+ "encoding": "files",
382
+ "files": _files(files),
383
+ "command": command,
384
+ }, queue)
385
+
386
+ async def submit(
387
+ self, environment: str, payload: Mapping[str, Any], queue: bool = True
388
+ ) -> Execution:
389
+ """Submit a raw execution payload."""
390
+ return await self._post("/v1/executions", {
391
+ "environment": environment,
392
+ "payload": payload,
393
+ "queue": queue,
394
+ })
395
+
396
+ async def execution(self, execution_id: str) -> Execution:
397
+ """Return one execution by ID."""
398
+ return await self._get(f"/v1/executions/{execution_id}")
399
+
400
+ async def wait(self, execution_id: str, interval: float = 0.1) -> Execution:
401
+ """Wait until an execution succeeds, fails, or times out."""
402
+ while True:
403
+ response = await self.client.get(f"/v1/executions/{execution_id}/wait", timeout=None)
404
+ response.raise_for_status()
405
+ execution = response.json()
406
+ if execution["status"] in {"succeeded", "failed", "timed_out"}:
407
+ return execution
408
+
409
+ async def vms(self) -> list[MicroVM]:
410
+ """Return live microVMs and their published ports."""
411
+ return await self._get("/v1/vms")
412
+
413
+ async def _get(self, path: str) -> Any:
414
+ response = await self.client.get(path)
415
+ response.raise_for_status()
416
+ return response.json()
417
+
418
+ async def _post(self, path: str, data: Mapping[str, Any]) -> Any:
419
+ response = await self.client.post(path, json=data)
420
+ response.raise_for_status()
421
+ return response.json()
422
+
423
+ async def _delete(self, path: str) -> None:
424
+ response = await self.client.delete(path)
425
+ response.raise_for_status()
File without changes
@@ -0,0 +1,149 @@
1
+ from typing import Any, Literal, TypedDict
2
+
3
+
4
+ NodeStatus = Literal["syncing", "ready"]
5
+ PortProtocol = Literal["tcp", "udp"]
6
+ ExecutionStatus = Literal[
7
+ "queued", "assigned", "running", "succeeded", "failed", "timed_out"
8
+ ]
9
+
10
+
11
+ class Image(TypedDict):
12
+ id: str
13
+ name: str
14
+ sha256: str
15
+ size: int
16
+ compatible: bool
17
+ executor: str | None
18
+ kind: Literal["micro_vm", "runtime"]
19
+ docker_source: str | None
20
+
21
+
22
+ class ImageView(Image):
23
+ ready: bool
24
+
25
+
26
+ class Pool(TypedDict):
27
+ name: str
28
+ image: str
29
+ warm_instances: int
30
+ max_instances: int | None
31
+ cpu_millis: int
32
+ memory_mib: int
33
+ disk_mib: int
34
+ timeout_secs: int
35
+ idle_timeout_secs: int
36
+ reuse: bool
37
+ network: bool
38
+ ports: list["PortSpec"]
39
+ managed_by: str | None
40
+ environment: str | None
41
+ environment_artifact: str | None
42
+
43
+
44
+ class Environment(TypedDict):
45
+ id: str
46
+ name: str
47
+ image: str
48
+ packages: list[str]
49
+ preload: list[str]
50
+ artifact: str | None
51
+ sha256: str | None
52
+ size: int
53
+ pool: str
54
+ warm_instances: int
55
+ max_instances: int | None
56
+ cpu_millis: int
57
+ memory_mib: int
58
+ disk_mib: int
59
+ timeout_secs: int
60
+ idle_timeout_secs: int
61
+ reuse: bool
62
+ network: bool
63
+ ready: bool
64
+
65
+
66
+ class PortSpec(TypedDict):
67
+ name: str
68
+ guest_port: int
69
+ host_port: int | None
70
+ protocol: PortProtocol
71
+
72
+
73
+ class PublishedPort(TypedDict):
74
+ name: str
75
+ guest_port: int
76
+ host_port: int
77
+ protocol: PortProtocol
78
+
79
+
80
+ class MicroVM(TypedDict):
81
+ id: str
82
+ pool: str
83
+ status: Literal["idle", "running"]
84
+ execution: str | None
85
+ pid: int | None
86
+ cpu_millis: int
87
+ memory_mib: int
88
+ guest_ip: str | None
89
+ ports: list[PublishedPort]
90
+ node: str
91
+ node_name: str
92
+ node_address: str | None
93
+ last_seen_ms: int
94
+ environment: str | None
95
+
96
+
97
+ class Node(TypedDict):
98
+ id: str
99
+ name: str
100
+ cpu_millis: int
101
+ memory_mib: int
102
+ address: str | None
103
+ used_cpu_millis: int
104
+ used_memory_mib: int
105
+ images: list[str]
106
+ environments: list[str]
107
+ idle_instances: dict[str, int]
108
+ vms: list[MicroVM]
109
+ status: NodeStatus
110
+ last_seen_ms: int
111
+
112
+
113
+ class EncodedValue(TypedDict):
114
+ encoding: Literal["json", "cloudpickle"]
115
+ data: Any
116
+
117
+
118
+ class ExecutionOutput(TypedDict, total=False):
119
+ value: EncodedValue
120
+ stdout: str
121
+ stderr: str
122
+
123
+
124
+ class ExecutionMetricPoint(TypedDict):
125
+ elapsed_ms: int
126
+ cpu_percent: float
127
+ memory_percent: float
128
+
129
+
130
+ class ExecutionMetrics(TypedDict):
131
+ average_cpu_percent: float
132
+ average_memory_percent: float
133
+ peak_memory_percent: float
134
+ samples: list[ExecutionMetricPoint]
135
+
136
+
137
+ class Execution(TypedDict):
138
+ id: str
139
+ pool: str
140
+ node: str | None
141
+ status: ExecutionStatus
142
+ payload: Any
143
+ result: ExecutionOutput | None
144
+ error: str | None
145
+ created_at_ms: int
146
+ started_at_ms: int | None
147
+ finished_at_ms: int | None
148
+ environment: str | None
149
+ metrics: ExecutionMetrics | None
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: scraperack
3
+ Version: 0.1.0a1
4
+ Summary: Python SDK for self-hosted ScrapeRack clusters
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/damadjan/scraperack
7
+ Project-URL: Issues, https://github.com/damadjan/scraperack/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: cloudpickle>=3
13
+ Requires-Dist: httpx>=0.27
14
+ Dynamic: license-file
15
+
16
+ # ScrapeRack SDK
17
+
18
+ Python client for submitting trusted Python functions to a self-hosted ScrapeRack cluster.
19
+
20
+ > ScrapeRack is alpha software. Use it on trusted infrastructure and expect breaking changes.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pip install scraperack
26
+ ```
27
+
28
+ ## Run a function
29
+
30
+ The environment must already exist on the cluster.
31
+
32
+ ```python
33
+ from scraperack import Cluster
34
+
35
+
36
+ def add(a, b):
37
+ return a + b
38
+
39
+
40
+ cluster = Cluster("http://controller:7070")
41
+ try:
42
+ execution = cluster.run("python", add, (2, 3))
43
+ result = cluster.wait(execution["id"])
44
+ print(result["result"]["value"]["data"])
45
+ finally:
46
+ cluster.close()
47
+ ```
48
+
49
+ Installation, cluster setup, and source code are available at [github.com/damadjan/scraperack](https://github.com/damadjan/scraperack).
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ scraperack/__init__.py
5
+ scraperack/client.py
6
+ scraperack/py.typed
7
+ scraperack/types.py
8
+ scraperack.egg-info/PKG-INFO
9
+ scraperack.egg-info/SOURCES.txt
10
+ scraperack.egg-info/dependency_links.txt
11
+ scraperack.egg-info/requires.txt
12
+ scraperack.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ cloudpickle>=3
2
+ httpx>=0.27
@@ -0,0 +1 @@
1
+ scraperack
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+