core

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: 15 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 core holds the domain types (Host, Preview, Endpoint) and the two extension points (HostProvider and Exposer) that the rest of provr builds on. It must not import provider implementations or cloud SDKs.

Index

Constants

View Source
const (
	// LabelManaged is the label key marking a resource as managed (value ManagedValue).
	LabelManaged = "provr"
	// LabelProject is the label key holding the project name.
	LabelProject = "provr-project"
	// LabelPreview is the label key holding the preview name.
	LabelPreview = "provr-preview"
	// ManagedValue is the value of LabelManaged on managed resources.
	ManagedValue = "managed"
)

Label keys. Resource labels are the only record of ownership and expiry, so these names live here and nowhere else.

View Source
const MaxPreviewIDLen = 40

MaxPreviewIDLen is the maximum length of a Preview ID (a DNS label budget).

View Source
const PreviewsRoot = "/srv/provr/previews"

PreviewsRoot is the host directory holding one subdirectory per preview.

Variables

View Source
var (
	// ErrNoCapacity is returned by a HostProvider when no host has free
	// capacity for another preview.
	ErrNoCapacity = errors.New("no host with free capacity")
	// ErrQuota is returned by a HostProvider when the cloud rejects a
	// request because a quota is exceeded.
	ErrQuota = errors.New("cloud quota exceeded")
	// ErrNotFound is returned by a HostProvider or Exposer when the
	// requested host, preview, or endpoint does not exist.
	ErrNotFound = errors.New("resource not found")
)

Functions

func BuildLabels

func BuildLabels(o Ownership) (map[string]string, error)

BuildLabels converts o into the cloud resource labels that record ownership.

func IsManaged

func IsManaged(labels map[string]string) bool

IsManaged reports whether labels mark a resource as managed by this tool.

func PreviewDir

func PreviewDir(id string) string

PreviewDir returns the host directory for preview id, where the core writes the override file and exposer-provided Files. The id is not validated here; callers use ValidPreviewID first.

func PreviewID

func PreviewID(project, branch string) (string, error)

PreviewID derives a deterministic, DNS-safe Preview ID of the form <project>-<slug> from a project name and a branch name. The slug is the lowercased branch with non-DNS characters replaced by '-'. When the result is truncated, or the slug is lossy (characters other than the plain separators '/', '_', '.', space were replaced), a short hash of the original branch is appended so truncated or lossy branches never collide (branches that differ only in separators, e.g. `a/b` and `a-b`, share an ID by design).

func ValidPreviewID

func ValidPreviewID(id string) bool

ValidPreviewID reports whether id is a lowercase DNS label of at most MaxPreviewIDLen characters.

Types

type ComposeFragment

type ComposeFragment struct {
	Services map[string]Service `yaml:"services,omitempty"`
	Networks map[string]Network `yaml:"networks,omitempty"`
	Volumes  map[string]Volume  `yaml:"volumes,omitempty"`

	// Files are written by the core into PreviewDir(id) before
	// `docker compose up`. They are never serialized into the override YAML.
	Files []File `yaml:"-"`
}

ComposeFragment is a typed set of compose services, networks and volumes to merge into a project's compose model. The core serializes it; exposers never write files themselves.

func (ComposeFragment) IsEmpty

func (f ComposeFragment) IsEmpty() bool

IsEmpty reports whether the fragment defines nothing.

func (ComposeFragment) Merge

Merge returns a new fragment holding both fragments' entries. A name present in both is a conflict and returns an error. Neither input is mutated.

func (ComposeFragment) YAML

func (f ComposeFragment) YAML() ([]byte, error)

YAML serializes the fragment. Map keys are sorted (yaml.v3 default) and empty fields are omitted; an empty fragment yields "{}\n". It writes no files.

type Endpoint

type Endpoint struct {
	// Service is the compose service name.
	Service string
	// Port is the port the service listens on.
	Port int
	// URL is the address at which the service is reachable.
	URL string
}

Endpoint is one reachable service of a Preview.

type Exposer

