Help us shape the future of Go! Take the 2026 Go Developer Survey

components

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package components defines component types, definitions, registries, and running component instances used by the test framework.

Index

Constants

View Source
const VarBlock = "BLOCK"

VarBlock is the overlay variable name for the current block.

Variables

This section is empty.

Functions

func AliasFor

func AliasFor(d *Definition, ordinal, replicas int) (string, error)

AliasFor returns the network alias for a component instance.

func Assemble

func Assemble(inj *ConfigInjection, repoRoot string, blockOverlay string, vars Vars) ([]byte, error)

Assemble merges a component's base, shared, and block overlays.

func EnvFileContent

func EnvFileContent(env map[string]string) []byte

EnvFileContent renders environment entries for a Compose env file.

func Label

func Label(name string, ordinal, replicas int) string

Label formats a component instance identity.

func Merge

func Merge(base string, overlays ...string) ([]byte, error)

Merge loads a TOML base and overlays, merges them in order, and returns TOML output.

func MergeTrees

func MergeTrees(base map[string]any, overlays ...map[string]any) (map[string]any, error)

MergeTrees deep-merges maps in order without modifying the inputs.

func MergeWithVars

func MergeWithVars(vars Vars, base string, overlays ...string) ([]byte, error)

MergeWithVars merges TOML layers after expanding variables in overlays.

Types

type ComposeSpec

type ComposeSpec struct {
	// ComposeFile is the repo-relative compose file. Its services are this component's
	// internals.
	ComposeFile string

	// ComposeOverrideFiles are repo-relative Compose files merged after ComposeFile.
	// They contain only component-specific overrides.
	ComposeOverrideFiles []string

	// StagedFiles maps repository-relative source files to their names beside the
	// staged Compose file.
	StagedFiles map[string]string

	// GeneratedFiles maps framework-generated file names to their contents.
	GeneratedFiles map[string][]byte

	// PrimaryService is the compose service whose ports back this component's
	// Endpoints. Everything a test addresses must be on this service.
	PrimaryService string

	// Services lists the services whose logs are collected.
	Services []string

	// Env contains variables passed to Compose for interpolation.
	Env map[string]string

	// ProjectEnv contains variables set only in the Compose project environment, for
	// interpolation and environment-sourced configs and secrets. Unlike Env, they are never
	// written to a service env file, so a value may span lines and stays out of every
	// container's environment.
	ProjectEnv map[string]string

	// CoverageServices lists services and artifact formats collected after shutdown.
	CoverageServices []CoverageService

	// BootAttempts caps how many times the runtime retries a failed boot of this stack,
	// tearing down and relaunching with a fresh stack each time. Zero or one means no
	// retry, matching the default for every compose component that does not set this.
	BootAttempts int
}

ComposeSpec describes a component backed by a Compose stack.

func (*ComposeSpec) StagingName

func (c *ComposeSpec) StagingName() string

StagingName returns the file name the compose file is staged under.

func (*ComposeSpec) StagingNames

func (c *ComposeSpec) StagingNames() []string

StagingNames returns the staged base Compose file followed by its overrides.

func (*ComposeSpec) WithGenerated

func (c *ComposeSpec) WithGenerated(files map[string][]byte) *ComposeSpec

WithGenerated returns a copy of the spec with generated files added.

type ConfigFormat

type ConfigFormat string

ConfigFormat is the syntax of a component's configuration file.

const TOML ConfigFormat = "toml"

TOML identifies TOML component configuration.

type ConfigInjection

type ConfigInjection struct {
	// BaseConfigPath is the product's shipped config, relative to the repo root.
	BaseConfigPath string
	// SharedOverlayPath is the small overlay every block gets, relative to the repo
	// root. Optional.
	SharedOverlayPath string
	// ExtraOverlays are optional overlays merged after the shared overlay and before the
	// block-specific overlay.
	ExtraOverlays []string
	// ContainerPath is where the merged file lands in the container.
	ContainerPath string
	// Format is the merge syntax.
	Format ConfigFormat
	// Versioned contains exact released-version configuration profiles. When a
	// component using versioned profiles is assigned an image version, it must
	// select one of these profiles instead of using the source-tree defaults.
	Versioned map[string]ConfigProfile
}

ConfigInjection describes how a component configuration is assembled and delivered.

func (*ConfigInjection) ForVersion

func (inj *ConfigInjection) ForVersion(version string) (*ConfigInjection, error)

