@cloudflare/sandbox 0.0.0-ee8c772 → 0.0.0-ef9e320

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 (42) hide show
  1. package/CHANGELOG.md +193 -0
  2. package/Dockerfile +96 -10
  3. package/README.md +806 -23
  4. package/container_src/bun.lock +76 -0
  5. package/container_src/circuit-breaker.ts +121 -0
  6. package/container_src/control-process.ts +784 -0
  7. package/container_src/handler/exec.ts +185 -0
  8. package/container_src/handler/file.ts +406 -0
  9. package/container_src/handler/git.ts +130 -0
  10. package/container_src/handler/ports.ts +314 -0
  11. package/container_src/handler/process.ts +568 -0
  12. package/container_src/handler/session.ts +92 -0
  13. package/container_src/index.ts +432 -2740
  14. package/container_src/interpreter-service.ts +276 -0
  15. package/container_src/isolation.ts +1038 -0
  16. package/container_src/mime-processor.ts +255 -0
  17. package/container_src/package.json +9 -0
  18. package/container_src/runtime/executors/javascript/node_executor.ts +123 -0
  19. package/container_src/runtime/executors/python/ipython_executor.py +338 -0
  20. package/container_src/runtime/executors/typescript/ts_executor.ts +138 -0
  21. package/container_src/runtime/process-pool.ts +464 -0
  22. package/container_src/shell-escape.ts +42 -0
  23. package/container_src/startup.sh +11 -0
  24. package/container_src/types.ts +131 -0
  25. package/package.json +6 -8
  26. package/src/client.ts +442 -1362
  27. package/src/errors.ts +219 -0
  28. package/src/index.ts +72 -126
  29. package/src/interpreter-client.ts +352 -0
  30. package/src/interpreter-types.ts +390 -0
  31. package/src/interpreter.ts +150 -0
  32. package/src/request-handler.ts +144 -0
  33. package/src/sandbox.ts +747 -0
  34. package/src/security.ts +113 -0
  35. package/src/sse-parser.ts +147 -0
  36. package/src/types.ts +502 -0
  37. package/tsconfig.json +1 -1
  38. package/tests/client.example.ts +0 -308
  39. package/tests/connection-test.ts +0 -81
  40. package/tests/simple-test.ts +0 -81
  41. package/tests/test1.ts +0 -281
  42. package/tests/test2.ts +0 -929
