scalebox-sdk 0.1.4__py3-none-any.whl → 0.1.25__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.
Files changed (68) hide show
  1. scalebox/__init__.py +1 -1
  2. scalebox/api/__init__.py +128 -128
  3. scalebox/api/client/__init__.py +8 -8
  4. scalebox/api/client/api/sandboxes/get_sandboxes.py +5 -3
  5. scalebox/api/client/api/sandboxes/get_sandboxes_sandbox_id_metrics.py +2 -2
  6. scalebox/api/client/api/sandboxes/post_sandboxes.py +2 -2
  7. scalebox/api/client/client.py +288 -288
  8. scalebox/api/client/models/listed_sandbox.py +11 -9
  9. scalebox/api/client/models/new_sandbox.py +1 -1
  10. scalebox/api/client/models/sandbox.py +125 -125
  11. scalebox/api/client/models/sandbox_state.py +1 -0
  12. scalebox/api/client/types.py +46 -46
  13. scalebox/code_interpreter/code_interpreter_async.py +370 -369
  14. scalebox/code_interpreter/code_interpreter_sync.py +318 -317
  15. scalebox/connection_config.py +92 -92
  16. scalebox/csx_desktop/main.py +12 -12
  17. scalebox/generated/api_pb2_connect.py +17 -66
  18. scalebox/sandbox_async/commands/command.py +307 -307
  19. scalebox/sandbox_async/commands/command_handle.py +187 -187
  20. scalebox/sandbox_async/commands/pty.py +187 -187
  21. scalebox/sandbox_async/filesystem/filesystem.py +557 -557
  22. scalebox/sandbox_async/filesystem/watch_handle.py +61 -61
  23. scalebox/sandbox_async/main.py +647 -646
  24. scalebox/sandbox_async/sandbox_api.py +365 -365
  25. scalebox/sandbox_async/utils.py +7 -7
  26. scalebox/sandbox_sync/__init__.py +2 -2
  27. scalebox/sandbox_sync/commands/command.py +300 -300
  28. scalebox/sandbox_sync/commands/command_handle.py +150 -150
  29. scalebox/sandbox_sync/commands/pty.py +181 -181
  30. scalebox/sandbox_sync/filesystem/filesystem.py +543 -543
  31. scalebox/sandbox_sync/filesystem/watch_handle.py +66 -66
  32. scalebox/sandbox_sync/main.py +789 -790
  33. scalebox/sandbox_sync/sandbox_api.py +356 -356
  34. scalebox/test/CODE_INTERPRETER_TESTS_READY.md +256 -256
  35. scalebox/test/README.md +164 -164
  36. scalebox/test/aclient.py +72 -72
  37. scalebox/test/code_interpreter_centext.py +21 -21
  38. scalebox/test/code_interpreter_centext_sync.py +21 -21
  39. scalebox/test/code_interpreter_test.py +1 -1
  40. scalebox/test/code_interpreter_test_sync.py +1 -1
  41. scalebox/test/run_all_validation_tests.py +334 -334
  42. scalebox/test/test_basic.py +78 -78
  43. scalebox/test/test_code_interpreter_async_comprehensive.py +2653 -2653
  44. scalebox/test/{test_code_interpreter_e2bsync_comprehensive.py → test_code_interpreter_execcode.py} +328 -392
  45. scalebox/test/test_code_interpreter_sync_comprehensive.py +3416 -3412
  46. scalebox/test/test_csx_desktop_examples.py +130 -0
  47. scalebox/test/test_sandbox_async_comprehensive.py +736 -738
  48. scalebox/test/test_sandbox_stress_and_edge_cases.py +778 -778
  49. scalebox/test/test_sandbox_sync_comprehensive.py +779 -770
  50. scalebox/test/test_sandbox_usage_examples.py +987 -987
  51. scalebox/test/testacreate.py +24 -24
  52. scalebox/test/testagetinfo.py +18 -18
  53. scalebox/test/testcodeinterpreter_async.py +508 -508
  54. scalebox/test/testcodeinterpreter_sync.py +239 -239
  55. scalebox/test/testcomputeuse.py +2 -2
  56. scalebox/test/testnovnc.py +12 -12
  57. scalebox/test/testsandbox_api.py +15 -0
  58. scalebox/test/testsandbox_async.py +202 -118
  59. scalebox/test/testsandbox_sync.py +71 -38
  60. scalebox/version.py +2 -2
  61. {scalebox_sdk-0.1.4.dist-info → scalebox_sdk-0.1.25.dist-info}/METADATA +104 -103
  62. {scalebox_sdk-0.1.4.dist-info → scalebox_sdk-0.1.25.dist-info}/RECORD +66 -66
  63. scalebox/test/test_code_interpreter_e2basync_comprehensive.py +0 -2655
  64. scalebox/test/test_e2b_first.py +0 -11
  65. {scalebox_sdk-0.1.4.dist-info → scalebox_sdk-0.1.25.dist-info}/WHEEL +0 -0
  66. {scalebox_sdk-0.1.4.dist-info → scalebox_sdk-0.1.25.dist-info}/entry_points.txt +0 -0
  67. {scalebox_sdk-0.1.4.dist-info → scalebox_sdk-0.1.25.dist-info}/licenses/LICENSE +0 -0
  68. {scalebox_sdk-0.1.4.dist-info → scalebox_sdk-0.1.25.dist-info}/top_level.txt +0 -0