ForVersion returns the configuration injection for version. A component that declares versioned profiles must select one for every explicitly requested version.

type ConfigProfile

type ConfigProfile struct {
	BaseConfigPath    string
	SharedOverlayPath string
}

ConfigProfile replaces the base and shared configuration layers for a released image. Extra and block-specific overlays retain their usual precedence.

type CoverageService

type CoverageService struct {
	Name string
	// OutputName optionally identifies the coverage output directory. Empty uses Name.
	OutputName string
	Types      []string
}

CoverageService identifies a service that writes coverage artifacts.

type DBContract

type DBContract struct {
	// Supported lists the database engines supported by the component.
	Supported []DBType

	// Schema maps database engines to the ordered DDL files applied by the framework.
	Schema map[DBType][]string

	// SelfMigrates lists engines whose schema is applied by the component.
	SelfMigrates []DBType

	// SharesStoreWith names the component that owns this component's runtime.
	SharesStoreWith string

	// Env maps a resolved DSN to component environment variables.
	Env func(DSN) map[string]string
}

DBContract declares a component's database requirements.

func (*DBContract) Owns

func (c *DBContract) Owns() bool

Owns reports whether this contract provisions its own store rather than borrowing another component's.

func (*DBContract) SchemaFor

func (c *DBContract) SchemaFor(t DBType) ([]string, bool)

SchemaFor returns the DDL the framework must apply for t, and whether it must apply any at all. A component that migrates itself, or shares another's store, returns false — provisioning it anyway would double-apply the schema.

func (*DBContract) Supports

func (c *DBContract) Supports(t DBType) bool

Supports reports whether t is an engine this component can run against.

type DBType

type DBType string

DBType is a database engine a component can be backed by.

const (
	// SQLite is embedded in the component container.
	SQLite DBType = "sqlite"
	// Postgres runs as a separate database container.
	Postgres DBType = "postgres"
	// SQLServer runs as a separate database container.
	SQLServer DBType = "sqlserver"
)

func (DBType) Embedded

func (d DBType) Embedded() bool

Embedded reports whether this engine runs inside the component's own container rather than as a container of its own.

func (DBType) Valid

func (d DBType) Valid() bool

Valid reports whether d is a known engine.

type DSN

type DSN struct {
	Type DBType

	// Host and Port identify the database on the component network.
	Host string
	Port int

	Database string
	User     string
	Password string
	SSLMode  string

	// FilePath is set only for embedded engines, where there is no host/port.
	FilePath string
}

DSN contains the resolved coordinates of a logical runtime.

type Definition

type Definition struct {
	// Name is the identifier a suite file references. Unique within a registry.
	Name string

	// Image is what to run, for a single-container component.
	Image ImageRef

	// Compose backs this component with a multi-container stack instead of a single
	// image, while still presenting it as ONE component to a suite file. Mutually
	// exclusive with Image.
	Compose *ComposeSpec

	// External describes a component hosted outside the test process. It is mutually
	// exclusive with Image and Compose.
	External *ExternalSpec

	// Alias is the component's DNS name on its network.
	Alias string

	// AliasIsFixed prevents the alias from being suffixed for replicas.
	AliasIsFixed bool

	// Endpoints are the component's addressable ports.
	Endpoints []Endpoint

	// Health is the application-level readiness gate. Nil disables this gate.
	Health *HealthCheck
	// VersionedHealth replaces Health for released image versions whose readiness
	// contract differs from the source-build contract.
	VersionedHealth map[string]HealthCheck

	// Config describes configuration assembly, if the component has any.
	Config *ConfigInjection

	// DB is the storage contract, if the component has storage.
	DB *DBContract

	// Wiring decodes and validates component-specific block configuration.
	Wiring WiringSpec

	// ApplyWiring returns the definition a block's decoded wiring selects, for wiring that
	// changes what the component runs. It must not modify def. Nil leaves the definition
	// as registered.
	ApplyWiring func(def *Definition, wiring any) (*Definition, error)

	// Env is static environment applied to every instance, before DSN and wiring.
	Env map[string]string

	// Files are copied in before start.
	Files []FileMount

	// Cmd overrides the image's command.
	Cmd []string

	// Provisions returns environment values for dependent components after this component
	// becomes ready.
	Provisions func(ctx context.Context, inst *Instance, dependent string) (map[string]string, error)

	// DependsOn lists components that must be ready before this one starts.
	DependsOn []string

	// Limits caps this container's host resources.
	Limits ResourceLimits

	// Shared starts one instance for all blocks that declare the component.
	Shared bool

	// SourceProduct names the product whose source build supplies this component's image,
	// for a component that runs another product's image under its own name. Empty means
	// the product named Name.
	SourceProduct string
}

