DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

A sandbox API client in Go with net/http and context deadlines

Go services that orchestrate agents tend to prefer the standard library over a dependency for every HTTP API they touch. The Sandscale sandbox API is a good fit for that: JSON over HTTPS, bearer-token auth, and five endpoints for a sandbox's whole life. This post builds a small client with net/http, encoding/json and context, then uses it to compile and run a Go program inside a sandbox.

The endpoints and fields come from the sandbox API guide and the Sandboxes API reference. If you have read our Python version, the design is the same; what changes is how Go expresses deadlines and errors.

The endpoints

All paths sit under https://api.sandscale.dev/api/v1/sandbox:

  • POST /instances starts a sandbox from a template, with ttl_seconds as its lifetime. It needs sandboxes:create.
  • PUT /instances/{id}/files writes one file, with its content in base64.
  • POST /instances/{id}/exec runs a command and answers with exit_code, stdout, stderr, duration_ms, oom_killed and timed_out.
  • GET /instances/{id}/files?path=... reads a file or lists a folder.
  • DELETE /instances/{id} stops the sandbox and deletes its disk. The reference lists sandboxes:manage for it.

Writing, running and reading need sandboxes:use.

The client

package main

import (
    "bytes"
    "context"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "time"
)

const api = "https://api.sandscale.dev/api/v1/sandbox"

type Client struct {
    key  string
    http *http.Client
}

type APIError struct {
    Status    int
    Code      string
    Message   string
    RequestID string
}

func (e *APIError) Error() string {
    return fmt.Sprintf("%d %s: %s (request %s)", e.Status, e.Code, e.Message, e.RequestID)
}

type errorFields struct {
    Code      string `json:"code"`
    Message   string `json:"message"`
    RequestID string `json:"request_id"`
}

// call sends one request. The context carries the deadline, so each caller decides how long to wait.
func (c *Client) call(ctx context.Context, method, path string, in, out any) error {
    var body io.Reader
    if in != nil {
        b, err := json.Marshal(in)
        if err != nil {
            return err
        }
        body = bytes.NewReader(b)
    }
    req, err := http.NewRequestWithContext(ctx, method, api+path, body)
    if err != nil {
        return err
    }
    req.Header.Set("Authorization", "Bearer "+c.key)
    if in != nil {
        req.Header.Set("Content-Type", "application/json")
    }
    resp, err := c.http.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    data, err := io.ReadAll(resp.Body)
    if err != nil {
        return err
    }
    if resp.StatusCode >= 300 {
        // The error may be nested under "error" or sit at the top level.
        var wrapped struct {
            Error *errorFields `json:"error"`
        }
        var flat errorFields
        fields := &flat
        if json.Unmarshal(data, &wrapped) == nil && wrapped.Error != nil {
            fields = wrapped.Error
        } else {
            _ = json.Unmarshal(data, &flat)
        }
        e := &APIError{Status: resp.StatusCode, Code: fields.Code, Message: fields.Message, RequestID: fields.RequestID}
        if e.Code == "" {
            e.Code = fmt.Sprintf("http_%d", resp.StatusCode)
        }
        if e.RequestID == "" {
            e.RequestID = resp.Header.Get("X-Request-ID")
        }
        return e
    }
    if out != nil && len(data) > 0 {
        return json.Unmarshal(data, out)
    }
    return nil
}

type Sandbox struct {
    ID     string `json:"id"`
    Status string `json:"status"`
}

type ExecOutcome struct {
    RunID      string `json:"run_id"`
    ExitCode   int    `json:"exit_code"`
    Stdout     string `json:"stdout"`
    Stderr     string `json:"stderr"`
    DurationMs int    `json:"duration_ms"`
    OOMKilled  bool   `json:"oom_killed"`
    TimedOut   bool   `json:"timed_out"`
}

func (c *Client) Create(ctx context.Context, template string, ttlSeconds int) (*Sandbox, error) {
    var sb Sandbox
    in := map[string]any{"template_id": template, "ttl_seconds": ttlSeconds}
    err := c.call(ctx, http.MethodPost, "/instances", in, &sb)
    return &sb, err
}

func (c *Client) Exec(ctx context.Context, id string, command []string, timeoutSec int) (*ExecOutcome, error) {
    // The request must outlive the command, so its deadline adds a margin.
    ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSec+30)*time.Second)
    defer cancel()
    var out ExecOutcome
    in := map[string]any{"command": command, "timeout_sec": timeoutSec}
    err := c.call(ctx, http.MethodPost, "/instances/"+url.PathEscape(id)+"/exec", in, &out)
    return &out, err
}

func (c *Client) WriteFile(ctx context.Context, id, path string, data []byte) error {
    in := map[string]string{"path": path, "content": base64.StdEncoding.EncodeToString(data)}
    return c.call(ctx, http.MethodPut, "/instances/"+url.PathEscape(id)+"/files", in, nil)
}