package/src/errors.ts ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Standard error response from the sandbox API
3
+ */
4
+ export interface SandboxErrorResponse {
5
+ error?: string;
6
+ status?: string;
7
+ progress?: number;
8
+ }
9
+
10
+ /**
11
+ * Base error class for all Sandbox-related errors
12
+ */
13
+ export class SandboxError extends Error {
14
+ constructor(message: string) {
15
+ super(message);
16
+ this.name = this.constructor.name;
17
+
18
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
19
+ if (Error.captureStackTrace) {
20
+ Error.captureStackTrace(this, this.constructor);
21
+ }
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Error thrown when interpreter functionality is requested but the service is still initializing.
27
+ *
28
+ * Note: With the current implementation, requests wait for interpreter to be ready.
29
+ * This error is only thrown when:
30
+ * 1. The request times out waiting for interpreter (default: 30 seconds)
31
+ * 2. interpreter initialization actually fails
32
+ *
33
+ * Most requests will succeed after a delay, not throw this error.
34
+ */
35
+ export class InterpreterNotReadyError extends SandboxError {
36
+ public readonly code = "INTERPRETER_NOT_READY";
37
+ public readonly retryAfter: number;
38
+ public readonly progress?: number;
39
+
40
+ constructor(
41
+ message?: string,
42
+ options?: { retryAfter?: number; progress?: number }
43
+ ) {
44
+ super(
45
+ message ||
46
+ "Interpreter is still initializing. Please retry in a few seconds."
47
+ );
48
+ this.retryAfter = options?.retryAfter || 5;
49
+ this.progress = options?.progress;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Error thrown when a context is not found
55
+ */
56
+ export class ContextNotFoundError extends SandboxError {
57
+ public readonly code = "CONTEXT_NOT_FOUND";
58
+ public readonly contextId: string;
59
+
60
+ constructor(contextId: string) {
61
+ super(`Context ${contextId} not found`);
62
+ this.contextId = contextId;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Error thrown when code execution fails
68
+ */
69
+ export class CodeExecutionError extends SandboxError {
70
+ public readonly code = "CODE_EXECUTION_ERROR";
71
+ public readonly executionError?: {
72
+ ename?: string;
73
+ evalue?: string;
74
+ traceback?: string[];
75
+ };
76
+
77
+ constructor(message: string, executionError?: any) {
78
+ super(message);
79
+ this.executionError = executionError;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Error thrown when the sandbox container is not ready
85
+ */
86
+ export class ContainerNotReadyError extends SandboxError {
87
+ public readonly code = "CONTAINER_NOT_READY";
88
+
89
+ constructor(message?: string) {
90
+ super(
91
+ message ||
92
+ "Container is not ready. Please wait for initialization to complete."
93
+ );
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Error thrown when a network request to the sandbox fails
99
+ */
100
+ export class SandboxNetworkError extends SandboxError {
101
+ public readonly code = "NETWORK_ERROR";
102
+ public readonly statusCode?: number;
103
+ public readonly statusText?: string;
104
+
105
+ constructor(message: string, statusCode?: number, statusText?: string) {
106
+ super(message);
107
+ this.statusCode = statusCode;
108
+ this.statusText = statusText;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Error thrown when service is temporarily unavailable (e.g., circuit breaker open)
114
+ */
115
+ export class ServiceUnavailableError extends SandboxError {
116
+ public readonly code = "SERVICE_UNAVAILABLE";
117
+ public readonly retryAfter?: number;
118
+
119
+ constructor(message?: string, retryAfter?: number) {
120
+ // Simple, user-friendly message without implementation details
121
+ super(message || "Service temporarily unavailable");
122
+ this.retryAfter = retryAfter;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Type guard to check if an error is a InterpreterNotReadyError
128
+ */
129
+ export function isInterpreterNotReadyError(
130
+ error: unknown
131
+ ): error is InterpreterNotReadyError {
132
+ return error instanceof InterpreterNotReadyError;
133
+ }
134
+
135
+ /**
136
+ * Type guard to check if an error is any SandboxError
137
+ */
138
+ export function isSandboxError(error: unknown): error is SandboxError {
139
+ return error instanceof SandboxError;
140
+ }
141
+
142
+ /**
143
+ * Helper to determine if an error is retryable
144
+ */
145
+ export function isRetryableError(error: unknown): boolean {
146
+ if (
147
+ error instanceof InterpreterNotReadyError ||
148
+ error instanceof ContainerNotReadyError ||
149
+ error instanceof ServiceUnavailableError
150
+ ) {
151
+ return true;
152
+ }
153
+
154
+ if (error instanceof SandboxNetworkError) {
155
+ // Retry on 502, 503, 504 (gateway/service unavailable errors)
156
+ return error.statusCode
157
+ ? [502, 503, 504].includes(error.statusCode)
158
+ : false;
159
+ }
160
+
161
+ return false;
162
+ }
163
+
164
+ /**
165
+ * Parse error response from the sandbox API and return appropriate error instance
166
+ */
167
+ export async function parseErrorResponse(
168
+ response: Response
169
+ ): Promise<SandboxError> {
170
+ let data: SandboxErrorResponse;
171
+
172
+ try {
173
+ data = (await response.json()) as SandboxErrorResponse;
174
+ } catch {
175
+ // If JSON parsing fails, return a generic network error
176
+ return new SandboxNetworkError(
177
+ `Request failed with status ${response.status}`,
178
+ response.status,
179
+ response.statusText
180
+ );
181
+ }
182
+
183
+ // Check for specific error types based on response
184
+ if (response.status === 503) {
185
+ // Circuit breaker error
186
+ if (data.status === "circuit_open") {
187
+ return new ServiceUnavailableError(
188
+ "Service temporarily unavailable",
189
+ parseInt(response.headers.get("Retry-After") || "30")
190
+ );
191
+ }
192
+
193
+ // Interpreter initialization error
194
+ if (data.status === "initializing") {
195
+ return new InterpreterNotReadyError(data.error, {
196
+ retryAfter: parseInt(response.headers.get("Retry-After") || "5"),
197
+ progress: data.progress,
198
+ });
199
+ }
200
+ }
201
+
202
+ // Check for context not found
203
+ if (
204
+ response.status === 404 &&
205
+ data.error?.includes("Context") &&
206
+ data.error?.includes("not found")
207
+ ) {
208
+ const contextId =
209
+ data.error.match(/Context (\S+) not found/)?.[1] || "unknown";
210
+ return new ContextNotFoundError(contextId);
211
+ }
212
+
213
+ // Default network error
214
+ return new SandboxNetworkError(
215
+ data.error || `Request failed with status ${response.status}`,
216
+ response.status,
217
+ response.statusText
218
+ );
219
+ }
package/src/index.ts CHANGED
@@ -1,129 +1,75 @@
1
- import { Container, getContainer } from "@cloudflare/containers";
2
- import { HttpClient } from "./client";
1
+ // biome-ignore-start assist/source/organizeImports: Need separate exports for deprecation warnings to work properly
2
+ /**
3
+ * @deprecated Use `InterpreterNotReadyError` instead. Will be removed in a future version.
4
+ */
5
+ export { InterpreterNotReadyError as JupyterNotReadyError } from "./errors";
3
6
 
4
- export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
5
- return getContainer(ns, id);
6
- }
7
+ /**
8
+ * @deprecated Use `isInterpreterNotReadyError` instead. Will be removed in a future version.
9
+ */
10
+ export { isInterpreterNotReadyError as isJupyterNotReadyError } from "./errors";
11
+ // biome-ignore-end assist/source/organizeImports: Need separate exports for deprecation warnings to work properly
7
12
 
8
- export class Sandbox<Env = unknown> extends Container<Env> {
9
- defaultPort = 3000; // The default port for the container to listen on
10
- sleepAfter = "3m"; // Sleep the sandbox if no requests are made in this timeframe
13
+ // Export API response types
14
+ export {
15
+ CodeExecutionError,
16
+ ContainerNotReadyError,
17
+ ContextNotFoundError,
18
+ InterpreterNotReadyError,
19
+ isInterpreterNotReadyError,
20
+ isRetryableError,
21
+ isSandboxError,
22
+ parseErrorResponse,
23
+ SandboxError,
24
+ type SandboxErrorResponse,
25
+ SandboxNetworkError,
26
+ ServiceUnavailableError,
27
+ } from "./errors";
11
28
 
12
- client: HttpClient = new HttpClient({
13
- onCommandComplete: (success, exitCode, stdout, stderr, command, args) => {
14
- console.log(
15
- `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
16
- );
17
- },
18
- onCommandStart: (command, args) => {
19
- console.log(`[Container] Command started: ${command} ${args.join(" ")}`);
20
- },
21
- onError: (error, command, args) => {
22
- console.error(`[Container] Command error: ${error}`);
23
- },
24
- onOutput: (stream, data, command) => {
25
- console.log(`[Container] [${stream}] ${data}`);
26
- },
27
- port: this.defaultPort,
28
- });
29
-
30
- envVars = {
31
- MESSAGE: "I was passed in via the Sandbox class!",
32
- };
33
-
34
- override onStart() {
35
- console.log("Sandbox successfully started");
36
- }
37
-
38
- override onStop() {
39
- console.log("Sandbox successfully shut down");
40
- if (this.client) {
41
- this.client.clearSession();
42
- }
43
- }
44
-
45
- override onError(error: unknown) {
46
- console.log("Sandbox error:", error);
47
- }
48
-
49
- async exec(command: string, args: string[], options?: { stream?: boolean }) {
50
- if (options?.stream) {
51
- return this.client.executeStream(command, args);
52
- }
53
- return this.client.execute(command, args);
54
- }
55
-
56
- async gitCheckout(
57
- repoUrl: string,
58
- options: { branch?: string; targetDir?: string; stream?: boolean }
59
- ) {
60
- if (options?.stream) {
61
- return this.client.gitCheckoutStream(
62
- repoUrl,
63
- options.branch,
64
- options.targetDir
65
- );
66
- }
67
- return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
68
- }
69
-
70
- async mkdir(
71
- path: string,
72
- options: { recursive?: boolean; stream?: boolean }
73
- ) {
74
- if (options?.stream) {
75
- return this.client.mkdirStream(path, options.recursive);
76
- }
77
- return this.client.mkdir(path, options.recursive);
78
- }
79
-
80
- async writeFile(
81
- path: string,
82
- content: string,
83
- options: { encoding?: string; stream?: boolean }
84
- ) {
85
- if (options?.stream) {
86
- return this.client.writeFileStream(path, content, options.encoding);
87
- }
88
- return this.client.writeFile(path, content, options.encoding);
89
- }
90
-
91
- async deleteFile(path: string, options: { stream?: boolean }) {
92
- if (options?.stream) {
93
- return this.client.deleteFileStream(path);
94
- }
95
- return this.client.deleteFile(path);
96
- }
97
-
98
- async renameFile(
99
- oldPath: string,
100
- newPath: string,
101
- options: { stream?: boolean }
102
- ) {
103
- if (options?.stream) {
104
- return this.client.renameFileStream(oldPath, newPath);
105
- }
106
- return this.client.renameFile(oldPath, newPath);
107
- }
108
-
109
- async moveFile(
110
- sourcePath: string,
111
- destinationPath: string,
112
- options: { stream?: boolean }
113
- ) {
114
- if (options?.stream) {
115
- return this.client.moveFileStream(sourcePath, destinationPath);
116
- }
117
- return this.client.moveFile(sourcePath, destinationPath);
118
- }
119
-
120
- async readFile(
121
- path: string,
122
- options: { encoding?: string; stream?: boolean }
123
- ) {
124
- if (options?.stream) {
125
- return this.client.readFileStream(path, options.encoding);
126
- }
127
- return this.client.readFile(path, options.encoding);
128
- }
129
- }
29
+ // Export code interpreter types
30
+ export type {
31
+ ChartData,
32
+ CodeContext,
33
+ CreateContextOptions,
34
+ Execution,
35
+ ExecutionError,
36
+ OutputMessage,
37
+ Result,
38
+ RunCodeOptions,
39
+ } from "./interpreter-types";
40
+ // Export the implementations
41
+ export { ResultImpl } from "./interpreter-types";
42
+ // Re-export request handler utilities
43
+ export {
44
+ proxyToSandbox,
45
+ type RouteInfo,
46
+ type SandboxEnv,
47
+ } from "./request-handler";
48
+ export { getSandbox, Sandbox } from "./sandbox";
49
+ // Export SSE parser for converting ReadableStream to AsyncIterable
50
+ export {
51
+ asyncIterableToSSEStream,
52
+ parseSSEStream,
53
+ responseToAsyncIterable,
54
+ } from "./sse-parser";
55
+ export type {
56
+ DeleteFileResponse,
57
+ ExecEvent,
58
+ ExecOptions,
59
+ ExecResult,
60
+ ExecuteResponse,
61
+ ExecutionSession,
62
+ GitCheckoutResponse,
63
+ ISandbox,
64
+ ListFilesResponse,
65
+ LogEvent,
66
+ MkdirResponse,
67
+ MoveFileResponse,
68
+ Process,
69
+ ProcessOptions,
70
+ ProcessStatus,
71
+ ReadFileResponse,
72
+ RenameFileResponse,
73
+ StreamOptions,
74
+ WriteFileResponse,
75
+ } from "./types";