Definition describes a component and its lifecycle contracts.

func (*Definition) Endpoint

func (d *Definition) Endpoint(name string) (Endpoint, bool)

Endpoint returns the named endpoint.

func (*Definition) ExternalEndpointNames

func (d *Definition) ExternalEndpointNames() []string

ExternalEndpointNames returns the names declared by an external component.

func (*Definition) IsCompose

func (d *Definition) IsCompose() bool

IsCompose reports whether this component is backed by a compose stack rather than a single container.

func (*Definition) IsExternal

func (d *Definition) IsExternal() bool

IsExternal reports whether the component is hosted outside the test process.

func (*Definition) Product

func (d *Definition) Product() string

Product returns the product whose source build supplies this component's image.

func (*Definition) ResolveDBType

func (d *Definition) ResolveDBType(explicit, blockDefault DBType) (DBType, error)

ResolveDBType selects a supported database engine.

func (*Definition) String

func (d *Definition) String() string

String renders the definition for error messages.

func (*Definition) Validate

func (d *Definition) Validate() error

Validate checks a definition's local invariants.

func (*Definition) WithConfigVersion

func (d *Definition) WithConfigVersion(version string) (*Definition, error)

WithConfigVersion returns a copy configured for the supplied released image version.

func (*Definition) WithImageVersion

func (d *Definition) WithImageVersion(version string) *Definition

WithImageVersion returns a copy whose image references use version.

func (*Definition) WithReleaseVersion

func (d *Definition) WithReleaseVersion(version string) (*Definition, error)

WithReleaseVersion returns a copy whose image, configuration, and readiness contracts match the supplied released image version.

func (*Definition) WithStagedFiles

func (d *Definition) WithStagedFiles(overrides map[string]string) (*Definition, error)

WithStagedFiles returns a copy with block-scoped sources for declared staged files.

type Endpoint

type Endpoint struct {
	// Name identifies the endpoint.
	Name string

	// Port is the in-container port.
	Port int

	// Scheme is "http", "https", "grpc", "tcp", …
	Scheme string

	// PathPrefix is prepended to paths built against this endpoint, for a component
	// that serves its API under a fixed prefix.
	PathPrefix string

	// AwaitListening includes the port in container-level readiness checks.
	AwaitListening bool

	// Service names the Compose service that provides this endpoint. Empty uses the
	// primary service.
	Service string
}

Endpoint describes an addressable port on a component.

type ExternalEndpoint

type ExternalEndpoint struct {
	// Name identifies the endpoint.
	Name string
}

ExternalEndpoint names an endpoint published by an external component. Its URL is resolved when the component is booted, rather than from container ports.

type ExternalSpec

type ExternalSpec struct {
	// Endpoints are the named addresses exposed by the component.
	Endpoints []ExternalEndpoint

	// RequiredParameters are runtime parameters that must be supplied before Resolve runs.
	RequiredParameters []string

	// Resolve constructs endpoint URLs from the repository root and runtime parameters.
	Resolve func(repoRoot string, parameters map[string]string) (map[string]string, error)
}

ExternalSpec describes a component that is reachable outside the test process. External components have no image, container, network, or database lifecycle.

type FileMount

type FileMount struct {
	// HostPath is relative to the repository root. Exactly one of HostPath and Content is set.
	HostPath string
	// Content is the file's bytes, for a file the framework generates instead of reading.
	Content []byte
	// ContainerPath is the absolute destination.
	ContainerPath string
	// Mode is the file mode to set on the copy.
	Mode int64
}

FileMount describes a file copied into a container before startup.

type HealthCheck

type HealthCheck struct {
	// Endpoint names the Endpoint to probe.
	Endpoint string

	// Service names the Compose service to probe. Empty uses the primary service.
	Service string
	// Path is appended to the endpoint's base URL.
	Path string
	// ExpectStatus is the status that means ready. Usually 200.
	ExpectStatus int
	// Timeout bounds the whole poll.
	Timeout time.Duration
	// Interval is the gap between probes.
	Interval time.Duration
}

HealthCheck describes an application-level readiness probe.

type ImageBuild

type ImageBuild struct {
	Context    string
	Dockerfile string
	Args       map[string]string
}

