preview

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package preview implements the preview lifecycle (up, exec, logs, ls, down) on top of the HostProvider and Exposer extension points. This file set holds the building blocks: per-preview locking, remote marker commands and preview ID resolution.

Index

Constants

View Source
const (
	ScriptTest = "test"
	ScriptSeed = "seed"
)

Script names accepted by ExecOptions.Script.

View Source
const (
	StatusHealthy   = "healthy"
	StatusUnhealthy = "unhealthy"
	StatusStarting  = "starting"
)

Preview status values in ListResult. A stack aggregates its containers: any unhealthy, restarting, paused, dead or failed (non-zero exit) container, or no running container at all, makes it "unhealthy"; otherwise any container still starting (created, or "health: starting") makes it "starting"; else "healthy". Running containers without a healthcheck and containers that exited with code 0 (one-shot jobs) count as healthy.

View Source
const ActivityMarker = "/srv/provr/last-active"

ActivityMarker is the host file whose mtime the idle-stop timer reads.

View Source
const DefaultLockTimeout = 30 * time.Second

DefaultLockTimeout is how long a caller waits for a busy preview.

View Source
const DefaultLogTail = 200

DefaultLogTail is the number of lines Logs shows when Tail is 0.

View Source
const ExpiryFileName = "expires-at"

ExpiryFileName is the per-preview file holding the expiry in Unix seconds.

View Source
const MetaFileName = "meta.json"

MetaFileName is the convenience metadata file in the preview directory. Labels stay the source of truth.

View Source
const OverrideFileName = "provr.override.yml"

OverrideFileName is the generated compose override. It lives in the preview directory, next to src/, so the sync's --delete never removes it.

Variables

View Source
var CLIWording = Wording{
	Down: func(id string) string { return "provr down " + id },
	List: "provr ls",
	Logs: func(id string) string { return "provr logs " + id },
	TTL:  func(max string) string { return "pass --ttl " + max + " at most" },
	Name: "pass --name <name>",
	Init: "provr init to create provr.yaml",
}

CLIWording names the next steps as provr commands.

View Source
var ErrDetachedHead = errors.New("preview: detached HEAD has no branch name; --name is required")

ErrDetachedHead is returned when the preview name is derived from the current branch and HEAD is detached.

View Source
var ErrPreviewNotFound = errors.New("preview not found")

ErrPreviewNotFound is returned (wrapped) when no running host of the project has the preview. Callers detect it with errors.Is.

View Source
var MCPWording = Wording{
	Down:     func(id string) string { return fmt.Sprintf("preview_down(id: %q)", id) },
	List:     "preview_list",
	Logs:     func(id string) string { return fmt.Sprintf("preview_logs(id: %q)", id) },
	TTL:      func(max string) string { return "pass ttl: " + max + " at most" },
	Name:     "pass name: <name>",
	Init:     "ask the user to run `provr init` to create provr.yaml",
	NameHint: "pass name: <name> to choose the preview name",
}

MCPWording names the next steps as MCP tool calls.

Functions

func DefaultLockDir

func DefaultLockDir() (string, error)

DefaultLockDir returns ~/.provr/locks.

func ResolveID

func ResolveID(ctx context.Context, r execx.Runner, dir, project, name string) (string, error)

ResolveID is not called by the commands yet; it is kept for the EPIC-005 agent surface, which resolves an ID from the current worktree.

ResolveID returns the preview ID for project. A non-empty name (from --name) takes precedence over the current branch of the git worktree in dir. On a detached HEAD without a name it fails, asking for --name.

func SrcDir

func SrcDir(id string) string

SrcDir is the synced worktree on the host.

func TouchActivityCommand

func TouchActivityCommand() string

TouchActivityCommand returns the remote shell command that marks the host as active.

func WriteExpiryCommand

func WriteExpiryCommand(id string, expiresAt time.Time) (string, error)

