sprites

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 28 Imported by: 5

README

Sprite SDK for Go

The Sprite SDK provides an idiomatic Go API for working with sprites. It mirrors the standard exec.Cmd API to execute commands on remote Sprites as if they were local.

Installation

go get github.com/superfly/sprites-go

Note: The import path is github.com/superfly/sprites-go but the package name is sprites. You'll need to import it with an alias or the package name will be sprites.

Quick Start

package main

import (
    "fmt"
    "log"

    sprites "github.com/superfly/sprites-go"
)

func main() {
    // Create a client with authentication
    client := sprites.New("your-auth-token")

    // Get a sprite handle
    sprite := client.Sprite("my-sprite")

    // Run a command - just like exec.Command!
    cmd := sprite.Command("echo", "hello", "world")
    output, err := cmd.Output()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Output: %s", output)
}

Usage

Client Setup
// Create a client with default settings
client := sprites.New("your-auth-token")

// Or with custom base URL
client := sprites.New("your-auth-token",
    sprites.WithBaseURL("http://localhost:8080"))

// Get a sprite handle
sprite := client.Sprite("my-sprite")
Basic Command Execution

The SDK provides a sprite.Cmd type that works exactly like exec.Cmd:

// Create a command
cmd := sprite.Command("ls", "-la", "/tmp")

// Run and wait for completion
err := cmd.Run()

// Or get the output
output, err := cmd.Output()

// Or get combined stdout and stderr
combined, err := cmd.CombinedOutput()
Setting Environment and Working Directory
cmd := sprite.Command("env")
cmd.Env = []string{"FOO=bar", "BAZ=qux"}
cmd.Dir = "/tmp"

output, err := cmd.Output()
Working with I/O
cmd := sprite.Command("grep", "pattern")

// Set stdin from a reader
cmd.Stdin = strings.NewReader("line 1\nline 2 with pattern\nline 3")

// Capture stdout and stderr separately
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr

err := cmd.Run()
Using Pipes

For streaming I/O, use pipes just like with exec.Cmd:

cmd := sprite.Command("cat")

// Get stdin pipe
stdin, err := cmd.StdinPipe()
if err != nil {
    log.Fatal(err)
}

// Get stdout pipe
stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Fatal(err)
}

// Start the command
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

// Write to stdin in a goroutine
go func() {
    defer stdin.Close()
    for i := 0; i < 10; i++ {
        fmt.Fprintf(stdin, "Line %d\n", i)
        time.Sleep(100 * time.Millisecond)
    }
}()

// Read from stdout
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
    fmt.Println("Got:", scanner.Text())
}

// Wait for command to finish
err = cmd.Wait()
Context Support

Use context for cancellation and timeouts:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

cmd := sprite.CommandContext(ctx, "long-running-command")
err := cmd.Run()
// Command will be killed if context times out
TTY Support

Enable TTY mode for interactive commands:

cmd := sprite.Command("bash")
cmd.SetTTY(true)

// Optionally set initial terminal size
err := cmd.SetTTYSize(24, 80)

// Start the command
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

// Resize the terminal while running
err = cmd.Resize(30, 100)

// Wait for completion
err = cmd.Wait()
Error Handling

The SDK provides the same error types as exec.Cmd:

cmd := sprite.Command("false")
err := cmd.Run()

if err != nil {
    // Check if it's an exit error
    if exitErr, ok := err.(*sprites.ExitError); ok {
        fmt.Printf("Command exited with code: %d\n", exitErr.ExitCode())
    } else {
        // Other error (connection, auth, etc.)
        log.Fatal(err)
    }
}
Port Forwarding

Forward local ports to services running in the sprite:

// Simple port forwarding (same port locally and remotely)
session, err := sprite.ProxyPort(ctx, 3000, 3000)
if err != nil {
    log.Fatal(err)
}
defer session.Close()

// Now localhost:3000 connects to the sprite's port 3000
// The session runs until Close() is called or context is cancelled

Forward multiple ports:

sessions, err := sprite.ProxyPorts(ctx, []sprites.PortMapping{
    {LocalPort: 3000, RemotePort: 3000},
    {LocalPort: 8080, RemotePort: 80},
    {LocalPort: 5432, RemotePort: 5432},
})
if err != nil {
    log.Fatal(err)
}
defer func() {
    for _, s := range sessions {
        s.Close()
    }
}()
Port Notifications and Auto-Forwarding

When running commands, you can receive notifications when ports are opened or closed inside the sprite and automatically set up port forwarding:

import (
    "encoding/json"
    "sync"
)

// Track active proxy sessions
var (
    proxies = make(map[int]*sprites.ProxySession)
    mu      sync.Mutex
)

cmd := sprite.Command("npm", "start")

// Handle port notifications
cmd.TextMessageHandler = func(data []byte) {
    var notification sprites.PortNotificationMessage
    if err := json.Unmarshal(data, &notification); err != nil {
        return
    }

    switch notification.Type {
    case "port_opened":
        fmt.Printf("Port %d opened on %s (PID %d)\n",
            notification.Port, notification.Address, notification.PID)

        // Create proxy session with the specific address
        session, err := sprite.ProxyPorts(ctx, []sprites.PortMapping{
            {
                LocalPort:  notification.Port,
                RemotePort: notification.Port,
                RemoteHost: notification.Address, // Use the address from notification
            },
        })
        if err != nil {
            log.Printf("Failed to create proxy for port %d: %v", notification.Port, err)
            return
        }

        mu.Lock()
        proxies[notification.Port] = session[0]
        mu.Unlock()

        fmt.Printf("Forwarding localhost:%d -> %s:%d\n",
            notification.Port, notification.Address, notification.Port)

    case "port_closed":
        fmt.Printf("Port %d closed (PID %d)\n", notification.Port, notification.PID)

        mu.Lock()
        if session, ok := proxies[notification.Port]; ok {
            session.Close()
            delete(proxies, notification.Port)
            fmt.Printf("Stopped forwarding port %d\n", notification.Port)
        }
        mu.Unlock()
    }
}

// Run the command
err := cmd.Run()

// Clean up any remaining proxies
mu.Lock()
for port, session := range proxies {
    session.Close()
    delete(proxies, port)
}
mu.Unlock()

Complete Example

Here's a complete example showing various features:

package main

import (
    "context"
    "fmt"
    "log"
    "strings"
    "time"

    sprites "github.com/superfly/sprites-go"
)

func main() {
    // Create client with authentication
    client := sprites.New("your-auth-token",
        sprites.WithBaseURL("https://api.sprite.example.com"))

    // Get a sprite handle
    sprite := client.Sprite("my-sprite")

    // Example 1: Simple command with output
    output, err := sprite.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Current date: %s", output)

    // Example 2: Command with pipes and timeout
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    cmd := sprite.CommandContext(ctx, "grep", "-i", "error")
    cmd.Stdin = strings.NewReader("Line 1\nError on line 2\nLine 3\nAnother ERROR\n")

    output, err = cmd.Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Grep results:\n%s", output)

    // Example 3: Interactive command with environment
    cmd = sprite.Command("bash", "-c", "echo Hello $USER from $HOSTNAME")
    cmd.Env = []string{"USER=sprite", "HOSTNAME=remote"}

    output, err = cmd.Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Greeting: %s", output)
}