ImageBuild describes building an image from the repository.

type ImageRef

type ImageRef struct {
	// Ref is the default image, tag included.
	Ref string
	// ByArch overrides Ref for a GOARCH value ("arm64", "amd64").
	ByArch map[string]string
	// Build, when set, means the image is built from the repo rather than pulled.
	// The path is relative to the repository root.
	Build *ImageBuild
}

ImageRef identifies a container image and optional architecture-specific images.

func (ImageRef) Resolve

func (i ImageRef) Resolve(arch string) string

Resolve returns the image to use on arch.

func (ImageRef) WithVersion

func (i ImageRef) WithVersion(version string) ImageRef

WithVersion returns a copy with the image tag replaced by version.

type Instance

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

Instance represents one running component instance.

func NewExternalInstance

func NewExternalInstance(def *Definition, ordinal, replicas int, urls map[string]string) (*Instance, error)

NewExternalInstance creates an instance whose endpoints are complete external URLs.

func NewInstance

func NewInstance(def *Definition, ordinal, replicas int, host string, mapped map[int]int) (*Instance, error)

NewInstance creates an instance from resolved runtime values.

func (*Instance) Alias

func (i *Instance) Alias() string

Alias is this instance's DNS name on its block's network.

func (*Instance) Definition

func (i *Instance) Definition() *Definition

Definition returns the instance definition.

func (*Instance) EndpointNames

func (i *Instance) EndpointNames() []string

EndpointNames returns all endpoint names addressable on this instance.

func (*Instance) Host

func (i *Instance) Host() string

Host returns the address used to reach mapped ports.

func (*Instance) InternalURL

func (i *Instance) InternalURL(endpoint string) (string, error)

InternalURL returns the network URL for an endpoint.

func (*Instance) Label

func (i *Instance) Label() string

Label identifies this instance in messages, disambiguating replicas.

func (*Instance) MappedPort

func (i *Instance) MappedPort(endpoint string) (int, error)

MappedPort returns the mapped host port for an endpoint.

func (*Instance) Name

func (i *Instance) Name() string

Name is the component name, shared by every replica.

func (*Instance) Ordinal

func (i *Instance) Ordinal() int

Ordinal is the 0-based replica index.

func (*Instance) RefreshPorts

func (i *Instance) RefreshPorts(mapped map[int]int)

RefreshPorts replaces the instance's mapped host ports.

func (*Instance) URL

func (i *Instance) URL(endpoint string) (string, error)

URL returns the external URL for an endpoint.

type Registry

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

Registry stores component definitions by name.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered components.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) (*Definition, bool)

Lookup returns the named definition.

func (*Registry) MustRegister

func (r *Registry) MustRegister(defs ...*Definition) *Registry

MustRegister registers definitions and panics on failure.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns every registered name, sorted, for error messages and --list.

func (*Registry) Register

func (r *Registry) Register(d *Definition) error

Register validates and adds a definition.

func (*Registry) Validate

func (r *Registry) Validate() error

Validate checks relationships between registered definitions.

type ResourceLimits

type ResourceLimits struct {
	CPUs     float64
	MemoryMB int64
}

ResourceLimits specifies per-container CPU and memory limits.

type Set

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

Set stores component instances by name.

func NewSet

func NewSet() *Set

NewSet returns an empty set.

func (*Set) Add

func (s *Set) Add(inst *Instance) error

Add adds an instance to the set.

func (*Set) All

func (s *Set) All(name string) []*Instance

All returns all replicas of a component in ordinal order.

func (*Set) At

func (s *Set) At(name string, ordinal int) (*Instance, error)

At returns a component replica by zero-based ordinal.

func (*Set) Get

func (s *Set) Get(name string) (*Instance, error)

Get returns the only instance with the given component name.

func (*Set) Len

func (s *Set) Len() int

Len returns the total number of instances.

func (*Set) Names

func (s *Set) Names() []string

Names returns component names in sorted order.

type Vars

type Vars map[string]string

Vars contains values substituted into an overlay before parsing.

type WiringSpec

type WiringSpec interface {
	// Decode parses a wiring node into the component's wiring type.
	Decode(node *yaml.Node) (any, error)
}

WiringSpec decodes component-specific block configuration.

func TypedWiring

func TypedWiring[T any]() WiringSpec

TypedWiring creates a strict WiringSpec for type T.

Jump to

Keyboard shortcuts

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