WriteExpiryCommand returns the remote shell command that writes the preview's expires-at file (Unix seconds), creating the preview directory first and replacing the file atomically (temporary file plus rename).

Types

type DownOptions

type DownOptions struct {
	// KeepHost is reserved: EPIC-004 stops idle hosts. Down never stops or
	// deletes a host, with or without it.
	KeepHost bool
}

DownOptions are the inputs of Down.

type DownResult

type DownResult struct {
	ID string `json:"id"`
	// HostID is the host the preview was found on; empty when not found.
	HostID string `json:"host_id,omitempty"`
	// NotFound is true when every host of the project was inspected and none
	// had containers or a directory for the preview.
	NotFound bool `json:"not_found"`
	// Removed is true when containers or files were removed by this call.
	Removed bool `json:"removed"`
	// Released is true when Exposer.Release succeeded.
	Released bool `json:"released"`
	// Note explains an outcome that is not a plain removal.
	Note string `json:"note,omitempty"`
}

DownResult describes what Down did.

type ExecOptions

type ExecOptions struct {
	// Script is "test" or "seed" to run the matching commands.* entry via
	// `sh -c`. Exactly one of Script and Args must be given.
	Script string
	// Args is a command line; each element is one argument (quoted for the
	// remote shell individually, so an element with spaces stays one argument).
	Args []string
	// Stdout and Stderr receive the remote output as it is produced.
	Stdout, Stderr io.Writer
}

ExecOptions are the inputs of Exec.

type HealthTimeoutError

type HealthTimeoutError struct {
	ID      string
	Timeout time.Duration
	Last    error
}

HealthTimeoutError is returned when the healthcheck did not pass in time. Last is the last real probe failure.

func (*HealthTimeoutError) Error

func (e *HealthTimeoutError) Error() string

func (*HealthTimeoutError) Unwrap

func (e *HealthTimeoutError) Unwrap() error

type HostInfo

type HostInfo struct {
	ID       string    `json:"id"`
	Project  string    `json:"project"`
	State    string    `json:"state"`
	Hostname string    `json:"hostname,omitempty"`
	Previews []Summary `json:"previews"`
	// Error is set when a running host could not be queried.
	Error string `json:"error,omitempty"`
}

HostInfo is one host and, when it is running, its previews.

type ListOptions

type ListOptions struct {
	// AllProjects lists every project recorded in projects.json (plus the
	// current one) instead of only the current project.
	AllProjects bool
}

ListOptions are the inputs of List.

type ListResult

type ListResult struct {
	Hosts []HostInfo `json:"hosts"`
}

ListResult is the schema of `provr ls --json`, reused by the MCP tools.

type Lock

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

Lock is a held per-preview lock. Release it when the operation ends.

func AcquireLock

func AcquireLock(ctx context.Context, dir, id string, timeout time.Duration) (*Lock, error)

AcquireLock takes the exclusive flock on <dir>/<id>.lock, waiting up to timeout for another holder. On timeout it fails with *LockBusyError. The id is validated before any path is built.

func (*Lock) Release

func (l *Lock) Release() error

Release drops the lock. It is safe to call more than once.

type LockBusyError

type LockBusyError struct{ ID string }

LockBusyError is returned when another operation holds the preview's lock past the wait timeout.

func (*LockBusyError) Error

func (e *LockBusyError) Error() string

type LogsOptions

type LogsOptions struct {
	// Service limits the output to one compose service; empty means all.
	Service string
	// Tail is the number of lines per container; 0 means DefaultLogTail.
	Tail int
	// Since is a positive Go duration such as "10m"; empty means no limit.
	Since string
	// Stdout and Stderr receive the output as it is produced.
	Stdout, Stderr io.Writer
}

LogsOptions are the inputs of Logs.

type Message

type Message struct {
	Summary string
	// Next is the single recommended next step (a command or an action).
	Next string
}

Message is a user-facing error: what happened and exactly one next step.

func Explain

