@cloudflare/sandbox 0.0.0-e1fa354 → 0.0.0-e489cbb

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 (94) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/Dockerfile +107 -38
  3. package/README.md +89 -771
  4. package/dist/chunk-53JFOF7F.js +2352 -0
  5. package/dist/chunk-53JFOF7F.js.map +1 -0
  6. package/dist/chunk-BFVUNTP4.js +104 -0
  7. package/dist/chunk-BFVUNTP4.js.map +1 -0
  8. package/dist/chunk-EKSWCBCA.js +86 -0
  9. package/dist/chunk-EKSWCBCA.js.map +1 -0
  10. package/dist/chunk-JXZMAU2C.js +559 -0
  11. package/dist/chunk-JXZMAU2C.js.map +1 -0
  12. package/dist/chunk-Z532A7QC.js +78 -0
  13. package/dist/chunk-Z532A7QC.js.map +1 -0
  14. package/dist/file-stream.d.ts +43 -0
  15. package/dist/file-stream.js +9 -0
  16. package/dist/file-stream.js.map +1 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +66 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/interpreter.d.ts +33 -0
  21. package/dist/interpreter.js +8 -0
  22. package/dist/interpreter.js.map +1 -0
  23. package/dist/request-handler.d.ts +18 -0
  24. package/dist/request-handler.js +12 -0
  25. package/dist/request-handler.js.map +1 -0
  26. package/dist/sandbox-D9K2ypln.d.ts +583 -0
  27. package/dist/sandbox.d.ts +4 -0
  28. package/dist/sandbox.js +12 -0
  29. package/dist/sandbox.js.map +1 -0
  30. package/dist/security.d.ts +31 -0
  31. package/dist/security.js +13 -0
  32. package/dist/security.js.map +1 -0
  33. package/dist/sse-parser.d.ts +28 -0
  34. package/dist/sse-parser.js +11 -0
  35. package/dist/sse-parser.js.map +1 -0
  36. package/package.json +13 -5
  37. package/src/clients/base-client.ts +280 -0
  38. package/src/clients/command-client.ts +115 -0
  39. package/src/clients/file-client.ts +269 -0
  40. package/src/clients/git-client.ts +92 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/{jupyter-client.ts → clients/interpreter-client.ts} +148 -168
  43. package/src/clients/port-client.ts +105 -0
  44. package/src/clients/process-client.ts +177 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +84 -0
  47. package/src/clients/utility-client.ts +94 -0
  48. package/src/errors/adapter.ts +180 -0
  49. package/src/errors/classes.ts +469 -0
  50. package/src/errors/index.ts +105 -0
  51. package/src/file-stream.ts +164 -0
  52. package/src/index.ts +82 -53
  53. package/src/interpreter.ts +22 -13
  54. package/src/request-handler.ts +69 -43
  55. package/src/sandbox.ts +697 -527
  56. package/src/security.ts +14 -23
  57. package/src/sse-parser.ts +4 -8
  58. package/startup.sh +3 -0
  59. package/tests/base-client.test.ts +328 -0
  60. package/tests/command-client.test.ts +407 -0
  61. package/tests/file-client.test.ts +643 -0
  62. package/tests/file-stream.test.ts +306 -0
  63. package/tests/git-client.test.ts +328 -0
  64. package/tests/port-client.test.ts +301 -0
  65. package/tests/process-client.test.ts +658 -0
  66. package/tests/sandbox.test.ts +465 -0
  67. package/tests/sse-parser.test.ts +290 -0
  68. package/tests/utility-client.test.ts +266 -0
  69. package/tests/wrangler.jsonc +35 -0
  70. package/tsconfig.json +9 -1
  71. package/vitest.config.ts +31 -0
  72. package/container_src/bun.lock +0 -122
  73. package/container_src/circuit-breaker.ts +0 -121
  74. package/container_src/control-process.ts +0 -784
  75. package/container_src/handler/exec.ts +0 -185
  76. package/container_src/handler/file.ts +0 -406
  77. package/container_src/handler/git.ts +0 -130
  78. package/container_src/handler/ports.ts +0 -314
  79. package/container_src/handler/process.ts +0 -568
  80. package/container_src/handler/session.ts +0 -92
  81. package/container_src/index.ts +0 -601
  82. package/container_src/isolation.ts +0 -1038
  83. package/container_src/jupyter-server.ts +0 -579
  84. package/container_src/jupyter-service.ts +0 -461
  85. package/container_src/jupyter_config.py +0 -48
  86. package/container_src/mime-processor.ts +0 -255
  87. package/container_src/package.json +0 -18
  88. package/container_src/shell-escape.ts +0 -42
  89. package/container_src/startup.sh +0 -84
  90. package/container_src/types.ts +0 -131
  91. package/src/client.ts +0 -1009
  92. package/src/errors.ts +0 -218
  93. package/src/interpreter-types.ts +0 -383
  94. package/src/types.ts +0 -502
