E2B/packages/python-sdk/e2b/exceptions.py

140 lines
3.0 KiB
Python
Raw Permalink Normal View History

2024-06-21 16:55:49 -07:00
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."
2024-06-21 16:55:49 -07:00
)
2024-07-18 15:05:43 +02:00
def format_request_timeout_error() -> Exception:
return TimeoutException(
"Request timed out — the 'request_timeout' option can be used to increase this timeout",
2024-07-18 15:05:43 +02:00
)
def format_execution_timeout_error() -> Exception:
return TimeoutException(
"Execution timed out — the 'timeout' option can be used to increase this timeout",
2024-07-18 15:05:43 +02:00
)
2024-06-21 16:55:49 -07:00
class SandboxException(Exception):
"""
Base class for all sandbox errors.
2024-10-16 00:52:13 -07:00
Raised when a general sandbox exception occurs.
"""
2024-06-21 16:55:49 -07:00
pass
class TimeoutException(SandboxException):
"""
Raised when a timeout occurs.
2024-10-07 16:47:00 +02:00
The `unavailable` exception type is caused by sandbox timeout.\n
The `canceled` exception type is caused by exceeding request timeout.\n
The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc.\n
The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly.\n
"""
2024-06-21 16:55:49 -07:00
pass
2024-10-16 00:52:13 -07:00
class InvalidArgumentException(SandboxException):
"""
2024-10-16 00:52:13 -07:00
Raised when an invalid argument is provided.
"""
2024-06-21 16:55:49 -07:00
pass
2024-10-16 00:52:13 -07:00
class NotEnoughSpaceException(SandboxException):
"""
2024-10-16 00:52:13 -07:00
Raised when there is not enough disk space.
"""
2024-06-21 16:55:49 -07:00
pass
2024-10-16 00:52:13 -07:00
class NotFoundException(SandboxException):
"""
2024-10-16 00:52:13 -07:00
Raised when a resource is not found.
.. deprecated::
Use :class:`FileNotFoundException` or :class:`SandboxNotFoundException` instead.
This class will be removed in the next major version.
"""
pass
class FileNotFoundException(NotFoundException):
"""
Raised when a file or directory is not found inside a sandbox.
"""
pass
class SandboxNotFoundException(NotFoundException):
"""
Raised when a sandbox is not found (e.g. it doesn't exist or is no longer running).
"""
2024-06-21 16:55:49 -07:00
pass
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
class AuthenticationException(Exception):
"""
Raised when authentication fails.
"""
2024-06-21 16:55:49 -07:00
pass
Feature: Add Git Support (#1101) # Sandbox Git Commands Adds Git support to the sandbox class. This allows the sandbox to manage git via standard clone, checkout, branch, add, pull, and push commands without needing to use commands.run. The API mirrors common Git workflows while handling sandbox-specific concerns like auth injection and safe remote handling. **Python example** ```python from e2b import Sandbox sandbox = Sandbox.create() repo_path = '/home/user/my-repo' # Optional: set author for commits sandbox.git.configure_user('Your Name', 'you@example.com') # Clone or init sandbox.git.clone('https://github.com/org/repo.git', path=repo_path) # or sandbox.git.init(repo_path, initial_branch='main') # Make a change sandbox.files.write(f'{repo_path}/README.md', '# Hello\n') # Commit sandbox.git.add(repo_path, files=['README.md']) sandbox.git.commit(repo_path, message='Initial commit') # Branching sandbox.git.create_branch(repo_path, 'feature1') # or sandbox.git.checkout_branch(repo_path, 'main') # Push sandbox.git.remote_add(repo_path, 'origin', 'https://github.com/org/repo.git', overwrite=True) sandbox.git.push(repo_path, remote='origin', branch='main', set_upstream=True) ``` **JavaScript / TypeScript example** ```ts import { Sandbox } from 'e2b' const sandbox = await Sandbox.create() const repoPath = '/home/user/my-repo' await sandbox.git.configureUser('Your Name', 'you@example.com') await sandbox.git.clone('https://github.com/org/repo.git', { path: repoPath }) // or await sandbox.git.init(repoPath, { initialBranch: 'main' }) await sandbox.files.write(`${repoPath}/README.md`, '# Hello\n') await sandbox.git.add(repoPath, { files: ['README.md'] }) await sandbox.git.commit(repoPath, { message: 'Initial commit' }) await sandbox.git.createBranch(repoPath, 'feature1') await sandbox.git.checkoutBranch(repoPath, 'main') await sandbox.git.remoteAdd(repoPath, 'origin', 'https://github.com/org/repo.git', { overwrite: true, }) await sandbox.git.push(repoPath, { remote: 'origin', branch: 'main', setUpstream: true }) ``` **Main commands** - `clone`: Clone a repo into the sandbox. Supports `branch`, `depth`, optional `username` + `password` for private repos, and `dangerously_store_credentials` / `dangerouslyStoreCredentials` to keep credentials in the remote URL. - `init`: Initialize a new repo. Supports `initial_branch` / `initialBranch` and `bare`. - `status`: Get parsed `git status --porcelain -b` info. - `branches`: List branches and current branch. - `create_branch` / `createBranch`: Create and check out a new branch. - `checkout_branch` / `checkoutBranch`: Switch to an existing branch. - `delete_branch` / `deleteBranch`: Delete a branch. Supports `force`. - `add`: Stage files. Supports explicit files or `all`. - `commit`: Create a commit. Supports author override and `allow_empty`. - `reset` / `reset`: Reset `HEAD` (supports modes like `soft`, `mixed`, `hard`, etc.) and optional paths. - `restore` / `restore`: Restore files or unstage changes (`worktree` / `staged`) from a source ref. - `pull`: Pull from a remote. Supports `remote`, `branch`, and optional auth. - `push`: Push to a remote. Supports `remote`, `branch`, `set_upstream`, and optional auth. - `remote_add` / `remoteAdd`: Add a remote. Supports `overwrite` and `fetch`. - `remote_get` / `remoteGet`: Read a remote URL. - `set_config` / `setConfig`: Set a git config value. Supports `scope` (`global`, `local`, `system`), and `path` for local scope. - `get_config` / `getConfig`: Read a git config value. Supports the same `scope` options and returns `None` / `undefined` if unset. - `dangerously_authenticate` / `dangerouslyAuthenticate`: Persist credentials via the git credential helper (global). - `configure_user` / `configureUser`: Set default `user.name` and `user.email` for commits. - `create_github_repo` (Python only): Create a GitHub repo from inside the sandbox and optionally add it as a remote. **Status shape** - `status` returns a `GitStatus` with `current_branch` / `currentBranch`, `upstream`, `ahead`, `behind`, `detached`, and `file_status` / `fileStatus`. - `file_status` entries include `name`, `status`, `index_status` / `indexStatus`, `working_tree_status` / `workingTreeStatus`, `staged`, and optional `renamed_from` / `renamedFrom`. - Convenience helpers include: `is_clean` / `isClean`, `has_changes` / `hasChanges`, `has_staged` / `hasStaged`, `has_untracked` / `hasUntracked`, `has_conflicts` / `hasConflicts`, plus counts (`total_count` / `totalCount`, `staged_count` / `stagedCount`, `unstaged_count` / `unstagedCount`, `untracked_count` / `untrackedCount`, `conflict_count` / `conflictCount`). In Python these are properties on the `GitStatus` object; in JS they are fields on the returned object. **Notes** - For private HTTPS remotes, pass `username` + `password` (token) on `clone`, `pull`, or `push`. - Use `remote_add` / `remoteAdd` with `overwrite=True` to update an existing remote URL and `fetch=True` to fetch after. - Use `dangerously_authenticate` / `dangerouslyAuthenticate` only when you want to persist credentials globally on the sandbox.
2026-01-29 11:13:15 -08:00
class GitAuthException(AuthenticationException):
"""
Raised when git authentication fails.
"""
pass
class GitUpstreamException(SandboxException):
"""
Raised when git upstream tracking is missing.
"""
pass
class TemplateException(SandboxException):
"""
Exception raised when the template uses old envd version. It isn't compatible with the new SDK.
"""
2024-10-22 21:41:08 -07:00
2024-10-22 21:57:08 -07:00
class RateLimitException(SandboxException):
2024-10-22 21:41:08 -07:00
"""
2024-10-22 21:57:08 -07:00
Raised when the API rate limit is exceeded.
2024-10-22 21:41:08 -07:00
"""
class BuildException(Exception):
"""
Raised when the build fails.
"""
class FileUploadException(BuildException):
"""
Raised when the file upload fails.
"""
class VolumeException(Exception):
"""
Base class for all volume errors.
Raised when general volume errors occur.
"""