func Explain(err error, previews []Summary) Message

Explain maps err to a short actionable Message with one recommended next step, worded for the CLI. See ExplainWith.

func ExplainWith

func ExplainWith(err error, previews []Summary, w Wording) Message

ExplainWith maps err to a short actionable Message with one recommended next step, named in w's wording. previews are the current previews (from List); they are used to name what to remove on ErrNoCapacity and may be nil. Unknown errors pass through with no next step, except that a trailing CLI "pass --name" hint becomes w's hint when w has one.

func (Message) String

func (m Message) String() string

String renders the message on two lines.

type Meta

type Meta struct {
	ID        string         `json:"id"`
	Project   string         `json:"project"`
	Worktree  string         `json:"worktree"`
	Branch    string         `json:"branch"`
	CreatedAt time.Time      `json:"created_at"`
	ExpiresAt time.Time      `json:"expires_at"`
	Endpoints []MetaEndpoint `json:"endpoints"`
}

Meta is the content of meta.json.

type MetaEndpoint

type MetaEndpoint struct {
	Service string `json:"service"`
	Port    int    `json:"port"`
	URL     string `json:"url"`
}

MetaEndpoint is one reachable service in meta.json.

type Options

type Options struct {
	Provider core.HostProvider
	Exposer  core.Exposer
	Runner   execx.Runner
	// Project is the loaded provr.yaml with defaults applied.
	Project config.Project

	// Now is the clock used for created-at and expiry; default time.Now.
	Now func() time.Time
	// LockDir is the per-preview lock directory; default ~/.provr/locks.
	LockDir string
	// LockTimeout is how long Up waits for a busy preview; default
	// DefaultLockTimeout.
	LockTimeout time.Duration
	// State records the project in projects.json; default ~/.provr/state.
	State *state.Store
	// HTTPClient performs the tailnet health GET; default http.DefaultClient.
	HTTPClient *http.Client
	// HealthInterval is the pause between health polls; default 2s.
	HealthInterval time.Duration
	// SSHBinary is the ssh executable; default "ssh".
	SSHBinary string
	// Owner is written into provr-owner; default the sanitized hostname.
	Owner string
}

Options builds a Service. Provider, Exposer, Runner and Project are required; every other field has a production default so tests can inject deterministic replacements.

type Service

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

Service runs the preview lifecycle for one project.

func New

func New(opts Options) (*Service, error)

New validates opts and fills defaults.

func (*Service) Down

func (s *Service) Down(ctx context.Context, id string, o DownOptions) (DownResult, error)

Down removes a preview: `docker compose down -v --remove-orphans`, the preview directory, then Exposer.Release. It is idempotent.

Compose is run with the project name alone. Compose finds the containers, networks and volumes by their project label, so this works even when src/ or the override are gone (a half-failed up, or a repeated down) and needs no compose file to parse.

Release runs on every successful call, including when nothing was found: it is idempotent, and it cleans a tailnet device left behind by a down that removed the containers but failed before Release. It is skipped only when compose down fails, because the stack (and its sidecar) is still running.

func (*Service) Exec

func (s *Service) Exec(ctx context.Context, id string, o ExecOptions) (int, error)

Exec runs a command in the preview's src/ directory on its host, with COMPOSE_PROJECT_NAME and COMPOSE_FILE set so plain `docker compose exec -T api pytest` targets the preview. It streams output and returns the remote command's exit code.

Exec does not take the up/down lock: it is read-only with respect to the preview's lifecycle, and exec must work while a long `up` runs (for example to inspect a stack that is still building). Racing a concurrent down simply makes the command fail.

Limitation: ssh reports its own failures (connection refused, auth) as exit 255, which cannot be told apart from a remote command that exits 255. Exit 255 is returned together with an error saying so; every other code is returned with a nil error, including non-zero ones.

func (*Service) List

func (s *Service) List(ctx context.Context, o ListOptions) (ListResult, error)

