sii-runfield 0.1.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.
- sii_runfield-0.1.0/PKG-INFO +130 -0
- sii_runfield-0.1.0/README.md +121 -0
- sii_runfield-0.1.0/pyproject.toml +16 -0
- sii_runfield-0.1.0/runfield/__init__.py +7 -0
- sii_runfield-0.1.0/runfield/archive.py +275 -0
- sii_runfield-0.1.0/runfield/client.py +348 -0
- sii_runfield-0.1.0/runfield/protocol.py +504 -0
- sii_runfield-0.1.0/runfield/proxy.py +581 -0
- sii_runfield-0.1.0/runfield/sandbox.py +954 -0
- sii_runfield-0.1.0/setup.cfg +4 -0
- sii_runfield-0.1.0/sii_runfield.egg-info/PKG-INFO +130 -0
- sii_runfield-0.1.0/sii_runfield.egg-info/SOURCES.txt +13 -0
- sii_runfield-0.1.0/sii_runfield.egg-info/dependency_links.txt +1 -0
- sii_runfield-0.1.0/sii_runfield.egg-info/requires.txt +1 -0
- sii_runfield-0.1.0/sii_runfield.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sii-runfield
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 通过 Runfield Controller API 与同机 UDS 加速代理统一管理 Sandbox 生命周期、执行与流式归档的异步 Python SDK
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: httpx<0.29,>=0.28
|
|
9
|
+
|
|
10
|
+
# Python Sandbox 异步 SDK(`sii-runfield`)
|
|
11
|
+
|
|
12
|
+
`sii-runfield`(导入包名 `runfield`)提供面向 `sandbox-lifecycle/v1alpha1` 的薄异步客户端 `SandboxClient` 与实例句柄 `Sandbox`,统一封装 Sandbox 创建/按身份获取/状态刷新/就绪等待/精确关闭(`create` / `get` / `refresh` / `wait_ready` / `close`)、异步命令两阶段或一体化执行与单条命令取消(`exec` / `get_execution` / `wait_execution` / `run_and_wait` / `cancel_execution`)、容器外只读路径探测(`stat`)以及流式未压缩 tar 归档传输(`upload_archive` / `download_archive`)。SDK 不直接管理计算节点、镜像存储或评测业务状态机。
|
|
13
|
+
|
|
14
|
+
要求 Python 3.11+ 与 httpx 0.28.x,纯 Python 实现零原生编译依赖。
|
|
15
|
+
|
|
16
|
+
## 传输模式、连接池与防串线握手
|
|
17
|
+
|
|
18
|
+
`SandboxClient` 在 UDS 代理模式与远端 HTTP(S) 直连模式下均在初始化时尝试将进程 `RLIMIT_NOFILE` 软上限提升至 `min(hard, 65536)`:当有效软上限 `>= 8192`(或无上限)时设置 `httpx.Limits(max_connections=None, max_keepalive_connections=256)` 解除连接池上限;当宿主/容器硬上限将 `RLIMIT_NOFILE` 限制在 `< 8192` 时,自动按文件描述符余量收敛 `max_connections = max(16, (soft_nofile - 32) // 2)` 并设置 `pool=None`,防止高并发直连或长等待触发 `EMFILE` 或过早 `PoolTimeout`:
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from runfield import ExecutionResult, SandboxClient, SandboxError
|
|
22
|
+
|
|
23
|
+
async def example(endpoint: str, image_digest_reference: str) -> None:
|
|
24
|
+
async with SandboxClient(endpoint=endpoint) as client:
|
|
25
|
+
sandbox = await client.create(
|
|
26
|
+
{
|
|
27
|
+
"backend": "container",
|
|
28
|
+
"image": image_digest_reference,
|
|
29
|
+
"resources": {
|
|
30
|
+
"cpu_millicores": 2000,
|
|
31
|
+
"memory_bytes": 2 * 1024**3,
|
|
32
|
+
"pids_limit": 256,
|
|
33
|
+
},
|
|
34
|
+
"lifecycle": {"ttl_seconds": 3600},
|
|
35
|
+
},
|
|
36
|
+
request_id="job-example-trial-0001",
|
|
37
|
+
wait_until="ready",
|
|
38
|
+
timeout_seconds=120,
|
|
39
|
+
)
|
|
40
|
+
try:
|
|
41
|
+
await sandbox.upload_archive("/workspace", "/path/to/input.tar")
|
|
42
|
+
res: ExecutionResult = await sandbox.run_and_wait(
|
|
43
|
+
["/bin/bash", "-lc", "pytest -q"],
|
|
44
|
+
working_directory="/workspace",
|
|
45
|
+
priority="normal",
|
|
46
|
+
cancel_on_disconnect=True,
|
|
47
|
+
timeout_seconds=300,
|
|
48
|
+
)
|
|
49
|
+
print(sandbox.sandbox_id, res.exit_code, len(res.stdout))
|
|
50
|
+
finally:
|
|
51
|
+
await sandbox.close(wait=True, timeout_seconds=120)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
可选关键字参数与环境变量解析优先级如下:
|
|
55
|
+
|
|
56
|
+
1. **显式同机 UDS 套接字**(传入 `proxy_socket=...` 或设置 `RUNFIELD_CLIENT_PROXY_SOCKET`,且 `proxy_mode != "direct"`):通过 `httpx.AsyncHTTPTransport(uds=...)` 连接已运行的同机伴生代理 `sandbox-client-proxy`;UDS 读超时设为无上限(`read=None`),完全由调用方 `timeout_seconds` 经 `asyncio.timeout` 控制长等待预算。
|
|
57
|
+
2. **远端 HTTP/HTTPS 直连**(`proxy_mode="direct"` 或 `RUNFIELD_CLIENT_PROXY_MODE="direct"`):直接访问 `endpoint`(短请求默认超时 15 秒,流式归档按单次 `timeout_seconds` 覆盖)。
|
|
58
|
+
3. **自动 / 按需拉起模式**(`proxy_mode in (None, "auto", "uds")` 且未指定显式 Socket):按 `proxy_binary` -> `RUNFIELD_CLIENT_PROXY_BIN` -> `PATH` 上的 `sandbox-client-proxy` 查找可执行文件。
|
|
59
|
+
- 若显式指定 `proxy_mode="uds"` 或提供了 `proxy_binary` / `RUNFIELD_CLIENT_PROXY_BIN` 但二进制缺失或不可执行,立即抛出 `FileNotFoundError`,绝不静默降级;
|
|
60
|
+
- 若 `proxy_mode` 为默认 `"auto"` 且 `PATH` 上未安装代理二进制,则平滑运行于远端直连模式;
|
|
61
|
+
- 找到二进制时,按 `(uid, canonical_endpoint, allow_insecure_http)` 计算确定性摘要,优先选用非 sticky 的 `$XDG_RUNTIME_DIR/runfield/client-proxy-<hash>.sock`(路径 `<= 100` 字节),否则落于私有 `0700` 目录 `/tmp/runfield-<uid>/client-proxy-<hash>.sock`;通过独立伴生锁 `<sock>.autospawn.lock`(与 Go 守护进程内部的 `<sock>.lock` 严格分离)执行非阻塞异步 `flock`,探活复用已有守护进程或拉起新守护进程(`--idle-timeout` 默认 `"5m"`,stderr 重定向至 `<sock>.stderr.log`)。
|
|
62
|
+
- 子进程回收与容器运行注意:存活的 Python 进程通过内部后台守护线程直接调用 `wait4` 回收自身拉起且已空闲退出的 `sandbox-client-proxy`(即使在无 init 的精简容器中也不会残留僵尸进程);但对于在 `--idle-timeout` 到期前即先行退出的短生命周期 CLI 脚本,若运行在容器内,建议配合标准容器 init 回收器(如 `--init` / `tini`)运行,或直接连接常驻 `RUNFIELD_CLIENT_PROXY_SOCKET`。
|
|
63
|
+
4. **强制防串线握手(`GET /v1alpha1/proxy/info`)**:任何 UDS 客户端(含显式 Socket 与自动拉起)在首次发送请求或进入 `async with` 时均强制核验代理返回的 `api_version`、规范化 `endpoint` 与 `allow_insecure_http`;任一不匹配立即抛出本地 `ValueError` 拒绝连接。
|
|
64
|
+
|
|
65
|
+
默认要求 HTTPS 并校验证书;受控内部明文验证须显式传 `allow_insecure_http=True`。客户端不使用环境代理,不跟随重定向,直连模式下不在每次 `create` 前追加健康预检。
|
|
66
|
+
|
|
67
|
+
## 生命周期、命令执行与流式归档语义
|
|
68
|
+
|
|
69
|
+
- **创建、就绪等待与精确关闭**:
|
|
70
|
+
- `request_id` 必填;`spec` 复用既有创建字段,`backend="container"` 继续只在客户端消费,`fullvm` 连同 guest 几何发送到服务端。`image` 必须为不可变 OCI digest reference;省略 `process` 时发送空对象,省略 `network_mode` 时使用 `none`,省略 `image_delivery` 时沿用服务端固定策略。未知字段明确拒绝。字段与限制以 `sandbox-lifecycle/v1alpha1` 公开生命周期契约为准。
|
|
71
|
+
- `create` 默认 `wait_until="ready"`,仅当 `state == "ready"` 且 `observation.reachable == True` 时返回;UDS 模式下内部拆分为 `POST /v1alpha1/sandboxes?wait_until=accepted` 与单次阻塞 `GET /v1alpha1/sandboxes/{id}?wait_until=ready`(零 Python 轮询睡眠),确保就绪等待超时或状态冲突时始终在 `SandboxError.sandbox` 上保留已受理句柄(`outcome_unknown=False`)。
|
|
72
|
+
- `Sandbox.record` 是最近观察的副本(`Sandbox.state` 返回当前状态字符串),不是实时状态。`await client.get(sandbox_id, *, timeout_seconds=15) -> Sandbox` 可按已知身份获取句柄;`await sandbox.refresh(*, timeout_seconds=15) -> Sandbox` 拉取单次最新快照并核验稳定身份;`wait_ready` 重新查询并等待;`close(wait=False)` 仅提交关闭,`close(wait=True)` 等待可达 `closed` 或无资源的 `create_failed`。
|
|
73
|
+
- **断连安全铁律**:关闭客户端、取消协程或等待超时均不隐式关闭远端 Sandbox;单对象 `close` 不触发节点 GC。
|
|
74
|
+
- **异步命令执行(两阶段与一体化)与单条取消**:
|
|
75
|
+
- `await sandbox.exec(argv, *, request_id=None, env=None, working_directory=None, output_limit_bytes=1 << 20, priority=None, timeout_seconds=30) -> dict`:校验参数后异步提交单条命令(`request_id=None` 时自动生成 UUID hex,显式传入时原样保留),返回深拷贝 `ExecutionRecord`。
|
|
76
|
+
- `await sandbox.get_execution(execution_id, *, timeout_seconds=15) -> dict`:单次只读查询指定 `execution_id` 的最新 `ExecutionRecord` 快照(失败时 `outcome_unknown=False`)。
|
|
77
|
+
- `await sandbox.wait_execution(execution_id, *, output_limit_bytes=1 << 20, include_output=True, cancel_on_disconnect=False, timeout_seconds=120) -> ExecutionResult`:等待已提交的 `execution_id` 进入终态并按需读取输出(`1 <= output_limit_bytes <= 16 MiB`,被服务端截断或超出 `output_limit_bytes` 时抛出 `SandboxError("resource_limit_exceeded", http_status=422, retryable=False)`)。UDS 模式下委托代理通过 `GET /v1alpha1/sandboxes/{id}/executions/{eid}?wait=true...` 批量聚合等待并内联返回 Base64 输出;直连模式下按 `0.2s` 周期轮询并分片读取。两阶段模式下默认 `cancel_on_disconnect=False`,仅当显式传 `True` 时在超时或协程取消时触发单命令取消(`outcome_unknown=False`)。
|
|
78
|
+
- `await sandbox.run_and_wait(..., include_output=True, cancel_on_disconnect=True, timeout_seconds=120) -> ExecutionResult`:UDS 模式下通过单次阻塞请求由代理聚合等待终态并内联返回 Base64 输出;直连模式下轮询终态并按 `<= 1 MiB` 分片拉取完整 `stdout`/`stderr`。当 `cancel_on_disconnect=True` 且发生本地超时或协程取消时,仅向该命令发送取消(绝不关闭所属 Sandbox)。
|
|
79
|
+
- `await sandbox.cancel_execution(execution_id, *, timeout_seconds=15) -> dict`:显式取消指定 `execution_id`。
|
|
80
|
+
- **容器外探测与流式 tar 归档**:
|
|
81
|
+
- `await sandbox.stat(path, *, timeout_seconds=None) -> dict`:容器外只读探测路径元数据,缺失路径返回 `exists=False`。
|
|
82
|
+
- `await sandbox.upload_archive(path, source, *, content_length=None, timeout_seconds=300) -> None`:支持 `bytes`/`memoryview`、宿主 tar 文件路径(按 `64 KiB` 分块流式读取,不整包读入内存)、二进制文件对象或带显式 `content_length` 的同步/异步字节迭代器;强制 `1 <= content_length <= 512 MiB` 且固定 `Content-Length` 头,**上传失败严禁任何自动重试**(`outcome_unknown=True`)。
|
|
83
|
+
- `await sandbox.download_archive(path, dest=None, *, max_bytes=None, timeout_seconds=300) -> bytes | int`:首字节前非 200 状态解码为 `SandboxError`;强制不超过协议 `512 MiB` 上限与可选流内阈值 `max_bytes`(正整数;流式接收中途一旦超出阈值即在写出溢出分片前立即中止,清理当前创建的本地目标文件并抛出 `SandboxError("resource_limit_exceeded", http_status=422, retryable=False)`,`outcome_unknown=False`),`dest=None` 返回 `bytes`,传入文件路径或可写二进制流对象时边收边写并返回写入字节数 `int`。
|
|
84
|
+
|
|
85
|
+
## 失败和原身份重试
|
|
86
|
+
|
|
87
|
+
本地参数错误抛出 `ValueError`;传输、协议、服务端和等待错误抛出 `SandboxError`。
|
|
88
|
+
错误保留 `code`、`request_id`、`http_status`、`retryable`,已知时带 `sandbox`、`sandbox_id`
|
|
89
|
+
与最近 `record`。错误消息只包含错误码,不复制服务端人读消息或请求中的敏感值。
|
|
90
|
+
|
|
91
|
+
提交结果无法核验时 `outcome_unknown=True`;不能据此判断未创建。已接受对象的等待超时保留句柄,
|
|
92
|
+
但不自动 close。SDK 不透明更换身份重试;调用方需要在服务端仍保留原请求记录时,以同一 `request_id` 和同一 `spec`
|
|
93
|
+
解析原结果。`retryable=true` 不表示允许更换身份、backend 或 owner,且非幂等 `upload_archive` 严禁自动重放。
|
|
94
|
+
|
|
95
|
+
**幂等恢复受服务端记录保留窗口限制。**Controller 删除终态 assignment 时也会删除 request-ID 索引,
|
|
96
|
+
之后同一请求可能创建新 Sandbox;服务端默认终态保留窗口为 180 秒,实际以目标集群部署配置为准。
|
|
97
|
+
长时间中断后的未知创建结果需要先核对原对象,不能把延迟重试当作无条件恢复。SDK 不修改服务端终态保留策略。
|
|
98
|
+
|
|
99
|
+
## 本地测试
|
|
100
|
+
|
|
101
|
+
在 Python 3.11+ 与 `httpx` 0.28.x 环境(若测试同机代理模式需同时安装 Go 工具链或提供 `sandbox-client-proxy`)中执行:
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
python3 -m unittest discover -s tests -v
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
测试套件通过本地模拟 Controller 与 `sandbox-client-proxy` 验证直连/UDS 双模一致性、响应丢失恢复、防串线握手、多协程并发 `flock` 自动拉起与空闲自退、有界流式归档以及 2,000 协程 UDS 挂起零额外线程/零 Python 轮询唤醒,不依赖远端集群。
|
|
108
|
+
|
|
109
|
+
## Docker/QEMU fullVM
|
|
110
|
+
|
|
111
|
+
在上例 `spec` 中使用以下字段,其余创建、等待、guest 命令执行和精确关闭接口相同:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
{
|
|
115
|
+
"backend": "fullvm",
|
|
116
|
+
"fullvm": {"vcpus": 2, "memory_bytes": 512 * 1024**2},
|
|
117
|
+
"image": image_digest_reference,
|
|
118
|
+
"resources": {"cpu_millicores": 2000, "memory_bytes": 1024**3, "pids_limit": 256},
|
|
119
|
+
"lifecycle": {"ttl_seconds": 3600},
|
|
120
|
+
"process": {"env": {"LANG": "C.UTF-8"}, "working_directory": "/"},
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`image` 是包含固定 QEMU、控制脚本和不可变 guest base 的 OCI 制品身份,仍走 EROFS lower 与
|
|
125
|
+
zero-layer Moby carrier。guest CPU 允许 1~16,内存允许 128MiB~1TiB 且按 MiB 对齐;固定 host
|
|
126
|
+
CPU 配额必须覆盖 guest vCPU 且不超过 16000 millicores,内存必须至少为 guest 内存加 256MiB。
|
|
127
|
+
禁止共享/无约束资源策略、bridge、非空启动 argv 和非 root 用户;`process.env/cwd` 为 guest exec 默认值。
|
|
128
|
+
Ready 额外确认 guest Linux、root、Python、QGA 和 KVM。`Sandbox.backend` 来自响应且纳入后续身份核验。
|
|
129
|
+
|
|
130
|
+
guest 命令执行可通过 `exec` / `run_and_wait` 调用生命周期 execution API;该 MVP 不支持容器外 `archive`/`stat` 传输、GUI 控制、工作区适配、快照或 guest 网络,不宣称外层 Toolkit 在 guest 内可用。
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Python Sandbox 异步 SDK(`sii-runfield`)
|
|
2
|
+
|
|
3
|
+
`sii-runfield`(导入包名 `runfield`)提供面向 `sandbox-lifecycle/v1alpha1` 的薄异步客户端 `SandboxClient` 与实例句柄 `Sandbox`,统一封装 Sandbox 创建/按身份获取/状态刷新/就绪等待/精确关闭(`create` / `get` / `refresh` / `wait_ready` / `close`)、异步命令两阶段或一体化执行与单条命令取消(`exec` / `get_execution` / `wait_execution` / `run_and_wait` / `cancel_execution`)、容器外只读路径探测(`stat`)以及流式未压缩 tar 归档传输(`upload_archive` / `download_archive`)。SDK 不直接管理计算节点、镜像存储或评测业务状态机。
|
|
4
|
+
|
|
5
|
+
要求 Python 3.11+ 与 httpx 0.28.x,纯 Python 实现零原生编译依赖。
|
|
6
|
+
|
|
7
|
+
## 传输模式、连接池与防串线握手
|
|
8
|
+
|
|
9
|
+
`SandboxClient` 在 UDS 代理模式与远端 HTTP(S) 直连模式下均在初始化时尝试将进程 `RLIMIT_NOFILE` 软上限提升至 `min(hard, 65536)`:当有效软上限 `>= 8192`(或无上限)时设置 `httpx.Limits(max_connections=None, max_keepalive_connections=256)` 解除连接池上限;当宿主/容器硬上限将 `RLIMIT_NOFILE` 限制在 `< 8192` 时,自动按文件描述符余量收敛 `max_connections = max(16, (soft_nofile - 32) // 2)` 并设置 `pool=None`,防止高并发直连或长等待触发 `EMFILE` 或过早 `PoolTimeout`:
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from runfield import ExecutionResult, SandboxClient, SandboxError
|
|
13
|
+
|
|
14
|
+
async def example(endpoint: str, image_digest_reference: str) -> None:
|
|
15
|
+
async with SandboxClient(endpoint=endpoint) as client:
|
|
16
|
+
sandbox = await client.create(
|
|
17
|
+
{
|
|
18
|
+
"backend": "container",
|
|
19
|
+
"image": image_digest_reference,
|
|
20
|
+
"resources": {
|
|
21
|
+
"cpu_millicores": 2000,
|
|
22
|
+
"memory_bytes": 2 * 1024**3,
|
|
23
|
+
"pids_limit": 256,
|
|
24
|
+
},
|
|
25
|
+
"lifecycle": {"ttl_seconds": 3600},
|
|
26
|
+
},
|
|
27
|
+
request_id="job-example-trial-0001",
|
|
28
|
+
wait_until="ready",
|
|
29
|
+
timeout_seconds=120,
|
|
30
|
+
)
|
|
31
|
+
try:
|
|
32
|
+
await sandbox.upload_archive("/workspace", "/path/to/input.tar")
|
|
33
|
+
res: ExecutionResult = await sandbox.run_and_wait(
|
|
34
|
+
["/bin/bash", "-lc", "pytest -q"],
|
|
35
|
+
working_directory="/workspace",
|
|
36
|
+
priority="normal",
|
|
37
|
+
cancel_on_disconnect=True,
|
|
38
|
+
timeout_seconds=300,
|
|
39
|
+
)
|
|
40
|
+
print(sandbox.sandbox_id, res.exit_code, len(res.stdout))
|
|
41
|
+
finally:
|
|
42
|
+
await sandbox.close(wait=True, timeout_seconds=120)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
可选关键字参数与环境变量解析优先级如下:
|
|
46
|
+
|
|
47
|
+
1. **显式同机 UDS 套接字**(传入 `proxy_socket=...` 或设置 `RUNFIELD_CLIENT_PROXY_SOCKET`,且 `proxy_mode != "direct"`):通过 `httpx.AsyncHTTPTransport(uds=...)` 连接已运行的同机伴生代理 `sandbox-client-proxy`;UDS 读超时设为无上限(`read=None`),完全由调用方 `timeout_seconds` 经 `asyncio.timeout` 控制长等待预算。
|
|
48
|
+
2. **远端 HTTP/HTTPS 直连**(`proxy_mode="direct"` 或 `RUNFIELD_CLIENT_PROXY_MODE="direct"`):直接访问 `endpoint`(短请求默认超时 15 秒,流式归档按单次 `timeout_seconds` 覆盖)。
|
|
49
|
+
3. **自动 / 按需拉起模式**(`proxy_mode in (None, "auto", "uds")` 且未指定显式 Socket):按 `proxy_binary` -> `RUNFIELD_CLIENT_PROXY_BIN` -> `PATH` 上的 `sandbox-client-proxy` 查找可执行文件。
|
|
50
|
+
- 若显式指定 `proxy_mode="uds"` 或提供了 `proxy_binary` / `RUNFIELD_CLIENT_PROXY_BIN` 但二进制缺失或不可执行,立即抛出 `FileNotFoundError`,绝不静默降级;
|
|
51
|
+
- 若 `proxy_mode` 为默认 `"auto"` 且 `PATH` 上未安装代理二进制,则平滑运行于远端直连模式;
|
|
52
|
+
- 找到二进制时,按 `(uid, canonical_endpoint, allow_insecure_http)` 计算确定性摘要,优先选用非 sticky 的 `$XDG_RUNTIME_DIR/runfield/client-proxy-<hash>.sock`(路径 `<= 100` 字节),否则落于私有 `0700` 目录 `/tmp/runfield-<uid>/client-proxy-<hash>.sock`;通过独立伴生锁 `<sock>.autospawn.lock`(与 Go 守护进程内部的 `<sock>.lock` 严格分离)执行非阻塞异步 `flock`,探活复用已有守护进程或拉起新守护进程(`--idle-timeout` 默认 `"5m"`,stderr 重定向至 `<sock>.stderr.log`)。
|
|
53
|
+
- 子进程回收与容器运行注意:存活的 Python 进程通过内部后台守护线程直接调用 `wait4` 回收自身拉起且已空闲退出的 `sandbox-client-proxy`(即使在无 init 的精简容器中也不会残留僵尸进程);但对于在 `--idle-timeout` 到期前即先行退出的短生命周期 CLI 脚本,若运行在容器内,建议配合标准容器 init 回收器(如 `--init` / `tini`)运行,或直接连接常驻 `RUNFIELD_CLIENT_PROXY_SOCKET`。
|
|
54
|
+
4. **强制防串线握手(`GET /v1alpha1/proxy/info`)**:任何 UDS 客户端(含显式 Socket 与自动拉起)在首次发送请求或进入 `async with` 时均强制核验代理返回的 `api_version`、规范化 `endpoint` 与 `allow_insecure_http`;任一不匹配立即抛出本地 `ValueError` 拒绝连接。
|
|
55
|
+
|
|
56
|
+
默认要求 HTTPS 并校验证书;受控内部明文验证须显式传 `allow_insecure_http=True`。客户端不使用环境代理,不跟随重定向,直连模式下不在每次 `create` 前追加健康预检。
|
|
57
|
+
|
|
58
|
+
## 生命周期、命令执行与流式归档语义
|
|
59
|
+
|
|
60
|
+
- **创建、就绪等待与精确关闭**:
|
|
61
|
+
- `request_id` 必填;`spec` 复用既有创建字段,`backend="container"` 继续只在客户端消费,`fullvm` 连同 guest 几何发送到服务端。`image` 必须为不可变 OCI digest reference;省略 `process` 时发送空对象,省略 `network_mode` 时使用 `none`,省略 `image_delivery` 时沿用服务端固定策略。未知字段明确拒绝。字段与限制以 `sandbox-lifecycle/v1alpha1` 公开生命周期契约为准。
|
|
62
|
+
- `create` 默认 `wait_until="ready"`,仅当 `state == "ready"` 且 `observation.reachable == True` 时返回;UDS 模式下内部拆分为 `POST /v1alpha1/sandboxes?wait_until=accepted` 与单次阻塞 `GET /v1alpha1/sandboxes/{id}?wait_until=ready`(零 Python 轮询睡眠),确保就绪等待超时或状态冲突时始终在 `SandboxError.sandbox` 上保留已受理句柄(`outcome_unknown=False`)。
|
|
63
|
+
- `Sandbox.record` 是最近观察的副本(`Sandbox.state` 返回当前状态字符串),不是实时状态。`await client.get(sandbox_id, *, timeout_seconds=15) -> Sandbox` 可按已知身份获取句柄;`await sandbox.refresh(*, timeout_seconds=15) -> Sandbox` 拉取单次最新快照并核验稳定身份;`wait_ready` 重新查询并等待;`close(wait=False)` 仅提交关闭,`close(wait=True)` 等待可达 `closed` 或无资源的 `create_failed`。
|
|
64
|
+
- **断连安全铁律**:关闭客户端、取消协程或等待超时均不隐式关闭远端 Sandbox;单对象 `close` 不触发节点 GC。
|
|
65
|
+
- **异步命令执行(两阶段与一体化)与单条取消**:
|
|
66
|
+
- `await sandbox.exec(argv, *, request_id=None, env=None, working_directory=None, output_limit_bytes=1 << 20, priority=None, timeout_seconds=30) -> dict`:校验参数后异步提交单条命令(`request_id=None` 时自动生成 UUID hex,显式传入时原样保留),返回深拷贝 `ExecutionRecord`。
|
|
67
|
+
- `await sandbox.get_execution(execution_id, *, timeout_seconds=15) -> dict`:单次只读查询指定 `execution_id` 的最新 `ExecutionRecord` 快照(失败时 `outcome_unknown=False`)。
|
|
68
|
+
- `await sandbox.wait_execution(execution_id, *, output_limit_bytes=1 << 20, include_output=True, cancel_on_disconnect=False, timeout_seconds=120) -> ExecutionResult`:等待已提交的 `execution_id` 进入终态并按需读取输出(`1 <= output_limit_bytes <= 16 MiB`,被服务端截断或超出 `output_limit_bytes` 时抛出 `SandboxError("resource_limit_exceeded", http_status=422, retryable=False)`)。UDS 模式下委托代理通过 `GET /v1alpha1/sandboxes/{id}/executions/{eid}?wait=true...` 批量聚合等待并内联返回 Base64 输出;直连模式下按 `0.2s` 周期轮询并分片读取。两阶段模式下默认 `cancel_on_disconnect=False`,仅当显式传 `True` 时在超时或协程取消时触发单命令取消(`outcome_unknown=False`)。
|
|
69
|
+
- `await sandbox.run_and_wait(..., include_output=True, cancel_on_disconnect=True, timeout_seconds=120) -> ExecutionResult`:UDS 模式下通过单次阻塞请求由代理聚合等待终态并内联返回 Base64 输出;直连模式下轮询终态并按 `<= 1 MiB` 分片拉取完整 `stdout`/`stderr`。当 `cancel_on_disconnect=True` 且发生本地超时或协程取消时,仅向该命令发送取消(绝不关闭所属 Sandbox)。
|
|
70
|
+
- `await sandbox.cancel_execution(execution_id, *, timeout_seconds=15) -> dict`:显式取消指定 `execution_id`。
|
|
71
|
+
- **容器外探测与流式 tar 归档**:
|
|
72
|
+
- `await sandbox.stat(path, *, timeout_seconds=None) -> dict`:容器外只读探测路径元数据,缺失路径返回 `exists=False`。
|
|
73
|
+
- `await sandbox.upload_archive(path, source, *, content_length=None, timeout_seconds=300) -> None`:支持 `bytes`/`memoryview`、宿主 tar 文件路径(按 `64 KiB` 分块流式读取,不整包读入内存)、二进制文件对象或带显式 `content_length` 的同步/异步字节迭代器;强制 `1 <= content_length <= 512 MiB` 且固定 `Content-Length` 头,**上传失败严禁任何自动重试**(`outcome_unknown=True`)。
|
|
74
|
+
- `await sandbox.download_archive(path, dest=None, *, max_bytes=None, timeout_seconds=300) -> bytes | int`:首字节前非 200 状态解码为 `SandboxError`;强制不超过协议 `512 MiB` 上限与可选流内阈值 `max_bytes`(正整数;流式接收中途一旦超出阈值即在写出溢出分片前立即中止,清理当前创建的本地目标文件并抛出 `SandboxError("resource_limit_exceeded", http_status=422, retryable=False)`,`outcome_unknown=False`),`dest=None` 返回 `bytes`,传入文件路径或可写二进制流对象时边收边写并返回写入字节数 `int`。
|
|
75
|
+
|
|
76
|
+
## 失败和原身份重试
|
|
77
|
+
|
|
78
|
+
本地参数错误抛出 `ValueError`;传输、协议、服务端和等待错误抛出 `SandboxError`。
|
|
79
|
+
错误保留 `code`、`request_id`、`http_status`、`retryable`,已知时带 `sandbox`、`sandbox_id`
|
|
80
|
+
与最近 `record`。错误消息只包含错误码,不复制服务端人读消息或请求中的敏感值。
|
|
81
|
+
|
|
82
|
+
提交结果无法核验时 `outcome_unknown=True`;不能据此判断未创建。已接受对象的等待超时保留句柄,
|
|
83
|
+
但不自动 close。SDK 不透明更换身份重试;调用方需要在服务端仍保留原请求记录时,以同一 `request_id` 和同一 `spec`
|
|
84
|
+
解析原结果。`retryable=true` 不表示允许更换身份、backend 或 owner,且非幂等 `upload_archive` 严禁自动重放。
|
|
85
|
+
|
|
86
|
+
**幂等恢复受服务端记录保留窗口限制。**Controller 删除终态 assignment 时也会删除 request-ID 索引,
|
|
87
|
+
之后同一请求可能创建新 Sandbox;服务端默认终态保留窗口为 180 秒,实际以目标集群部署配置为准。
|
|
88
|
+
长时间中断后的未知创建结果需要先核对原对象,不能把延迟重试当作无条件恢复。SDK 不修改服务端终态保留策略。
|
|
89
|
+
|
|
90
|
+
## 本地测试
|
|
91
|
+
|
|
92
|
+
在 Python 3.11+ 与 `httpx` 0.28.x 环境(若测试同机代理模式需同时安装 Go 工具链或提供 `sandbox-client-proxy`)中执行:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
python3 -m unittest discover -s tests -v
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
测试套件通过本地模拟 Controller 与 `sandbox-client-proxy` 验证直连/UDS 双模一致性、响应丢失恢复、防串线握手、多协程并发 `flock` 自动拉起与空闲自退、有界流式归档以及 2,000 协程 UDS 挂起零额外线程/零 Python 轮询唤醒,不依赖远端集群。
|
|
99
|
+
|
|
100
|
+
## Docker/QEMU fullVM
|
|
101
|
+
|
|
102
|
+
在上例 `spec` 中使用以下字段,其余创建、等待、guest 命令执行和精确关闭接口相同:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
{
|
|
106
|
+
"backend": "fullvm",
|
|
107
|
+
"fullvm": {"vcpus": 2, "memory_bytes": 512 * 1024**2},
|
|
108
|
+
"image": image_digest_reference,
|
|
109
|
+
"resources": {"cpu_millicores": 2000, "memory_bytes": 1024**3, "pids_limit": 256},
|
|
110
|
+
"lifecycle": {"ttl_seconds": 3600},
|
|
111
|
+
"process": {"env": {"LANG": "C.UTF-8"}, "working_directory": "/"},
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`image` 是包含固定 QEMU、控制脚本和不可变 guest base 的 OCI 制品身份,仍走 EROFS lower 与
|
|
116
|
+
zero-layer Moby carrier。guest CPU 允许 1~16,内存允许 128MiB~1TiB 且按 MiB 对齐;固定 host
|
|
117
|
+
CPU 配额必须覆盖 guest vCPU 且不超过 16000 millicores,内存必须至少为 guest 内存加 256MiB。
|
|
118
|
+
禁止共享/无约束资源策略、bridge、非空启动 argv 和非 root 用户;`process.env/cwd` 为 guest exec 默认值。
|
|
119
|
+
Ready 额外确认 guest Linux、root、Python、QGA 和 KVM。`Sandbox.backend` 来自响应且纳入后续身份核验。
|
|
120
|
+
|
|
121
|
+
guest 命令执行可通过 `exec` / `run_and_wait` 调用生命周期 execution API;该 MVP 不支持容器外 `archive`/`stat` 传输、GUI 控制、工作区适配、快照或 guest 网络,不宣称外层 Toolkit 在 guest 内可用。
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sii-runfield"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "通过 Runfield Controller API 与同机 UDS 加速代理统一管理 Sandbox 生命周期、执行与流式归档的异步 Python SDK"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = {text = "Apache-2.0"}
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = ["httpx>=0.28,<0.29"]
|
|
13
|
+
|
|
14
|
+
[tool.setuptools.packages.find]
|
|
15
|
+
where = ["."]
|
|
16
|
+
include = ["runfield*"]
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""封装容器外未压缩 tar 归档的零整包内存缓冲流式上传源适配与有界流式下载落盘辅助。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterable, Iterable
|
|
4
|
+
import inspect
|
|
5
|
+
import os
|
|
6
|
+
import stat
|
|
7
|
+
|
|
8
|
+
from .protocol import MAX_ARCHIVE_BYTES, SandboxError, decode_envelope
|
|
9
|
+
|
|
10
|
+
ARCHIVE_CHUNK_BYTES = 64 * 1024
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _validate_archive_content_length(length):
|
|
14
|
+
"""核验上传归档字节长度必须为 [1, 512 MiB] 闭区间内的精确整数。"""
|
|
15
|
+
if type(length) is not int or not (1 <= length <= MAX_ARCHIVE_BYTES):
|
|
16
|
+
raise ValueError(
|
|
17
|
+
f"archive content_length must be an integer in [1, {MAX_ARCHIVE_BYTES}]"
|
|
18
|
+
)
|
|
19
|
+
return length
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _coerce_chunk_bytes(chunk):
|
|
23
|
+
"""将归档流分片规范化为不可变 bytes;拒绝非字节缓冲对象。"""
|
|
24
|
+
if isinstance(chunk, bytes):
|
|
25
|
+
return chunk
|
|
26
|
+
if isinstance(chunk, (bytearray, memoryview)):
|
|
27
|
+
return bytes(chunk)
|
|
28
|
+
raise ValueError("archive stream chunks must be bytes-like objects")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def prepare_archive_upload(source, *, content_length=None):
|
|
32
|
+
"""校验归档输入源并构造固定 Content-Length 的 64 KiB 异步流;路径输入在迭代结束或取消时自动关闭内部文件句柄,调用方传入的文件对象仍归调用方关闭。"""
|
|
33
|
+
if content_length is not None:
|
|
34
|
+
_validate_archive_content_length(content_length)
|
|
35
|
+
|
|
36
|
+
if isinstance(source, (bytes, bytearray, memoryview)):
|
|
37
|
+
view = memoryview(source).cast("B")
|
|
38
|
+
total = len(view)
|
|
39
|
+
if content_length is not None and content_length != total:
|
|
40
|
+
raise ValueError("content_length does not match byte buffer length")
|
|
41
|
+
_validate_archive_content_length(total)
|
|
42
|
+
|
|
43
|
+
async def _iter_buffer():
|
|
44
|
+
for offset in range(0, total, ARCHIVE_CHUNK_BYTES):
|
|
45
|
+
yield bytes(view[offset : offset + ARCHIVE_CHUNK_BYTES])
|
|
46
|
+
|
|
47
|
+
return total, _iter_buffer()
|
|
48
|
+
|
|
49
|
+
if isinstance(source, (str, os.PathLike)):
|
|
50
|
+
fs_path = os.fspath(source)
|
|
51
|
+
st = os.stat(fs_path)
|
|
52
|
+
if not stat.S_ISREG(st.st_mode):
|
|
53
|
+
raise ValueError("archive source path must be a regular file")
|
|
54
|
+
file_size = st.st_size
|
|
55
|
+
if content_length is not None and content_length != file_size:
|
|
56
|
+
raise ValueError("content_length does not match archive file size")
|
|
57
|
+
_validate_archive_content_length(file_size)
|
|
58
|
+
|
|
59
|
+
async def _iter_file():
|
|
60
|
+
fh = open(fs_path, "rb")
|
|
61
|
+
sent = 0
|
|
62
|
+
try:
|
|
63
|
+
while sent < file_size:
|
|
64
|
+
to_read = min(ARCHIVE_CHUNK_BYTES, file_size - sent)
|
|
65
|
+
chunk = fh.read(to_read)
|
|
66
|
+
if not chunk:
|
|
67
|
+
raise ValueError("archive file truncated during upload")
|
|
68
|
+
sent += len(chunk)
|
|
69
|
+
yield chunk
|
|
70
|
+
finally:
|
|
71
|
+
fh.close()
|
|
72
|
+
|
|
73
|
+
return file_size, _iter_file()
|
|
74
|
+
|
|
75
|
+
read_fn = getattr(source, "read", None)
|
|
76
|
+
if callable(read_fn):
|
|
77
|
+
resolved_len = content_length
|
|
78
|
+
if resolved_len is None:
|
|
79
|
+
seekable_fn = getattr(source, "seekable", None)
|
|
80
|
+
tell_fn = getattr(source, "tell", None)
|
|
81
|
+
seek_fn = getattr(source, "seek", None)
|
|
82
|
+
if callable(seekable_fn) and callable(tell_fn) and callable(seek_fn) and seekable_fn():
|
|
83
|
+
cur = tell_fn()
|
|
84
|
+
seek_fn(0, os.SEEK_END)
|
|
85
|
+
end = tell_fn()
|
|
86
|
+
seek_fn(cur, os.SEEK_SET)
|
|
87
|
+
resolved_len = end - cur
|
|
88
|
+
else:
|
|
89
|
+
raise ValueError(
|
|
90
|
+
"content_length is required for non-seekable file-like archive source"
|
|
91
|
+
)
|
|
92
|
+
_validate_archive_content_length(resolved_len)
|
|
93
|
+
|
|
94
|
+
async def _iter_reader():
|
|
95
|
+
sent = 0
|
|
96
|
+
while sent < resolved_len:
|
|
97
|
+
to_read = min(ARCHIVE_CHUNK_BYTES, resolved_len - sent)
|
|
98
|
+
raw = read_fn(to_read)
|
|
99
|
+
if inspect.isawaitable(raw):
|
|
100
|
+
raw = await raw
|
|
101
|
+
chunk = _coerce_chunk_bytes(raw)
|
|
102
|
+
if not chunk:
|
|
103
|
+
raise ValueError(
|
|
104
|
+
f"archive file-like source ended at {sent} bytes (expected {resolved_len})"
|
|
105
|
+
)
|
|
106
|
+
sent += len(chunk)
|
|
107
|
+
yield chunk
|
|
108
|
+
|
|
109
|
+
return resolved_len, _iter_reader()
|
|
110
|
+
|
|
111
|
+
if isinstance(source, AsyncIterable):
|
|
112
|
+
if content_length is None:
|
|
113
|
+
raise ValueError("content_length is required for async iterable archive source")
|
|
114
|
+
|
|
115
|
+
async def _iter_async_iterable():
|
|
116
|
+
sent = 0
|
|
117
|
+
async for item in source:
|
|
118
|
+
chunk = _coerce_chunk_bytes(item)
|
|
119
|
+
if not chunk:
|
|
120
|
+
continue
|
|
121
|
+
sent += len(chunk)
|
|
122
|
+
if sent > content_length:
|
|
123
|
+
raise ValueError("async iterable archive source exceeded content_length")
|
|
124
|
+
yield chunk
|
|
125
|
+
if sent != content_length:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
f"async iterable archive source yielded {sent} bytes (expected {content_length})"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return content_length, _iter_async_iterable()
|
|
131
|
+
|
|
132
|
+
if isinstance(source, Iterable):
|
|
133
|
+
if content_length is None:
|
|
134
|
+
raise ValueError("content_length is required for iterable archive source")
|
|
135
|
+
|
|
136
|
+
async def _iter_sync_iterable():
|
|
137
|
+
sent = 0
|
|
138
|
+
for item in source:
|
|
139
|
+
chunk = _coerce_chunk_bytes(item)
|
|
140
|
+
if not chunk:
|
|
141
|
+
continue
|
|
142
|
+
sent += len(chunk)
|
|
143
|
+
if sent > content_length:
|
|
144
|
+
raise ValueError("iterable archive source exceeded content_length")
|
|
145
|
+
yield chunk
|
|
146
|
+
if sent != content_length:
|
|
147
|
+
raise ValueError(
|
|
148
|
+
f"iterable archive source yielded {sent} bytes (expected {content_length})"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
return content_length, _iter_sync_iterable()
|
|
152
|
+
|
|
153
|
+
raise ValueError(
|
|
154
|
+
"archive source must be bytes-like, a regular file path, a binary file-like object, or a bytes iterable"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def validate_archive_dest(dest):
|
|
159
|
+
"""在发起网络请求前校验下载目标类型(None、宿主文件路径或可写二进制流对象)。"""
|
|
160
|
+
if dest is None or isinstance(dest, (str, os.PathLike)):
|
|
161
|
+
if isinstance(dest, str) and (not dest or "\x00" in dest):
|
|
162
|
+
raise ValueError("invalid archive destination path")
|
|
163
|
+
return
|
|
164
|
+
write_fn = getattr(dest, "write", None)
|
|
165
|
+
if callable(write_fn):
|
|
166
|
+
return
|
|
167
|
+
raise ValueError(
|
|
168
|
+
"dest must be None, a filesystem path, or a writable binary file-like object"
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def validate_archive_max_bytes(max_bytes):
|
|
173
|
+
"""在发起请求前核验可选下载字节上限(None 或正整数,拒绝 bool),返回不超过 512 MiB 协议上限的有效阈值。"""
|
|
174
|
+
if max_bytes is None:
|
|
175
|
+
return MAX_ARCHIVE_BYTES
|
|
176
|
+
if type(max_bytes) is not int or max_bytes < 1:
|
|
177
|
+
raise ValueError("max_bytes must be a positive integer or None")
|
|
178
|
+
return min(max_bytes, MAX_ARCHIVE_BYTES)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
async def stream_archive_download(response, dest, *, max_error_bytes, max_bytes=None):
|
|
182
|
+
"""处理 GET /archive 响应:首字节前非 200 解码为 SandboxError;200 时在流内强制 <= min(max_bytes, 512 MiB) 并在溢出分片落盘前中止清理。"""
|
|
183
|
+
effective_max_bytes = validate_archive_max_bytes(max_bytes)
|
|
184
|
+
|
|
185
|
+
if response.status_code != 200:
|
|
186
|
+
err_buf = bytearray()
|
|
187
|
+
async for chunk in response.aiter_bytes():
|
|
188
|
+
err_buf.extend(chunk)
|
|
189
|
+
if len(err_buf) > max_error_bytes:
|
|
190
|
+
raise SandboxError(
|
|
191
|
+
"invalid_response", http_status=response.status_code
|
|
192
|
+
)
|
|
193
|
+
decode_envelope(
|
|
194
|
+
bytes(err_buf),
|
|
195
|
+
status_code=response.status_code,
|
|
196
|
+
expected_status=(200,),
|
|
197
|
+
result_key=None,
|
|
198
|
+
)
|
|
199
|
+
raise SandboxError("invalid_response", http_status=response.status_code)
|
|
200
|
+
|
|
201
|
+
raw_ct = response.headers.get("content-type", "")
|
|
202
|
+
if raw_ct:
|
|
203
|
+
media_type = raw_ct.split(";", 1)[0].strip().lower()
|
|
204
|
+
if media_type != "application/x-tar":
|
|
205
|
+
raise SandboxError("invalid_response", http_status=200)
|
|
206
|
+
|
|
207
|
+
raw_cl = response.headers.get("content-length")
|
|
208
|
+
if raw_cl is not None:
|
|
209
|
+
try:
|
|
210
|
+
parsed_cl = int(raw_cl)
|
|
211
|
+
except ValueError:
|
|
212
|
+
raise SandboxError("invalid_response", http_status=200) from None
|
|
213
|
+
if parsed_cl < 0:
|
|
214
|
+
raise SandboxError("invalid_response", http_status=200)
|
|
215
|
+
if parsed_cl > effective_max_bytes:
|
|
216
|
+
raise SandboxError(
|
|
217
|
+
"resource_limit_exceeded", http_status=422, retryable=False
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
if dest is None:
|
|
221
|
+
buf = bytearray()
|
|
222
|
+
async for chunk in response.aiter_bytes():
|
|
223
|
+
if not chunk:
|
|
224
|
+
continue
|
|
225
|
+
if len(buf) + len(chunk) > effective_max_bytes:
|
|
226
|
+
raise SandboxError(
|
|
227
|
+
"resource_limit_exceeded", http_status=422, retryable=False
|
|
228
|
+
)
|
|
229
|
+
buf.extend(chunk)
|
|
230
|
+
return bytes(buf)
|
|
231
|
+
|
|
232
|
+
if isinstance(dest, (str, os.PathLike)):
|
|
233
|
+
fs_path = os.fspath(dest)
|
|
234
|
+
written = 0
|
|
235
|
+
failed = False
|
|
236
|
+
try:
|
|
237
|
+
with open(fs_path, "wb") as fh:
|
|
238
|
+
async for chunk in response.aiter_bytes():
|
|
239
|
+
if not chunk:
|
|
240
|
+
continue
|
|
241
|
+
if written + len(chunk) > effective_max_bytes:
|
|
242
|
+
raise SandboxError(
|
|
243
|
+
"resource_limit_exceeded",
|
|
244
|
+
http_status=422,
|
|
245
|
+
retryable=False,
|
|
246
|
+
)
|
|
247
|
+
fh.write(chunk)
|
|
248
|
+
written += len(chunk)
|
|
249
|
+
except BaseException:
|
|
250
|
+
failed = True
|
|
251
|
+
raise
|
|
252
|
+
finally:
|
|
253
|
+
if failed:
|
|
254
|
+
try:
|
|
255
|
+
os.unlink(fs_path)
|
|
256
|
+
except FileNotFoundError:
|
|
257
|
+
pass
|
|
258
|
+
return written
|
|
259
|
+
|
|
260
|
+
write_fn = dest.write
|
|
261
|
+
written = 0
|
|
262
|
+
async for chunk in response.aiter_bytes():
|
|
263
|
+
if not chunk:
|
|
264
|
+
continue
|
|
265
|
+
if written + len(chunk) > effective_max_bytes:
|
|
266
|
+
raise SandboxError(
|
|
267
|
+
"resource_limit_exceeded", http_status=422, retryable=False
|
|
268
|
+
)
|
|
269
|
+
res = write_fn(chunk)
|
|
270
|
+
if inspect.isawaitable(res):
|
|
271
|
+
res = await res
|
|
272
|
+
if isinstance(res, int) and not isinstance(res, bool) and res != len(chunk):
|
|
273
|
+
raise SandboxError("transport_error")
|
|
274
|
+
written += len(chunk)
|
|
275
|
+
return written
|