Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(sdk): add ServiceBusyError for 503 and expose the HTTP status on API errors (#1832)
Babis Chalios6b759bf762b6
diff --git a/.changeset/service-busy-error.md b/.changeset/service-busy-error.mdnew file mode 100644index 000000000..35e14401a--- /dev/null+++ b/.changeset/service-busy-error.md@@ -0,0 +1,6 @@+---+'e2b': minor+'@e2b/python-sdk': minor+---++Add `ServiceBusyError` (JavaScript) / `ServiceBusyException` (Python) for HTTP 503 responses: the API refused the operation because the service or the node running the sandbox is temporarily busy, the sandbox is unchanged, and the call can be retried. A refused `pause()` is the first case. The base `SandboxError` / `SandboxException` also carries the HTTP status as `statusCode` / `status_code` when the error came from an API response, so callers can branch on the status without parsing the message. Like `AuthenticationError` / `AuthenticationException`, the new class does not subclass the sandbox base error: it is raised for every 503 whatever the operation, so catch it explicitly.diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.tsindex 8750ff112..a89ed0951 100644--- a/packages/js-sdk/src/api/index.ts+++ b/packages/js-sdk/src/api/index.ts@@ -4,7 +4,12 @@ import type { components, paths } from './schema.gen'import { defaultHeaders } from './metadata'import { createApiFetch } from './http2'import { ConnectionConfig } from '../connectionConfig'-import { AuthenticationError, RateLimitError, SandboxError } from '../errors'+import {+ AuthenticationError,+ RateLimitError,+ ServiceBusyError,+ SandboxError,+} from '../errors'import { createApiLogger } from '../logs'/**@@ -33,7 +38,17 @@ export function apiErrorFromCode(return new RateLimitError(content ? `${message} - ${content}` : message)}- return new errorClass(`${code}: ${content}`, stackTrace)+ if (code === 503) {+ const message = 'Service temporarily unavailable, please retry'+ return new ServiceBusyError(content ? `${message} - ${content}` : message)+ }++ const err = new errorClass(`${code}: ${content}`, stackTrace)+ if (err instanceof SandboxError) {+ err.statusCode = code+ }++ return err}export function handleApiError(@@ -51,7 +66,7 @@ export function handleApiError(}const status = response.response.status- if (status === 401 || status === 429) {+ if (status === 401 || status === 429 || status === 503) {return apiErrorFromCode(status,response.error?.message ?? response.error,diff --git a/packages/js-sdk/src/errors.ts b/packages/js-sdk/src/errors.tsindex e9fbcdc23..f14893506 100644--- a/packages/js-sdk/src/errors.ts+++ b/packages/js-sdk/src/errors.ts@@ -11,6 +11,11 @@ export function formatSandboxTimeoutError(message: string) {* Thrown when general sandbox errors occur.*/export class SandboxError extends Error {+ /**+ * HTTP status of the API response that produced this error, when there was one.+ */+ statusCode?: number+constructor(message?: string) {super(message)this.name = 'SandboxError'@@ -144,6 +149,32 @@ export class RateLimitError extends SandboxError {constructor(message: string) {super(message)this.name = 'RateLimitError'+ this.statusCode = 429+ }+}++/**+ * Thrown when the API refused the operation because the service is+ * temporarily busy (HTTP 503): no capacity to place a sandbox right now, or+ * the node running the sandbox declined a request it cannot serve yet.+ *+ * Nothing was changed by the refused call: for example a refused pause+ * leaves the sandbox running with its state intact, so the same call can be+ * retried after a short wait.+ *+ * Like {@link AuthenticationError} and unlike the other API errors, this is+ * not a {@link SandboxError}: it is raised for every 503 whatever the+ * operation, so catch it explicitly.+ */+export class ServiceBusyError extends Error {+ /**+ * HTTP status of the API response: always 503.+ */+ readonly statusCode = 503++ constructor(message: string) {+ super(message)+ this.name = 'ServiceBusyError'}}diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.tsindex 8d1e15c28..1a49508e6 100644--- a/packages/js-sdk/src/index.ts+++ b/packages/js-sdk/src/index.ts@@ -20,6 +20,7 @@ export {TemplateError,TimeoutError,RateLimitError,+ ServiceBusyError,BuildError,FileUploadError,VolumeError,diff --git a/packages/js-sdk/tests/api/handleApiError.test.ts b/packages/js-sdk/tests/api/handleApiError.test.tsindex 82c24bb3d..249850280 100644--- a/packages/js-sdk/tests/api/handleApiError.test.ts+++ b/packages/js-sdk/tests/api/handleApiError.test.ts@@ -3,6 +3,7 @@ import { handleApiError } from '../../src/api'import {AuthenticationError,RateLimitError,+ ServiceBusyError,SandboxError,} from '../../src/errors'@@ -67,6 +68,51 @@ describe('handleApiError', () => {assert.instanceOf(err, AuthenticationError)assert.include(err?.message, 'Unauthorized')})++ test('returns ServiceBusyError for 503 with undefined error', () => {+ const res = createMockResponse(503, undefined)+ const err = handleApiError(res as any)+ assert.instanceOf(err, ServiceBusyError)+ assert.include(err?.message, 'temporarily unavailable')+ })+ })++ describe('status code on the error', () => {+ test('a refused pause is a ServiceBusyError carrying 503 and the API message', () => {+ const res = createMockResponse(503, {+ message: 'node is busy persisting sandbox, please retry',+ })+ const err = handleApiError(res as any) as ServiceBusyError+ assert.instanceOf(err, ServiceBusyError)+ assert.equal(err.statusCode, 503)+ assert.include(err.message, 'node is busy persisting sandbox')+ })++ test('a generic failure keeps SandboxError and carries its status', () => {+ const res = createMockResponse(500, { message: 'boom' })+ const err = handleApiError(res as any) as SandboxError+ assert.instanceOf(err, SandboxError)+ assert.equal(err.statusCode, 500)+ })++ test('a 503 is a ServiceBusyError whatever error class the caller asked for', () => {+ class BuildLikeError extends SandboxError {+ constructor(message: string) {+ super(message)+ this.name = 'BuildLikeError'+ }+ }+ const res = createMockResponse(503, { message: 'no capacity' })+ const err = handleApiError(res as any, BuildLikeError)+ assert.instanceOf(err, ServiceBusyError)+ })++ test('RateLimitError carries 429', () => {+ const res = createMockResponse(429, { message: 'slow down' })+ const err = handleApiError(res as any) as SandboxError+ assert.instanceOf(err, RateLimitError)+ assert.equal(err.statusCode, 429)+ })})describe('with empty error body', () => {diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex 03ab1bcbc..ff010de53 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -47,6 +47,7 @@ from .exceptions import (NotEnoughSpaceException,NotFoundException,RateLimitException,+ ServiceBusyException,SandboxException,SandboxNotFoundException,TemplateException,@@ -176,6 +177,7 @@ __all__ = ["Username",# Exceptions"SandboxException",+ "ServiceBusyException","TimeoutException","NotFoundException","FileNotFoundException",diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.pyindex fa9ec3f3d..845658ccf 100644--- a/packages/python-sdk/e2b/api/__init__.py+++ b/packages/python-sdk/e2b/api/__init__.py@@ -19,6 +19,7 @@ from e2b.exceptions import (AuthenticationException,InvalidArgumentException,RateLimitException,+ ServiceBusyException,SandboxException,)@@ -199,9 +200,19 @@ def api_exception_from_code(text += f" - {message}"return RateLimitException(text)- return default_exception_class(f"{status_code}: {message}").with_traceback(+ if status_code == 503:+ text = f"{status_code}: Service temporarily unavailable, please retry."+ if message:+ text += f" - {message}"+ return ServiceBusyException(text)++ err = default_exception_class(f"{status_code}: {message}").with_traceback(stack_trace)+ if isinstance(err, SandboxException):+ err.status_code = status_code++ return errdef handle_api_exception(@@ -215,10 +226,14 @@ def handle_api_exception(body = {}message = body["message"] if "message" in body else None- if message is None and e.status_code not in (401, 429):- return default_exception_class(f"{e.status_code}: {e.content}").with_traceback(+ if message is None and e.status_code not in (401, 429, 503):+ err = default_exception_class(f"{e.status_code}: {e.content}").with_traceback(stack_trace)+ if isinstance(err, SandboxException):+ err.status_code = e.status_code++ return errreturn api_exception_from_code(e.status_code,diff --git a/packages/python-sdk/e2b/exceptions.py b/packages/python-sdk/e2b/exceptions.pyindex 1ac9689f0..4cc3abb62 100644--- a/packages/python-sdk/e2b/exceptions.py+++ b/packages/python-sdk/e2b/exceptions.py@@ -1,3 +1,6 @@+from typing import Optional++def format_sandbox_timeout_exception(message: str):return TimeoutException(f"{message}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeout' when starting the sandbox or calling '.set_timeout' on the sandbox with the desired timeout."@@ -15,9 +18,17 @@ class SandboxException(Exception):Base class for all sandbox errors.Raised when a general sandbox exception occurs.++ :param status_code: HTTP status of the API response that produced this error, when there was one."""- pass+ # Class-level default so subclasses that bypass this initializer (dataclass+ # exceptions such as CommandExitException) still expose the attribute.+ status_code: Optional[int] = None++ def __init__(self, *args, status_code: Optional[int] = None):+ super().__init__(*args)+ self.status_code = status_codeclass TimeoutException(SandboxException):@@ -116,6 +127,29 @@ class RateLimitException(SandboxException):Raised when the API rate limit is exceeded."""+ def __init__(self, *args):+ super().__init__(*args, status_code=429)+++class ServiceBusyException(Exception):+ """+ Raised when the API refused the operation because the service is+ temporarily busy (HTTP 503): no capacity to place a sandbox right now, or+ the node running the sandbox declined a request it cannot serve yet.++ Nothing was changed by the refused call: for example a refused pause+ leaves the sandbox running with its state intact, so the same call can be+ retried after a short wait.++ Like `AuthenticationException` and unlike the other API errors, this is not+ a `SandboxException`: it is raised for every 503 whatever the operation, so+ catch it explicitly.++ :param status_code: HTTP status of the API response: always 503.+ """++ status_code = 503+class BuildException(Exception):"""diff --git a/packages/python-sdk/tests/test_api_exception.py b/packages/python-sdk/tests/test_api_exception.pynew file mode 100644index 000000000..cd6dc8168--- /dev/null+++ b/packages/python-sdk/tests/test_api_exception.py@@ -0,0 +1,73 @@+from types import SimpleNamespace++from e2b.api import api_exception_from_code, handle_api_exception+from e2b.exceptions import (+ RateLimitException,+ ServiceBusyException,+ SandboxException,+)+++def response(status_code: int, content: bytes = b""):+ return SimpleNamespace(status_code=status_code, content=content, headers={})+++def test_refused_pause_is_a_busy_exception_with_the_status_and_message():+ err = handle_api_exception(+ response(503, b'{"message":"node is busy persisting sandbox, please retry"}')+ )++ assert isinstance(err, ServiceBusyException)+ assert err.status_code == 503+ assert "node is busy persisting sandbox" in str(err)+++def test_503_without_a_body_is_still_a_busy_exception():+ err = handle_api_exception(response(503))++ assert isinstance(err, ServiceBusyException)+ assert err.status_code == 503+++def test_generic_failure_stays_a_sandbox_exception_and_carries_its_status():+ err = handle_api_exception(response(500, b'{"message":"Internal error"}'))++ assert isinstance(err, SandboxException)+ assert err.status_code == 500+ assert str(err) == "500: Internal error"+++def test_generic_failure_without_a_body_carries_its_status():+ err = handle_api_exception(response(502, b"bad gateway"))++ assert isinstance(err, SandboxException)+ assert err.status_code == 502+++def test_503_is_a_busy_exception_whatever_class_the_caller_asked_for():+ class BuildLikeException(SandboxException):+ pass++ err = handle_api_exception(+ response(503, b'{"message":"no capacity"}'),+ default_exception_class=BuildLikeException,+ )++ assert isinstance(err, ServiceBusyException)+ assert err.status_code == 503+++def test_exceptions_that_bypass_the_initializer_still_expose_the_status():+ from e2b.sandbox.commands.command_handle import CommandExitException++ err = CommandExitException(stdout="", stderr="boom", exit_code=1, error="boom")++ assert isinstance(err, SandboxException)+ assert err.status_code is None+++def test_rate_limit_carries_429():+ err = api_exception_from_code(429, "slow down")++ assert isinstance(err, RateLimitException)+ assert err.status_code == 429