Skip to content

sandboxes generated API reference

sandboxes

Cloudflare Sandbox SDK for Python Workers.

__all__ = ('DirectoryBackup', 'DirectoryBackupGateway', 'DirectoryBackupRecord', 'FileContent', 'Files', 'ProviderCredentials', 'S3Credentials', 'S3Gateway', 'S3Mount', 'S3MountAccess', 'S3MountConfiguration', 'S3MountInspection', 'S3Source', 'SandboxAbortError', 'SandboxBackupError', 'SandboxDirectoryEntry', 'SandboxError', 'SandboxFileError', 'SandboxFileStat', 'SandboxFileType', 'SandboxProtocolError', 'SandboxS3MountError', 'StaticCredentials') module-attribute

__title__ = 'sandboxes' module-attribute

__version__ = '0.1.1' module-attribute

__license__ = 'Apache-2.0' module-attribute

FileContent = str | bytes | bytearray | memoryview | AsyncIterable[bytes] | Any

str, bytes-like, an async iterable of bytes, or a JS ReadableStream.

SandboxFileType = Literal['file', 'directory', 'symlink', 'block_device', 'character_device', 'fifo', 'socket']

S3Credentials = StaticCredentials | ProviderCredentials

S3MountAccess = Literal['read-only', 'read-write']

DirectoryBackup

Saves a directory of a running container to R2, and restores it.

One backup or restore runs at a time per container, and others wait their turn, so asyncio.gather() over several directories works. Start the container first. This class never starts, retries, or times out anything.

Parameters:

Name Type Description Default
container InterceptContainer

ctx.container.

required
gateway Callable[[Any], Any]

ctx.exports.DirectoryBackupGateway.

required
binding str

The name of the R2 bucket binding the gateway writes to.

required
prefix str

A key prefix for backup objects. Empty, or ending in /.

''

__init__(container, gateway, *, binding, prefix='')

__repr__()

intercept() async

Route backup traffic to the gateway, which refuses it until an operation starts.

Call this right after starting the container, and only when the Durable Object also registers interceptAllOutboundHttp(), which takes every host registered after it. Never call it while an operation may be running: it would replace that operation's grant.

backup(dir, *, name=None, exclude=(), gitignore=False, abort=None) async

Save dir as one tar+zstd object and return its record.

Pause writers in dir first. Files that change while it is read are captured as they are at that moment.

Parameters:

Name Type Description Default
dir str

The absolute directory to save.

required
name str | None

A label stored in the record and in the R2 object's custom metadata.

None
exclude Sequence[str]

Patterns of paths to leave out.

()
gitignore bool

Also leave out paths that .gitignore files in dir ignore.

False
abort Event | None

Set it to stop the backup. The call raises SandboxAbortError and the partial upload is aborted.

None

Returns:

Type Description
DirectoryBackupRecord

Raises:

Type Description
SandboxFileError

dir is missing or not a directory, a file can't be read, or an exclude pattern is invalid (EINVAL).

SandboxBackupError

BACKUP_TRANSFER when a part upload fails, or BACKUP_INTEGRITY when R2 stored a different size than was uploaded.

restore(record, *, dir=None, abort=None) async

Replace dir, or the record's dir, with the backup's contents.

The shim extracts beside the target and swaps it in only after it verifies the download. A SandboxFileError or SandboxBackupError means the target was not replaced, and so does an abort before the download is verified. The target's parent must exist.

Parameters:

Name Type Description Default
record DirectoryBackupRecord

A record that backup() returned.

required
dir str | None

Restore here instead of the record's dir.

None
abort Event | None

Set it to stop the restore. Once the download is verified, the restore finishes anyway.

None

Raises:

Type Description
ValueError

record isn't a valid record.

SandboxFileError

The target's parent is missing, or a file can't be written.

SandboxBackupError

BACKUP_NOT_FOUND when the object is gone, BACKUP_INTEGRITY when its size or hash differs from the record, or BACKUP_TRANSFER when the download fails.

delete(record, *, abort=None) async

Delete the backup's object. Needs no running container.

Deleting an object that is already gone succeeds.

Parameters:

Name Type Description Default
record DirectoryBackupRecord

A record that backup() returned.