@@ -1,461 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { CircuitBreaker } from "./circuit-breaker";
3
- import { type CreateContextRequest, JupyterServer } from "./jupyter-server";
4
-
5
- interface PoolStats {
6
- available: number;
7
- inUse: number;
8
- total: number;
9
- minSize: number;
10
- maxSize: number;
11
- warming: boolean;
12
- }
13
-
14
- interface CircuitBreakerState {
15
- state: string;
16
- failures: number;
17
- lastFailure: number;
18
- isOpen: boolean;
19
- }
20
-
21
- export interface JupyterHealthStatus {
22
- ready: boolean;
23
- initializing: boolean;
24
- error?: string;
25
- checks?: {
26
- httpApi: boolean;
27
- kernelManager: boolean;
28
- markerFile: boolean;
29
- kernelSpawn?: boolean;
30
- websocket?: boolean;
31
- };
32
- timestamp: number;
33
- performance?: {
34
- poolStats?: Record<string, PoolStats>;
35
- activeContexts?: number;
36
- uptime?: number;
37
- circuitBreakers?: {
38
- contextCreation: CircuitBreakerState;
39
- codeExecution: CircuitBreakerState;
40
- kernelCommunication: CircuitBreakerState;
41
- };
42
- };
43
- }
44
-
45
- /**
46
- * Wrapper service that provides graceful degradation for Jupyter functionality
47
- */
48
- export class JupyterService {
49
- private jupyterServer: JupyterServer;
50
- private initPromise: Promise<void> | null = null;
51
- private initialized = false;
52
- private initError: Error | null = null;
53
- private startTime = Date.now();
54
- private circuitBreakers: {
55
- contextCreation: CircuitBreaker;
56
- codeExecution: CircuitBreaker;
57
- kernelCommunication: CircuitBreaker;
58
- };
59
-
60
- constructor() {
61
- this.jupyterServer = new JupyterServer();
62
-
63
- // Initialize circuit breakers for different operations
64
- this.circuitBreakers = {
65
- contextCreation: new CircuitBreaker({
66
- name: "context-creation",
67
- threshold: 3,
68
- timeout: 60000, // 1 minute
69
- }),
70
- codeExecution: new CircuitBreaker({
71
- name: "code-execution",
72
- threshold: 5,
73
- timeout: 30000, // 30 seconds
74
- }),
75
- kernelCommunication: new CircuitBreaker({
76
- name: "kernel-communication",
77
- threshold: 10,
78
- timeout: 20000, // 20 seconds
79
- }),
80
- };
81
- }
82
-
83
- /**
84
- * Initialize Jupyter server with retry logic
85
- */
86
- async initialize(): Promise<void> {
87
- if (this.initialized) return;
88
-
89
- if (!this.initPromise) {
90
- this.initPromise = this.doInitialize()
91
- .then(() => {
92
- this.initialized = true;
93
- console.log("[JupyterService] Initialization complete");
94
- })
95
- .catch((err) => {
96
- this.initError = err;
97
- // Don't null out initPromise on error - keep it so we can return the same error
98
- console.error("[JupyterService] Initialization failed:", err);
99
- throw err;
100
- });
101
- }
102
-
103
- return this.initPromise;
104
- }
105
-
106
- private async doInitialize(): Promise<void> {
107
- // Wait for Jupyter marker file or timeout
108
- const markerCheckPromise = this.waitForMarkerFile();
109
- const timeoutPromise = new Promise<void>((_, reject) => {
110
- setTimeout(
111
- () => reject(new Error("Jupyter initialization timeout")),
112
- 60000
113
- );
114
- });
115
-
116
- try {
117
- await Promise.race([markerCheckPromise, timeoutPromise]);
118
- console.log("[JupyterService] Jupyter process detected via marker file");
119
- } catch (error) {
120
- console.log(
121
- "[JupyterService] Marker file not found yet - proceeding with initialization"
122
- );
123
- }
124
-
125
- // Initialize Jupyter server
126
- await this.jupyterServer.initialize();
127
-
128
- // Pre-warm context pools in background after Jupyter is ready
129
- this.warmContextPools();
130
- }
131
-
132
- /**
133
- * Pre-warm context pools for better performance
134
- */
135
- private async warmContextPools() {
136
- // Delay pre-warming to avoid startup rush that triggers Bun WebSocket bug
137
- await new Promise((resolve) => setTimeout(resolve, 2000));
138
-
139
- try {
140
- console.log(
141
- "[JupyterService] Pre-warming context pools for better performance"
142
- );
143
-
144
- // Only pre-warm Python contexts to avoid Bun WebSocket validation errors
145
- // JavaScript contexts will be created on-demand
146
- await this.jupyterServer.enablePoolWarming("python", 1);
147
-
148
- // Commenting out JavaScript pre-warming due to kernel message validation errors
149
- // The errors appear to be related to Bun's handling of WebSocket messages
150
- // JavaScript contexts still work fine when created on-demand
151
- //
152
- // await new Promise((resolve) => setTimeout(resolve, 1000));
153
- // await this.jupyterServer.enablePoolWarming("javascript", 1);
154
- } catch (error) {
155
- console.error("[JupyterService] Error pre-warming context pools:", error);
156
- console.error(
157
- "[JupyterService] Pre-warming failed but service continues"
158
- );
159
- }
160
- }
161
-
162
- private async waitForMarkerFile(): Promise<void> {
163
- const markerPath = "/tmp/jupyter-ready";
164
- let attempts = 0;
165
- const maxAttempts = 120; // 2 minutes with 1s intervals
166
-
167
- while (attempts < maxAttempts) {
168
- if (existsSync(markerPath)) {
169
- return;
170
- }
171
- attempts++;
172
- await new Promise((resolve) => setTimeout(resolve, 1000));
173
- }
174
-
175
- throw new Error("Marker file not found within timeout");
176
- }
177
-
178
- /**
179
- * Get current health status
180
- */
181
- async getHealthStatus(): Promise<JupyterHealthStatus> {
182
- const status: JupyterHealthStatus = {
183
- ready: this.initialized,
184
- initializing: this.initPromise !== null && !this.initialized,
185
- timestamp: Date.now(),
186
- };
187
-
188
- if (this.initError) {
189
- status.error = this.initError.message;
190
- }
191
-
192
- // Detailed health checks
193
- if (this.initialized || this.initPromise) {
194
- status.checks = {
195
- httpApi: await this.checkHttpApi(),
196
- kernelManager: this.initialized,
197
- markerFile: existsSync("/tmp/jupyter-ready"),
198
- };
199
-
200
- // Advanced health checks only if fully initialized
201
- if (this.initialized) {
202
- const advancedChecks = await this.performAdvancedHealthChecks();
203
- status.checks.kernelSpawn = advancedChecks.kernelSpawn;
204
- status.checks.websocket = advancedChecks.websocket;
205
-
206
- // Performance metrics
207
- status.performance = {
208
- poolStats: await this.jupyterServer.getPoolStats(),
209
- activeContexts: (await this.jupyterServer.listContexts()).length,
210
- uptime: Date.now() - this.startTime,
211
- };
212
- }
213
- }
214
-
215
- // Add circuit breaker status
216
- if (status.performance) {
217
- status.performance.circuitBreakers = {
218
- contextCreation: this.circuitBreakers.contextCreation.getState(),
219
- codeExecution: this.circuitBreakers.codeExecution.getState(),
220
- kernelCommunication:
221
- this.circuitBreakers.kernelCommunication.getState(),
222
- };
223
- }
224
-
225
- return status;
226
- }
227
-
228
- private async checkHttpApi(): Promise<boolean> {
229
- try {
230
- const response = await fetch("http://localhost:8888/api", {
231
- signal: AbortSignal.timeout(2000),
232
- });
233
- return response.ok;
234
- } catch {
235
- return false;
236
- }
237
- }
238
-
239
- /**
240
- * Perform advanced health checks including kernel spawn and WebSocket
241
- */
242
- private async performAdvancedHealthChecks(): Promise<{
243
- kernelSpawn: boolean;
244
- websocket: boolean;
245
- }> {
246
- const checks = {
247
- kernelSpawn: false,
248
- websocket: false,
249
- };
250
-
251
- try {
252
- // Test kernel spawn with timeout
253
- const testContext = await Promise.race([
254
- this.jupyterServer.createContext({ language: "python" }),
255
- new Promise<null>((_, reject) =>
256
- setTimeout(() => reject(new Error("Kernel spawn timeout")), 5000)
257
- ),
258
- ]);
259
-
260
- if (testContext) {
261
- checks.kernelSpawn = true;
262
-
263
- // Test WebSocket by executing simple code
264
- try {
265
- const result = await Promise.race([
266
- this.jupyterServer.executeCode(
267
- testContext.id,
268
- "print('health_check')"
269
- ),
270
- new Promise<null>((_, reject) =>
271
- setTimeout(() => reject(new Error("WebSocket timeout")), 3000)
272
- ),
273
- ]);
274
-
275
- checks.websocket = result !== null;
276
- } catch {
277
- // WebSocket test failed
278
- }
279
-
280
- // Clean up test context
281
- try {
282
- await this.jupyterServer.deleteContext(testContext.id);
283
- } catch {
284
- // Ignore cleanup errors
285
- }
286
- }
287
- } catch (error) {
288
- console.log("[JupyterService] Advanced health check failed:", error);
289
- }
290
-
291
- return checks;
292
- }
293
-
294
- /**
295
- * Ensure Jupyter is initialized before proceeding
296
- * This will wait for initialization to complete or fail
297
- */
298
- private async ensureInitialized(timeoutMs: number = 30000): Promise<void> {
299
- if (this.initialized) return;
300
-
301
- // Start initialization if not already started
302
- if (!this.initPromise) {
303
- this.initPromise = this.initialize();
304
- }
305
-
306
- // Wait for initialization with timeout
307
- try {
308
- await Promise.race([
309
- this.initPromise,
310
- new Promise<never>((_, reject) =>
311
- setTimeout(
312
- () =>
313
- reject(new Error("Timeout waiting for Jupyter initialization")),
314
- timeoutMs
315
- )
316
- ),
317
- ]);
318
- } catch (error) {
319
- // If it's a timeout and Jupyter is still initializing, throw a retryable error
320
- if (
321
- error instanceof Error &&
322
- error.message.includes("Timeout") &&
323
- !this.initError
324
- ) {
325
- throw new JupyterNotReadyError(
326
- "Jupyter is taking longer than expected to initialize. Please try again.",
327
- {
328
- retryAfter: 10,
329
- progress: this.getInitializationProgress(),
330
- }
331
- );
332
- }
333
- // If initialization actually failed, throw the real error
334
- throw new Error(
335
- `Jupyter initialization failed: ${
336
- error instanceof Error ? error.message : "Unknown error"
337
- }`
338
- );
339
- }
340
- }
341
-
342
- /**
343
- * Create context - will wait for Jupyter if still initializing
344
- */
345
- async createContext(req: CreateContextRequest): Promise<any> {
346
- if (!this.initialized) {
347
- console.log(
348
- "[JupyterService] Context creation requested while Jupyter is initializing - waiting..."
349
- );
350
- const startWait = Date.now();
351
- await this.ensureInitialized();
352
- const waitTime = Date.now() - startWait;
353
- console.log(
354
- `[JupyterService] Jupyter ready after ${waitTime}ms wait - proceeding with context creation`
355
- );
356
- }
357
-
358
- // Use circuit breaker for context creation
359
- return await this.circuitBreakers.contextCreation.execute(async () => {
360
- return await this.jupyterServer.createContext(req);
361
- });
362
- }
363
-
364
- /**
365
- * Execute code - will wait for Jupyter if still initializing
366
- */
367
- async executeCode(
368
- contextId: string | undefined,
369
- code: string,
370
- language?: string
371
- ): Promise<Response> {
372
- if (!this.initialized) {
373
- console.log(
374
- "[JupyterService] Code execution requested while Jupyter is initializing - waiting..."
375
- );
376
- const startWait = Date.now();
377
- await this.ensureInitialized();
378
- const waitTime = Date.now() - startWait;
379
- console.log(
380
- `[JupyterService] Jupyter ready after ${waitTime}ms wait - proceeding with code execution`
381
- );
382
- }
383
-
384
- // Use circuit breaker for code execution
385
- return await this.circuitBreakers.codeExecution.execute(async () => {
386
- return await this.jupyterServer.executeCode(contextId, code, language);
387
- });
388
- }
389
-
390
- /**
391
- * List contexts with graceful degradation
392
- */
393
- async listContexts(): Promise<any[]> {
394
- if (!this.initialized) {
395
- return [];
396
- }
397
- return await this.jupyterServer.listContexts();
398
- }
399
-
400
- /**
401
- * Delete context - will wait for Jupyter if still initializing
402
- */
403
- async deleteContext(contextId: string): Promise<void> {
404
- if (!this.initialized) {
405
- console.log(
406
- "[JupyterService] Context deletion requested while Jupyter is initializing - waiting..."
407
- );
408
- const startWait = Date.now();
409
- await this.ensureInitialized();
410
- const waitTime = Date.now() - startWait;
411
- console.log(
412
- `[JupyterService] Jupyter ready after ${waitTime}ms wait - proceeding with context deletion`
413
- );
414
- }
415
-
416
- // Use circuit breaker for kernel communication
417
- return await this.circuitBreakers.kernelCommunication.execute(async () => {
418
- return await this.jupyterServer.deleteContext(contextId);
419
- });
420
- }
421
-
422
- /**
423
- * Shutdown the service
424
- */
425
- async shutdown(): Promise<void> {
426
- if (this.initialized) {
427
- await this.jupyterServer.shutdown();
428
- }
429
- }
430
-
431
- /**
432
- * Get initialization progress
433
- */
434
- private getInitializationProgress(): number {
435
- if (this.initialized) return 100;
436
- if (!this.initPromise) return 0;
437
-
438
- const elapsed = Date.now() - this.startTime;
439
- const estimatedTotal = 20000; // 20 seconds estimated
440
- return Math.min(95, Math.round((elapsed / estimatedTotal) * 100));
441
- }
442
- }
443
-
444
- /**
445
- * Error thrown when Jupyter is not ready yet
446
- * This matches the interface of the SDK's JupyterNotReadyError
447
- */
448
- export class JupyterNotReadyError extends Error {
449
- public readonly retryAfter: number;
450
- public readonly progress?: number;
451
-
452
- constructor(
453
- message: string,
454
- options?: { retryAfter?: number; progress?: number }
455
- ) {
456
- super(message);
457
- this.name = "JupyterNotReadyError";
458
- this.retryAfter = options?.retryAfter || 5;
459
- this.progress = options?.progress;
460
- }
461
- }
@@ -1,48 +0,0 @@
1
- """
2
- Minimal Jupyter configuration focused on kernel-only usage
3
- """
4
-
5
- c = get_config() # noqa
6
-
7
- # Disable all authentication - we handle security at container level
8
- c.ServerApp.token = ''
9
- c.ServerApp.password = ''
10
- c.IdentityProvider.token = ''
11
- c.ServerApp.allow_origin = '*'
12
- c.ServerApp.allow_remote_access = True
13
- c.ServerApp.disable_check_xsrf = True
14
- c.ServerApp.allow_root = True
15
- c.ServerApp.allow_credentials = True
16
-
17
- # Also set NotebookApp settings for compatibility
18
- c.NotebookApp.token = ''
19
- c.NotebookApp.password = ''
20
- c.NotebookApp.allow_origin = '*'
21
- c.NotebookApp.allow_remote_access = True
22
- c.NotebookApp.disable_check_xsrf = True
23
- c.NotebookApp.allow_credentials = True
24
-
25
- # Performance settings
26
- c.ServerApp.iopub_data_rate_limit = 1000000000 # E2B uses 1GB/s
27
-
28
- # Minimal logging
29
- c.Application.log_level = 'ERROR'
30
-
31
- # Disable browser
32
- c.ServerApp.open_browser = False
33
-
34
- # Optimize for container environment
35
- c.ServerApp.ip = '0.0.0.0'
36
- c.ServerApp.port = 8888
37
-
38
- # Kernel optimizations
39
- c.KernelManager.shutdown_wait_time = 0.0
40
- c.MappingKernelManager.cull_idle_timeout = 0
41
- c.MappingKernelManager.cull_interval = 0
42
-
43
- # Disable terminals
44
- c.ServerApp.terminals_enabled = False
45
-
46
- # Disable all extensions to speed up startup
47
- c.ServerApp.jpserver_extensions = {}
48
- c.ServerApp.nbserver_extensions = {}