type Exposer interface {
	// Plan returns the compose override additions (for example sidecars)
	// and the endpoints a preview will be reachable on.
	Plan(ctx context.Context, p Preview, ports []ServicePort) (ComposeFragment, []Endpoint, error)
	// Release removes everything the exposer created outside the host
	// (for example tailnet nodes). It must be idempotent.
	Release(ctx context.Context, p Preview) error
}

Exposer makes a preview reachable from outside the host.

Implementations live in internal/expose/<name>. Plan is pure: it has no side effects on files, and the core serializes the returned ComposeFragment. Release must be idempotent and return nil when nothing exists.

type File

type File struct {
	Path    string      // relative to PreviewDir(id); no "..", not absolute
	Mode    fs.FileMode // e.g. 0o600 for secrets
	Content []byte
}

File is a file the core writes into the preview directory before `docker compose up`. Content may hold secrets, so File never prints it.

func (File) GoString

func (f File) GoString() string

GoString implements fmt.GoStringer for %#v; it never prints the content.

func (File) MarshalJSON

func (f File) MarshalJSON() ([]byte, error)

MarshalJSON emits the path, mode and content length, never the content.

func (File) MarshalYAML

func (f File) MarshalYAML() (any, error)

MarshalYAML emits the path, mode and content length, never the content.

func (File) String

func (f File) String() string

String renders the path, mode and content length, never the content.

func (File) Validate

func (f File) Validate() error

Validate checks that the path is non-empty, relative, clean and free of "..", and that the mode is non-zero.

type Host

type Host struct {
	// ID is the provider-specific identifier of the host.
	ID string
	// Project is the project the host belongs to.
	Project string
	// Zone is the cloud zone the host runs in.
	Zone string
	// MachineType is the cloud machine type.
	MachineType string
	// State is the lifecycle state of the host.
	State HostState
	// TailnetHostname is the host's name on the tailnet.
	TailnetHostname string
	// Labels are the cloud labels attached to the host.
	Labels map[string]string
	// PreviewCount is the number of previews currently placed on the host.
	PreviewCount int
	// StartedAt is when the host last started (its creation time if the
	// provider never recorded a start). Zero if unknown.
	StartedAt time.Time
	// StoppedAt is when the host last stopped (its creation time if the
	// provider never recorded a stop). Meaningful only for stopped hosts.
	StoppedAt time.Time
	// TimesFromCreation is true when StartedAt or StoppedAt fell back to the
	// host's creation time because the provider recorded no start or stop;
	// callers that act on those times (gc) should log it.
	TimesFromCreation bool
	// Reachable is meaningful only for running hosts: true when the host
	// answered over Tailscale SSH during List.
	Reachable bool
	// ReachError explains why a running host is not Reachable, including how
	// to inspect it. Empty when Reachable.
	ReachError string
}

Host is a machine that runs previews.

type HostProvider

type HostProvider interface {
	// Ensure returns a running host for the project with free capacity,
	// starting a stopped one or creating a new one if needed.
	Ensure(ctx context.Context, spec HostSpec) (Host, error)
	List(ctx context.Context, project string) ([]Host, error)
	Stop(ctx context.Context, hostID string) error
	Delete(ctx context.Context, hostID string) error
}

HostProvider creates, finds, stops and deletes the hosts that run previews.

Implementations live in internal/host/<name>. Hosts must be created WITHOUT an external IP (principle 3), and every created host carries the labels from BuildLabels (provr=managed).

Errors: Ensure returns ErrNoCapacity when no host can be reused and a new one cannot be created within limits, and ErrQuota when the cloud refuses for quota. Stop, Delete and List return ErrNotFound where applicable; Delete of an already-missing host is idempotent and returns nil.

type HostSpec

type HostSpec struct {
	// Project is the project the host serves.
	Project string
	// Zone is the cloud zone to run the host in.
	Zone string
	// MachineType is the cloud machine type.
	MachineType string
	// DiskGB is the boot disk size in GB; 0 means the provider default.
	DiskGB int
	// IdleStop is how long the host may sit without active previews or
	// sessions before it stops itself; 0 means the provider default.
	IdleStop time.Duration
	// MaxPreviews is the maximum number of previews per host (at least 1).
	MaxPreviews int
	// Owner is the dev-server hostname written into provr-owner.
	Owner string
	// PreviewID is the preview being placed. A running host that already
	// runs it has room for it, since updates never need a new slot. Optional;
	// empty means the preview is treated as new.
	PreviewID string
}