List returns the project's hosts with their state and, for running hosts, their previews. Labels are the source of truth; meta.json only adds endpoints, branch and worktree, and a missing or corrupt one is ignored. An unreachable running host is reported in HostInfo.Error, not as a failure.

All-projects uses the project names recorded in projects.json, because HostProvider.List needs a project name; the current project is always included.

func (*Service) Logs

func (s *Service) Logs(ctx context.Context, id string, o LogsOptions) error

Logs prints `docker compose logs` of the preview. It does not follow. Inputs are validated before any remote call. Like Exec, it takes no lock.

func (*Service) PreviewID

func (s *Service) PreviewID(ctx context.Context, o UpOptions) (string, error)

PreviewID returns the ID Up would use for o, without touching any host: it resolves the worktree and the branch (or o.Name) exactly as Up does.

func (*Service) Up

func (s *Service) Up(ctx context.Context, o UpOptions) (UpResult, error)

Up creates the preview for the worktree, or updates it when it exists. Steps are timed and logged at debug level.

type Summary

type Summary struct {
	ID         string         `json:"id"`
	Project    string         `json:"project"`
	HostID     string         `json:"host_id"`
	Status     string         `json:"status"`
	CreatedAt  *time.Time     `json:"created_at,omitempty"`
	ExpiresAt  time.Time      `json:"expires_at"`
	AgeSeconds int64          `json:"age_seconds"`
	Expired    bool           `json:"expired"`
	Branch     string         `json:"branch,omitempty"`
	Worktree   string         `json:"worktree,omitempty"`
	Endpoints  []MetaEndpoint `json:"endpoints"`
}

Summary is one preview as seen from container labels and meta.json.

type TTLTooLongError

type TTLTooLongError struct{ Requested, Max time.Duration }

TTLTooLongError is returned when the requested TTL exceeds the maximum.

func (*TTLTooLongError) Error

func (e *TTLTooLongError) Error() string

type UpOptions

type UpOptions struct {
	// Name overrides the branch name when computing the preview ID; required
	// on a detached HEAD.
	Name string
	// TTL is the requested lifetime; zero means ttl.default for a new preview
	// and "keep the current expiry" for an existing one.
	TTL time.Duration
	// Worktree is the git worktree to preview; default the project's repo root.
	Worktree string
	// Progress, when set, is called with each step name ("record-project",
	// "ensure-host", "read-labels", "write-expiry", "sync", "override",
	// "compose-up", "health", "seed") once, just before the step runs.
	// It is called from Up's goroutine and must not block.
	Progress func(step string)
}

UpOptions are the inputs of Up.

type UpResult

type UpResult struct {
	ID        string
	HostID    string
	Endpoints []core.Endpoint
	CreatedAt time.Time
	ExpiresAt time.Time
	// Created is true for a new preview and false for an update.
	Created bool
	// TTLCapped is true when a requested TTL was cut to created_at + ttl.max.
	TTLCapped bool
	// Seeded is true when commands.seed ran during this up.
	Seeded bool
}

UpResult describes the preview after Up.

func (UpResult) MarshalJSON

func (r UpResult) MarshalJSON() ([]byte, error)

MarshalJSON is the schema of `provr up --json`, reused by the MCP tools: snake_case keys, endpoints in the same shape as in `provr ls --json`.

type Wording

type Wording struct {
	Down     func(id string) string  // remove a preview
	List     string                  // list previews
	Logs     func(id string) string  // read a preview's logs
	TTL      func(max string) string // shorten the TTL
	Name     string                  // choose a preview name
	Init     string                  // create the project config
	NameHint string                  // replaces the CLI "pass --name" hint at the end of an unknown error; "" keeps the text as is
}

Wording holds the command-shaped phrases of a Message, so the CLI and the MCP server share one classification and differ only in how they name the next step. It is a plain value, not an interface.

Jump to

Keyboard shortcuts

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