scalebox/test/README.md CHANGED
@@ -1,79 +1,79 @@
1
- # ScaleBox Sandbox 验证测试套件
1
+ # ScaleBox Sandbox Verification Test Suite
2
2
 
3
- 这个测试套件包含了针对 `sandbox_async` `sandbox_sync` 模块的全面验证示例,涵盖了从基本功能到高级使用场景的各个方面。
3
+ This test suite contains comprehensive validation examples for the `sandbox_async` and `sandbox_sync` modules, covering everything from basic functionality to advanced use cases.
4
4
 
5
- ## 📋 测试文件概览
5
+ ## 📋 Test Files Overview
6
6
 
7
- ### 1. 基础功能验证
7
+ ### 1. Basic Functionality Verification
8
8
 
9
9
  #### `test_sandbox_async_comprehensive.py`
10
- **异步沙箱综合验证测试**
11
- - ✅ 沙箱生命周期管理(创建、连接、销毁)
12
- - ✅ 文件系统操作(读写、列表、删除、重命名等)
13
- - ✅ 命令执行(前台、后台、PTY
14
- - ✅ 静态方法和类方法
15
- - ✅ 错误处理和异常情况
16
- - ✅ 性能测试和并发操作
17
- - ✅ 上下文管理器使用
18
-
19
- **运行方式:**
10
+ **Asynchronous Sandbox Comprehensive Verification Tests**
11
+ - ✅ Sandbox lifecycle management (create, connect, destroy)
12
+ - ✅ Filesystem operations (read/write, list, delete, rename, etc.)
13
+ - ✅ Command execution (foreground, background, PTY)
14
+ - ✅ Static methods and class methods
15
+ - ✅ Error handling and exception cases
16
+ - ✅ Performance testing and concurrent operations
17
+ - ✅ Context manager usage
18
+
19
+ **Run with:**
20
20
  ```bash
21
21
  cd /home/ubuntu/git_home/scalebox/test
22
22
  python test_sandbox_async_comprehensive.py
23
23
  ```
24
24
 
25
25
  #### `test_sandbox_sync_comprehensive.py`
26
- **同步沙箱综合验证测试**
27
- - ✅ 与异步版本相同的功能覆盖
28
- - ✅ 同步特定的操作模式
29
- - ✅ 线程池并发处理
30
- - ✅ 目录监控功能
26
+ **Synchronous Sandbox Comprehensive Verification Tests**
27
+ - ✅ Same functionality coverage as async version
28
+ - ✅ Synchronous-specific operation modes
29
+ - ✅ Thread pool concurrent processing
30
+ - ✅ Directory monitoring functionality
31
31
 
32
- **运行方式:**
32
+ **Run with:**
33
33
  ```bash
34
34
  cd /home/ubuntu/git_home/scalebox/test
35
35
  python test_sandbox_sync_comprehensive.py
36
36
  ```
37
37
 
38
- ### 2. 压力测试和边界条件
38
+ ### 2. Stress Testing and Edge Cases
39
39
 
40
40
  #### `test_sandbox_stress_and_edge_cases.py`
41
- **压力测试和边界条件验证**
42
- - 🔥 大数据文件处理(10MB+ 文件)
43
- - 🔥 高并发操作(同步和异步)
44
- - 🔥 内存压力测试(1000+ 文件操作)
45
- - 🔥 边界条件测试(空文件、特殊字符、深层目录)
46
- - 🔥 错误恢复能力测试
47
- - 🔥 资源管理测试(多沙箱实例)
48
-
49
- **运行方式:**
41
+ **Stress Testing and Edge Case Verification**
42
+ - 🔥 Large file handling (10MB+ files)
43
+ - 🔥 High concurrency operations (sync and async)
44
+ - 🔥 Memory stress testing (1000+ file operations)
45
+ - 🔥 Edge case testing (empty files, special characters, deep directories)
46
+ - 🔥 Error recovery capability testing
47
+ - 🔥 Resource management testing (multiple sandbox instances)
48
+
49
+ **Run with:**
50
50
  ```bash
51
51
  cd /home/ubuntu/git_home/scalebox/test
52
52
  python test_sandbox_stress_and_edge_cases.py
53
53
  ```
54
54
 
55
- ### 3. 实际应用示例
55
+ ### 3. Real-World Application Examples
56
56
 
57
57
  #### `test_sandbox_usage_examples.py`
58
- **使用示例和最佳实践**
59
- - 💡 代码执行服务实现
60
- - 💡 文件处理服务实现
61
- - 💡 交互式会话管理
62
- - 💡 性能优化技巧
63
- - 💡 资源管理最佳实践
64
- - 💡 错误处理策略
65
- - 💡 并发和异步编程模式
66
-
67
- **运行方式:**
58
+ **Usage Examples and Best Practices**
59
+ - 💡 Code execution service implementation
60
+ - 💡 File processing service implementation
61
+ - 💡 Interactive session management
62
+ - 💡 Performance optimization techniques
63
+ - 💡 Resource management best practices
64
+ - 💡 Error handling strategies
65
+ - 💡 Concurrency and asynchronous programming patterns
66
+
67
+ **Run with:**
68
68
  ```bash
69
69
  cd /home/ubuntu/git_home/scalebox/test
70
70
  python test_sandbox_usage_examples.py
71
71
  ```
72
72
 
73
- ## 🏗️ 测试架构设计
73
+ ## 🏗️ Test Architecture Design
74
74
 
75
- ### 测试结果记录系统
76
- 每个测试套件都包含完整的测试结果记录系统:
75
+ ### Test Result Recording System
76
+ Each test suite includes a complete test result recording system:
77
77
  ```python
78
78
  class TestValidator:
79
79
  def log_test_result(self, test_name: str, success: bool, message: str = "", duration: float = 0)
@@ -81,8 +81,8 @@ class TestValidator:
81
81
  def print_summary(self)
82
82
  ```
83
83
 
84
- ### 资源管理系统
85
- 智能的沙箱资源管理:
84
+ ### Resource Management System
85
+ Intelligent sandbox resource management:
86
86
  ```python
87
87
  class SandboxManager:
88
88
  @contextmanager
@@ -93,116 +93,116 @@ class AsyncSandboxManager:
93
93
  async def get_sandbox(self, sandbox_id: Optional[str] = None)
94
94
  ```
95
95
 
96
- ### 重试机制
97
- 内置的重试装饰器:
96
+ ### Retry Mechanism
97
+ Built-in retry decorators:
98
98
  ```python
99
99
  @retry_on_failure(max_retries=3, delay=1.0)
100
100
  def your_function():
101
- # 自动重试失败的操作
101
+ # Auto-retry failed operations
102
102
  pass
103
103
 
104
104
  @async_retry_on_failure(max_retries=3, delay=1.0)
105
105
  async def your_async_function():
106
- # 异步重试机制
106
+ # Asynchronous retry mechanism
107
107
  pass
108
108
  ```
109
109
 
110
- ## 📊 测试覆盖范围
111
-
112
- ### 功能覆盖
113
- | 功能模块 | 同步测试 | 异步测试 | 压力测试 | 使用示例 |
114
- |---------|---------|---------|---------|---------|
115
- | 沙箱创建/销毁 | ✅ | ✅ | ✅ | ✅ |
116
- | 文件系统操作 | ✅ | ✅ | ✅ | ✅ |
117
- | 命令执行 | ✅ | ✅ | ✅ | ✅ |
118
- | PTY 操作 | ✅ | ✅ | ✅ | ✅ |
119
- | 静态方法 | ✅ | ✅ | ✅ | ✅ |
120
- | 错误处理 | ✅ | ✅ | ✅ | ✅ |
121
- | 性能优化 | ✅ | ✅ | ✅ | ✅ |
122
- | 并发处理 | ✅ | ✅ | ✅ | ✅ |
123
-
124
- ### 测试场景
125
- - **基础功能**:单一操作的正确性验证
126
- - **批量操作**:大量数据的批处理能力
127
- - **并发处理**:多任务并行执行
128
- - **错误恢复**:异常情况下的系统稳定性
129
- - **资源管理**:内存和连接的有效管理
130
- - **性能基准**:各种操作的性能指标
131
-
132
- ## 🚀 快速开始
133
-
134
- ### 1. 环境准备
135
- 确保你的环境中已经安装了必要的依赖:
110
+ ## 📊 Test Coverage
111
+
112
+ ### Functionality Coverage
113
+ | Functional Module | Sync Tests | Async Tests | Stress Tests | Usage Examples |
114
+ |-------------------|------------|-------------|--------------|----------------|
115
+ | Sandbox Create/Destroy | ✅ | ✅ | ✅ | ✅ |
116
+ | Filesystem Operations | ✅ | ✅ | ✅ | ✅ |
117
+ | Command Execution | ✅ | ✅ | ✅ | ✅ |
118
+ | PTY Operations | ✅ | ✅ | ✅ | ✅ |
119
+ | Static Methods | ✅ | ✅ | ✅ | ✅ |
120
+ | Error Handling | ✅ | ✅ | ✅ | ✅ |
121
+ | Performance Optimization | ✅ | ✅ | ✅ | ✅ |
122
+ | Concurrent Processing | ✅ | ✅ | ✅ | ✅ |
123
+
124
+ ### Test Scenarios
125
+ - **Basic Functionality**: Correctness verification of single operations
126
+ - **Batch Operations**: Batch processing capability for large amounts of data
127
+ - **Concurrent Processing**: Multi-task parallel execution
128
+ - **Error Recovery**: System stability under exceptional circumstances
129
+ - **Resource Management**: Effective management of memory and connections
130
+ - **Performance Benchmarks**: Performance metrics for various operations
131
+
132
+ ## 🚀 Quick Start
133
+
134
+ ### 1. Environment Preparation
135
+ Ensure necessary dependencies are installed in your environment:
136
136
  ```bash
137
- # 确保模块路径正确
137
+ # Ensure module path is correct
138
138
  export PYTHONPATH=/home/ubuntu/git_home/scalebox:$PYTHONPATH
139
139
 
140
- # 安装依赖(如果需要)
140
+ # Install dependencies (if needed)
141
141
  pip install -r requirements.txt
142
142
  ```
143
143
 
144
- ### 2. 运行单个测试
144
+ ### 2. Run Individual Tests
145
145
  ```bash
146
- # 运行异步综合测试
146
+ # Run async comprehensive tests
147
147
  python test_sandbox_async_comprehensive.py
148
148
 
149
- # 运行同步综合测试
149
+ # Run sync comprehensive tests
150
150
  python test_sandbox_sync_comprehensive.py
151
151
 
152
- # 运行压力测试
152
+ # Run stress tests
153
153
  python test_sandbox_stress_and_edge_cases.py
154
154
 
155
- # 运行使用示例
155
+ # Run usage examples
156
156
  python test_sandbox_usage_examples.py
157
157
  ```
158
158
 
159
- ### 3. 批量运行所有测试
159
+ ### 3. Run All Tests in Batch
160
160
  ```bash
161
- # 创建运行脚本
161
+ # Create run script
162
162
  cat > run_all_tests.sh << 'EOF'
163
163
  #!/bin/bash
164
164
 
165
- echo "开始运行所有沙箱测试..."
165
+ echo "Starting all sandbox tests..."
166
166
 
167
- echo "=== 异步综合测试 ==="
167
+ echo "=== Async Comprehensive Tests ==="
168
168
  python test_sandbox_async_comprehensive.py
169
169
 
170
- echo "=== 同步综合测试 ==="
170
+ echo "=== Sync Comprehensive Tests ==="
171
171
  python test_sandbox_sync_comprehensive.py
172
172
 
173
- echo "=== 压力测试和边界条件 ==="
173
+ echo "=== Stress Tests and Edge Cases ==="
174
174
  python test_sandbox_stress_and_edge_cases.py
175
175
 
176
- echo "=== 使用示例和最佳实践 ==="
176
+ echo "=== Usage Examples and Best Practices ==="
177
177
  python test_sandbox_usage_examples.py
178
178
 
179
- echo "所有测试完成!"
179
+ echo "All tests completed!"
180
180
  EOF
181
181
 
182
182
  chmod +x run_all_tests.sh
183
183
  ./run_all_tests.sh
184
184
  ```
185
185
 
186
- ## 📈 性能基准
186
+ ## 📈 Performance Benchmarks
187
187
 
188
- ### 同步 vs 异步性能对比
188
+ ### Sync vs Async Performance Comparison
189
189
 
190
- | 操作类型 | 同步版本 | 异步版本 | 性能提升 |
191
- |---------|---------|---------|---------|
192
- | 单文件操作 | ~0.1s | ~0.1s | 持平 |
193
- | 批量文件操作(100) | ~2.0s | ~0.5s | **4x 更快** |
194
- | 并发命令执行(10) | ~1.5s | ~0.3s | **5x 更快** |
195
- | PTY 交互会话 | ~0.2s | ~0.2s | 持平 |
190
+ | Operation Type | Sync Version | Async Version | Performance Improvement |
191
+ |----------------|--------------|---------------|------------------------|
192
+ | Single File Operation | ~0.1s | ~0.1s | Equal |
193
+ | Batch File Operations (100) | ~2.0s | ~0.5s | **4x faster** |
194
+ | Concurrent Command Execution (10) | ~1.5s | ~0.3s | **5x faster** |
195
+ | PTY Interactive Session | ~0.2s | ~0.2s | Equal |
196
196
 
197
- ### 资源使用情况
198
- - **内存使用**:异步版本在大批量操作时内存使用更高效
199
- - **CPU 利用率**:异步版本能更好地利用多核 CPU
200
- - **网络连接**:异步版本支持更多并发连接
197
+ ### Resource Usage
198
+ - **Memory Usage**: Async version uses memory more efficiently during large batch operations
199
+ - **CPU Utilization**: Async version better utilizes multi-core CPUs
200
+ - **Network Connections**: Async version supports more concurrent connections
201
201
 
202
- ## 🛠️ 自定义测试
202
+ ## 🛠️ Custom Testing
203
203
 
204
- ### 添加新测试
205
- 1. **继承测试基类**:
204
+ ### Adding New Tests
205
+ 1. **Inherit Test Base Class**:
206
206
  ```python
207
207
  class YourTestValidator:
208
208
  def __init__(self):
@@ -210,32 +210,32 @@ class YourTestValidator:
210
210
  self.failed_tests = []
211
211
 
212
212
  def log_test_result(self, test_name: str, success: bool, message: str = "", duration: float = 0):
213
- # 实现测试结果记录
213
+ # Implement test result recording
214
214
  pass
215
215
  ```
216
216
 
217
- 2. **编写测试方法**:
217
+ 2. **Write Test Methods**:
218
218
  ```python
219
219
  def test_your_feature(self):
220
- """测试你的功能"""
221
- # 测试逻辑
220
+ """Test your functionality"""
221
+ # Test logic
222
222
  pass
223
223
 
224
224
  async def test_your_async_feature(self):
225
- """测试你的异步功能"""
226
- # 异步测试逻辑
225
+ """Test your async functionality"""
226
+ # Async test logic
227
227
  pass
228
228
  ```
229
229
 
230
- 3. **运行测试**:
230
+ 3. **Run Tests**:
231
231
  ```python
232
232
  def run_all_tests(self):
233
233
  self.run_test(self.test_your_feature, "Your Feature Test")
234
234
  ```
235
235
 
236
- ### 配置测试参数
236
+ ### Configure Test Parameters
237
237
  ```python
238
- # 在测试文件顶部配置
238
+ # Configure at top of test file
239
239
  TEST_CONFIG = {
240
240
  'debug_mode': True,
241
241
  'max_concurrent': 10,
@@ -245,85 +245,85 @@ TEST_CONFIG = {
245
245
  }
246
246
  ```
247
247
 
248
- ## 🐛 故障排除
248
+ ## 🐛 Troubleshooting
249
249
 
250
- ### 常见问题
250
+ ### Common Issues
251
251
 
252
- 1. **沙箱创建失败**
253
- - 检查网络连接
254
- - 验证 API 密钥配置
255
- - 确认服务器状态
252
+ 1. **Sandbox Creation Failure**
253
+ - Check network connection
254
+ - Verify API key configuration
255
+ - Confirm server status
256
256
 
257
- 2. **文件操作失败**
258
- - 检查文件路径权限
259
- - 验证磁盘空间
260
- - 确认文件格式
257
+ 2. **File Operation Failure**
258
+ - Check file path permissions
259
+ - Verify disk space
260
+ - Confirm file format
261
261
 
262
- 3. **命令执行超时**
263
- - 调整超时参数
264
- - 检查命令语法
265
- - 验证环境变量
262
+ 3. **Command Execution Timeout**
263
+ - Adjust timeout parameters
264
+ - Check command syntax
265
+ - Verify environment variables
266
266
 
267
- 4. **内存不足错误**
268
- - 减少并发数量
269
- - 调整批处理大小
270
- - 增加系统内存
267
+ 4. **Out of Memory Errors**
268
+ - Reduce concurrency count
269
+ - Adjust batch size
270
+ - Increase system memory
271
271
 
272
- ### 调试技巧
272
+ ### Debugging Tips
273
273
 
274
- 1. **启用调试日志**:
274
+ 1. **Enable Debug Logging**:
275
275
  ```python
276
276
  import logging
277
277
  logging.basicConfig(level=logging.DEBUG)
278
278
  ```
279
279
 
280
- 2. **使用调试模式**:
280
+ 2. **Use Debug Mode**:
281
281
  ```python
282
282
  sandbox = Sandbox(debug=True)
283
- #
283
+ # or
284
284
  sandbox = await AsyncSandbox.create(debug=True)
285
285
  ```
286
286
 
287
- 3. **监控资源使用**:
287
+ 3. **Monitor Resource Usage**:
288
288
  ```python
289
289
  import psutil
290
- print(f"内存使用: {psutil.virtual_memory().percent}%")
291
- print(f"CPU 使用: {psutil.cpu_percent()}%")
290
+ print(f"Memory usage: {psutil.virtual_memory().percent}%")
291
+ print(f"CPU usage: {psutil.cpu_percent()}%")
292
292
  ```
293
293
 
294
- ## 📝 贡献指南
294
+ ## 📝 Contribution Guidelines
295
295
 
296
- ### 添加新测试
297
- 1. Fork 项目
298
- 2. 创建特性分支
299
- 3. 添加测试用例
300
- 4. 更新文档
301
- 5. 提交 Pull Request
296
+ ### Adding New Tests
297
+ 1. Fork the project
298
+ 2. Create a feature branch
299
+ 3. Add test cases
300
+ 4. Update documentation
301
+ 5. Submit a Pull Request
302
302
 
303
- ### 测试规范
304
- - 每个测试函数都应该有清晰的文档字符串
305
- - 使用断言验证结果
306
- - 包含适当的错误处理
307
- - 记录性能指标
308
- - 清理测试资源
303
+ ### Testing Standards
304
+ - Each test function should have clear docstrings
305
+ - Use assertions to verify results
306
+ - Include appropriate error handling
307
+ - Record performance metrics
308
+ - Clean up test resources
309
309
 
310
- ## 📚 参考资料
310
+ ## 📚 References
311
311
 
312
- ### API 文档
312
+ ### API Documentation
313
313
  - [AsyncSandbox API](../sandbox_async/main.py)
314
314
  - [Sandbox API](../sandbox_sync/main.py)
315
- - [文件系统 API](../sandbox/filesystem/)
316
- - [命令执行 API](../sandbox/commands/)
315
+ - [Filesystem API](../sandbox/filesystem/)
316
+ - [Command Execution API](../sandbox/commands/)
317
317
 
318
- ### 最佳实践
319
- - 始终使用上下文管理器管理沙箱资源
320
- - 批量操作优于单个操作
321
- - 异步版本适合 I/O 密集型任务
322
- - 同步版本适合 CPU 密集型任务
323
- - 实现适当的重试和错误恢复机制
318
+ ### Best Practices
319
+ - Always use context managers to manage sandbox resources
320
+ - Batch operations are better than individual operations
321
+ - Async version is suitable for I/O-intensive tasks
322
+ - Sync version is suitable for CPU-intensive tasks
323
+ - Implement appropriate retry and error recovery mechanisms
324
324
 
325
325
  ---
326
326
 
327
327
  **Happy Testing! 🎉**
328
328
 
329
- 如有问题或建议,请提交 Issue 或联系维护团队。
329
+ For questions or suggestions, please submit an Issue or contact the maintenance team.
scalebox/test/aclient.py CHANGED
@@ -1,72 +1,72 @@
1
- # import sys, os
2
- # sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'generated'))
3
- import asyncio
4
-
5
- import aiohttp
6
- from generated import api_pb2
7
- from generated.api_pb2_connect import AsyncFilesystemClient
8
- from tenacity import (
9
- retry,
10
- retry_if_exception_type,
11
- stop_after_attempt,
12
- wait_exponential,
13
- )
14
-
15
-
16
- @retry(
17
- stop=stop_after_attempt(5), # 最大重试5次
18
- wait=wait_exponential(multiplier=1, min=4, max=10), # 指数退避等待
19
- retry=retry_if_exception_type(
20
- (aiohttp.ClientError, asyncio.TimeoutError)
21
- ), # 针对这些异常重试
22
- )
23
- async def watch_directory_example():
24
- # 创建 aiohttp 客户端会话
25
- async with aiohttp.ClientSession(
26
- timeout=aiohttp.ClientTimeout(total=None)
27
- ) as session:
28
- # 创建文件系统客户端
29
- client = AsyncFilesystemClient(
30
- base_url="http://localhost:8080",
31
- http_client=session,
32
- # protocol=ConnectProtocol.CONNECT_PROTOBUF # 如果需要指定协议
33
- )
34
- # extra = {"authorization": "Bearer root"}
35
- # 创建监视请求
36
- request = api_pb2.WatchDirRequest(path="/root")
37
-
38
- # 可选:添加额外的请求头
39
- extra_headers = {
40
- "Authorization": "Bearer root",
41
- "X-Custom-Header": "custom-value",
42
- }
43
-
44
- try:
45
- # 使用 async for 循环处理流式响应
46
- async for response in client.watch_dir(
47
- request, extra_headers=extra_headers
48
- ):
49
- print(f"Received event: {response}")
50
- # 在这里处理每个事件
51
- # 例如,根据事件类型执行不同的操作
52
-
53
- # 如果收到特定事件,可以中断循环
54
- # if response.event_type == api_pb2.WatchDirResponse.EVENT_TYPE_STOP:
55
- # break
56
-
57
- except Exception as e:
58
- print(f"Error during directory watching: {e}")
59
-
60
- finally:
61
- # 关闭会话(在 with 语句中会自动关闭,但这里为了清晰展示)
62
- await session.close()
63
-
64
-
65
- async def main():
66
- # 运行监视示例
67
- await watch_directory_example()
68
-
69
-
70
- if __name__ == "__main__":
71
- # 运行异步主函数
72
- asyncio.run(main())
1
+ # import sys, os
2
+ # sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'generated'))
3
+ import asyncio
4
+
5
+ import aiohttp
6
+ from generated import api_pb2
7
+ from generated.api_pb2_connect import AsyncFilesystemClient
8
+ from tenacity import (
9
+ retry,
10
+ retry_if_exception_type,
11
+ stop_after_attempt,
12
+ wait_exponential,
13
+ )
14
+
15
+
16
+ @retry(
17
+ stop=stop_after_attempt(5), # 最大重试5次
18
+ wait=wait_exponential(multiplier=1, min=4, max=10), # 指数退避等待
19
+ retry=retry_if_exception_type(
20
+ (aiohttp.ClientError, asyncio.TimeoutError)
21
+ ), # 针对这些异常重试
22
+ )
23
+ async def watch_directory_example():
24
+ # 创建 aiohttp 客户端会话
25
+ async with aiohttp.ClientSession(
26
+ timeout=aiohttp.ClientTimeout(total=None)
27
+ ) as session:
28
+ # 创建文件系统客户端
29
+ client = AsyncFilesystemClient(
30
+ base_url="http://localhost:8080",
31
+ http_client=session,
32
+ # protocol=ConnectProtocol.CONNECT_PROTOBUF # 如果需要指定协议
33
+ )
34
+ # extra = {"authorization": "Bearer root"}
35
+ # 创建监视请求
36
+ request = api_pb2.WatchDirRequest(path="/root")
37
+
38
+ # 可选:添加额外的请求头
39
+ extra_headers = {
40
+ "Authorization": "Bearer root",
41
+ "X-Custom-Header": "custom-value",
42
+ }
43
+
44
+ try:
45
+ # 使用 async for 循环处理流式响应
46
+ async for response in client.watch_dir(
47
+ request, extra_headers=extra_headers
48
+ ):
49
+ print(f"Received event: {response}")
50
+ # 在这里处理每个事件
51
+ # 例如,根据事件类型执行不同的操作
52
+
53
+ # 如果收到特定事件,可以中断循环
54
+ # if response.event_type == api_pb2.WatchDirResponse.EVENT_TYPE_STOP:
55
+ # break
56
+
57
+ except Exception as e:
58
+ print(f"Error during directory watching: {e}")
59
+
60
+ finally:
61
+ # 关闭会话(在 with 语句中会自动关闭,但这里为了清晰展示)
62
+ await session.close()
63
+
64
+
65
+ async def main():
66
+ # 运行监视示例
67
+ await watch_directory_example()
68
+
69
+
70
+ if __name__ == "__main__":
71
+ # 运行异步主函数
72
+ asyncio.run(main())
@@ -1,21 +1,21 @@
1
- import asyncio
2
- import time
3
-
4
- from scalebox.code_interpreter import AsyncSandbox
5
-
6
- # from scalebox.sandbox_async.main import AsyncSandbox
7
-
8
-
9
- async def pty_output_handler(output):
10
- """处理 PTY 输出的回调函数"""
11
- print(f"输出: {output}")
12
-
13
-
14
- async def main():
15
- sandbox = AsyncSandbox()
16
- context = await sandbox.create_code_context(language="python3")
17
- print(context.__dict__)
18
-
19
-
20
- if __name__ == "__main__":
21
- asyncio.run(main())
1
+ import asyncio
2
+ import time
3
+
4
+ from scalebox.code_interpreter import AsyncSandbox
5
+
6
+ # from scalebox.sandbox_async.main import AsyncSandbox
7
+
8
+
9
+ async def pty_output_handler(output):
10
+ """处理 PTY 输出的回调函数"""
11
+ print(f"输出: {output}")
12
+
13
+
14
+ async def main():
15
+ sandbox = AsyncSandbox()
16
+ context = await sandbox.create_code_context(language="python3")
17
+ print(context.__dict__)
18
+
19
+
20
+ if __name__ == "__main__":
21
+ asyncio.run(main())