crosswind-sandboxes 0.1.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.
- crosswind_sandboxes-0.1.0.dist-info/METADATA +63 -0
- crosswind_sandboxes-0.1.0.dist-info/RECORD +16 -0
- crosswind_sandboxes-0.1.0.dist-info/WHEEL +4 -0
- crosswind_sandboxes-0.1.0.dist-info/licenses/LICENSE-APACHE +201 -0
- sandboxes/__init__.py +64 -0
- sandboxes/_ffi.py +141 -0
- sandboxes/_shim.py +327 -0
- sandboxes/_sigv4.py +118 -0
- sandboxes/_streams.py +372 -0
- sandboxes/_utils.py +29 -0
- sandboxes/directory_backup.py +728 -0
- sandboxes/errors.py +189 -0
- sandboxes/files.py +661 -0
- sandboxes/py.typed +0 -0
- sandboxes/s3_gateway.py +584 -0
- sandboxes/s3_mount.py +839 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: crosswind-sandboxes
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cloudflare Sandbox SDK for Python Workers
|
|
5
|
+
Author: Viswa Marepalli
|
|
6
|
+
Author-email: Viswa Marepalli <reachvishm@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE-APACHE
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Project-URL: Source, https://github.com/justanotherbyte/crosswind/tree/main/sandboxes
|
|
11
|
+
Project-URL: Documentation, https://crosswind.viswa.space
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# crosswind-sandboxes
|
|
15
|
+
|
|
16
|
+
A Python port of [`@cloudflare/sandbox`](https://developers.cloudflare.com/sandbox/reference/) 1.0.3 for Python Workers. It has file operations, S3 mounts and directory backups for a running container. It installs as `crosswind-sandboxes` and imports as `sandboxes`.
|
|
17
|
+
|
|
18
|
+
The package has no Python dependencies. It calls `ctx.container` through the Pyodide FFI and runs the official `sandbox-shim` binary inside the container, speaking shim protocol version 1.
|
|
19
|
+
|
|
20
|
+
## Requirements
|
|
21
|
+
|
|
22
|
+
- The container image must contain `/usr/local/bin/sandbox-shim`, copied from `cloudflare/sandbox:<VERSION>`.
|
|
23
|
+
- The container must be running. No class starts, stops, or monitors it.
|
|
24
|
+
- `nodejs_compat` is not needed. Errno names come from a fixed table of Linux values.
|
|
25
|
+
|
|
26
|
+
## Example
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from sandboxes import DirectoryBackup, Files
|
|
30
|
+
from workers import DurableObject
|
|
31
|
+
|
|
32
|
+
# Export the gateways so ctx.exports can reach them.
|
|
33
|
+
from sandboxes import DirectoryBackupGateway, S3Gateway # noqa: F401
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Workspace(DurableObject):
|
|
37
|
+
async def snapshot(self) -> dict:
|
|
38
|
+
container = self.ctx.container
|
|
39
|
+
if not container.running:
|
|
40
|
+
container.start()
|
|
41
|
+
|
|
42
|
+
files = Files(container)
|
|
43
|
+
await files.write_file("/workspace/notes.txt", "hello")
|
|
44
|
+
entries = await files.read_directory("/workspace")
|
|
45
|
+
|
|
46
|
+
backups = DirectoryBackup(
|
|
47
|
+
container, self.ctx.exports.DirectoryBackupGateway, binding="BACKUPS"
|
|
48
|
+
)
|
|
49
|
+
record = await backups.backup("/workspace")
|
|
50
|
+
return {"entries": [entry.name for entry in entries], "record": record}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Differences from the TypeScript SDK
|
|
54
|
+
|
|
55
|
+
- Names use `snake_case`, and option objects become keyword-only arguments.
|
|
56
|
+
- `AbortSignal` becomes an `asyncio.Event` passed as `abort=`. Setting it raises `SandboxAbortError`. An event can't cross RPC, so cancellation works only inside the Durable Object.
|
|
57
|
+
- Invalid values raise `ValueError`, and values of the wrong type raise `TypeError`.
|
|
58
|
+
- Errors are exception classes under `SandboxError`, checked with `isinstance`. There is no `is()` helper.
|
|
59
|
+
- `stat()` returns a `SandboxFileStat` dataclass with an `int` size and UTC `datetime` times. File types use `snake_case`: `block_device` and `character_device`.
|
|
60
|
+
- `read_file()` returns a JS `Response`. A failure after the file opens errors the body with a JS `Error` whose `name` is the Python exception's class name.
|
|
61
|
+
- `DirectoryBackupRecord` is a `TypedDict` compatible with the JS SDK's records.
|
|
62
|
+
|
|
63
|
+
See [`sandbox-sdk-api.md`](sandbox-sdk-api.md) for the full API map.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
sandboxes/__init__.py,sha256=Er1vgNzqfllhrLY-3srIEIT1MHaqp14jaQIAdk-aLXM,1328
|
|
2
|
+
sandboxes/_ffi.py,sha256=1T9N5Ia04SE9qUCm3Eg95LGEhhAcGk3JM_-rVajT4Xo,4059
|
|
3
|
+
sandboxes/_shim.py,sha256=p-umjz198z_qT0gGLpU_PKZNM40KcTHx_jqkkXIaGgo,10259
|
|
4
|
+
sandboxes/_sigv4.py,sha256=5ep5h5DQ4YKjo380T4bV9zQhGI6mtND60WVrVngqzDc,3670
|
|
5
|
+
sandboxes/_streams.py,sha256=VazkZm5-CP0SULszNeGqYeUvrXjenq9yM19omrJY48k,12188
|
|
6
|
+
sandboxes/_utils.py,sha256=yMre9LxNDhW85JmKB-cEBXw1O9qTK6ZFbbmAsZlnriY,872
|
|
7
|
+
sandboxes/directory_backup.py,sha256=NRNitTVPbe_57O969od7-snF_2ZTKssKo3ph0LKxCzk,25039
|
|
8
|
+
sandboxes/errors.py,sha256=4FBD_Pi7IEBwa470oUCNoErfS2ieiCsqh_nF4H1u_wQ,5762
|
|
9
|
+
sandboxes/files.py,sha256=_CIWg3M0q05HXRKlkt1ha-DaHyBRnHbCcQyg_ti2Z8M,19658
|
|
10
|
+
sandboxes/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
sandboxes/s3_gateway.py,sha256=shMK6JN6JLpWlwvj2M-yWb5koaQxtnl0kAOHrX7yWLs,19029
|
|
12
|
+
sandboxes/s3_mount.py,sha256=KoODHHnsCq_oFLKqqYrWhaFza-rDNd5pAAaL7ZINEeU,27724
|
|
13
|
+
crosswind_sandboxes-0.1.0.dist-info/licenses/LICENSE-APACHE,sha256=_18arsrGE1ssQH7MeECC2gyZ2uEUXNFU4wUep-jm8q0,11337
|
|
14
|
+
crosswind_sandboxes-0.1.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
|
|
15
|
+
crosswind_sandboxes-0.1.0.dist-info/METADATA,sha256=l--B94PxChs_3a8KdNbV9ZR-OpENwg4xQivnP3vL97s,3010
|
|
16
|
+
crosswind_sandboxes-0.1.0.dist-info/RECORD,,
|
|
@@ -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 2026 Viswa M
|
|
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.
|
sandboxes/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Cloudflare Sandbox SDK for Python Workers."""
|
|
2
|
+
|
|
3
|
+
from .directory_backup import (
|
|
4
|
+
DirectoryBackup,
|
|
5
|
+
DirectoryBackupGateway,
|
|
6
|
+
DirectoryBackupRecord,
|
|
7
|
+
)
|
|
8
|
+
from .errors import (
|
|
9
|
+
SandboxAbortError,
|
|
10
|
+
SandboxBackupError,
|
|
11
|
+
SandboxError,
|
|
12
|
+
SandboxFileError,
|
|
13
|
+
SandboxProtocolError,
|
|
14
|
+
SandboxS3MountError,
|
|
15
|
+
)
|
|
16
|
+
from .files import (
|
|
17
|
+
FileContent,
|
|
18
|
+
Files,
|
|
19
|
+
SandboxDirectoryEntry,
|
|
20
|
+
SandboxFileStat,
|
|
21
|
+
SandboxFileType,
|
|
22
|
+
)
|
|
23
|
+
from .s3_gateway import S3Gateway
|
|
24
|
+
from .s3_mount import (
|
|
25
|
+
ProviderCredentials,
|
|
26
|
+
S3Credentials,
|
|
27
|
+
S3Mount,
|
|
28
|
+
S3MountAccess,
|
|
29
|
+
S3MountConfiguration,
|
|
30
|
+
S3MountInspection,
|
|
31
|
+
S3Source,
|
|
32
|
+
StaticCredentials,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = (
|
|
36
|
+
"DirectoryBackup",
|
|
37
|
+
"DirectoryBackupGateway",
|
|
38
|
+
"DirectoryBackupRecord",
|
|
39
|
+
"FileContent",
|
|
40
|
+
"Files",
|
|
41
|
+
"ProviderCredentials",
|
|
42
|
+
"S3Credentials",
|
|
43
|
+
"S3Gateway",
|
|
44
|
+
"S3Mount",
|
|
45
|
+
"S3MountAccess",
|
|
46
|
+
"S3MountConfiguration",
|
|
47
|
+
"S3MountInspection",
|
|
48
|
+
"S3Source",
|
|
49
|
+
"SandboxAbortError",
|
|
50
|
+
"SandboxBackupError",
|
|
51
|
+
"SandboxDirectoryEntry",
|
|
52
|
+
"SandboxError",
|
|
53
|
+
"SandboxFileError",
|
|
54
|
+
"SandboxFileStat",
|
|
55
|
+
"SandboxFileType",
|
|
56
|
+
"SandboxProtocolError",
|
|
57
|
+
"SandboxS3MountError",
|
|
58
|
+
"StaticCredentials",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
__title__ = "sandboxes"
|
|
62
|
+
__version__ = "0.1.0"
|
|
63
|
+
__license__ = "Apache-2.0"
|
|
64
|
+
__copyright__ = "Copyright 2026 Viswa M"
|
sandboxes/_ffi.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Helpers for crossing the Python/JavaScript boundary inside Pyodide.
|
|
3
|
+
|
|
4
|
+
This is the only module in the package that imports ``js`` or ``pyodide``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import js
|
|
11
|
+
from pyodide.ffi import create_once_callable, create_proxy, to_js
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
from pyodide.ffi import jsnull
|
|
15
|
+
except ImportError:
|
|
16
|
+
jsnull = None
|
|
17
|
+
|
|
18
|
+
__all__ = (
|
|
19
|
+
"abort_controller",
|
|
20
|
+
"fixed_length_stream",
|
|
21
|
+
"header_items",
|
|
22
|
+
"is_absent",
|
|
23
|
+
"is_bytes_chunk",
|
|
24
|
+
"is_readable_stream",
|
|
25
|
+
"js_fetch",
|
|
26
|
+
"json_response",
|
|
27
|
+
"readable_stream",
|
|
28
|
+
"response",
|
|
29
|
+
"to_bytes",
|
|
30
|
+
"to_js_error",
|
|
31
|
+
"to_js_object",
|
|
32
|
+
"to_py",
|
|
33
|
+
"to_uint8array",
|
|
34
|
+
"unwrap",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def to_js_object(value: Any) -> Any:
|
|
39
|
+
"""Convert dicts and lists into plain JavaScript objects and arrays."""
|
|
40
|
+
return to_js(value, dict_converter=js.Object.fromEntries)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def to_py(value: Any) -> Any:
|
|
44
|
+
"""Convert a JavaScript value into Python dicts, lists and scalars."""
|
|
45
|
+
return value.to_py() if hasattr(value, "to_py") else value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def unwrap(value: Any) -> Any:
|
|
49
|
+
"""The JavaScript object behind a Python ``workers`` wrapper, if any."""
|
|
50
|
+
# Runtime quirk: binding wrappers keep the JS object in ``_binding`` and
|
|
51
|
+
# forward unknown names to JS, so ``js_object`` would return a JS function.
|
|
52
|
+
binding = getattr(value, "_binding", None)
|
|
53
|
+
return binding if binding is not None else getattr(value, "js_object", value)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def is_absent(value: Any) -> bool:
|
|
57
|
+
return value is None or value is jsnull
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def to_bytes(chunk: Any) -> bytes:
|
|
61
|
+
"""Convert a ``Uint8Array`` read from a stream into ``bytes``."""
|
|
62
|
+
return bytes(chunk) if isinstance(chunk, bytes | bytearray) else chunk.to_bytes()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def to_uint8array(data: bytes) -> Any:
|
|
66
|
+
return to_js(data)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_bytes_chunk(chunk: Any) -> bool:
|
|
70
|
+
if isinstance(chunk, bytes | bytearray):
|
|
71
|
+
return True
|
|
72
|
+
return getattr(getattr(chunk, "constructor", None), "name", None) == "Uint8Array"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_readable_stream(value: Any) -> bool:
|
|
76
|
+
return callable(getattr(value, "getReader", None))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def header_items(headers: Any) -> list[tuple[str, str]]:
|
|
80
|
+
"""The name and value pairs of a JavaScript ``Headers``, names lowercase."""
|
|
81
|
+
return [(str(name).lower(), str(value)) for name, value in headers]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def abort_controller() -> Any:
|
|
85
|
+
return js.AbortController.new()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def to_js_error(error: BaseException) -> Any:
|
|
89
|
+
"""A JavaScript ``Error`` with the exception's class name and message."""
|
|
90
|
+
js_error = js.Error.new(str(error))
|
|
91
|
+
js_error.name = type(error).__name__
|
|
92
|
+
return js_error
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def readable_stream(
|
|
96
|
+
pull: Callable[[Any], Awaitable[bool]], cancel: Callable[[Any], None]
|
|
97
|
+
) -> Any:
|
|
98
|
+
"""
|
|
99
|
+
A ``ReadableStream`` that calls ``pull`` for each chunk it needs.
|
|
100
|
+
|
|
101
|
+
``pull`` returns ``True`` once it has closed or errored the stream. The
|
|
102
|
+
proxies are destroyed then, or after ``cancel``.
|
|
103
|
+
"""
|
|
104
|
+
proxies: list[Any] = []
|
|
105
|
+
|
|
106
|
+
def destroy() -> None:
|
|
107
|
+
for proxy in proxies:
|
|
108
|
+
proxy.destroy()
|
|
109
|
+
|
|
110
|
+
async def pull_once(controller: Any) -> None:
|
|
111
|
+
if await pull(controller):
|
|
112
|
+
js.queueMicrotask(create_once_callable(destroy))
|
|
113
|
+
|
|
114
|
+
def cancel_once(reason: Any) -> None:
|
|
115
|
+
try:
|
|
116
|
+
cancel(reason)
|
|
117
|
+
finally:
|
|
118
|
+
js.queueMicrotask(create_once_callable(destroy))
|
|
119
|
+
|
|
120
|
+
proxies.extend((create_proxy(pull_once), create_proxy(cancel_once)))
|
|
121
|
+
source = to_js_object({"pull": proxies[0], "cancel": proxies[1]})
|
|
122
|
+
return js.ReadableStream.new(source)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def response(body: Any = None, *, status: int = 200, headers: Any = None) -> Any:
|
|
126
|
+
init: dict[str, Any] = {"status": status}
|
|
127
|
+
if headers is not None:
|
|
128
|
+
init["headers"] = headers
|
|
129
|
+
return js.Response.new(body, to_js_object(init))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def json_response(value: Any) -> Any:
|
|
133
|
+
return js.Response.json(to_js_object(value))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def js_fetch(url: str, init: dict[str, Any]) -> Awaitable[Any]:
|
|
137
|
+
return js.fetch(url, to_js_object(init))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def fixed_length_stream(length: int) -> Any:
|
|
141
|
+
return js.FixedLengthStream.new(length)
|