Documentation
¶
Overview ¶
Package sandbox creates and works with Baseten sandboxes.
Create one Client up front and reuse it, then create a sandbox and run a command in it:
client, err := sandbox.NewClient(sandbox.ClientOptions{
APIKey: os.Getenv("BASETEN_API_KEY"),
})
if err != nil {
return err
}
sb, err := client.Create(ctx, sandbox.CreateOptions{})
if err != nil {
return err
}
process, err := sb.Process().Exec(ctx, sandbox.ProcessExecOptions{
Command: "echo hello",
WaitForCompletion: true,
})
if err != nil {
return err
}
fmt.Print(process.Stdout)
Index ¶
- func DefaultImageIgnoreFile(_ context.Context, opts ImageIgnoreFileOptions) (bool, error)
- type APIError
- type Client
- func (c *Client) API() *managementapi.Client
- func (c *Client) Create(ctx context.Context, opts CreateOptions) (*CreateResult, error)
- func (c *Client) Delete(ctx context.Context, opts DeleteOptions) (*Info, error)
- func (c *Client) Get(ctx context.Context, opts GetOptions) (*Sandbox, error)
- func (c *Client) GetInfo(ctx context.Context, opts GetInfoOptions) (*Info, error)
- func (c *Client) Images() *ImageClient
- func (c *Client) List(ctx context.Context, opts ListOptions) iter.Seq2[*Info, error]
- func (c *Client) SandboxFromURL(opts SandboxFromURLOptions) (*Sandbox, error)
- func (c *Client) Update(ctx context.Context, opts UpdateOptions) (*Info, error)
- type ClientOptions
- type CreateOptions
- type CreateResult
- type DeleteOptions
- type EnvValue
- type ExpirationAction
- type ExpirationPolicy
- type ExpirationPolicyType
- type FileSystemCopyError
- type FileSystemCopyOptions
- type FileSystemDirectory
- type FileSystemEntryType
- type FileSystemFileInfo
- type FileSystemFindMatch
- type FileSystemFindOptions
- type FileSystemFindResult
- type FileSystemGrepMatch
- type FileSystemGrepOptions
- type FileSystemGrepResult
- type FileSystemListOptions
- type FileSystemMkdirOptions
- type FileSystemReadBytesOptions
- type FileSystemReadOptions
- type FileSystemRemoveOptions
- type FileSystemService
- func (f *FileSystemService) Copy(ctx context.Context, opts FileSystemCopyOptions) error
- func (f *FileSystemService) Find(ctx context.Context, opts FileSystemFindOptions) (*FileSystemFindResult, error)
- func (f *FileSystemService) Grep(ctx context.Context, opts FileSystemGrepOptions) (*FileSystemGrepResult, error)
- func (f *FileSystemService) List(ctx context.Context, opts FileSystemListOptions) (*FileSystemDirectory, error)
- func (f *FileSystemService) Mkdir(ctx context.Context, opts FileSystemMkdirOptions) error
- func (f *FileSystemService) Read(ctx context.Context, opts FileSystemReadOptions) (string, error)
- func (f *FileSystemService) ReadBytes(ctx context.Context, opts FileSystemReadBytesOptions) ([]byte, error)
- func (f *FileSystemService) Remove(ctx context.Context, opts FileSystemRemoveOptions) error
- func (f *FileSystemService) Watch(ctx context.Context, opts FileSystemWatchOptions) iter.Seq2[FileSystemWatchEvent, error]
- func (f *FileSystemService) Write(ctx context.Context, opts FileSystemWriteOptions) error
- func (f *FileSystemService) WriteBytes(ctx context.Context, opts FileSystemWriteBytesOptions) error
- func (f *FileSystemService) WriteTree(ctx context.Context, opts FileSystemWriteTreeOptions) error
- type FileSystemSubdirectoryInfo
- type FileSystemWatchEvent
- type FileSystemWatchOp
- type FileSystemWatchOptions
- type FileSystemWriteBytesOptions
- type FileSystemWriteOptions
- type FileSystemWriteTreeOptions
- type GatewayError
- type GetInfoOptions
- type GetOptions
- type ImageBuildError
- type ImageBuilder
- func (b *ImageBuilder) AddFile(destination string, content []byte) *ImageBuilder
- func (b *ImageBuilder) AddFileWithOptions(opts ImageBuilderAddFileOptions) *ImageBuilder
- func (b *ImageBuilder) AddLocalDir(source, destination string) *ImageBuilder
- func (b *ImageBuilder) AddLocalDirWithOptions(opts ImageBuilderAddLocalDirOptions) *ImageBuilder
- func (b *ImageBuilder) AddLocalFile(source, destination string) *ImageBuilder
- func (b *ImageBuilder) AddLocalFileWithOptions(opts ImageBuilderAddLocalFileOptions) *ImageBuilder
- func (b *ImageBuilder) ApkAdd(args ...string) *ImageBuilder
- func (b *ImageBuilder) AptInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) Arg(name, defaultValue string) *ImageBuilder
- func (b *ImageBuilder) BaseImage() string
- func (b *ImageBuilder) CargoInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) ComposerInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) Copy(source, destination string) *ImageBuilder
- func (b *ImageBuilder) Dockerfile() (string, error)
- func (b *ImageBuilder) DockerfileLines(lines ...string) *ImageBuilder
- func (b *ImageBuilder) Entrypoint(args ...string) *ImageBuilder
- func (b *ImageBuilder) Env(variables map[string]string) *ImageBuilder
- func (b *ImageBuilder) Expose(ports ...int) *ImageBuilder
- func (b *ImageBuilder) GemInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) GoInstall(packages ...string) *ImageBuilder
- func (b *ImageBuilder) Label(labels map[string]string) *ImageBuilder
- func (b *ImageBuilder) NpmInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) PipInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) PipxInstall(packages ...string) *ImageBuilder
- func (b *ImageBuilder) RunCommands(commands ...string) *ImageBuilder
- func (b *ImageBuilder) User(user string) *ImageBuilder
- func (b *ImageBuilder) UvInstall(args ...string) *ImageBuilder
- func (b *ImageBuilder) Workdir(path string) *ImageBuilder
- type ImageBuilderAddFileOptions
- type ImageBuilderAddLocalDirOptions
- type ImageBuilderAddLocalFileOptions
- type ImageBuilderOptions
- type ImageCleanupOptions
- type ImageCleanupResult
- type ImageClient
- func (c *ImageClient) Cleanup(ctx context.Context, opts ImageCleanupOptions) (*ImageCleanupResult, error)
- func (c *ImageClient) Delete(ctx context.Context, opts ImageDeleteOptions) (*ImageInfo, error)
- func (c *ImageClient) DeleteTag(ctx context.Context, opts ImageDeleteTagOptions) (*ImageInfo, error)
- func (c *ImageClient) GetInfo(ctx context.Context, opts ImageGetInfoOptions) (*ImageInfo, error)
- func (c *ImageClient) List(ctx context.Context, opts ImageListOptions) iter.Seq2[*ImageInfo, error]
- func (c *ImageClient) ListLibrary(ctx context.Context, opts ImageListLibraryOptions) ([]ImageLibraryInfo, error)
- func (c *ImageClient) ListTags(ctx context.Context, opts ImageListTagsOptions) iter.Seq2[*ImageTagInfo, error]
- func (c *ImageClient) Logs(ctx context.Context, opts ImageLogsOptions) ([]ImageLogLine, error)
- func (c *ImageClient) Push(ctx context.Context, opts ImagePushOptions) (*ImageInfo, error)
- func (c *ImageClient) WaitBuilt(ctx context.Context, opts ImageWaitBuiltOptions) (*ImageInfo, error)
- type ImageDeleteOptions
- type ImageDeleteTagOptions
- type ImageGetInfoOptions
- type ImageIgnoreFileFunc
- type ImageIgnoreFileOptions
- type ImageIgnoreFileProcessorOptions
- type ImageInfo
- type ImageLibraryInfo
- type ImageLibraryVolume
- type ImageListLibraryOptions
- type ImageListOptions
- type ImageListTagsOptions
- type ImageLogLine
- type ImageLogsOptions
- type ImagePushOptions
- type ImageRegistrySource
- type ImageSort
- type ImageStatus
- type ImageTagInfo
- type ImageTagSort
- type ImageUploadError
- type ImageWaitBuiltOptions
- type Info
- type Lifecycle
- type ListOptions
- type Network
- type NetworkProxy
- type NetworkProxyRoute
- type Port
- type PortProtocol
- type ProcessCloseStdinOptions
- type ProcessExecEvent
- type ProcessExecOptions
- type ProcessExecStreamOptions
- type ProcessGetOptions
- type ProcessInfo
- type ProcessKillOptions
- type ProcessListOptions
- type ProcessLogLine
- type ProcessLogs
- type ProcessLogsOptions
- type ProcessService
- func (p *ProcessService) CloseStdin(ctx context.Context, opts ProcessCloseStdinOptions) error
- func (p *ProcessService) Exec(ctx context.Context, opts ProcessExecOptions) (*ProcessInfo, error)
- func (p *ProcessService) ExecStream(ctx context.Context, opts ProcessExecStreamOptions) iter.Seq2[ProcessExecEvent, error]
- func (p *ProcessService) Get(ctx context.Context, opts ProcessGetOptions) (*ProcessInfo, error)
- func (p *ProcessService) Kill(ctx context.Context, opts ProcessKillOptions) error
- func (p *ProcessService) List(ctx context.Context, opts ProcessListOptions) ([]ProcessInfo, error)
- func (p *ProcessService) Logs(ctx context.Context, opts ProcessLogsOptions) (*ProcessLogs, error)
- func (p *ProcessService) Stop(ctx context.Context, opts ProcessStopOptions) error
- func (p *ProcessService) StreamLogs(ctx context.Context, opts ProcessStreamLogsOptions) iter.Seq2[ProcessLogLine, error]
- func (p *ProcessService) Wait(ctx context.Context, opts ProcessWaitOptions) (*ProcessInfo, error)
- func (p *ProcessService) WriteStdin(ctx context.Context, opts ProcessWriteStdinOptions) error
- type ProcessStatus
- type ProcessStopOptions
- type ProcessStream
- type ProcessStreamLogsOptions
- type ProcessWaitOptions
- type ProcessWaitTimeoutError
- type ProcessWriteStdinOptions
- type RetryOptions
- type Sandbox
- type SandboxFromURLOptions
- type Status
- type TokenProvider
- type TokenProviderOptions
- type UpdateOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultImageIgnoreFile ¶
func DefaultImageIgnoreFile(_ context.Context, opts ImageIgnoreFileOptions) (bool, error)
DefaultImageIgnoreFile reports whether a path is left out of a pushed build context by the default rules, applied when the directory has no .dockerignore. Its result is the same as this .dockerignore:
**/.blaxel **/.env.build **/.docker **/.git **/dist **/.venv **/venv **/node_modules **/.env .env* **/.next **/__pycache__
So each of those names is left out at any depth, as a file or as a directory with everything in it, and a name starting with .env is left out at the root. To extend the defaults, copy them into a .dockerignore.
Types ¶
type APIError ¶
type APIError struct {
// Status is the HTTP status of the response.
Status int
// Code is the machine-readable error code, empty when the response has
// none.
Code string
// Details are additional error details, nil when the response has none.
Details any
// Body is the response body, parsed as JSON when possible, otherwise the
// raw text.
Body any
// contains filtered or unexported fields
}
APIError is an error response from the sandbox control plane or from a sandbox.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client works with Baseten sandboxes: creating, finding, updating, and deleting them, and getting a Sandbox to work in one.
func NewClient ¶
func NewClient(opts ClientOptions) (*Client, error)
NewClient creates a Client without making a network request.
func (*Client) API ¶
func (c *Client) API() *managementapi.Client
API returns the underlying generated management API client, authenticated for sandboxes, for operations this package does not wrap. The generated API surface is not covered by Go compatibility guarantees and may change between versions.
func (*Client) Create ¶
func (c *Client) Create(ctx context.Context, opts CreateOptions) (*CreateResult, error)
Create creates a sandbox.
func (*Client) Delete ¶
Delete deletes a sandbox and returns its record. Deletion continues after this returns, so the record usually shows the sandbox as deleting.
func (*Client) Images ¶
func (c *Client) Images() *ImageClient
Images works with the images that sandboxes are created from.
func (*Client) List ¶
List lists sandbox records, fetching further pages as iteration reaches them. An error is yielded as the second value and ends the iteration.
func (*Client) SandboxFromURL ¶
func (c *Client) SandboxFromURL(opts SandboxFromURLOptions) (*Sandbox, error)
SandboxFromURL returns a Sandbox for a sandbox whose URL is already known, without a call. Prefer Client.Get or Client.Create, which take the URL from the sandbox's record. The returned Sandbox has no name.
type ClientOptions ¶
type ClientOptions struct {
// APIKey is the Baseten API key used for authentication. Required unless
// one of the advanced ManagementClient or TokenProvider options is set.
APIKey string
// TeamID is the team to act in. Empty uses the caller's only team, and
// is an error for callers in more than one team.
TeamID string
// BaseURL overrides the default management API base URL. If empty,
// "https://api.baseten.co" is used.
BaseURL string
// HTTPClient overrides the default HTTP client. If nil,
// http.DefaultClient is used.
HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
// Headers are added to every request. The map is cloned at construction,
// so later mutations by the caller do not affect the live client.
Headers http.Header
// Retries sets how many times calls to a sandbox are retried on dropped
// connections and gateway errors.
Retries RetryOptions
// ManagementClient is an advanced alternative to APIKey: the management
// client that sandbox tokens are requested through, with its own base
// URL and authentication. For callers that authenticate the management
// API other than with an API key. APIKey and TokenProvider must then be
// empty.
ManagementClient *client.ManagementClient
// TokenProvider is an advanced alternative to APIKey: it returns the
// bearer token for each request, for callers that obtain sandbox tokens
// themselves. APIKey and ManagementClient must then be empty.
TokenProvider TokenProvider
}
ClientOptions configures a Client.
type CreateOptions ¶
type CreateOptions struct {
// Name is the sandbox's unique name. The server assigns one when empty.
Name string
// CreateIfNotExists returns the existing sandbox with this name instead
// of failing when one exists. Requires Name.
CreateIfNotExists bool
// Image is the image reference, including its tag. Defaults to
// "baseten/base-image:latest".
Image string
// Memory is the memory allocation in megabytes, which also sets the CPU
// allocation. Defaults to 4096.
Memory int
// Region is where the sandbox runs. Empty uses the closest region.
Region string
// Envs are the environment variables injected into the sandbox, by name.
Envs map[string]EnvValue
// Labels are the key-value pairs for organizing and filtering.
Labels map[string]string
// ExternalID is a caller-owned identifier for external lookups.
ExternalID string
// Lifecycle is when the sandbox expires.
Lifecycle *Lifecycle
// Ports are the ports the sandbox exposes.
Ports []Port
// Network is the sandbox's network configuration. It cannot be updated
// later.
Network *Network
}
CreateOptions are the options for Client.Create. Unset fields are omitted, so the server applies its defaults.
type CreateResult ¶
type CreateResult struct {
*Sandbox
// Info is the sandbox's record as of creation. The sandbox becomes ready
// asynchronously, so its status is usually still deploying.
Info Info
}
CreateResult is a created sandbox: a Sandbox to work in, plus its record as of creation.
type DeleteOptions ¶
type DeleteOptions struct {
// Name is the sandbox's name. Required.
Name string
}
DeleteOptions are the options for Client.Delete.
type EnvValue ¶
type EnvValue struct {
// Value of the variable.
Value string
// NonSecret marks the value as not secret, so it is returned unmasked.
// False, the default, keeps it secret.
NonSecret bool
}
EnvValue is the value of one environment variable.
type ExpirationAction ¶
type ExpirationAction string
ExpirationAction is what happens when a sandbox expires. Other values may be added, so do not treat the constants as exhaustive.
const ( // ExpirationActionDelete deletes the sandbox. ExpirationActionDelete ExpirationAction = "DELETE" )
Values for ExpirationAction.
type ExpirationPolicy ¶
type ExpirationPolicy struct {
// Type is the kind of policy, which decides whether After or At applies.
Type ExpirationPolicyType
// After is the duration for [ExpirationPolicyTypeTTLIdle] and
// [ExpirationPolicyTypeTTLMaxAge].
After time.Duration
// At is the time for [ExpirationPolicyTypeDate].
At time.Time
// Action is what happens on expiry. Empty sends [ExpirationActionDelete].
Action ExpirationAction
}
ExpirationPolicy is one rule for when a sandbox expires.
type ExpirationPolicyType ¶
type ExpirationPolicyType string
ExpirationPolicyType is the kind of an expiration policy. Other values may be added, so do not treat the constants as exhaustive.
const ( // ExpirationPolicyTypeTTLIdle expires the sandbox after it has been idle // for [ExpirationPolicy.After]. ExpirationPolicyTypeTTLIdle ExpirationPolicyType = "TTL_IDLE" // ExpirationPolicyTypeTTLMaxAge expires the sandbox // [ExpirationPolicy.After] its creation. ExpirationPolicyTypeTTLMaxAge ExpirationPolicyType = "TTL_MAX_AGE" // ExpirationPolicyTypeDate expires the sandbox at [ExpirationPolicy.At]. ExpirationPolicyTypeDate ExpirationPolicyType = "DATE" )
Values for ExpirationPolicyType.
type FileSystemCopyError ¶
type FileSystemCopyError struct {
// Source is the path copied from.
Source string
// Destination is the path copied to.
Destination string
// Process is the cp process as it ended, whose Stderr holds its error
// output.
Process *ProcessInfo
}
FileSystemCopyError is a FileSystemService.Copy whose cp process did not complete successfully.
func (*FileSystemCopyError) Error ¶
func (e *FileSystemCopyError) Error() string
type FileSystemCopyOptions ¶
type FileSystemCopyOptions struct {
// Source is the path of the file or directory to copy. Required.
Source string
// Destination is the path to copy to. Required.
Destination string
// Timeout is how long to wait for the copy. Zero uses 180 seconds, and a
// negative value waits with no limit. The copy keeps running regardless.
Timeout time.Duration
}
FileSystemCopyOptions are the options for FileSystemService.Copy.
type FileSystemDirectory ¶
type FileSystemDirectory struct {
Name string
Path string
Files []FileSystemFileInfo
Subdirectories []FileSystemSubdirectoryInfo
}
FileSystemDirectory is a directory's contents, one level deep, from FileSystemService.List.
type FileSystemEntryType ¶
type FileSystemEntryType string
FileSystemEntryType is the kind of a filesystem entry. Other values may be added, so do not treat the constants as exhaustive.
const ( FileSystemEntryTypeFile FileSystemEntryType = "file" FileSystemEntryTypeDirectory FileSystemEntryType = "directory" )
Values for FileSystemEntryType.
type FileSystemFileInfo ¶
type FileSystemFileInfo struct {
Name string
Path string
// Size is the file's size in bytes.
Size int64
// Permissions is the file's mode, as the sandbox reports it.
Permissions string
Owner string
Group string
LastModified time.Time
}
FileSystemFileInfo is a file in a FileSystemDirectory.
type FileSystemFindMatch ¶
type FileSystemFindMatch struct {
// Path is relative to the searched path.
Path string
Type FileSystemEntryType
}
FileSystemFindMatch is an entry found by FileSystemService.Find.
type FileSystemFindOptions ¶
type FileSystemFindOptions struct {
// Path is the path of the directory to search in. Required.
Path string
// Type finds only files or only directories. Empty finds both.
Type FileSystemEntryType
// Patterns are file patterns to include, such as "*.go".
Patterns []string
// MaxResults is the most results to return. Zero uses the sandbox's
// default of 20, and a negative value returns all.
MaxResults int
// ExcludeDirs are directory names to skip. Empty uses the sandbox's
// default of common dependency and build directories, such as
// node_modules and .git.
ExcludeDirs []string
// IncludeHidden includes hidden files and directories, which the sandbox
// skips by default.
IncludeHidden bool
}
FileSystemFindOptions are the options for FileSystemService.Find.
type FileSystemFindResult ¶
type FileSystemFindResult struct {
Matches []FileSystemFindMatch
// Total is the number of entries found, which may exceed the matches
// returned.
Total int
}
FileSystemFindResult is the result of FileSystemService.Find.
type FileSystemGrepMatch ¶
type FileSystemGrepMatch struct {
// Path is relative to the searched path.
Path string
// Line is the line number, starting at 1.
Line int
Column int
// Text is the matching line.
Text string
// Context is the matching line with up to
// [FileSystemGrepOptions.ContextLines] lines before and after it,
// newline-separated. Empty when ContextLines is zero.
Context string
}
FileSystemGrepMatch is a matching line found by FileSystemService.Grep.
type FileSystemGrepOptions ¶
type FileSystemGrepOptions struct {
// Path is the path of the directory to search in. Required.
Path string
// Query is the text to search for. Required.
Query string
// CaseSensitive makes the search case sensitive.
CaseSensitive bool
// MaxResults is the most results to return. Zero uses the sandbox's
// default of 100.
MaxResults int
// FilePattern is a file pattern to include, such as "*.go".
FilePattern string
// ExcludeDirs are directory names to skip. Empty uses the sandbox's
// default of common dependency and build directories, such as
// node_modules and .git.
ExcludeDirs []string
// ContextLines is how many lines before and after each match to include
// in its Context, at most 20. Zero includes none.
ContextLines int
}
FileSystemGrepOptions are the options for FileSystemService.Grep.
type FileSystemGrepResult ¶
type FileSystemGrepResult struct {
Matches []FileSystemGrepMatch
// Total is the number of matching lines, which may exceed the matches
// returned.
Total int
}
FileSystemGrepResult is the result of FileSystemService.Grep.
type FileSystemListOptions ¶
type FileSystemListOptions struct {
// Path is the path of the directory. Required.
Path string
}
FileSystemListOptions are the options for FileSystemService.List.
type FileSystemMkdirOptions ¶
type FileSystemMkdirOptions struct {
// Path is the path of the directory. Required.
Path string
// Permissions is the octal directory mode, such as "0755". Empty uses the
// sandbox's default.
Permissions string
}
FileSystemMkdirOptions are the options for FileSystemService.Mkdir.
type FileSystemReadBytesOptions ¶
type FileSystemReadBytesOptions struct {
// Path is the path of the file. Required.
Path string
}
FileSystemReadBytesOptions are the options for FileSystemService.ReadBytes.
type FileSystemReadOptions ¶
type FileSystemReadOptions struct {
// Path is the path of the file. Required.
Path string
}
FileSystemReadOptions are the options for FileSystemService.Read.
type FileSystemRemoveOptions ¶
type FileSystemRemoveOptions struct {
// Path is the path of the file or directory. Required.
Path string
// Recursive removes a directory and everything in it.
Recursive bool
}
FileSystemRemoveOptions are the options for FileSystemService.Remove.
type FileSystemService ¶
type FileSystemService struct {
// contains filtered or unexported fields
}
FileSystemService reads and writes files and directories in a sandbox. Get it from Sandbox.FS. Relative paths are resolved against the sandbox's working directory.
func (*FileSystemService) Copy ¶
func (f *FileSystemService) Copy(ctx context.Context, opts FileSystemCopyOptions) error
Copy copies a file or directory. It runs cp -r in the sandbox through ProcessService.Exec, then waits for it with ProcessService.Wait, so cp's rules apply, such as copying into a destination that is an existing directory.
It returns a *FileSystemCopyError if the copy fails, and a *ProcessWaitTimeoutError if it outlasts the timeout, which does not stop it.
func (*FileSystemService) Find ¶
func (f *FileSystemService) Find(ctx context.Context, opts FileSystemFindOptions) (*FileSystemFindResult, error)
Find finds files and directories by name under a directory.
func (*FileSystemService) Grep ¶
func (f *FileSystemService) Grep(ctx context.Context, opts FileSystemGrepOptions) (*FileSystemGrepResult, error)
Grep searches the contents of files under a directory for text.
func (*FileSystemService) List ¶
func (f *FileSystemService) List(ctx context.Context, opts FileSystemListOptions) (*FileSystemDirectory, error)
List lists a directory's files and subdirectories, one level deep.
func (*FileSystemService) Mkdir ¶
func (f *FileSystemService) Mkdir(ctx context.Context, opts FileSystemMkdirOptions) error
Mkdir creates a directory.
func (*FileSystemService) Read ¶
func (f *FileSystemService) Read(ctx context.Context, opts FileSystemReadOptions) (string, error)
Read reads a text file.
func (*FileSystemService) ReadBytes ¶
func (f *FileSystemService) ReadBytes(ctx context.Context, opts FileSystemReadBytesOptions) ([]byte, error)
ReadBytes reads a file as bytes.
func (*FileSystemService) Remove ¶
func (f *FileSystemService) Remove(ctx context.Context, opts FileSystemRemoveOptions) error
Remove removes a file or directory.
func (*FileSystemService) Watch ¶
func (f *FileSystemService) Watch(ctx context.Context, opts FileSystemWatchOptions) iter.Seq2[FileSystemWatchEvent, error]
Watch yields changes in a directory as they happen, until the iteration stops or ctx is done. Only the directory's direct entries are watched unless Recursive is set. An error is yielded as the second value and ends the iteration.
func (*FileSystemService) Write ¶
func (f *FileSystemService) Write(ctx context.Context, opts FileSystemWriteOptions) error
Write writes a text file, creating it or replacing its content. Content over 5MB is uploaded in 5MB parts through the multipart upload endpoints, at most 2 parts at a time per sandbox.
func (*FileSystemService) WriteBytes ¶
func (f *FileSystemService) WriteBytes(ctx context.Context, opts FileSystemWriteBytesOptions) error
WriteBytes writes a file from bytes, creating it or replacing its content. Content over 5MB is uploaded in 5MB parts through the multipart upload endpoints, at most 2 parts at a time per sandbox.
func (*FileSystemService) WriteTree ¶
func (f *FileSystemService) WriteTree(ctx context.Context, opts FileSystemWriteTreeOptions) error
WriteTree writes several text files under a directory in one call, creating or replacing each.
type FileSystemSubdirectoryInfo ¶
FileSystemSubdirectoryInfo is a subdirectory in a FileSystemDirectory.
type FileSystemWatchEvent ¶
type FileSystemWatchEvent struct {
// Ops are the kinds of change, more than one when the sandbox reports
// several together.
Ops []FileSystemWatchOp
// Path is the full path of the changed entry.
Path string
}
FileSystemWatchEvent is a change seen by FileSystemService.Watch.
type FileSystemWatchOp ¶
type FileSystemWatchOp string
FileSystemWatchOp is a kind of change in a FileSystemWatchEvent. Other values may be added, so do not treat the constants as exhaustive.
const ( FileSystemWatchOpCreate FileSystemWatchOp = "CREATE" FileSystemWatchOpWrite FileSystemWatchOp = "WRITE" FileSystemWatchOpRemove FileSystemWatchOp = "REMOVE" FileSystemWatchOpRename FileSystemWatchOp = "RENAME" FileSystemWatchOpChmod FileSystemWatchOp = "CHMOD" )
Values for FileSystemWatchOp.
type FileSystemWatchOptions ¶
type FileSystemWatchOptions struct {
// Path is the path of the directory to watch. Required.
Path string
// Recursive also watches every subdirectory, including ones created
// later.
Recursive bool
// Ignore skips events whose full path contains any of these substrings.
Ignore []string
}
FileSystemWatchOptions are the options for FileSystemService.Watch.
type FileSystemWriteBytesOptions ¶
type FileSystemWriteBytesOptions struct {
// Path is the path of the file, created or replaced. Required.
Path string
// Content is the content to write.
Content []byte
// Permissions is the octal file mode, such as "0755", applied when the
// file is created. An existing file keeps its mode. Empty uses the
// sandbox's default.
Permissions string
}
FileSystemWriteBytesOptions are the options for FileSystemService.WriteBytes.
type FileSystemWriteOptions ¶
type FileSystemWriteOptions struct {
// Path is the path of the file, created or replaced. Required.
Path string
// Content is the text content to write.
Content string
}
FileSystemWriteOptions are the options for FileSystemService.Write.
type FileSystemWriteTreeOptions ¶
type FileSystemWriteTreeOptions struct {
// Path is the path of the directory to write under. Required.
Path string
// Files is the text content of each file, by path relative to Path.
Files map[string]string
}
FileSystemWriteTreeOptions are the options for FileSystemService.WriteTree.
type GatewayError ¶
type GatewayError struct {
APIError
}
GatewayError is a 502, 503, or 504 from the edge in front of a sandbox rather than from the sandbox itself. Usually transient, for example while a sandbox wakes from standby or when a request outlasts the edge's timeout.
func (*GatewayError) Unwrap ¶
func (e *GatewayError) Unwrap() error
Unwrap returns the embedded APIError, so errors.As for *APIError matches gateway errors too.
type GetInfoOptions ¶
type GetInfoOptions struct {
// Name is the sandbox's name. Required.
Name string
// ShowSecrets returns environment variable values unmasked. Requires the
// workspace admin role.
ShowSecrets bool
}
GetInfoOptions are the options for Client.GetInfo.
type GetOptions ¶
type GetOptions struct {
// Name is the sandbox's name. Required.
Name string
}
GetOptions are the options for Client.Get.
type ImageBuildError ¶
type ImageBuildError struct {
// ImageName is the name of the image.
ImageName string
// Status is the status last seen, [ImageStatusFailed] when the build
// failed.
Status ImageStatus
// TimedOut is whether the wait ran out of time. Processing continues
// regardless.
TimedOut bool
}
ImageBuildError is an image that did not become ready to use: either its build failed, or it was still processing when the wait ran out of time. ImageClient.Logs shows the build's output.
func (*ImageBuildError) Error ¶
func (e *ImageBuildError) Error() string
type ImageBuilder ¶
type ImageBuilder struct {
// contains filtered or unexported fields
}
ImageBuilder describes an image as a Dockerfile and the files it copies in, to push with ImagePushOptions.SourceBuilder. Start one with NewImageBuilder.
A builder never changes: each method returns a new builder with the instruction appended, so one builder can safely be the base of several.
Invalid input, such as a newline in a value that must fit on one line, does not stop the chain. The method leaves its instruction out and records the error, and ImageBuilder.Dockerfile and the push return every recorded error.
Package helpers such as ImageBuilder.PipInstall pass each argument to the shell unquoted if it has only letters, digits, and ._-+=:/@~^*, and single-quote it otherwise. So * and ~ still expand, as in PipInstall("dist/*.whl"), while characters such as >, ;, $, and spaces stay literal. Use ImageBuilder.RunCommands for full control.
The Dockerfile it pushes ends by copying in the sandbox API binary and making it the entrypoint, unless the builder already did either, since a sandbox needs it running to be reached. ImageBuilder.Dockerfile shows the Dockerfile exactly as pushed.
func NewImageBuilder ¶
func NewImageBuilder(baseImage string) *ImageBuilder
NewImageBuilder starts a builder from a registry image, as FROM <baseImage>. See NewImageBuilderWithOptions for more options.
func NewImageBuilderWithOptions ¶
func NewImageBuilderWithOptions(opts ImageBuilderOptions) *ImageBuilder
NewImageBuilderWithOptions starts a builder from a registry image, as FROM <BaseImage>.
func (*ImageBuilder) AddFile ¶
func (b *ImageBuilder) AddFile(destination string, content []byte) *ImageBuilder
AddFile adds a file with the given content to the build context and appends COPY ["<name>", "<destination>"], where name is its name in the context. See ImageBuilder.AddFileWithOptions for more options.
func (*ImageBuilder) AddFileWithOptions ¶
func (b *ImageBuilder) AddFileWithOptions(opts ImageBuilderAddFileOptions) *ImageBuilder
AddFileWithOptions adds a file with the given content to the build context and appends COPY ["<name>", "<destination>"], where name is its name in the context.
func (*ImageBuilder) AddLocalDir ¶
func (b *ImageBuilder) AddLocalDir(source, destination string) *ImageBuilder
AddLocalDir adds a local directory to the build context and appends COPY ["<name>", "<destination>"], where name is its name in the context. As with any COPY of a directory, its contents are copied into the destination, not the directory itself. It is read when pushed, with files keeping their permissions, a link to a file within the directory stored as a copy of the file, a link to a file outside it failing the push, and a link to a directory stored as an empty directory. Everything in it is added: no .dockerignore or default ignore rules apply. See ImageBuilder.AddLocalDirWithOptions for more options.
func (*ImageBuilder) AddLocalDirWithOptions ¶
func (b *ImageBuilder) AddLocalDirWithOptions(opts ImageBuilderAddLocalDirOptions) *ImageBuilder
AddLocalDirWithOptions adds a local directory to the build context and appends COPY ["<name>", "<destination>"], where name is its name in the context. As with any COPY of a directory, its contents are copied into the destination, not the directory itself. It is read when pushed, with files keeping their permissions, a link to a file within the directory stored as a copy of the file, a link to a file outside it failing the push, and a link to a directory stored as an empty directory. Everything in it is added: no .dockerignore or default ignore rules apply.
func (*ImageBuilder) AddLocalFile ¶
func (b *ImageBuilder) AddLocalFile(source, destination string) *ImageBuilder
AddLocalFile adds a local file to the build context and appends COPY ["<name>", "<destination>"], where name is its name in the context. The file is read when pushed, keeping its permissions, and a symbolic link is read as the file it points to. See ImageBuilder.AddLocalFileWithOptions for more options.
func (*ImageBuilder) AddLocalFileWithOptions ¶
func (b *ImageBuilder) AddLocalFileWithOptions(opts ImageBuilderAddLocalFileOptions) *ImageBuilder
AddLocalFileWithOptions adds a local file to the build context and appends COPY ["<name>", "<destination>"], where name is its name in the context. The file is read when pushed, keeping its permissions, and a symbolic link is read as the file it points to.
func (*ImageBuilder) ApkAdd ¶
func (b *ImageBuilder) ApkAdd(args ...string) *ImageBuilder
ApkAdd appends RUN apk add --no-cache <args>.
func (*ImageBuilder) AptInstall ¶
func (b *ImageBuilder) AptInstall(args ...string) *ImageBuilder
AptInstall appends RUN apt-get update && apt-get install -y --no-install-recommends <args> && rm -rf /var/lib/apt/lists/*, as one step so the package lists add nothing to the image.
func (*ImageBuilder) Arg ¶
func (b *ImageBuilder) Arg(name, defaultValue string) *ImageBuilder
Arg appends ARG <name>, or ARG <name>="<defaultValue>" when defaultValue is not empty, escaped as in ImageBuilder.Env.
func (*ImageBuilder) BaseImage ¶
func (b *ImageBuilder) BaseImage() string
BaseImage is the image this builder starts from.
func (*ImageBuilder) CargoInstall ¶
func (b *ImageBuilder) CargoInstall(args ...string) *ImageBuilder
CargoInstall appends RUN cargo install <args>.
func (*ImageBuilder) ComposerInstall ¶
func (b *ImageBuilder) ComposerInstall(args ...string) *ImageBuilder
ComposerInstall appends RUN composer require <args>.
func (*ImageBuilder) Copy ¶
func (b *ImageBuilder) Copy(source, destination string) *ImageBuilder
Copy appends COPY ["<source>", "<destination>"], copying from the build context.
func (*ImageBuilder) Dockerfile ¶
func (b *ImageBuilder) Dockerfile() (string, error)
Dockerfile is the Dockerfile exactly as it is pushed, or every error the builder recorded, joined.
func (*ImageBuilder) DockerfileLines ¶
func (b *ImageBuilder) DockerfileLines(lines ...string) *ImageBuilder
DockerfileLines appends each line verbatim, for anything the other methods do not cover, such as comments, CMD, or a heredoc. A line may contain newlines, and nothing is checked or escaped.
func (*ImageBuilder) Entrypoint ¶
func (b *ImageBuilder) Entrypoint(args ...string) *ImageBuilder
Entrypoint appends ENTRYPOINT ["<arg>", ...], in exec form. The image then runs this instead of the sandbox API binary, so it must start that itself for the sandbox to be reachable.
func (*ImageBuilder) Env ¶
func (b *ImageBuilder) Env(variables map[string]string) *ImageBuilder
Env appends ENV <name>="<value>" for each variable, in name order, with " and \ in the value escaped. $ is left as is, so the build expands variables in it, as in {"PATH": "/opt/bin:$PATH"}.
func (*ImageBuilder) Expose ¶
func (b *ImageBuilder) Expose(ports ...int) *ImageBuilder
Expose appends EXPOSE <port> for each port.
func (*ImageBuilder) GemInstall ¶
func (b *ImageBuilder) GemInstall(args ...string) *ImageBuilder
GemInstall appends RUN gem install --no-document <args>.
func (*ImageBuilder) GoInstall ¶
func (b *ImageBuilder) GoInstall(packages ...string) *ImageBuilder
GoInstall appends RUN go install <package> && go install <package> ..., one go install per package, since one call can only install packages from a single module.
func (*ImageBuilder) Label ¶
func (b *ImageBuilder) Label(labels map[string]string) *ImageBuilder
Label appends LABEL <key>="<value>" for each label, in key order, escaped as in ImageBuilder.Env.
func (*ImageBuilder) NpmInstall ¶
func (b *ImageBuilder) NpmInstall(args ...string) *ImageBuilder
NpmInstall appends RUN npm install <args>, or RUN npm install with no arguments to install from the working directory's package.json.
func (*ImageBuilder) PipInstall ¶
func (b *ImageBuilder) PipInstall(args ...string) *ImageBuilder
PipInstall appends RUN pip install <args>.
func (*ImageBuilder) PipxInstall ¶
func (b *ImageBuilder) PipxInstall(packages ...string) *ImageBuilder
PipxInstall appends RUN pipx install <package> && pipx install <package> ..., one per package.
func (*ImageBuilder) RunCommands ¶
func (b *ImageBuilder) RunCommands(commands ...string) *ImageBuilder
RunCommands appends RUN <command> for each command, in shell form.
func (*ImageBuilder) User ¶
func (b *ImageBuilder) User(user string) *ImageBuilder
User appends USER <user>.
func (*ImageBuilder) UvInstall ¶
func (b *ImageBuilder) UvInstall(args ...string) *ImageBuilder
UvInstall appends RUN uv pip install --system <args>.
func (*ImageBuilder) Workdir ¶
func (b *ImageBuilder) Workdir(path string) *ImageBuilder
Workdir appends WORKDIR <path>.
type ImageBuilderAddFileOptions ¶
type ImageBuilderAddFileOptions struct {
// Destination is the path in the image. Required.
Destination string
// Content is the file's content.
Content []byte
// ContextName is the file's name in the build context. Empty uses the
// destination's base name, with a suffix such as " (1)" if another entry
// already has that name.
ContextName string
// Mode is the file's permission bits in the image. Zero uses 0644.
Mode fs.FileMode
}
ImageBuilderAddFileOptions are the options for ImageBuilder.AddFileWithOptions.
type ImageBuilderAddLocalDirOptions ¶
type ImageBuilderAddLocalDirOptions struct {
// Source is the local directory's path. Required.
Source string
// Destination is the path in the image. Required.
Destination string
// ContextName is the directory's name in the build context. Empty uses
// the source's base name, with a suffix such as " (1)" if another entry
// already has that name.
ContextName string
}
ImageBuilderAddLocalDirOptions are the options for ImageBuilder.AddLocalDirWithOptions.
type ImageBuilderAddLocalFileOptions ¶
type ImageBuilderAddLocalFileOptions struct {
// Source is the local file's path. Required.
Source string
// Destination is the path in the image. Required.
Destination string
// ContextName is the file's name in the build context. Empty uses the
// source's base name, with a suffix such as " (1)" if another entry
// already has that name.
ContextName string
}
ImageBuilderAddLocalFileOptions are the options for ImageBuilder.AddLocalFileWithOptions.
type ImageBuilderOptions ¶
type ImageBuilderOptions struct {
// BaseImage is the registry image to start from, as FROM <BaseImage>.
// Required.
BaseImage string
// SandboxAPIImage is the image to copy the sandbox API binary from, when
// the Dockerfile does not bring it in itself. Empty uses
// ghcr.io/blaxel-ai/sandbox:latest.
SandboxAPIImage string
}
ImageBuilderOptions are the options for NewImageBuilderWithOptions.
type ImageCleanupOptions ¶
type ImageCleanupOptions struct{}
ImageCleanupOptions are the options for ImageClient.Cleanup.
type ImageCleanupResult ¶
type ImageCleanupResult struct {
// Deleted is how many image versions were removed.
Deleted int
// Message describes the outcome.
Message string
}
ImageCleanupResult is the outcome of ImageClient.Cleanup.
type ImageClient ¶
type ImageClient struct {
// contains filtered or unexported fields
}
ImageClient works with the images that sandboxes are created from: pushing them from a build context or a registry, and finding and deleting them. Get it from Client.Images.
func (*ImageClient) Cleanup ¶
func (c *ImageClient) Cleanup(ctx context.Context, opts ImageCleanupOptions) (*ImageCleanupResult, error)
Cleanup removes image versions that no sandbox uses.
func (*ImageClient) Delete ¶
func (c *ImageClient) Delete(ctx context.Context, opts ImageDeleteOptions) (*ImageInfo, error)
Delete deletes an image and all its versions, and returns its record. Fails while a sandbox uses any version.
func (*ImageClient) DeleteTag ¶
func (c *ImageClient) DeleteTag(ctx context.Context, opts ImageDeleteTagOptions) (*ImageInfo, error)
DeleteTag deletes one version of an image and returns the image's record as it is afterwards. Fails while a sandbox uses the version.
func (*ImageClient) GetInfo ¶
func (c *ImageClient) GetInfo(ctx context.Context, opts ImageGetInfoOptions) (*ImageInfo, error)
GetInfo gets an image's record.
func (*ImageClient) List ¶
func (c *ImageClient) List(ctx context.Context, opts ImageListOptions) iter.Seq2[*ImageInfo, error]
List lists images, fetching further pages as iteration reaches them. An error is yielded as the second value and ends the iteration.
func (*ImageClient) ListLibrary ¶
func (c *ImageClient) ListLibrary(ctx context.Context, opts ImageListLibraryOptions) ([]ImageLibraryInfo, error)
ListLibrary lists the built-in images available to every team.
func (*ImageClient) ListTags ¶
func (c *ImageClient) ListTags(ctx context.Context, opts ImageListTagsOptions) iter.Seq2[*ImageTagInfo, error]
ListTags lists an image's versions, fetching further pages as iteration reaches them. An error is yielded as the second value and ends the iteration.
func (*ImageClient) Logs ¶
func (c *ImageClient) Logs(ctx context.Context, opts ImageLogsOptions) ([]ImageLogLine, error)
Logs gets the build log of an image's latest build, including a failed one, oldest line first. Logs may take a short time to appear. Returns at most the 11,000 most recent lines in the range; narrow the range to see earlier ones.
func (*ImageClient) Push ¶
func (c *ImageClient) Push(ctx context.Context, opts ImagePushOptions) (*ImageInfo, error)
Push pushes an image, from a registry or from a build context that is built into one. Waits for the image to be ready to use unless NoWait is set, returning an *ImageBuildError if its build fails or the wait times out.
A build context read from local files is zipped into a temporary file, removed when Push returns, unless NoTempFile is set; any other is zipped in memory. It is uploaded in one attempt. If the upload fails, with an *ImageUploadError, the image is left as the service has it, so push again or delete it.
func (*ImageClient) WaitBuilt ¶
func (c *ImageClient) WaitBuilt(ctx context.Context, opts ImageWaitBuiltOptions) (*ImageInfo, error)
WaitBuilt waits for an image to be ready to use, returning an *ImageBuildError if its build fails or the wait times out. It checks the image's current status, so right after pushing a new version of an image that was already built, it may return before the new version is processed; push without NoWait to avoid that.
type ImageDeleteOptions ¶
type ImageDeleteOptions struct {
// Name is the image's name. Required.
Name string
}
ImageDeleteOptions are the options for ImageClient.Delete.
type ImageDeleteTagOptions ¶
type ImageDeleteTagOptions struct {
// Name is the image's name. Required.
Name string
// Tag is the version to delete. Required.
Tag string
}
ImageDeleteTagOptions are the options for ImageClient.DeleteTag.
type ImageGetInfoOptions ¶
type ImageGetInfoOptions struct {
// Name is the image's name. Required.
Name string
}
ImageGetInfoOptions are the options for ImageClient.GetInfo.
type ImageIgnoreFileFunc ¶
type ImageIgnoreFileFunc func(context.Context, ImageIgnoreFileOptions) (ignore bool, err error)
ImageIgnoreFileFunc reports whether a path should be left out of a pushed build context. Returning an error fails the push before anything is sent.
When the function returns true for a directory, its entire subtree is left out.
type ImageIgnoreFileOptions ¶
type ImageIgnoreFileOptions struct {
// RelPath is the path relative to the directory's root, using forward
// slashes on all platforms.
RelPath string
// Entry is the directory entry as returned by [os.ReadDir].
Entry fs.DirEntry
}
ImageIgnoreFileOptions is passed to an ImageIgnoreFileFunc for each candidate path in a directory being pushed.
type ImageIgnoreFileProcessorOptions ¶
type ImageIgnoreFileProcessorOptions struct {
// Path is the absolute path to the .dockerignore file.
Path string
// Contents is the raw bytes of the .dockerignore file.
Contents []byte
}
ImageIgnoreFileProcessorOptions is passed to ImagePushOptions.IgnoreFileProcessor when a .dockerignore file is found at the root of ImagePushOptions.SourceDirectory.
type ImageInfo ¶
type ImageInfo struct {
// Name is the image's unique name.
Name string
// Status is the status of the image's latest version.
Status ImageStatus
// CreatedAt is when the image was created, zero when unknown.
CreatedAt time.Time
// UpdatedAt is when the image was last updated, zero when unknown.
UpdatedAt time.Time
// LastDeployedAt is when a sandbox last used the image, zero when none
// has.
LastDeployedAt time.Time
// SizeBytes is the image's size, zero when unknown.
SizeBytes int64
// TagCount is how many versions the image has.
TagCount int
}
ImageInfo is an image's record.
type ImageLibraryInfo ¶
type ImageLibraryInfo struct {
// Name is the image's stable identifier.
Name string
// DisplayName is the image's human-readable name.
DisplayName string
// Description is a short description.
Description string
// LongDescription is a detailed description.
LongDescription string
// Image is the image reference, including its tag, to pass as
// [CreateOptions.Image].
Image string
// Memory is the recommended memory allocation in megabytes, zero when
// there is none.
Memory int
// Ports are the ports the image exposes.
Ports []Port
// Categories are the image's categories.
Categories []string
// Tags are the image's tags.
Tags []string
// URL is the image's documentation URL.
URL string
// Icon is the URL of the image's icon.
Icon string
// IconLight is the URL of the image's light-mode icon.
IconLight string
// IconDark is the URL of the image's dark-mode icon.
IconDark string
// Enterprise is whether the image requires an enterprise plan.
Enterprise bool
// CreationExtraArgs are kernel selection arguments suggested when
// creating a sandbox from this image.
CreationExtraArgs map[string]string
// CreationVolumes are volume attachments suggested when creating a
// sandbox from this image.
CreationVolumes []ImageLibraryVolume
}
ImageLibraryInfo is a built-in image available to every team, usable directly as a sandbox's image without pushing it.
type ImageLibraryVolume ¶
type ImageLibraryVolume struct {
// Name is the volume's name, or an internal identifier for an ephemeral
// volume.
Name string
// MountPath is the absolute path the volume is mounted at.
MountPath string
// Type is the volume's type, empty for a persistent volume.
Type string
// SizeMB is the storage capacity in megabytes of an ephemeral volume.
SizeMB int
// ReadOnly is whether the volume is mounted read-only.
ReadOnly bool
}
ImageLibraryVolume is a volume attachment a built-in image suggests.
type ImageListLibraryOptions ¶
type ImageListLibraryOptions struct{}
ImageListLibraryOptions are the options for ImageClient.ListLibrary.
type ImageListOptions ¶
type ImageListOptions struct {
// NamePrefix keeps only images whose names start with this,
// case-sensitively.
NamePrefix string
// Sort is the order of the listing. Empty uses [ImageSortCreatedAtDesc].
Sort ImageSort
// PageSize is how many images each underlying request fetches. Zero uses
// the server's default.
PageSize int
}
ImageListOptions are the options for ImageClient.List.
type ImageListTagsOptions ¶
type ImageListTagsOptions struct {
// Name is the image's name. Required.
Name string
// NamePrefix keeps only tags that start with this.
NamePrefix string
// Sort is the order of the listing.
Sort ImageTagSort
// PageSize is how many versions each underlying request fetches. Zero
// uses the server's default.
PageSize int
}
ImageListTagsOptions are the options for ImageClient.ListTags.
type ImageLogLine ¶
type ImageLogLine struct {
// Timestamp is when the line was written.
Timestamp time.Time
// Severity is the line's severity level.
Severity int
// Text is the line's text.
Text string
}
ImageLogLine is one line of an image's build log.
type ImageLogsOptions ¶
type ImageLogsOptions struct {
// Name is the image's name. Required.
Name string
// StartTime keeps only lines from this time on. Zero means no lower
// bound.
StartTime time.Time
// EndTime keeps only lines up to this time. Zero means now.
EndTime time.Time
}
ImageLogsOptions are the options for ImageClient.Logs.
type ImagePushOptions ¶
type ImagePushOptions struct {
// Name is the image's name. Required. To create a sandbox from the
// image, pass "<name>:latest" as [CreateOptions.Image].
Name string
// SourceBuilder is a builder whose Dockerfile and files make up the
// build context. Its recorded errors, if any, fail the push before
// anything is sent.
SourceBuilder *ImageBuilder
// SourceRegistry is a registry image to import.
SourceRegistry *ImageRegistrySource
// SourceZip is a build context, already zipped.
SourceZip []byte
// SourceDirectory is a local directory to zip as the build context.
// Files keep their modes, a link to a file within the directory stores
// a copy of the file, a link to a file outside it fails the push, a link
// to a directory stores an empty directory, and a broken link is left
// out.
//
// Paths are left out as a .dockerignore at the directory's root says,
// read through IgnoreFileProcessor, or else by DefaultIgnoreFile. The
// root Dockerfile and .dockerignore are always kept, as Docker keeps them.
SourceDirectory string
// SourceFiles are the build context's files, by forward-slashed path
// relative to its root, each with mode 0644.
SourceFiles map[string][]byte
// IgnoreFileProcessor parses the .dockerignore at the root of
// SourceDirectory into an [ImageIgnoreFileFunc], which should match
// Docker's .dockerignore semantics. Required if SourceDirectory has a
// .dockerignore; otherwise the push fails before anything is sent. This
// package has no .dockerignore parser of its own.
IgnoreFileProcessor func(context.Context, ImageIgnoreFileProcessorOptions) (ImageIgnoreFileFunc, error)
// DefaultIgnoreFile filters SourceDirectory when it has no
// .dockerignore. If nil, [DefaultImageIgnoreFile] is used. Pass a
// function that always returns false to push everything.
DefaultIgnoreFile ImageIgnoreFileFunc
// NoTempFile zips a build context read from local files, from
// SourceDirectory or a builder's local files and directories, in memory
// instead of in a temporary file. Other build contexts are always zipped
// in memory.
NoTempFile bool
// NoWait returns as soon as the image is pushed, instead of waiting for
// it to be ready to use.
NoWait bool
// Timeout is how long to wait for the image to be ready to use. Zero
// uses 15 minutes, and a negative value waits with no limit. The build
// continues regardless.
Timeout time.Duration
// PollInterval is how often to check the image's status while waiting.
// Zero uses 3 seconds.
PollInterval time.Duration
}
ImagePushOptions are the options for ImageClient.Push.
type ImageRegistrySource ¶
type ImageRegistrySource struct {
// Image is the registry image reference to import. Required.
Image string
// DockerConfig is a Docker config.json with the credentials for pulling
// Image from a private registry.
DockerConfig string
}
ImageRegistrySource is a registry image for ImagePushOptions.SourceRegistry.
type ImageSort ¶
type ImageSort string
ImageSort is the sort order of an image listing. Other values may be added, so do not treat the constants as exhaustive.
type ImageStatus ¶
type ImageStatus string
ImageStatus is the status of an image. Other values may be added, so do not treat the constants as exhaustive.
const ( ImageStatusUploading ImageStatus = "UPLOADING" ImageStatusBuilding ImageStatus = "BUILDING" ImageStatusBuilt ImageStatus = "BUILT" ImageStatusFailed ImageStatus = "FAILED" )
Values for ImageStatus.
type ImageTagInfo ¶
type ImageTagInfo struct {
// Name is the version's tag.
Name string
// CreatedAt is when the version was created, zero when unknown.
CreatedAt time.Time
// UpdatedAt is when the version was last updated, zero when unknown.
UpdatedAt time.Time
// SizeBytes is the version's size, zero when unknown.
SizeBytes int64
}
ImageTagInfo is one version of an image.
type ImageTagSort ¶
type ImageTagSort string
ImageTagSort is the sort order of an image's version listing. Other values may be added, so do not treat the constants as exhaustive.
const ( ImageTagSortNameAsc ImageTagSort = "name:asc" ImageTagSortNameDesc ImageTagSort = "name:desc" )
Values for ImageTagSort.
type ImageUploadError ¶
type ImageUploadError struct {
// ImageName is the name of the image whose source was being uploaded.
ImageName string
// Status is the HTTP status of the storage response.
Status int
// Body is the raw text of the storage response body.
Body string
}
ImageUploadError is a failed upload of an image's source archive. The upload goes to storage rather than to the API, so its error body has no fixed shape.
func (*ImageUploadError) Error ¶
func (e *ImageUploadError) Error() string
type ImageWaitBuiltOptions ¶
type ImageWaitBuiltOptions struct {
// Name is the image's name. Required.
Name string
// Timeout is how long to wait. Zero uses 15 minutes, and a negative
// value waits with no limit. The build continues regardless.
Timeout time.Duration
// PollInterval is how often to check the image's status. Zero uses 3
// seconds.
PollInterval time.Duration
}
ImageWaitBuiltOptions are the options for ImageClient.WaitBuilt.
type Info ¶
type Info struct {
// Name is the sandbox's unique name.
Name string
// URL is the base URL of the sandbox's execution API. Empty until the
// server assigns one.
URL string
// Status is the sandbox's status.
Status Status
// Image is the image reference, including its tag.
Image string
// Memory is the memory allocation in megabytes, which also sets the CPU
// allocation.
Memory int
// Region is where the sandbox runs.
Region string
// Envs are the environment variables injected into the sandbox, by name.
// Values come back masked unless revealed with
// [GetInfoOptions.ShowSecrets], so sending them back in an update
// overwrites the real values with the mask.
Envs map[string]EnvValue
// Labels are the key-value pairs for organizing and filtering.
Labels map[string]string
// ExternalID is the caller-owned identifier for external lookups.
ExternalID string
// Lifecycle is when the sandbox expires, nil when it has no lifecycle.
Lifecycle *Lifecycle
// Ports are the ports the sandbox exposes.
Ports []Port
// Network is the sandbox's network configuration, nil when it has none.
Network *Network
// CreatedAt is when the sandbox was created.
CreatedAt time.Time
// UpdatedAt is when the sandbox was last updated, zero when it never was.
UpdatedAt time.Time
// CreatedBy is who created the sandbox.
CreatedBy string
// UpdatedBy is who last updated the sandbox.
UpdatedBy string
// LastUsedAt is when the sandbox was last used, zero when it never was.
LastUsedAt time.Time
// ExpiresIn is how long until the sandbox expires, zero when it does not.
ExpiresIn time.Duration
}
Info is a sandbox's record.
type Lifecycle ¶
type Lifecycle struct {
// ExpirationPolicies are the rules for when the sandbox expires.
ExpirationPolicies []ExpirationPolicy
// TerminatedRetention is how long a terminated sandbox is kept before it
// is deleted. Zero uses the server's default.
TerminatedRetention time.Duration
}
Lifecycle is when a sandbox expires and how long it is kept afterwards.
type ListOptions ¶
type ListOptions struct {
// Query searches sandbox names and labels.
Query string
// Statuses keeps only sandboxes with one of these statuses. Cannot be
// combined with ExternalID.
Statuses []Status
// ExternalID keeps only sandboxes with this external identifier. Cannot
// be combined with Statuses.
ExternalID string
// PageSize is how many sandboxes each underlying request fetches. Zero
// uses the server's default.
PageSize int
}
ListOptions are the options for Client.List.
type Network ¶
type Network struct {
// Subnet is the subnet the sandbox joins. Empty uses the server's
// default.
Subnet string
// Proxy routes the sandbox's outbound traffic, nil for none.
Proxy *NetworkProxy
}
Network is a sandbox's network configuration. It is set at creation and cannot be updated.
type NetworkProxy ¶
type NetworkProxy struct {
// AllowedDomains are the only domains the sandbox may reach, when set.
AllowedDomains []string
// ForbiddenDomains are domains the sandbox may not reach.
ForbiddenDomains []string
// Bypass are domains whose traffic goes direct instead of through the
// proxy.
Bypass []string
// Routing adds headers, body fields, and secrets to requests for
// matching destinations.
Routing []NetworkProxyRoute
}
NetworkProxy controls a sandbox's outbound traffic.
type NetworkProxyRoute ¶
type NetworkProxyRoute struct {
// Destinations are the domains this route applies to.
Destinations []string
// Headers are added to matching requests.
Headers map[string]string
// Body fields are added to matching requests.
Body map[string]string
// Secrets are added to matching requests. Write-only: never returned.
Secrets map[string]string
}
NetworkProxyRoute adds to outbound requests for matching destinations.
type Port ¶
type Port struct {
// Target is the port number in the sandbox.
Target int
// Name is the port's name.
Name string
// Protocol is the port's protocol. Empty uses the server's default.
Protocol PortProtocol
}
Port is a port a sandbox exposes.
type PortProtocol ¶
type PortProtocol string
PortProtocol is the protocol of a port. Other values may be added, so do not treat the constants as exhaustive.
const ( PortProtocolHTTP PortProtocol = "HTTP" PortProtocolTCP PortProtocol = "TCP" PortProtocolUDP PortProtocol = "UDP" PortProtocolTLS PortProtocol = "TLS" )
Values for PortProtocol.
type ProcessCloseStdinOptions ¶
type ProcessCloseStdinOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
}
ProcessCloseStdinOptions are the options for ProcessService.CloseStdin.
type ProcessExecEvent ¶
type ProcessExecEvent struct {
// TextStream is which output Text came from.
TextStream ProcessStream
// Text is a chunk of output exactly as written: not split into lines,
// so output such as a prompt arrives without waiting for a newline. It
// may be empty when the sandbox sends an empty chunk. If the process
// finished before streaming started, each line instead arrives as its
// own event, without its newline.
Text string
// Exit is the process's final state, set on the last event only.
Exit *ProcessInfo
}
ProcessExecEvent is one event of ProcessService.ExecStream: either output, with TextStream and Text set, or, last, the process's exit, with Exit set.
type ProcessExecOptions ¶
type ProcessExecOptions struct {
// Command is the shell command to run. Required.
Command string
// WorkingDir is the directory to run the command in. Empty uses the
// sandbox's default.
WorkingDir string
// Env are environment variables for the process, on top of the
// sandbox's own.
Env map[string]string
// Name names the process, so it can be referred to by name instead of
// its PID.
Name string
// Timeout kills the process after this long, rounded up to whole
// seconds. Zero means never.
Timeout time.Duration
// KeepAlive keeps the sandbox from going idle while the process runs.
KeepAlive bool
// RestartOnFailure restarts the process when it fails.
RestartOnFailure bool
// MaxRestarts is how many times the process is restarted on failure.
MaxRestarts int
// Stdin keeps the process's standard input open for writing.
Stdin bool
// WaitForPorts returns only once the process listens on these ports.
WaitForPorts []int
// WaitForCompletion returns only once the process has exited. When
// false, the process keeps running in the background.
WaitForCompletion bool
}
ProcessExecOptions are the options for ProcessService.Exec.
type ProcessExecStreamOptions ¶
type ProcessExecStreamOptions struct {
// Command is the shell command to run. Required.
Command string
// WorkingDir is the directory to run the command in. Empty uses the
// sandbox's default.
WorkingDir string
// Env are environment variables for the process, on top of the
// sandbox's own.
Env map[string]string
// Name names the process, so it can be referred to by name instead of
// its PID.
Name string
// Timeout kills the process after this long, rounded up to whole
// seconds. Zero means never.
Timeout time.Duration
// KeepAlive keeps the sandbox from going idle while the process runs.
KeepAlive bool
// RestartOnFailure restarts the process when it fails.
RestartOnFailure bool
// MaxRestarts is how many times the process is restarted on failure.
MaxRestarts int
// Stdin keeps the process's standard input open for writing.
Stdin bool
// WaitForPorts starts streaming only once the process listens on these
// ports.
WaitForPorts []int
}
ProcessExecStreamOptions are the options for ProcessService.ExecStream.
type ProcessGetOptions ¶
type ProcessGetOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
}
ProcessGetOptions are the options for ProcessService.Get.
type ProcessInfo ¶
type ProcessInfo struct {
// PID is the process ID.
PID string
// Name is the process's name, if it was given one.
Name string
// Command is the command the process runs.
Command string
// Status is the process's status.
Status ProcessStatus
// ExitCode is the process's exit code, once it has exited.
ExitCode int
// Stdout is the process's standard output so far.
Stdout string
// Stderr is the process's standard error so far.
Stderr string
// Logs is the process's standard output and standard error so far,
// interleaved.
Logs string
// WorkingDir is the directory the process runs in.
WorkingDir string
// StartedAt is when the process started.
StartedAt time.Time
// CompletedAt is when the process exited, zero while it runs.
CompletedAt time.Time
// KeepAlive is whether the process keeps the sandbox from going idle.
KeepAlive bool
// MaxRestarts is how many times the process is restarted on failure.
MaxRestarts int
// RestartCount is how many times the process has been restarted.
RestartCount int
// RestartOnFailure is whether the process is restarted when it fails.
RestartOnFailure bool
// Stdin is whether the process accepts standard input.
Stdin bool
}
ProcessInfo is the state of a process in a sandbox.
type ProcessKillOptions ¶
type ProcessKillOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
}
ProcessKillOptions are the options for ProcessService.Kill.
type ProcessListOptions ¶
type ProcessListOptions struct{}
ProcessListOptions are the options for ProcessService.List.
type ProcessLogLine ¶
type ProcessLogLine struct {
// TextStream is which output Text came from, empty when the sandbox did
// not report it.
TextStream ProcessStream
// Text is the line, without its line ending. It may be empty, for an
// empty line.
Text string
}
ProcessLogLine is one line of a process's output.
type ProcessLogs ¶
type ProcessLogs struct {
// Stdout is the process's standard output.
Stdout string
// Stderr is the process's standard error.
Stderr string
// Logs is the process's standard output and standard error,
// interleaved.
Logs string
}
ProcessLogs is a process's captured output.
type ProcessLogsOptions ¶
type ProcessLogsOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
}
ProcessLogsOptions are the options for ProcessService.Logs.
type ProcessService ¶
type ProcessService struct {
// contains filtered or unexported fields
}
ProcessService runs and inspects processes in a sandbox. Get it from Sandbox.Process.
func (*ProcessService) CloseStdin ¶
func (p *ProcessService) CloseStdin(ctx context.Context, opts ProcessCloseStdinOptions) error
CloseStdin closes a process's standard input, so it reads end of input.
func (*ProcessService) Exec ¶
func (p *ProcessService) Exec(ctx context.Context, opts ProcessExecOptions) (*ProcessInfo, error)
Exec starts a process and returns its state.
func (*ProcessService) ExecStream ¶
func (p *ProcessService) ExecStream(ctx context.Context, opts ProcessExecStreamOptions) iter.Seq2[ProcessExecEvent, error]
ExecStream starts a process and yields its output as it is written, then its final state. An error is yielded as the second value and ends the iteration. Stopping the iteration early leaves the process running.
func (*ProcessService) Get ¶
func (p *ProcessService) Get(ctx context.Context, opts ProcessGetOptions) (*ProcessInfo, error)
Get returns a process's state.
func (*ProcessService) Kill ¶
func (p *ProcessService) Kill(ctx context.Context, opts ProcessKillOptions) error
Kill requests that a process exit forcefully and returns without waiting. Use ProcessService.Wait for it to end, with ProcessStatusKilled.
func (*ProcessService) List ¶
func (p *ProcessService) List(ctx context.Context, opts ProcessListOptions) ([]ProcessInfo, error)
List returns the sandbox's processes.
func (*ProcessService) Logs ¶
func (p *ProcessService) Logs(ctx context.Context, opts ProcessLogsOptions) (*ProcessLogs, error)
Logs returns a process's captured output.
func (*ProcessService) Stop ¶
func (p *ProcessService) Stop(ctx context.Context, opts ProcessStopOptions) error
Stop requests that a process exit gracefully and returns without waiting. Use ProcessService.Wait for it to end, with ProcessStatusStopped.
func (*ProcessService) StreamLogs ¶
func (p *ProcessService) StreamLogs(ctx context.Context, opts ProcessStreamLogsOptions) iter.Seq2[ProcessLogLine, error]
StreamLogs yields a process's output line by line, from the start, until the process exits. A partial line, such as a prompt, is yielded once its newline arrives or the stream ends; use ProcessService.ExecStream for output as it is written. An error is yielded as the second value and ends the iteration. Stopping the iteration early leaves the process running.
func (*ProcessService) Wait ¶
func (p *ProcessService) Wait(ctx context.Context, opts ProcessWaitOptions) (*ProcessInfo, error)
Wait waits for a process to exit and returns its final state, whether it completed, failed, was killed, or was stopped. A failed process is returned, not an error. If the wait times out, it returns a *ProcessWaitTimeoutError and the process keeps running.
func (*ProcessService) WriteStdin ¶
func (p *ProcessService) WriteStdin(ctx context.Context, opts ProcessWriteStdinOptions) error
WriteStdin writes to a process's standard input.
type ProcessStatus ¶
type ProcessStatus string
ProcessStatus is the status of a process in a sandbox. Other values may be added, so do not treat the constants as exhaustive.
const ( ProcessStatusRunning ProcessStatus = "running" ProcessStatusCompleted ProcessStatus = "completed" ProcessStatusFailed ProcessStatus = "failed" ProcessStatusKilled ProcessStatus = "killed" ProcessStatusStopped ProcessStatus = "stopped" )
Values for ProcessStatus.
type ProcessStopOptions ¶
type ProcessStopOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
}
ProcessStopOptions are the options for ProcessService.Stop.
type ProcessStream ¶
type ProcessStream string
ProcessStream is which output of a process some text came from. Other values may be added, so do not treat the constants as exhaustive.
const ( ProcessStreamStdout ProcessStream = "stdout" ProcessStreamStderr ProcessStream = "stderr" )
Values for ProcessStream.
type ProcessStreamLogsOptions ¶
type ProcessStreamLogsOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
}
ProcessStreamLogsOptions are the options for ProcessService.StreamLogs.
type ProcessWaitOptions ¶
type ProcessWaitOptions struct {
// Identifier is the process's PID or name. Required.
Identifier string
// Timeout is how long to wait. Zero uses 60 seconds, and a negative
// value waits with no limit. The process keeps running regardless.
Timeout time.Duration
// PollInterval is how often to check the process. Zero uses 1 second.
PollInterval time.Duration
}
ProcessWaitOptions are the options for ProcessService.Wait.
type ProcessWaitTimeoutError ¶
type ProcessWaitTimeoutError struct {
// Identifier is the PID or name of the process waited on.
Identifier string
// Err is the last error seen while polling, nil when the last poll
// succeeded.
Err error
}
ProcessWaitTimeoutError is a process still running when a wait for it ran out of time. The process keeps running regardless.
func (*ProcessWaitTimeoutError) Error ¶
func (e *ProcessWaitTimeoutError) Error() string
func (*ProcessWaitTimeoutError) Unwrap ¶
func (e *ProcessWaitTimeoutError) Unwrap() error
Unwrap returns the last error seen while polling.
type ProcessWriteStdinOptions ¶
type ProcessWriteStdinOptions struct {
// Identifier is the process's PID or name, which must have been started
// with [ProcessExecOptions.Stdin]. Required.
Identifier string
// Data is written to the process's standard input as is. Include any
// trailing newline the process expects.
Data []byte
}
ProcessWriteStdinOptions are the options for ProcessService.WriteStdin.
type RetryOptions ¶
type RetryOptions struct {
// ReadMaxRetries is the retry limit for reads on a dropped or reset
// connection. Defaults to 5.
ReadMaxRetries int
// GatewayMaxRetries is the retry limit for 502, 503, and 504 responses
// from the edge in front of a sandbox. Defaults to 2.
GatewayMaxRetries int
// UploadMaxRetries is the retry limit for uploads on a dropped or reset
// connection. Defaults to 3.
UploadMaxRetries int
}
RetryOptions sets how many times calls to a sandbox are retried on dropped connections and gateway errors. Only calls that are safe to repeat are ever retried. For each field, zero uses the default and a negative value turns retries off.
type Sandbox ¶
type Sandbox struct {
// contains filtered or unexported fields
}
Sandbox works in one sandbox: running processes and reading and writing its filesystem.
Get one from Client.Create or Client.Get, or, without a call, from Client.SandboxFromURL when the sandbox's URL is already known. A Sandbox uses its client's credentials, HTTP client, headers, and retries.
func (*Sandbox) API ¶
func (s *Sandbox) API() *sandboxapi.Client
API returns the underlying generated execution API client for this sandbox, for operations this package does not wrap. The generated API surface is not covered by Go compatibility guarantees and may change between versions. The caller must close the body of a response returned by a Raw method.
func (*Sandbox) FS ¶
func (s *Sandbox) FS() *FileSystemService
FS reads and writes files and directories in the sandbox.
func (*Sandbox) Name ¶
Name is the sandbox's name, empty for a Sandbox from Client.SandboxFromURL.
func (*Sandbox) Process ¶
func (s *Sandbox) Process() *ProcessService
Process runs and inspects processes in the sandbox.
type SandboxFromURLOptions ¶
type SandboxFromURLOptions struct {
// URL is the base URL of the sandbox's execution API, as in [Info.URL].
// Required.
URL string
}
SandboxFromURLOptions are the options for Client.SandboxFromURL.
type Status ¶
type Status string
Status is the status of a sandbox. Other values may be added, so do not treat the constants as exhaustive.
const ( StatusDeploying Status = "DEPLOYING" StatusDeployed Status = "DEPLOYED" StatusFailed Status = "FAILED" StatusTerminated Status = "TERMINATED" StatusDeleting Status = "DELETING" StatusDeactivating Status = "DEACTIVATING" StatusDeactivated Status = "DEACTIVATED" StatusBuilding Status = "BUILDING" StatusUploading Status = "UPLOADING" StatusArchiving Status = "ARCHIVING" StatusArchived Status = "ARCHIVED" StatusUnarchiving Status = "UNARCHIVING" )
Values for Status.
type TokenProvider ¶
type TokenProvider func(ctx context.Context, opts TokenProviderOptions) (string, error)
TokenProvider returns the bearer token to send on a request. Called for every request.
A provider that caches tokens must drop its cached token when it matches TokenProviderOptions.RevokedToken, since the server rejects that token for good.
type TokenProviderOptions ¶
type TokenProviderOptions struct {
// RevokedToken is a token the server just rejected as revoked, set when
// the request is being sent again with a new one. Revocation can happen
// well before a token's expiry, for example when any API key of the
// token's user changes.
RevokedToken string
}
TokenProviderOptions is what a TokenProvider is told about the token it is asked for.
type UpdateOptions ¶
type UpdateOptions struct {
// Name is the sandbox's name. Required.
Name string
// Lifecycle replaces when the sandbox expires.
Lifecycle *Lifecycle
// Envs replace the sandbox's environment variables. Values returned
// masked in [Info.Envs] overwrite the real values if sent back.
Envs map[string]EnvValue
// ExternalID is a caller-owned identifier for external lookups.
ExternalID string
// Labels replace the sandbox's labels.
Labels map[string]string
}
UpdateOptions are the options for Client.Update. Unset fields stay unchanged, and set ones replace their previous values, including set but empty maps and slices. A field cannot be cleared back to unset.