template

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package template owns the persistent metadata store for user-defined sandbox templates and the types shared between the control plane, the builder runtime, and the sandbox manager.

A Template is edvabe's record of one image the user can launch a sandbox from. Templates are created via the E2B SDK's programmatic Template() builder: the SDK calls POST /v3/templates with metadata, uploads file contexts into the content-addressed cache, then posts a TemplateBuildStartV2 with a step array that the builder translates into a generated Dockerfile and feeds to docker build. See docs/06-phases.md Phase 3 for the full wire protocol.

This package owns no HTTP and no Docker — higher layers compose those in. Builder runtime lives under internal/template/builder, file-context cache under internal/template/filecache.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned for an unknown template ID or alias.
	ErrNotFound = errors.New("template: not found")
	// ErrAliasTaken is returned when creating a template with an alias
	// already claimed by another template.
	ErrAliasTaken = errors.New("template: alias already in use")
)

Sentinel errors so HTTP handlers can discriminate without string matching.

Functions

func NewBuildID

func NewBuildID() string

NewBuildID returns "bld_" followed by 16 random base32 characters.

func NewSandboxResolver

func NewSandboxResolver(store *Store) sandbox.TemplateResolver

NewSandboxResolver adapts a Store so it satisfies sandbox.TemplateResolver, which the sandbox manager consults at Create time to turn `Sandbox.create('webmaster-chrome')` into an actual image tag.

Resolution order (matches the Phase 3 scope):

  1. Look up by UUID.
  2. Look up by alias/name.
  3. Return sandbox.ErrTemplateNotFound so the manager falls back to its base image.

The returned resolution carries the ImageTag persisted on the template record plus the template's StartCmd / ReadyCmd so the runtime can inject them as env vars into the container.

func NewTemplateID

func NewTemplateID() string

NewTemplateID returns "tpl_" followed by 16 random base32 characters. The E2B SDK treats template IDs as opaque strings, so the prefix is a local convention to disambiguate from sandbox IDs at a glance.

Types

type Build

type Build struct {
	ID         string      `json:"id"`
	Status     BuildStatus `json:"status"`
	Reason     string      `json:"reason,omitempty"`
	StartedAt  time.Time   `json:"startedAt"`
	FinishedAt *time.Time  `json:"finishedAt,omitempty"`
}

Build is one attempt at materializing a template into an image. A Template can accumulate multiple Builds over its lifetime; the most recent successful one wins for sandbox create.

type BuildSpec

type BuildSpec struct {
	FromImage         string        `json:"fromImage,omitempty"`
	FromTemplate      string        `json:"fromTemplate,omitempty"`
	FromImageRegistry *RegistryAuth `json:"fromImageRegistry,omitempty"`
	Steps             []Step        `json:"steps,omitempty"`
	StartCmd          string        `json:"startCmd,omitempty"`
	ReadyCmd          string        `json:"readyCmd,omitempty"`
	Force             bool          `json:"force,omitempty"`
}

BuildSpec is the decoded TemplateBuildStartV2 body. Carries the base image selection, the step array, and the start/ready commands that apply at sandbox create time.

type BuildStatus

type BuildStatus string

BuildStatus is the lifecycle state of a template build.

const (
	// BuildStatusWaiting is set the instant a build is enqueued. In
	// local mode it transitions to building almost immediately; the
	// state exists for wire compatibility with the E2B SDK.
	BuildStatusWaiting BuildStatus = "waiting"
	// BuildStatusBuilding is set while docker build is running.
	BuildStatusBuilding BuildStatus = "building"
	// BuildStatusReady is set on successful completion. The resulting
	// image is tagged edvabe/user-<templateID>:latest.
	BuildStatusReady BuildStatus = "ready"
	// BuildStatusError is set on any failure. Build.Reason carries the
	// human-readable cause.
	BuildStatusError BuildStatus = "error"
)

type Clock

type Clock interface {
	Now() time.Time
}

Clock is a tiny injection point so unit tests can control CreatedAt / Build.StartedAt without wall-clock sleeping. Mirrors the Clock in internal/sandbox/manager.go.

type CreateOptions

type CreateOptions struct {
	Name     string
	Alias    string
	Tags     []string
	CPUCount int
	MemoryMB int
}

CreateOptions is the input to Store.Create. Name is required and doubles as the alias unless Alias is set explicitly (E2B convention: the `name` field on POST /v3/templates is used as both).

type Options

type Options struct {
	// Path is the JSON file the store persists to. If empty, an
	// in-memory store is used (useful for tests).
	Path string
	// Clock is injected for deterministic timestamps in tests. Defaults
	// to wall-clock time.
	Clock Clock
}

Options configures NewStore.

type RegistryAuth

type RegistryAuth struct {
	Username      string `json:"username,omitempty"`
	Password      string `json:"password,omitempty"`
	ServerAddress string `json:"serverAddress,omitempty"`
}

RegistryAuth carries private-registry credentials from the SDK to the docker build invocation. Passthrough — edvabe does not introspect.