func (c *Client) ReadFile(ctx context.Context, id, path string) ([]byte, error) {
    var got struct {
        Type    string `json:"type"`
        Content string `json:"content"`
    }
    q := "?path=" + url.QueryEscape(path)
    if err := c.call(ctx, http.MethodGet, "/instances/"+url.PathEscape(id)+"/files"+q, nil, &got); err != nil {
        return nil, err
    }
    if got.Type != "file" {
        return nil, fmt.Errorf("%s is not a regular file", path)
    }
    return base64.StdEncoding.DecodeString(got.Content)
}

func (c *Client) Stop(ctx context.Context, id string) error {
    err := c.call(ctx, http.MethodDelete, "/instances/"+url.PathEscape(id), nil, nil)
    if e, ok := err.(*APIError); ok && e.Code == "sandbox_not_found" {
        return nil
    }
    return err
}
Enter fullscreen mode Exit fullscreen mode

Design notes

Deadlines live in the context

The http.Client has no global timeout. Instead every call takes a context.Context, and the caller decides how long that particular call may take. This matters because the calls are not alike. Creating a sandbox or writing a file should take seconds. An exec request does not answer until the command ends, so it must be allowed to run at least as long as the command's own timeout_sec.

Exec handles that itself: it wraps whatever context it is given with a deadline of timeoutSec plus 30 seconds. If the caller's context has an earlier deadline, that one still wins, which is the behavior you want when a whole request handler has a budget. Our post on sandbox timeouts goes into the three clocks involved.

Typed results, loose requests

ExecOutcome mirrors the reference's fields exactly, so the compiler catches a typo in TimedOut and your editor can autocomplete the result. Request bodies are maps here to keep the post short. In a real codebase, give them structs too, with omitempty on optional fields such as env, workdir and stdin.

Errors you can switch on

Non-2xx answers come back as *APIError with the status, a Code, the message and a request ID. The reference lists the codes each endpoint can return, such as template_not_found, quota_exceeded, policy_denied, file_too_large and sandbox_not_found. With Go's errors.As, a caller can branch on the code:

var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.Code == "quota_exceeded" {
    // Queue the work instead of failing it.
}
Enter fullscreen mode Exit fullscreen mode

The decoder accepts the error fields nested under "error" or at the top level, and falls back to the X-Request-ID response header. That matches the TypeScript SDK's parser, so the client copes with either shape.

Stop treats "already gone" as success

Stop returns nil on sandbox_not_found. A sandbox whose ttl_seconds ran out, or that something else already stopped, is in the state you wanted.

Running it

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func main() {
    if err := run(); err != nil {
        log.Fatal(err)
    }
}

// run holds the work, so its deferred Stop runs before main exits (log.Fatal skips defers).
func run() error {
    c := &Client{key: os.Getenv("SANDSCALE_API_KEY"), http: &http.Client{}}
    ctx := context.Background()

    short, cancel := context.WithTimeout(ctx, 30*time.Second)
    sb, err := c.Create(short, "builtin:go", 600)
    cancel()
    if err != nil {
        return err
    }
    defer func() {
        stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
        defer cancel()
        if err := c.Stop(stopCtx, sb.ID); err != nil {
            log.Printf("stop %s: %v", sb.ID, err)
        }
    }()

    src := []byte("package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"hello from the sandbox\") }\n")
    writeCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
    defer cancel()
    if err := c.WriteFile(writeCtx, sb.ID, "/workspace/main.go", src); err != nil {
        return err
    }
    out, err := c.Exec(ctx, sb.ID, []string{"go", "run", "main.go"}, 120)
    if err != nil {
        return err
    }
    switch {
    case out.TimedOut:
        fmt.Println("timed out")
    case out.OOMKilled:
        fmt.Println("ran out of memory")
    default:
        fmt.Println(out.ExitCode, out.Stdout, out.Stderr)
    }
    return nil
}
Enter fullscreen mode Exit fullscreen mode

Two Go-specific details are worth calling out.

log.Fatal skips deferred functions. It calls os.Exit, which does not run defers. If main created the sandbox, deferred Stop, and then called log.Fatal on an error, the sandbox would be left running until its ttl_seconds ran out. Putting the work in run() and returning errors means the deferred Stop always runs first.

Stop gets a fresh context. The deferred stop uses context.Background() with its own 30 second deadline, not the work's context. If the work was cancelled or hit its deadline, a stop that reused the same context would fail immediately, exactly when cleanup matters most.

The ttl_seconds of 600 on create is the backstop for everything else: if the process is killed outright, the sandbox still stops by itself.

Before production

  • Retries for reads only. Retry GET on 429 and 503, with backoff, a cap, and Retry-After when present. Avoid automatic retries for POST /instances and exec: after a timeout you cannot tell whether the server acted, and a retry may start a second sandbox or run the command twice.
  • Cap output. stdout and stderr arrive in the JSON body. Limit them before logging them or handing them to a model.
  • Read the body with a limit. io.ReadAll trusts the server. Wrapping resp.Body in io.LimitReader protects your process from a surprisingly large answer.
  • Folders, not files. For a whole project, POST /instances/{id}/project takes a gzip tar archive in one request. See getting code into a sandbox.

The rest of the API, from snapshots to logs, follows the same pattern: a path, a JSON body, and a code when something goes wrong.

Originally published on the Sandscale blog.

Top comments (0)