required
abort Event | None

If already set, the call raises SandboxAbortError and deletes nothing.

None

Raises:

Type Description
ValueError

record isn't a valid record.

DirectoryBackupGateway

Bases: WorkerEntrypoint

Moves directory backups between a container and an R2 bucket binding.

Export it from the Worker and pass ctx.exports.DirectoryBackupGateway to DirectoryBackup. The container reaches fetch() and can use only the grant its current operation holds. The other methods are for the Durable Object alone.

fetch(request) async

create_upload(name=None) async

complete_upload(upload_id, parts) async

abort_upload(upload_id) async

delete_object() async

DirectoryBackupRecord

Bases: TypedDict

What backup() returns. Store it to restore or delete the backup later.

Records match the JS SDK's, so either SDK can restore them.

Attributes:

Name Type Description
id str

A UUID that names the R2 object, <prefix><id>.tar.zst.

dir str

The directory that was saved.

size int

The object's size in bytes.

name NotRequired[str]

The name passed to backup(), if any.

sha256 str

The hex SHA-256 of the object.

format Literal['tar+zstd/1']

Always "tar+zstd/1".

id instance-attribute

dir instance-attribute

size instance-attribute

name instance-attribute

sha256 instance-attribute

format instance-attribute

SandboxAbortError

Bases: SandboxError

The caller set the abort event before the operation finished.

__init__()

SandboxBackupError

Bases: SandboxError

A directory backup is missing, changed, or failed to transfer.

Attributes:

Name Type Description
code BackupErrorCode

BACKUP_NOT_FOUND, BACKUP_INTEGRITY or BACKUP_TRANSFER.

operation BackupOperation

"backup", "restore" or "delete".

path

The directory being saved or restored.

detail

A description of the failure.

code = code instance-attribute

operation = operation instance-attribute

path = path instance-attribute

detail = detail instance-attribute

__init__(code, operation, path, detail)

SandboxError

Bases: Exception

The base class of every error this package raises.

SandboxFileError

Bases: SandboxError

Linux rejected a file operation in the container.

Attributes:

Name Type Description
code

The errno name, such as "ENOENT", or "UNKNOWN".

operation FileOperation

The method that failed.

path

The path the method was called with.

destination

The destination of a rename, otherwise None.

detail

The shim's description of the failure.

code = code instance-attribute

operation = operation instance-attribute

path = path instance-attribute

destination = destination instance-attribute

detail = detail instance-attribute

__init__(code, operation, path, detail, *, destination=None)

from_errno(errno, detail, operation, path, *, destination=None) classmethod

SandboxProtocolError

Bases: SandboxError

The package and sandbox-shim could not complete their exchange.

This usually means the image's shim and the package version don't match.

code = 'SANDBOX_PROTOCOL_ERROR' class-attribute instance-attribute

detail = detail instance-attribute

__init__(detail)

SandboxS3MountError

Bases: SandboxError

An S3 mount operation failed in the container.

Attributes:

Name Type Description
code S3MountErrorCode

S3_MOUNT_BUSY, S3_MOUNT_CONFLICT, S3_MOUNT_FAILED or S3_MOUNT_INCOMPATIBLE.

operation S3MountOperation

"mount", "inspect" or "unmount".

path

The mount path.

detail

The shim's description of the failure.

code = code instance-attribute

operation = operation instance-attribute

path = path instance-attribute

detail = detail instance-attribute

__init__(code, operation, path, detail)

Files

File operations in a running container.

Every method is a coroutine and accepts cwd, user and abort.

The image must provide /usr/local/bin/sandbox-shim from the cloudflare/sandbox image this package was tested against.

Parameters:

Name Type Description Default
container Container

ctx.container, or any object with a compatible exec.

required

__init__(container)

__repr__()

read_file(path, /, *, cwd=None, user=None, abort=None) async

Stream a file's bytes.

Parameters:

Name Type Description Default
path str

The file to read.

required
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Returns:

Type Description
Response

A response whose body applies backpressure to the shim. A failure after the file opened errors the body.

Raises:

Type Description
SandboxFileError

The file could not be opened.

SandboxProtocolError

The shim's reply was invalid.