Examples

The examples/ directory contains runnable examples for each API endpoint. Each file is a standalone main package:

cd examples
export SPRITE_TOKEN="your-token"
export SPRITE_NAME="your-sprite"

go run sprite_list.go
go run service_create.go

API Reference

Client Creation
// Create a new sprites client
client := sprites.New(token string, opts ...Option)

// Available options:
sprites.WithBaseURL(url string)      // Set custom API endpoint
sprites.WithHTTPClient(client *http.Client)  // Use custom HTTP client
Sprite Operations
// Get a sprite handle (doesn't create it on the server)
sprite := client.Sprite(name string)

// Create a new sprite (future functionality)
sprite, err := client.Create(name string)

// List sprites (future functionality)
sprites, err := client.List()
Command Execution

The sprite.Cmd type is designed to be a drop-in replacement for exec.Cmd. It implements the same methods with the same behavior:

  • Run() - Start and wait for completion
  • Start() - Start the command asynchronously
  • Wait() - Wait for a started command to complete
  • Output() - Run and return stdout
  • CombinedOutput() - Run and return combined stdout/stderr
  • StdinPipe() - Create a pipe connected to stdin
  • StdoutPipe() - Create a pipe connected to stdout
  • StderrPipe() - Create a pipe connected to stderr

The following fields work identically to exec.Cmd:

  • Path - The command to run
  • Args - Command arguments (including Path as Args[0])
  • Env - Environment variables
  • Dir - Working directory
  • Stdin - Standard input (nil, *os.File, or io.Reader)
  • Stdout - Standard output (nil, *os.File, or io.Writer)
  • Stderr - Standard error (nil, *os.File, or io.Writer)

Testing

The SDK includes comprehensive tests that verify compatibility with exec.Cmd behavior. Run tests with:

# Tests run only on Linux
go test -v ./sdk/...

Cutting a Release

If you have write access to this repo, you can ship a release with:

scripts/bump_version.sh

Or a prerelease with:

scripts/bump_version.sh prerel

The release and notes will be created automatically via Github Actions. Follow along in: https://github.com/superfly/sprites-go/actions/workflows/release.yml

License

See the main project LICENSE file.

Documentation

Overview

Package sprites provides a Go API for Fly.io Sprites: computers for agents. It offers an exec.Cmd-style API for running commands on persistent, hardware-isolated Linux machines.

Index

Constants

View Source
const (
	ErrCodeCreationRateLimited     = "sprite_creation_rate_limited"
	ErrCodeConcurrentLimitExceeded = "concurrent_sprite_limit_exceeded"
)

Error codes returned by the API for rate limiting

Variables

View Source
var ErrNotStarted = errors.New("sprite: command not started")

ErrNotStarted is returned when Wait is called before Start.

Functions

func CreateToken

func CreateToken(ctx context.Context, flyMacaroon, orgSlug string, inviteCode string, apiURL ...string) (string, error)

CreateToken creates a sprite access token using a Fly.io macaroon token. This is a static method that doesn't require a client instance.

The flyMacaroon should be a valid Fly.io authentication token (starts with "FlyV1"). The orgSlug is the organization slug (e.g., "personal" or organization name). The inviteCode is optional and only needed for organizations that require it.

This method is typically used during initial setup to exchange Fly.io credentials for sprite-specific access tokens.

func SetDebug

func SetDebug(enabled bool)

SetDebug enables or disables SDK debug logging. When enabled, debug messages are written via slog.Default(). This allows the calling application to control SDK debug output programmatically (e.g., when a CLI debug flag is set).

Types

type APIError

type APIError struct {
	// ErrorCode is the machine-readable error code (e.g., "sprite_creation_rate_limited")
	ErrorCode string `json:"error"`

	// Message is the human-readable error message
	Message string `json:"message"`

	// Limit is the rate limit value (e.g., 10 sprites per minute)
	Limit int `json:"limit,omitempty"`

	// WindowSeconds is the rate limit window in seconds
	WindowSeconds int `json:"window_seconds,omitempty"`

	// RetryAfterSeconds is the number of seconds to wait before retrying
	RetryAfterSeconds int `json:"retry_after_seconds,omitempty"`

	// CurrentCount is the current count (for concurrent limit errors)
	CurrentCount int `json:"current_count,omitempty"`

	// UpgradeAvailable indicates if an upgrade is available
	UpgradeAvailable bool `json:"upgrade_available,omitempty"`

	// UpgradeURL is the URL to upgrade the account (for rate limit errors)
	UpgradeURL string `json:"upgrade_url,omitempty"`

	// StatusCode is the HTTP status code (not from JSON, set by parser)
	StatusCode int `json:"-"`

	// RetryAfterHeader is the Retry-After header value in seconds
	RetryAfterHeader int `json:"-"`

	// RateLimitLimit is the X-RateLimit-Limit header value
	RateLimitLimit int `json:"-"`

	// RateLimitRemaining is the X-RateLimit-Remaining header value
	RateLimitRemaining int `json:"-"`

	// RateLimitReset is the X-RateLimit-Reset header value (Unix timestamp)
	RateLimitReset int64 `json:"-"`
}

APIError represents a structured error response from the Sprites API. It implements the error interface and provides detailed information about rate limits and other API errors.

func IsAPIError

func IsAPIError(err error) *APIError

IsAPIError checks if an error is an APIError and returns it. Returns nil if the error is not an APIError.

func IsRateLimitErr

func IsRateLimitErr(err error) *APIError

IsRateLimitError checks if an error is a rate limit error (HTTP 429). Returns the APIError if it is, nil otherwise.

func ParseAPIError

func ParseAPIError(resp *http.Response, body []byte) *APIError

ParseAPIError parses an API error from an HTTP response. Returns nil if the response is not an error (status < 400). This is the exported version of parseAPIError for use by clients.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface

func (*APIError) GetRetryAfterSeconds

func (e *APIError) GetRetryAfterSeconds() int

GetRetryAfterSeconds returns the number of seconds to wait before retrying. It prefers the JSON field, falling back to the header value.

func (*APIError) IsConcurrentLimitExceeded

func (e *APIError) IsConcurrentLimitExceeded() bool

IsConcurrentLimitExceeded returns true if this is a concurrent sprite limit error

func (*APIError) IsCreationRateLimited

func (e *APIError) IsCreationRateLimited() bool

IsCreationRateLimited returns true if this is a sprite creation rate limit error

func (*APIError) IsRateLimitError

func (e *APIError) IsRateLimitError() bool

IsRateLimitError returns true if this is a 429 rate limit error

type Checkpoint

type Checkpoint struct {
	ID         string    `json:"id"`
	CreateTime time.Time `json:"create_time"`
	History    []string  `json:"history,omitempty"`
	Comment    string    `json:"comment,omitempty"`
	IsAuto     bool      `json:"is_auto,omitempty"`
}