HostSpec describes the host a project needs. It is built from config.Project by the lifecycle service (EPIC-003); core deliberately does not import internal/config.

func (HostSpec) Validate

func (s HostSpec) Validate() error

Validate reports every problem with the spec in a single error prefixed with "host spec:". It returns nil when the spec is valid.

type HostState

type HostState string

HostState is the lifecycle state of a Host.

const (
	// HostRunning means the host is up and can accept previews.
	HostRunning HostState = "running"
	// HostStopped means the host exists but is powered off.
	HostStopped HostState = "stopped"
	// HostMissing means the host no longer exists in the cloud.
	HostMissing HostState = "missing"
)

func ParseHostState

func ParseHostState(s string) (HostState, error)

ParseHostState converts s to a HostState, rejecting unknown values.

func (HostState) String

func (s HostState) String() string

String returns the string form of the state.

type Network

type Network struct {
	Driver   string `yaml:"driver,omitempty"`
	Internal bool   `yaml:"internal,omitempty"`
	External bool   `yaml:"external,omitempty"`
}

Network is a compose network definition.

type Ownership

type Ownership struct {
	// Project is the project name the resource belongs to.
	Project string
	// Preview is the preview name; empty for hosts.
	Preview string
	// Owner is the hostname of the dev server that owns the resource.
	Owner string
	// ExpiresAt is when a preview expires; zero for hosts.
	ExpiresAt time.Time
	// CreatedAt is when a preview was first created; zero when unknown and
	// for hosts. When set it must not be after ExpiresAt.
	CreatedAt time.Time
}

Ownership describes who owns a cloud resource and when it expires. Hosts carry Project and Owner only; previews also carry Preview and ExpiresAt.

func ParseLabels

func ParseLabels(labels map[string]string) (Ownership, error)

ParseLabels reads ownership back from resource labels.

type Preview

type Preview struct {
	// ID is "<project>-<slug>": DNS-safe and at most 40 characters.
	ID string
	// Project is the project the preview belongs to.
	Project string
	// HostID is the ID of the Host running the preview.
	HostID string
	// Worktree is the worktree the preview was created from.
	Worktree string
	// CreatedAt is when the preview was created.
	CreatedAt time.Time
	// ExpiresAt is when the preview becomes eligible for cleanup.
	ExpiresAt time.Time
	// Endpoints are the reachable services of the preview.
	Endpoints []Endpoint
}

Preview is an isolated environment for one worktree on a Host.

type Service

type Service struct {
	Image       string            `yaml:"image,omitempty"`
	Command     []string          `yaml:"command,omitempty"`
	Environment map[string]string `yaml:"environment,omitempty"`
	EnvFile     []string          `yaml:"env_file,omitempty"`
	Volumes     []string          `yaml:"volumes,omitempty"`
	Networks    []string          `yaml:"networks,omitempty"`
	DependsOn   []string          `yaml:"depends_on,omitempty"`
	Labels      map[string]string `yaml:"labels,omitempty"`
	CapAdd      []string          `yaml:"cap_add,omitempty"`
}

Service is a compose service definition, limited to the fields a sidecar (such as a Tailscale container) needs.

type ServicePort

type ServicePort struct {
	// Service is the compose service name.
	Service string
	// Port is the port the service listens on (1-65535).
	Port int
}

ServicePort is a compose service port that a preview should expose.

func (ServicePort) Validate

func (p ServicePort) Validate() error

Validate checks that the service is named and the port is in 1-65535.

type Volume

type Volume struct {
	Driver   string `yaml:"driver,omitempty"`
	External bool   `yaml:"external,omitempty"`
}

Volume is a compose volume definition.

Jump to

Keyboard shortcuts

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