write_file(path, content, /, *, cwd=None, user=None, abort=None) async

Create or truncate a file and stream content into it.

The file is opened before content is read, so a later failure can leave it created, truncated or partly written.

Parameters:

Name Type Description Default
path str

The file to write. Its parent directory must exist.

required
content FileContent

str (written as UTF-8), bytes-like, an async iterable of bytes, or a JS ReadableStream of Uint8Array chunks.

required
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Raises:

Type Description
TypeError

content has an unsupported type.

SandboxFileError

Linux rejected the write, for example with ENOENT or EISDIR.

stat(path, /, *, cwd=None, user=None, abort=None) async

Return metadata for path, following a final symbolic link.

Parameters:

Name Type Description Default
path str

The path to describe.

required
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Returns:

Type Description
SandboxFileStat

Raises:

Type Description
SandboxFileError

Linux rejected the call, for example with ENOENT.

lstat(path, /, *, cwd=None, user=None, abort=None) async

Return metadata for path without following a final symbolic link.

Parameters:

Name Type Description Default
path str

The path to describe.

required
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Returns:

Type Description
SandboxFileStat

Raises:

Type Description
SandboxFileError

Linux rejected the call, for example with ENOENT.

read_directory(path, /, *, cwd=None, user=None, abort=None) async

List the immediate entries of a directory, in native order.

Parameters:

Name Type Description Default
path str

The directory to list.

required
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Returns:

Type Description
list[SandboxDirectoryEntry]

Raises:

Type Description
SandboxFileError

Linux rejected the call, for example with ENOTDIR.

mkdir(path, /, *, recursive=False, cwd=None, user=None, abort=None) async

Create a directory, and with recursive, its missing parents.

Parameters:

Name Type Description Default
path str

The directory to create.

required
recursive bool

Create missing parents too.

False
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Raises:

Type Description
SandboxFileError

Linux rejected the call, for example with EEXIST.

rename(source, destination, /, *, cwd=None, user=None, abort=None) async

Rename a path with Linux rename rules.

Crossing filesystems fails with EXDEV. Nothing is copied instead.

Parameters:

Name Type Description Default
source str

The path to rename.

required
destination str

The new path.

required
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Raises:

Type Description
SandboxFileError

Linux rejected the call, for example with ENOENT or EXDEV.

remove(path, /, *, recursive=False, force=False, cwd=None, user=None, abort=None) async

Remove a file, a symbolic link, or with recursive, a directory tree.

Parameters:

Name Type Description Default
path str

The path to remove.

required
recursive bool

Remove a directory and everything in it.

False
force bool

Succeed when path doesn't exist. Other errors still raise.

False
cwd str | None

An absolute directory that relative paths are joined onto. Without it, relative paths raise ValueError.

None
user str | None

The numeric user and group the shim runs as, as "uid:gid". Defaults to the container's user.

None
abort Event | None

Set it to stop the operation. The call then raises SandboxAbortError.

None

Raises:

Type Description
SandboxFileError

Linux rejected the call, for example with ENOENT or EISDIR.

SandboxDirectoryEntry dataclass

One entry of a directory.

Attributes:

Name Type Description
name str

The entry's name, without its directory.

type SandboxFileType

The kind of entry. A symbolic link is "symlink", not its target.

name instance-attribute

type instance-attribute

__init__(name, type)

SandboxFileStat dataclass

Metadata for a path in the container.

Attributes:

Name Type Description
type SandboxFileType

The kind of path.

size int

The size in bytes.

mode int

The permission bits.

uid int

The owner's user ID.

gid int

The owner's group ID.

accessed_at datetime

The last access time, in UTC.

modified_at datetime

The last time the contents changed, in UTC.

changed_at datetime

The last time the metadata changed, in UTC.

type instance-attribute

size instance-attribute

mode instance-attribute

uid instance-attribute

gid instance-attribute

accessed_at instance-attribute

modified_at instance-attribute

changed_at instance-attribute

__init__(type, size, mode, uid, gid, accessed_at, modified_at, changed_at)

S3Gateway

Bases: WorkerEntrypoint

Signs the container's storage requests for S3Mount.

Export it from the Worker and pass ctx.exports.S3Gateway to S3Mount.