Checkpoint represents a checkpoint

type CheckpointStream

type CheckpointStream struct {
	// contains filtered or unexported fields
}

CheckpointStream represents a streaming checkpoint operation

func (*CheckpointStream) Close

func (cs *CheckpointStream) Close() error

Close closes the checkpoint stream

func (*CheckpointStream) Next

func (cs *CheckpointStream) Next() (*StreamMessage, error)

Next reads the next message from the checkpoint stream

func (*CheckpointStream) ProcessAll

func (cs *CheckpointStream) ProcessAll(handler func(*StreamMessage) error) error

ProcessAll processes all messages in the checkpoint stream

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main SDK client for interacting with the sprite API.

func New

func New(token string, opts ...Option) *Client

New creates a new SDK client with the given token and options.

func NewClient

func NewClient(baseURL, token string) *Client

NewClient creates a new Sprites API client with explicit parameters. This is an alternative constructor for compatibility.

func (*Client) AttachSession

func (c *Client) AttachSession(spriteName string, sessionID string) *Cmd

AttachSession creates a new Cmd that attaches to an existing session

func (*Client) AttachSessionContext

func (c *Client) AttachSessionContext(ctx context.Context, spriteName string, sessionID string) *Cmd

AttachSessionContext creates a new Cmd with context that attaches to an existing session

func (*Client) AttachSessionWithOrg

func (c *Client) AttachSessionWithOrg(spriteName string, sessionID string, org *OrganizationInfo) *Cmd

AttachSessionWithOrg creates a new Cmd that attaches to an existing session with organization information

func (*Client) Close

func (c *Client) Close() error

Close closes the client and all pooled connections

func (*Client) Create

func (c *Client) Create(name string) (*Sprite, error)

Create creates a new sprite with the given name and returns a handle to it. Deprecated: Use CreateSprite with context instead.

func (*Client) CreateCheckpoint

func (c *Client) CreateCheckpoint(ctx context.Context, spriteName string) (*CheckpointStream, error)

CreateCheckpoint creates a new checkpoint for the sprite (no comment)

func (*Client) CreateCheckpointWithComment

func (c *Client) CreateCheckpointWithComment(ctx context.Context, spriteName string, comment string) (*CheckpointStream, error)

CreateCheckpointWithComment creates a new checkpoint for the sprite with an optional comment

func (*Client) CreateService

func (c *Client) CreateService(ctx context.Context, spriteName, serviceName string, req *ServiceRequest) (*ServiceStream, error)

CreateService creates or updates a service and returns a stream of log events

func (*Client) CreateServiceWithDuration

func (c *Client) CreateServiceWithDuration(ctx context.Context, spriteName, serviceName string, req *ServiceRequest, duration time.Duration) (*ServiceStream, error)

CreateServiceWithDuration creates a service with a custom monitoring duration

func (*Client) CreateSprite

func (c *Client) CreateSprite(ctx context.Context, name string, config *SpriteConfig) (*Sprite, error)

CreateSprite creates a new sprite with the given name and optional configuration

func (*Client) CreateSpriteWithOrg

func (c *Client) CreateSpriteWithOrg(ctx context.Context, name string, config *SpriteConfig, org *OrganizationInfo, labels []string) (*Sprite, error)

CreateSpriteWithOrg creates a new sprite with the given name, optional configuration, organization information, and labels

func (*Client) DeleteService

func (c *Client) DeleteService(ctx context.Context, spriteName, serviceName string) error

DeleteService deletes a service

func (*Client) DeleteSprite

func (c *Client) DeleteSprite(ctx context.Context, name string) error

DeleteSprite deletes a sprite

func (*Client) DestroySprite

func (c *Client) DestroySprite(ctx context.Context, name string) error

DestroySprite is an alias for DeleteSprite to match the client's naming

func (*Client) FetchVersion

func (c *Client) FetchVersion(ctx context.Context, spriteName string) error

FetchVersion makes a lightweight API call to capture the sprite's version. This is called automatically before attach operations if the version is unknown. The spriteName parameter is required to route the request to the specific sprite, since each sprite has its own version.

func (*Client) GetCheckpoint

func (c *Client) GetCheckpoint(ctx context.Context, spriteName string, checkpointID string) (*Checkpoint, error)

GetCheckpoint retrieves information about a specific checkpoint

func (*Client) GetNetworkPolicy

func (c *Client) GetNetworkPolicy(ctx context.Context, spriteName string) (*NetworkPolicy, error)

GetNetworkPolicy retrieves the current network policy for a sprite

func (*Client) GetService

func (c *Client) GetService(ctx context.Context, spriteName, serviceName string) (*ServiceWithState, error)

GetService retrieves a specific service

func (*Client) GetSprite

func (c *Client) GetSprite(ctx context.Context, name string) (*Sprite, error)

GetSprite retrieves information about a specific sprite

func (*Client) GetSpriteWithOrg

func (c *Client) GetSpriteWithOrg(ctx context.Context, name string, org *OrganizationInfo) (*Sprite, error)

GetSpriteWithOrg retrieves information about a specific sprite with organization information

func (*Client) List

func (c *Client) List() ([]*Sprite, error)

List returns a list of available sprites. Deprecated: Use ListSprites with context instead.

func (*Client) ListAllSprites

func (c *Client) ListAllSprites(ctx context.Context, prefix string) ([]*Sprite, error)

ListAllSprites retrieves all sprites, handling pagination automatically

func (*Client) ListAllSpritesResult

func (c *Client) ListAllSpritesResult(ctx context.Context, prefix string, org *OrganizationInfo) (*ListResult, error)

ListAllSpritesResult retrieves all sprites with aggregate org stats, handling pagination automatically

func (*Client) ListAllSpritesWithOrg

func (c *Client) ListAllSpritesWithOrg(ctx context.Context, prefix string, org *OrganizationInfo) ([]*Sprite, error)

ListAllSpritesWithOrg retrieves all sprites with organization information, handling pagination automatically

func (*Client) ListCheckpoints

func (c *Client) ListCheckpoints(ctx context.Context, spriteName string, historyFilter string) ([]*Checkpoint, error)

ListCheckpoints retrieves a list of checkpoints for a sprite (excludes auto checkpoints)

func (*Client) ListCheckpointsWithOptions

func (c *Client) ListCheckpointsWithOptions(ctx context.Context, spriteName string, opts ListCheckpointsOptions) ([]*Checkpoint, error)

ListCheckpointsWithOptions retrieves a list of checkpoints with configurable options

func (*Client) ListServices

func (c *Client) ListServices(ctx context.Context, spriteName string) ([]*ServiceWithState, error)

ListServices retrieves all services for a sprite

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context, spriteName string) ([]*Session, error)

ListSessions retrieves a list of active sessions for a sprite

func (*Client) ListSprites

func (c *Client) ListSprites(ctx context.Context, opts *ListOptions) (*SpriteList, error)