type SeedOptions

type SeedOptions struct {
	Alias    string
	ImageTag string
	StartCmd string
	ReadyCmd string
}

SeedOptions describes a built-in template that edvabe registers at startup. Built-in templates are idempotent: if the alias already exists the record is updated in-place (startCmd, readyCmd, imageTag may have changed after a binary upgrade); if it does not exist a new template is created.

type Step

type Step struct {
	Type      string   `json:"type"`
	Args      []string `json:"args,omitempty"`
	FilesHash string   `json:"filesHash,omitempty"`
	Force     bool     `json:"force,omitempty"`
}

Step is one element of a TemplateBuildStartV2.steps array as the SDK sends it. Kept here (rather than under builder/) so the HTTP handler and the builder package can share the decoded shape without a cycle.

type Store

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

Store is a mutex-guarded, JSON-file-backed registry of templates.

Reads use an RWMutex so concurrent lookups from sandbox create don't serialize. Writes take the full lock and flush synchronously to disk so a crash between Create and the next read cannot strand a template in memory-only state.

func NewStore

func NewStore(opts Options) (*Store, error)

NewStore constructs a Store and loads any existing templates from disk. A missing file is not an error — the store starts empty. A malformed file IS an error; callers decide whether to bail or move it aside.

func (*Store) AppendBuild

func (s *Store) AppendBuild(templateID string, build Build) (*Build, error)

AppendBuild inserts a new Build entry onto the template and flushes. Returns the cloned build so callers can log its ID.

func (*Store) Create

func (s *Store) Create(opts CreateOptions) (*Template, error)

Create inserts a new template and flushes. Returns ErrAliasTaken if the chosen alias already belongs to another template.

func (*Store) Delete

func (s *Store) Delete(id string) error

Delete removes a template. Returns ErrNotFound if the template does not exist.

func (*Store) Get

func (s *Store) Get(id string) (*Template, error)

Get returns a defensive copy of the template with the given ID, or ErrNotFound.

func (*Store) List

func (s *Store) List() []*Template

List returns a snapshot of all templates sorted by CreatedAt ascending.

func (*Store) ResolveAlias

func (s *Store) ResolveAlias(alias string) (*Template, error)

ResolveAlias returns the template whose alias matches, or ErrNotFound.

func (*Store) ResolveNameOrID

func (s *Store) ResolveNameOrID(idOrAlias string) (*Template, error)

ResolveNameOrID looks up a template by ID first, then by alias. This is the resolver the sandbox manager uses at create time.

func (*Store) SeedBuiltIn

func (s *Store) SeedBuiltIn(opts SeedOptions) error

SeedBuiltIn creates or updates a built-in template. See SeedOptions.

func (*Store) UpdateBuild

func (s *Store) UpdateBuild(templateID, buildID string, mutator func(*Build)) error

UpdateBuild finds a build by ID and runs the mutator on it under the write lock. Returns ErrNotFound if either the template or the build is unknown.

func (*Store) UpdateMeta

func (s *Store) UpdateMeta(id string, mutator func(*Template)) (*Template, error)

UpdateMeta applies a mutator to the template's mutable fields under the write lock and flushes. The mutator must not change ID. Returns ErrNotFound if no such template exists, ErrAliasTaken if the mutator sets an alias already held by another template.

type Template

type Template struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Tags      []string  `json:"tags,omitempty"`
	Alias     string    `json:"alias,omitempty"`
	CPUCount  int       `json:"cpuCount,omitempty"`
	MemoryMB  int       `json:"memoryMB,omitempty"`
	StartCmd  string    `json:"startCmd,omitempty"`
	ReadyCmd  string    `json:"readyCmd,omitempty"`
	ImageTag  string    `json:"imageTag,omitempty"`
	Public    bool      `json:"public"`
	CreatedAt time.Time `json:"createdAt"`
	Builds    []Build   `json:"builds,omitempty"`
}

Template is edvabe's persistent record of a user template.

The store is the source of truth for alias → image resolution at sandbox create time. StartCmd and ReadyCmd are applied by the sandbox manager (injected into the container's env as EDVABE_START_CMD / EDVABE_READY_CMD), not baked into the Dockerfile.

func (*Template) LatestReady

func (t *Template) LatestReady() *Build

LatestReady returns the most recent build whose Status == Ready, or nil if none exist yet. Used at sandbox-create to pick the image tag.

Directories

Path Synopsis
Package builder owns the async template build runtime — translator from SDK step arrays into generated Dockerfiles, file-context staging, and the BuildManager state machine that drives docker build to completion.
Package builder owns the async template build runtime — translator from SDK step arrays into generated Dockerfiles, file-context staging, and the BuildManager state machine that drives docker build to completion.
Package filecache is the content-addressed blob store edvabe uses for template file contexts.
Package filecache is the content-addressed blob store edvabe uses for template file contexts.

Jump to

Keyboard shortcuts

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