fetch(request) async

ProviderCredentials

Bases: TypedDict

Credentials that S3Gateway fetches per request.

fetcher answers GET https://credentials.sandbox.internal/ with {"accessKeyId", "secretAccessKey", "sessionToken"?, "expiresAt"}.

type instance-attribute

fetcher instance-attribute

S3Mount

Mounts an S3-compatible bucket or prefix in a running container with s3fs.

The container never sees the credentials: S3Gateway checks and signs each request. Start the container first. This class never starts, monitors, or replaces it. Call mount() before any interceptAllOutboundHttp().

Parameters:

Name Type Description Default
container InterceptContainer

ctx.container.

required
gateway Callable[[Any], Any]

ctx.exports.S3Gateway.

required

__init__(container, gateway)

__repr__()

mount(mount_path, *, source, access, key_prefix=None, s3fs_options=None, abort=None) async

Mount source at mount_path.

A mount with the same settings is reused, and leftover state repaired.

Parameters:

Name Type Description Default
mount_path str

An absolute, normalized path, such as "/mnt/data". Not /, and no trailing /.

required
source S3Source

The bucket and its credentials.

required
access S3MountAccess

"read-only" or "read-write".

required
key_prefix str | None

Mount only the keys under this prefix. A trailing / is added.

None
s3fs_options Mapping[str, str | float | bool] | None

Extra s3fs options. True passes a flag, False drops it, and a string or number passes name=value. Options the package sets itself, such as endpoint or ro, raise ValueError.

None
abort Event | None

Set it to stop the mount. The call then raises SandboxAbortError.

None

Raises:

Type Description
ValueError

An argument is invalid, or mount_path overlaps a path the package needs.

SandboxS3MountError

S3_MOUNT_CONFLICT when a different mount holds the path, S3_MOUNT_BUSY, S3_MOUNT_INCOMPATIBLE or S3_MOUNT_FAILED.

inspect(mount_path, *, abort=None) async

Report the state of mount_path without changing it.

Waits for a mount() or unmount() in progress on the path first.

Parameters:

Name Type Description Default
mount_path str

The path to inspect.

required
abort Event | None

Set it to stop the call. The call then raises SandboxAbortError.

None

Returns:

Type Description
S3MountInspection

unmount(mount_path, *, abort=None) async

Deny further storage requests, then unmount mount_path.

Unmounting a path with nothing mounted succeeds.

Parameters:

Name Type Description Default
mount_path str

The path to unmount.

required
abort Event | None

Set it to stop the call. The call then raises SandboxAbortError.

None

Raises:

Type Description
SandboxS3MountError

S3_MOUNT_BUSY when the path is in use. Requests stay denied.

S3MountConfiguration

Bases: TypedDict

The settings of a mount, without credentials, as the container records them.

source instance-attribute

key_prefix instance-attribute

access instance-attribute

s3fs_options instance-attribute

S3MountInspection

Bases: TypedDict

The state of a mount path.

Only stale and managed attachments include gateway, and only managed includes fuse.

mount_path instance-attribute

attachment instance-attribute

fuse instance-attribute

gateway instance-attribute

S3Source

Bases: TypedDict

The bucket to mount and the credentials that reach it.

Attributes:

Name Type Description
type Literal['s3']

Always "s3".

endpoint str

The S3 API origin, such as "https://<ACCOUNT_ID>.r2.cloudflarestorage.com". HTTP or HTTPS, with no path, query or credentials.

region str

The region requests are signed for. R2 uses "auto".

bucket str

The bucket name. It can't start with - or contain / or :.

credentials S3Credentials

StaticCredentials or ProviderCredentials.

type instance-attribute

endpoint instance-attribute

region instance-attribute

bucket instance-attribute

credentials instance-attribute

StaticCredentials

Bases: TypedDict

Fixed S3 keys, such as an R2 API token's access key ID and secret.

Attributes:

Name Type Description
type Literal['static']

Always "static".

access_key_id str

The access key ID.

secret_access_key str

The secret access key.

session_token NotRequired[str]

A session token, for temporary credentials.

type instance-attribute

access_key_id instance-attribute

secret_access_key instance-attribute

session_token instance-attribute