ListSprites retrieves a list of sprites with optional filtering

func (*Client) ProxyPort

func (c *Client) ProxyPort(ctx context.Context, spriteName string, localPort, remotePort int) (*ProxySession, error)

ProxyPort creates a proxy session for a single port

func (*Client) ProxyPorts

func (c *Client) ProxyPorts(ctx context.Context, spriteName string, mappings []PortMapping) ([]*ProxySession, error)

ProxyPorts creates proxy sessions for multiple port mappings

func (*Client) ProxySocket

func (c *Client) ProxySocket(ctx context.Context, network, spriteName, addr string) (net.Conn, error)

ProxySocket establishes a proxied connection to a port on a sprite.

The only known network is "tcp".

func (*Client) RestoreCheckpoint

func (c *Client) RestoreCheckpoint(ctx context.Context, spriteName string, checkpointID string) (*RestoreStream, error)

RestoreCheckpoint restores a sprite from a checkpoint

func (*Client) SignalService

func (c *Client) SignalService(ctx context.Context, spriteName, serviceName, signal string) error

SignalService sends a signal to a running service

func (*Client) Sprite

func (c *Client) Sprite(name string) *Sprite

Sprite returns a Sprite instance for the given name. This doesn't create the sprite on the server, it just returns a handle to work with it.

func (*Client) SpriteVersion

func (c *Client) SpriteVersion() string

SpriteVersion returns the captured server version, or empty string if unknown.

func (*Client) SpriteWithOrg

func (c *Client) SpriteWithOrg(name string, org *OrganizationInfo) *Sprite

SpriteWithOrg returns a Sprite instance for the given name with organization information. This doesn't create the sprite on the server, it just returns a handle to work with it.

func (*Client) StartService

func (c *Client) StartService(ctx context.Context, spriteName, serviceName string) (*ServiceStream, error)

StartService starts a service and returns a stream of log events

func (*Client) StartServiceWithDuration

func (c *Client) StartServiceWithDuration(ctx context.Context, spriteName, serviceName string, duration time.Duration) (*ServiceStream, error)

StartServiceWithDuration starts a service with a custom monitoring duration

func (*Client) StopService

func (c *Client) StopService(ctx context.Context, spriteName, serviceName string) (*ServiceStream, error)

StopService stops a service and returns a stream of log events

func (*Client) StopServiceWithTimeout

func (c *Client) StopServiceWithTimeout(ctx context.Context, spriteName, serviceName string, timeout time.Duration) (*ServiceStream, error)

StopServiceWithTimeout stops a service with a custom timeout

func (*Client) UpdateNetworkPolicy

func (c *Client) UpdateNetworkPolicy(ctx context.Context, spriteName string, policy *NetworkPolicy) error

UpdateNetworkPolicy updates the network policy for a sprite

func (*Client) UpdateSprite

func (c *Client) UpdateSprite(ctx context.Context, spriteName string, req *UpdateSpriteRequest) error

UpdateSprite updates a sprite's settings (URL auth, labels, etc.)

func (*Client) UpdateURLSettings

func (c *Client) UpdateURLSettings(ctx context.Context, spriteName string, settings *URLSettings) error

UpdateURLSettings updates the URL authentication settings for a sprite

func (*Client) UpgradeSprite

func (c *Client) UpgradeSprite(ctx context.Context, name string) error

UpgradeSprite upgrades a sprite to the latest version

type Cmd

type Cmd struct {
	// Path is the path of the command to run.
	Path string

	// Args holds command line arguments, including the command as Args[0].
	Args []string

	// Env specifies the environment of the process.
	// Each entry is of the form "key=value".
	// If Env is nil, the new process uses the current process's environment.
	Env []string

	// Dir specifies the working directory of the command.
	// If Dir is the empty string, the command runs in the sprite's default directory.
	Dir string

	// Stdin specifies the process's standard input.
	// If Stdin is nil, the process reads from the null device (os.DevNull).
	// If Stdin is an *os.File, the process's standard input is connected
	// directly to that file.
	// Otherwise, during the execution of the command a separate
	// goroutine reads from Stdin and delivers that data to the command
	// over the network. In this case, Wait does not complete until the goroutine
	// stops copying, either because it has reached the end of Stdin
	// (EOF or a read error) or because writing to the network returned an error.
	Stdin io.Reader

	// Stdout and Stderr specify the process's standard output and error.
	// If either is nil, the command uses the null device (os.DevNull).
	// If either is an *os.File, the process's corresponding output
	// is connected directly to that file.
	// Otherwise, during the execution of the command a separate goroutine
	// reads from the network and delivers that data to the corresponding Writer.
	// In this case, Wait does not complete until the goroutine reaches EOF or
	// encounters an error.
	Stdout io.Writer
	Stderr io.Writer

	// TextMessageHandler is called when text messages are received from the server.
	// This is typically used for port notifications or other out-of-band messages.
	// The handler is called with the raw message data.
	//
	// Example usage for handling port notifications:
	//
	//     import "encoding/json"
	//
	//     cmd.TextMessageHandler = func(data []byte) {
	//         var notification sprites.PortNotificationMessage
	//         if err := json.Unmarshal(data, &notification); err != nil {
	//             log.Printf("Failed to parse notification: %v", err)
	//             return
	//         }
	//
	//         switch notification.Type {
	//         case "port_opened":
	//             fmt.Printf("Port %d opened by PID %d\n", notification.Port, notification.PID)
	//             // Start local proxy or take other action
	//         case "port_closed":
	//             fmt.Printf("Port %d closed by PID %d\n", notification.Port, notification.PID)
	//             // Stop local proxy or take other action
	//         }
	//     }
	TextMessageHandler func([]byte)
	// contains filtered or unexported fields
}

Cmd represents a command to be run on a sprite. It mirrors the API of exec.Cmd for compatibility.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the command and returns its combined standard output and standard error.

func (*Cmd) ConnectionMode

func (c *Cmd) ConnectionMode() string

ConnectionMode returns the connection mode used by this command. Returns "control" for multiplexed control connections, "direct" for direct WebSocket connections, or "" if Start() hasn't been called yet.

func (*Cmd) ExitCode

func (c *Cmd) ExitCode() int

ExitCode returns the exit code of the exited process, or -1 if the process hasn't exited or was terminated by a signal.

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs the command and returns its standard output.

func (*Cmd) Resize

func (c *Cmd) Resize(rows, cols uint16) error

Resize changes the terminal size of a running TTY command. Deprecated: Use SetTTYSize instead, which works both before and after Start().

func (*Cmd) Run

func (c *Cmd) Run() error

Run starts the specified command and waits for it to complete.

func (*Cmd) SetControlMode

func (c *Cmd) SetControlMode(enable bool) error

SetControlMode enables control mode (requires session ID)

func (*Cmd) SetTTY

func (c *Cmd) SetTTY(enable bool)

SetTTY enables or disables TTY mode for the command. When TTY mode is enabled, the command runs with a pseudo-terminal.

func (*Cmd) SetTTYSize

func (c *Cmd) SetTTYSize(rows, cols uint16) error

SetTTYSize sets the terminal size for TTY mode. If called before Start(), it sets the initial size. If called after Start(), it resizes the running terminal.

func (*Cmd) Signal

func (c *Cmd) Signal(signal string) error

Signal sends a signal to the remote process. If the server supports WebSocket signals (advertised via X-Sprite-Capabilities header), it sends the signal over the existing WebSocket connection. Otherwise, it falls back to an HTTP POST request to the kill endpoint. Valid signal names: INT, TERM, HUP, KILL, QUIT, USR1, USR2

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the specified command but does not wait for it to complete.

func (*Cmd) StderrPipe

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.

func (*Cmd) StdinPipe

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts.

func (*Cmd) StdoutPipe

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts.

func (*Cmd) String

func (c *Cmd) String() string

String returns a human-readable description of c. It is intended only for debugging.

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

type ControlMessage

type ControlMessage struct {
	Type   string `json:"type"`
	Cols   uint16 `json:"cols,omitempty"`
	Rows   uint16 `json:"rows,omitempty"`
	Signal string `json:"signal,omitempty"`
}

ControlMessage represents control messages sent over the WebSocket

type CreateSpriteRequest

type CreateSpriteRequest struct {
	Name        string            `json:"name"`
	Config      *SpriteConfig     `json:"config,omitempty"`
	Environment map[string]string `json:"environment,omitempty"`
	Labels      []string          `json:"labels,omitempty"`
}

CreateSpriteRequest represents the request to create a sprite

type CreateSpriteResponse

type CreateSpriteResponse struct {
	Name string `json:"name"`
}

CreateSpriteResponse represents the response from sprite creation

type ExecOptions

type ExecOptions struct {
	WorkingDir  string
	Environment []string
	TTY         bool
	SessionID   string
	ControlMode bool
	InitialCols int
	InitialRows int
}

ExecOptions represents options for executing commands

type ExitError

type ExitError struct {
	Code int
}

ExitError reports an unsuccessful exit by a command.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) ExitCode

func (e *ExitError) ExitCode() int

ExitCode returns the exit code of the exited process.

func (*ExitError) Sys

func (e *ExitError) Sys() interface{}

Sys returns the system-specific exit information. On Unix, this is a syscall.WaitStatus.

type FS

type FS interface {
	fs.FS         // Open(name string) (fs.File, error)
	fs.StatFS     // Stat(name string) (fs.FileInfo, error)
	fs.ReadFileFS // ReadFile(name string) ([]byte, error)
	fs.ReadDirFS  // ReadDir(name string) ([]DirEntry, error)

	// Write operations
	WriteFile(name string, data []byte, perm fs.FileMode) error
	Mkdir(name string, perm fs.FileMode) error
	MkdirAll(path string, perm fs.FileMode) error
	Remove(name string) error
	RemoveAll(path string) error
	Rename(oldname, newname string) error
	Copy(src, dst string) error
	Chmod(name string, mode fs.FileMode) error

	// Context variants for long operations
	WriteFileContext(ctx context.Context, name string, data []byte, perm fs.FileMode) error
	RemoveContext(ctx context.Context, name string) error
	RemoveAllContext(ctx context.Context, path string) error
	CopyContext(ctx context.Context, src, dst string) error
	ChmodContext(ctx context.Context, name string, mode fs.FileMode) error
}

FS provides filesystem operations on a sprite. It implements io/fs.FS for read operations and adds write operations.

type FsChmodEntry

type FsChmodEntry struct {
	Path string `json:"path"`
	Mode string `json:"mode"`
}

FsChmodEntry represents a single chmod result

type FsChmodResult

type FsChmodResult struct {
	Affected []FsChmodEntry `json:"affected"`
	Count    int            `json:"count"`
}

FsChmodResult contains the result of a fs.chmod operation

type FsChownEntry

type FsChownEntry struct {
	Path string `json:"path"`
	UID  int    `json:"uid"`
	GID  int    `json:"gid"`
}

FsChownEntry represents a single chown result

type FsChownResult

type FsChownResult struct {
	Affected []FsChownEntry `json:"affected"`
	Count    int            `json:"count"`
}

FsChownResult contains the result of a fs.chown operation

type FsControlOption

type FsControlOption func(*fsControlOpts)

FsControlOption is a functional option for filesystem control operations

func WithFsAsRoot

func WithFsAsRoot(enable bool) FsControlOption

WithFsAsRoot runs the operation as root user

func WithFsGid

func WithFsGid(gid int) FsControlOption

WithFsGid sets the group ID for chown operations

func WithFsMkdirParents

func WithFsMkdirParents(enable bool) FsControlOption

WithFsMkdirParents enables automatic parent directory creation

func WithFsMode

func WithFsMode(mode fs.FileMode) FsControlOption

WithFsMode sets the file mode for write operations

func WithFsPreserveAttrs

func WithFsPreserveAttrs(enable bool) FsControlOption

WithFsPreserveAttrs preserves file attributes during copy

func WithFsRange

func WithFsRange(start, end int64) FsControlOption

WithFsRange sets the byte range for read operations

func WithFsRecursive

func WithFsRecursive(enable bool) FsControlOption

WithFsRecursive enables recursive operation

func WithFsUid

func WithFsUid(uid int) FsControlOption

WithFsUid sets the user ID for chown operations

func WithFsWorkingDir

func WithFsWorkingDir(dir string) FsControlOption

WithFsWorkingDir sets the working directory for path resolution

type FsCopyEntry

type FsCopyEntry struct {
	Source string `json:"source"`
	Dest   string `json:"dest"`
}

FsCopyEntry represents a single copy result

type FsCopyResult

type FsCopyResult struct {
	Copied     []FsCopyEntry `json:"copied"`
	Count      int           `json:"count"`
	TotalBytes int64         `json:"totalBytes"`
}

FsCopyResult contains the result of a fs.copy operation

type FsDeleteResult

type FsDeleteResult struct {
	Deleted []string `json:"deleted"`
	Count   int      `json:"count"`
}

FsDeleteResult contains the result of a fs.delete operation

type FsEntry

type FsEntry struct {
	Name    string    `json:"name"`
	Path    string    `json:"path"`
	Type    string    `json:"type"`
	Size    int64     `json:"size"`
	Mode    string    `json:"mode"`
	ModTime time.Time `json:"modTime"`
	IsDir   bool      `json:"isDir"`
}

FsEntry represents a file or directory entry

type FsErrorResponse

type FsErrorResponse struct {
	Error string `json:"error"`
	Code  string `json:"code,omitempty"`
	Path  string `json:"path,omitempty"`
}

FsErrorResponse represents a filesystem operation error

type FsListResult

type FsListResult struct {
	Path    string    `json:"path"`
	Entries []FsEntry `json:"entries"`
	Count   int       `json:"count"`
}

FsListResult contains the result of a fs.list operation

type FsReadResult

type FsReadResult struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
	Data []byte `json:"-"`
}

FsReadResult contains the result of a fs.read operation

type FsRenameResult

type FsRenameResult struct {
	Source string `json:"source"`
	Dest   string `json:"dest"`
}

FsRenameResult contains the result of a fs.rename operation

type FsWriteResult

type FsWriteResult struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
	Mode string `json:"mode"`
}

FsWriteResult contains the result of a fs.write operation

type ListCheckpointsOptions

type ListCheckpointsOptions struct {
	HistoryFilter string
	IncludeAuto   bool
}

ListCheckpointsOptions contains options for listing checkpoints

type ListOptions

type ListOptions struct {
	Prefix            string
	MaxResults        int
	ContinuationToken string
}

ListOptions represents options for listing sprites

type ListResult

type ListResult struct {
	Sprites []*Sprite
	Org     *OrgInfo
}

ListResult holds the result of listing all sprites, including aggregate org info.

type NetworkPolicy

type NetworkPolicy struct {
	Rules []NetworkPolicyRule `json:"rules"`
}

NetworkPolicy represents the network policy configuration

type NetworkPolicyRule

type NetworkPolicyRule struct {
	Domain  string `json:"domain,omitempty"`
	Action  string `json:"action,omitempty"` // "allow" or "deny"
	Include string `json:"include,omitempty"`
}

NetworkPolicyRule represents a single network policy rule

type Option

type Option func(*Client)

Option is a functional option for configuring the SDK client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets a custom base URL for the sprite API.

func WithClientSignals

func WithClientSignals(sig *clientsignals.Signals) Option

WithClientSignals attaches coarse, privacy-safe client-signal headers (interactive/CI/agent detection; see github.com/superfly/client-signals) to every outgoing request the Client makes — both plain HTTP calls and the WebSocket dials used for exec/proxy/control connections. Pass the result of clientsignals.DetectOnce() (or Detect()), computed once by the caller.

Disabled by default; a nil sig is a no-op.

func WithControlInitTimeout

func WithControlInitTimeout(d time.Duration) Option

WithControlInitTimeout sets how long Sprite() will wait to establish a control connection before falling back to legacy endpoint API for that Sprite. Defaults to 2s.

func WithDisableControl

func WithDisableControl() Option

WithDisableControl prevents the SDK from using control connections. When disabled, all operations use direct WebSocket connections per request.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithNetDialContext

func WithNetDialContext(fn func(ctx context.Context, network, addr string) (net.Conn, error)) Option

WithNetDialContext sets a custom dial function used for all outbound TCP connections.

type OrgInfo

type OrgInfo struct {
	Name         string `json:"name"`
	Running      int    `json:"running"`
	Warm         int    `json:"warm"`
	Cold         int    `json:"cold"`
	RunningLimit int    `json:"running_limit"`
	WarmLimit    int    `json:"warm_limit"`
}

OrgInfo represents aggregate organization stats returned with sprite listings.

type OrganizationInfo

type OrganizationInfo struct {
	Name string
	URL  string
}

OrganizationInfo represents organization information attached to a sprite

type PortMapping

type PortMapping struct {
	LocalPort  int
	RemotePort int
	RemoteHost string // Optional: specific host to connect to (e.g., "10.0.0.1", "fdf::1"). Defaults to "localhost" if empty.
}

PortMapping represents a local to remote port mapping

type PortNotificationMessage

type PortNotificationMessage struct {
	Type    string `json:"type"`    // "port_opened" or "port_closed"
	Port    int    `json:"port"`    // Port number
	Address string `json:"address"` // Address (e.g., "127.0.0.1", "0.0.0.0")
	PID     int    `json:"pid"`     // Process ID
}

PortNotificationMessage represents a port event notification

type ProxyInitMessage

type ProxyInitMessage struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

ProxyInitMessage represents the initial message sent to establish a proxy

type ProxyManager

type ProxyManager struct {
	// contains filtered or unexported fields
}

ProxyManager manages multiple proxy sessions

func NewProxyManager

func NewProxyManager() *ProxyManager

NewProxyManager creates a new proxy manager

func (*ProxyManager) AddSession

func (pm *ProxyManager) AddSession(session *ProxySession)

AddSession adds a session to the manager

func (*ProxyManager) CloseAll

func (pm *ProxyManager) CloseAll()

CloseAll closes all managed proxy sessions

func (*ProxyManager) WaitAll

func (pm *ProxyManager) WaitAll()

WaitAll waits for all proxy sessions to close

type ProxyResponseMessage

type ProxyResponseMessage struct {
	Status string `json:"status"`
	Target string `json:"target"`
}

ProxyResponseMessage represents the response from establishing a proxy

type ProxySession

type ProxySession struct {
	LocalPort  int
	RemotePort int
	RemoteHost string // Optional: specific host to connect to (e.g., "10.0.0.1", "fdf::1"). Defaults to "localhost" if empty.
	// contains filtered or unexported fields
}

ProxySession represents an active port proxy session

func (*ProxySession) Close

func (ps *ProxySession) Close() error

Close closes the proxy session

func (*ProxySession) LocalAddr

func (ps *ProxySession) LocalAddr() net.Addr

LocalAddr returns the local address of the proxy listener

func (*ProxySession) Wait

func (ps *ProxySession) Wait()

Wait waits for the proxy session to close

type RestoreStream

type RestoreStream struct {
	// contains filtered or unexported fields
}

RestoreStream represents a streaming restore operation

func (*RestoreStream) Close

func (rs *RestoreStream) Close() error

Close closes the restore stream

func (*RestoreStream) Next

func (rs *RestoreStream) Next() (*StreamMessage, error)

Next reads the next message from the restore stream

func (*RestoreStream) ProcessAll

func (rs *RestoreStream) ProcessAll(handler func(*StreamMessage) error) error

ProcessAll processes all messages in the restore stream

type Service

type Service struct {
	Name     string   `json:"name"`
	Cmd      string   `json:"cmd"`
	Args     []string `json:"args"`
	Needs    []string `json:"needs"`
	HTTPPort *int     `json:"http_port,omitempty"`
}

Service represents a service definition

type ServiceLogEvent

type ServiceLogEvent struct {
	Type      string            `json:"type"` // "stdout", "stderr", "exit", "error", "complete", "started", "stopping", "stopped"
	Data      string            `json:"data,omitempty"`
	ExitCode  *int              `json:"exit_code,omitempty"`
	Timestamp int64             `json:"timestamp"`
	LogFiles  map[string]string `json:"log_files,omitempty"`
}

ServiceLogEvent represents a log event from service start/stop streaming

type ServiceRequest

type ServiceRequest struct {
	Cmd      string   `json:"cmd"`
	Args     []string `json:"args,omitempty"`
	Needs    []string `json:"needs,omitempty"`
	HTTPPort *int     `json:"http_port,omitempty"`
}

ServiceRequest represents the request body for creating/updating services

type ServiceState

type ServiceState struct {
	Name          string    `json:"name"`
	Status        string    `json:"status"` // "stopped", "starting", "running", "stopping", "failed"
	PID           int       `json:"pid,omitempty"`
	StartedAt     time.Time `json:"started_at,omitempty"`
	Error         string    `json:"error,omitempty"`
	RestartCount  int       `json:"restart_count,omitempty"`
	NextRestartAt time.Time `json:"next_restart_at,omitempty"`
}

ServiceState represents the runtime state of a service

type ServiceStream

type ServiceStream struct {
	// contains filtered or unexported fields
}

ServiceStream represents a streaming service operation (start/stop/create)

func (*ServiceStream) Close

func (ss *ServiceStream) Close() error

Close closes the service stream

func (*ServiceStream) Next

func (ss *ServiceStream) Next() (*ServiceLogEvent, error)

Next reads the next log event from the service stream

func (*ServiceStream) ProcessAll

func (ss *ServiceStream) ProcessAll(handler func(*ServiceLogEvent) error) error

ProcessAll processes all messages in the service stream

type ServiceWithState

type ServiceWithState struct {
	Service
	State *ServiceState `json:"state,omitempty"`
}

ServiceWithState combines service definition with runtime state

type Session

type Session struct {
	ID             string     `json:"id"`
	Command        string     `json:"command"`
	Workdir        string     `json:"workdir"`
	Created        time.Time  `json:"created"`
	BytesPerSecond float64    `json:"bytes_per_second"`
	IsActive       bool       `json:"is_active"`
	LastActivity   *time.Time `json:"last_activity,omitempty"`
	TTY            bool       `json:"tty"`
}

Session represents an execution session

func (*Session) GetActivityAge

func (s *Session) GetActivityAge() time.Duration

GetActivityAge returns how long ago the last activity was

func (*Session) IsSessionActive

func (s *Session) IsSessionActive() bool

IsSessionActive returns true if the session has recent activity

type SessionList

type SessionList struct {
	Sessions []Session `json:"sessions"`
}

SessionList represents a list of execution sessions

type Sprite

type Sprite struct {

	// Additional fields from API responses
	ID               string
	OrganizationName string
	Status           string
	Config           *SpriteConfig
	Environment      map[string]string
	CreatedAt        time.Time
	UpdatedAt        time.Time
	BucketName       string
	PrimaryRegion    string
	URL              string
	URLSettings      *URLSettings
	Labels           []string
	LastRunningAt    *time.Time
	LastWarmingAt    *time.Time
	// contains filtered or unexported fields
}

Sprite represents a sprite instance.

func (*Sprite) AttachSession

func (s *Sprite) AttachSession(sessionID string) *Cmd

AttachSession creates a new Cmd that attaches to an existing session

func (*Sprite) AttachSessionContext

func (s *Sprite) AttachSessionContext(ctx context.Context, sessionID string) *Cmd

AttachSessionContext creates a new Cmd with context that attaches to an existing session

func (*Sprite) Client

func (s *Sprite) Client() *Client

Client returns the client associated with this sprite.

func (*Sprite) Command

func (s *Sprite) Command(name string, arg ...string) *Cmd

Command returns a new Cmd to execute the named program with the given arguments on the sprite.

func (*Sprite) CommandContext

func (s *Sprite) CommandContext(ctx context.Context, name string, arg ...string) *Cmd

CommandContext is like Command but includes a context. The provided context is used to kill the process (by calling os.Process.Kill) if the context becomes done before the command completes on its own.

func (*Sprite) CreateCheckpoint

func (s *Sprite) CreateCheckpoint(ctx context.Context) (*CheckpointStream, error)

CreateCheckpoint creates a new checkpoint for this sprite (no comment)

func (*Sprite) CreateCheckpointWithComment

func (s *Sprite) CreateCheckpointWithComment(ctx context.Context, comment string) (*CheckpointStream, error)

CreateCheckpointWithComment creates a new checkpoint for this sprite with an optional comment

func (*Sprite) CreateService

func (s *Sprite) CreateService(ctx context.Context, serviceName string, req *ServiceRequest) (*ServiceStream, error)

CreateService creates a service for this sprite

func (*Sprite) CreateServiceWithDuration

func (s *Sprite) CreateServiceWithDuration(ctx context.Context, serviceName string, req *ServiceRequest, duration time.Duration) (*ServiceStream, error)

CreateServiceWithDuration creates a service with a custom monitoring duration

func (*Sprite) Delete

func (s *Sprite) Delete(ctx context.Context) error

Delete deletes this sprite

func (*Sprite) DeleteService

func (s *Sprite) DeleteService(ctx context.Context, serviceName string) error

DeleteService deletes a service for this sprite

func (*Sprite) Destroy

func (s *Sprite) Destroy() error

Destroy destroys the sprite.

func (*Sprite) Filesystem

func (s *Sprite) Filesystem() FS

Filesystem returns a filesystem interface for the sprite.

func (*Sprite) FilesystemAt

func (s *Sprite) FilesystemAt(workingDir string) FS

FilesystemAt returns a filesystem interface rooted at the given directory.

func (*Sprite) FsChmodControl

func (s *Sprite) FsChmodControl(ctx context.Context, filePath string, mode fs.FileMode, opts ...FsControlOption) (*FsChmodResult, error)

FsChmodControl changes file permissions using the control channel

func (*Sprite) FsChownControl

func (s *Sprite) FsChownControl(ctx context.Context, filePath string, opts ...FsControlOption) (*FsChownResult, error)

FsChownControl changes file ownership using the control channel

func (*Sprite) FsCopyControl

func (s *Sprite) FsCopyControl(ctx context.Context, source, dest string, opts ...FsControlOption) (*FsCopyResult, error)

FsCopyControl copies files using the control channel

func (*Sprite) FsDeleteControl

func (s *Sprite) FsDeleteControl(ctx context.Context, filePath string, opts ...FsControlOption) (*FsDeleteResult, error)

FsDeleteControl deletes a file or directory using the control channel

func (*Sprite) FsListControl

func (s *Sprite) FsListControl(ctx context.Context, dirPath string, opts ...FsControlOption) (*FsListResult, error)

FsListControl lists directory contents using the control channel

func (*Sprite) FsReadControl

func (s *Sprite) FsReadControl(ctx context.Context, filePath string, opts ...FsControlOption) (*FsReadResult, error)

FsReadControl reads a file using the control channel

func (*Sprite) FsRenameControl

func (s *Sprite) FsRenameControl(ctx context.Context, source, dest string, opts ...FsControlOption) (*FsRenameResult, error)

FsRenameControl renames/moves a file using the control channel

func (*Sprite) FsStatControl

func (s *Sprite) FsStatControl(ctx context.Context, filePath string, opts ...FsControlOption) (*FsEntry, error)

FsStatControl returns file info using the control channel (via fs.list)

func (*Sprite) FsWriteControl

func (s *Sprite) FsWriteControl(ctx context.Context, filePath string, data []byte, opts ...FsControlOption) (*FsWriteResult, error)

FsWriteControl writes a file using the control channel

func (*Sprite) GetCheckpoint

func (s *Sprite) GetCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)

GetCheckpoint retrieves information about a specific checkpoint for this sprite

func (*Sprite) GetNetworkPolicy

func (s *Sprite) GetNetworkPolicy(ctx context.Context) (*NetworkPolicy, error)

GetNetworkPolicy retrieves the current network policy for this sprite

func (*Sprite) GetService

func (s *Sprite) GetService(ctx context.Context, serviceName string) (*ServiceWithState, error)

GetService retrieves a specific service for this sprite

func (*Sprite) ListCheckpoints

func (s *Sprite) ListCheckpoints(ctx context.Context, historyFilter string) ([]*Checkpoint, error)

ListCheckpoints retrieves a list of checkpoints for this sprite (excludes auto checkpoints)

func (*Sprite) ListCheckpointsWithOptions

func (s *Sprite) ListCheckpointsWithOptions(ctx context.Context, opts ListCheckpointsOptions) ([]*Checkpoint, error)

ListCheckpointsWithOptions retrieves a list of checkpoints with configurable options

func (*Sprite) ListServices

func (s *Sprite) ListServices(ctx context.Context) ([]*ServiceWithState, error)

ListServices retrieves all services for this sprite

func (*Sprite) ListSessions

func (s *Sprite) ListSessions(ctx context.Context) ([]*Session, error)

ListSessions retrieves a list of active sessions for this sprite

func (*Sprite) Name

func (s *Sprite) Name() string

Name returns the sprite's name.

func (*Sprite) Organization

func (s *Sprite) Organization() *OrganizationInfo

Organization returns the organization information associated with this sprite.

func (*Sprite) ProxyPort

func (s *Sprite) ProxyPort(ctx context.Context, localPort, remotePort int) (*ProxySession, error)

ProxyPort creates a proxy session for a single port on this sprite

func (*Sprite) ProxyPorts

func (s *Sprite) ProxyPorts(ctx context.Context, mappings []PortMapping) ([]*ProxySession, error)

ProxyPorts creates proxy sessions for multiple port mappings on this sprite

func (*Sprite) ProxySocket

func (s *Sprite) ProxySocket(ctx context.Context, network, addr string) (net.Conn, error)

ProxySocket establishes a proxied connection to a port on this sprite

func (*Sprite) RestoreCheckpoint

func (s *Sprite) RestoreCheckpoint(ctx context.Context, checkpointID string) (*RestoreStream, error)

RestoreCheckpoint restores this sprite from a checkpoint

func (*Sprite) SignalService

func (s *Sprite) SignalService(ctx context.Context, serviceName, signal string) error

SignalService sends a signal to a service for this sprite

func (*Sprite) StartService

func (s *Sprite) StartService(ctx context.Context, serviceName string) (*ServiceStream, error)

StartService starts a service for this sprite

func (*Sprite) StartServiceWithDuration

func (s *Sprite) StartServiceWithDuration(ctx context.Context, serviceName string, duration time.Duration) (*ServiceStream, error)

StartServiceWithDuration starts a service with a custom monitoring duration

func (*Sprite) StopService

func (s *Sprite) StopService(ctx context.Context, serviceName string) (*ServiceStream, error)

StopService stops a service for this sprite

func (*Sprite) StopServiceWithTimeout

func (s *Sprite) StopServiceWithTimeout(ctx context.Context, serviceName string, timeout time.Duration) (*ServiceStream, error)

StopServiceWithTimeout stops a service with a custom timeout

func (*Sprite) UpdateNetworkPolicy

func (s *Sprite) UpdateNetworkPolicy(ctx context.Context, policy *NetworkPolicy) error

UpdateNetworkPolicy updates the network policy for this sprite

func (*Sprite) UpdateURLSettings

func (s *Sprite) UpdateURLSettings(ctx context.Context, settings *URLSettings) error

UpdateURLSettings updates the URL authentication settings for this sprite

func (*Sprite) Upgrade

func (s *Sprite) Upgrade(ctx context.Context) error

Upgrade upgrades this sprite to the latest version

type SpriteConfig

type SpriteConfig struct {
	RamMB     int    `json:"ram_mb,omitempty"`
	CPUs      int    `json:"cpus,omitempty"`
	Region    string `json:"region,omitempty"`
	StorageGB int    `json:"storage_gb,omitempty"`
}

SpriteConfig represents sprite configuration options

type SpriteInfo

type SpriteInfo struct {
	ID            string            `json:"id"`
	Name          string            `json:"name"`
	Organization  string            `json:"organization"`
	Status        string            `json:"status"`
	Config        *SpriteConfig     `json:"config,omitempty"`
	Environment   map[string]string `json:"environment,omitempty"`
	CreatedAt     time.Time         `json:"created_at"`
	UpdatedAt     time.Time         `json:"updated_at"`
	BucketName    string            `json:"bucket_name,omitempty"`
	PrimaryRegion string            `json:"primary_region,omitempty"`
	URL           string            `json:"url,omitempty"`
	URLSettings   *URLSettings      `json:"url_settings,omitempty"`
	Labels        []string          `json:"labels,omitempty"`
	LastRunningAt *time.Time        `json:"last_running_at,omitempty"`
	LastWarmingAt *time.Time        `json:"last_warming_at,omitempty"`
}

SpriteInfo represents sprite information from the API

type SpriteList

type SpriteList struct {
	Sprites               []SpriteInfo `json:"sprites"`
	Org                   *OrgInfo     `json:"org,omitempty"`
	HasMore               bool         `json:"has_more"`
	NextContinuationToken string       `json:"next_continuation_token,omitempty"`
}

SpriteList represents a paginated list of sprites

type StreamID

type StreamID byte

StreamID represents different stream types in the protocol

const (
	StreamStdin    StreamID = 0
	StreamStdout   StreamID = 1
	StreamStderr   StreamID = 2
	StreamExit     StreamID = 3
	StreamStdinEOF StreamID = 4
)

type StreamMessage

type StreamMessage struct {
	Type  string `json:"type"` // "info", "stdout", "stderr", "error"
	Data  string `json:"data,omitempty"`
	Error string `json:"error,omitempty"`
}

StreamMessage represents a message in a streaming response

type URLSettings

type URLSettings struct {
	Auth          string `json:"auth,omitempty"`
	PrivateAccess string `json:"private_access,omitempty"`
}

URLSettings represents URL authentication settings

type UpdateSpriteRequest

type UpdateSpriteRequest struct {
	URLSettings *URLSettings `json:"url_settings,omitempty"`
	Labels      []string     `json:"labels,omitempty"`
	ClearLabels bool         `json:"clear_labels,omitempty"`
}

UpdateSpriteRequest represents the request to update a sprite's settings

type UpdateURLSettingsRequest

type UpdateURLSettingsRequest struct {
	URLSettings *URLSettings `json:"url_settings"`
}

UpdateURLSettingsRequest represents the request to update URL settings

Directories

Path Synopsis
test-cli module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL