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

engine

package
v0.31.0 Latest Latest
Warning

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

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

Documentation

Overview

Package engine ties a project to one environment: it builds components lazily from the plugin registry, resolves svc:// addresses through the runtime, and runs the multi-service operations (up, down, status) every front end shares.

Index

Constants

View Source
const (
	TestRunning = "run"
	TestPass    = "pass"
	TestFail    = "fail"
	TestSkip    = "skip"
	TestStopped = "stopped"
)

Test statuses; a test still going is TestRunning, one cut short by a stop TestStopped.

View Source
const AllValue = "$__all"

AllValue is the "all" choice of a dashboard variable: a regex that matches anything.

View Source
const FixPrompt = `` /* 254-byte string literal not displayed */

FixPrompt is what "fix" after a rig why analysis tells the assistant.

View Source
const InstallStd = "rig plugin add --user pack-std"

InstallStd installs the everyday official plugins (runtimes, builders, importers, git) from the registry; rig does it by itself for the types rig.yaml names.

View Source
const WorkingTree = "(working tree)"

WorkingTree is the branch choice that builds the checkout as it is, uncommitted changes included.

Variables

View Source
var DefaultAlerts = []spec.Alert{
	{Name: "memory", Source: "hosts", Metric: "memory", Warn: 90, Crit: 98, Unit: "%"},
	{Name: "cpu", Source: "hosts", Metric: "cpu", Warn: 90, Crit: 98, Unit: "%"},
	{Name: "disk", Source: "hosts", Metric: "disk", Warn: 97, Crit: 98, Unit: "%"},
}

DefaultAlerts watch the nodes when rig.yaml names no alerts: memory and CPU at 90% and 98%, disk at 97% and 98%.

View Source
var ErrFailed = errors.New("failed")

ErrFailed is a check that ran and failed: tests, load assertions, a report's compare. The CLI exits 3.

View Source
var ErrOverMax = errors.New("rate above the generator's max (pass force to exceed it)")
View Source
var ErrProtected = errors.New("environment is protected: pass --yes to change it")

ErrProtected stops a mutating operation on a protected environment unless the caller confirmed.

View Source
var NamespaceOverride string

NamespaceOverride, when set, replaces the namespace of a Kubernetes environment for this run (rig -n); otherwise the one `rig ns` picked, kept in .rig/<env>/namespace, does.

Functions

func All

func All[T any](a *App, kind core.Kind) (map[string]T, map[string]error)

All builds every configured component of kind; failures come back per name.

func DefaultVar

func DefaultVar(v *spec.DashVar, values []string) []string

DefaultVar is what a variable starts as: its default, else all (when offered), else the first value. A default the values no longer hold (a Grafana export's host) is skipped.

func ExpandQuery

func ExpandQuery(q string, vars map[string][]string, rng, step time.Duration) string

ExpandQuery fills a panel query's $variables (several values become a|b, all becomes .*) and Grafana's $__range, $__interval and $__rate_interval for the time range and step.

func FillQuery

func FillQuery(q *spec.Query, args map[string]string) (string, []string)

FillQuery replaces {{name}} placeholders with args, then the query's defaults; it reports placeholders left without a value.

func Get

func Get[T any](a *App, kind core.Kind, name string) (T, string, error)

Get returns component name of kind as T; with name "" the only (or first) one of that kind, falling back to what the runtime itself provides (logs, hosts) or to a default adapter.

func KubeTarget added in v0.7.0

func KubeTarget(file, env string) (name, context, server string, err error)

KubeTarget is the kubeconfig context and server env's runtime names, read from rig.yaml alone so it works while the cluster cannot be reached.

func LastEnv added in v0.6.1

func LastEnv(file string) string

LastEnv is the environment the UI last showed in the project of file ("" finds rig.yaml from here up).

func MarshalTargets

func MarshalTargets(ts []ScrapeTarget) ([]byte, error)

func Pattern

func Pattern(names []string) string

Pattern is a -run expression that matches exactly these tests (full names, TestX/sub/...), level by level: every name of a level is allowed at that level, so a few more may run.

func PresetTaskArgs added in v0.6.0

func PresetTaskArgs(args []spec.TaskArg, words []string) (out []string, named bool)

PresetTaskArgs maps name=value words that name one of the task's args onto it (whatever its case), the args not named taking their defaults, and keeps the other words after them. named is false when no word names an arg: words is then not touched.

func PresetTaskArgsDefaults added in v0.6.0

func PresetTaskArgsDefaults(args []spec.TaskArg) []string

PresetTaskArgsDefaults is what a task's args come to when nothing answers them: their defaults, except an UPPER_CASE one already set in the environment, which passes through.

func ProfileRate added in v0.26.0

func ProfileRate(profile string, target float64, elapsed, total time.Duration) float64

ProfileRate is the rate a profile asks for at elapsed into a run of total (0: open-ended). ramp climbs to target over the first 80% (a minute when open-ended), spike runs at a fifth with the middle fifth at target, steady and soak hold target.

func Ready

func Ready(st core.Status) bool

Ready is the one readiness rule every front end uses.

func ReportFormat added in v0.21.0

func ReportFormat(file, fallback string) string

ReportFormat is the format a file name asks for, else the report's own.

func Served added in v0.31.0

func Served(root *protocol.Node, plugin string)

Served points a contract's standard view at the plugin serving it: scm.mrs becomes <plugin>.scm.mrs.

func SortedKeys

func SortedKeys[V any](m map[string]V) []string

SortedKeys is a small helper front ends use for stable output.

func TaskArgValues added in v0.5.0

func TaskArgValues(args []spec.TaskArg, answers []string) []string

TaskArgValues turns the answers to a task's args, in order, into what RunTask takes: NAME=value for an UPPER_CASE arg, the words of the answer for a positional one; empty answers are left out.

func WriteReportFile

func WriteReportFile(file string, write func(io.Writer)) error

Types

type App

type App struct {
	Spec *spec.Project
	Env  *spec.Environment
	// Confirmed lets mutating operations run on a protected environment.
	Confirmed bool
	// Inferred is a project with no rig.yaml, built in memory from the directory as rig init would.
	Inferred bool
	// Ask, when set, puts a yes/no question to the user (a terminal), so a protected environment
	// can be changed after a yes instead of only with --yes.
	Ask func(question string) bool
	// contains filtered or unexported fields
}

func Open

func Open(file, env string) (*App, error)

Open loads the project file (found from dir when file is "") for env. With no rig.yaml anywhere up, it infers one in memory from what the directory has, as rig init would write it (Inferred).

func (*App) AI

func (a *App) AI(sock string) (*ai.Runner, error)

AI is the assistant's runner for this project and environment; sock is the bridge that answers its approvals and UI actions ("" when nothing can).

func (*App) AIDir

func (a *App) AIDir() string

AIDir is where the project's AI sessions live.

func (*App) Affected added in v0.26.0

func (a *App) Affected(ctx context.Context, files []string) []string

Affected are the services whose sources (as rig watch sees them) hold one of files, paths from the project directory: what a change set touches and so what to rebuild, deploy and test.

func (*App) Agent added in v0.26.0

func (a *App) Agent(name string) (*ai.Runner, *spec.Agent, error)

Agent is the runner for the rig.yaml agent name: the assistant's, as that agent and bounded to its tools, which default to reading.

func (*App) AlertRules

func (a *App) AlertRules() []spec.Alert

func (*App) AuditFile added in v0.6.0

func (a *App) AuditFile() string

AuditFile is the log of what the assistant ran on this environment (ai.AuditEntry lines).

func (*App) Branches added in v0.23.0

func (a *App) Branches(ctx context.Context) []string

Branches are the repository's branches, local then origin's not checked out, newest commit first.

func (*App) Build

func (a *App) Build(ctx context.Context, s *spec.Service, tag string, out io.Writer) (string, error)

Build builds one service's image from the working tree and returns the reference.

func (*App) BuildFrom

func (a *App) BuildFrom(ctx context.Context, s *spec.Service, tag, ref string, out io.Writer) (string, error)

BuildFrom builds one service's image with the builder its build section asks for, from a git ref when given, and returns the reference. Pushing over a tag the registry already has needs confirmation.

func (*App) BuildLocal added in v0.6.1

func (a *App) BuildLocal(ctx context.Context, s *spec.Service, tag, ref string, out io.Writer) (string, error)

BuildLocal builds s's image (from a git ref when given) into the local Docker daemon (a kind cluster's nodes, when the environment has no registry) without pushing it; Push sends it later.

func (*App) CheckAlerts

func (a *App) CheckAlerts(ctx context.Context) ([]Firing, []error)

CheckAlerts evaluates every rule once; the most severe firings come first. A rule that cannot be evaluated is reported as an error, not as a firing.

func (*App) Close

func (a *App) Close() error

func (*App) Component

func (a *App) Component(name string) (any, error)

Component builds (once) and returns the named component.

func (*App) Configured added in v0.31.0

func (a *App) Configured(n string) bool

Configured is whether the project sets up anything the screen n of spec.Screens shows.

func (*App) CreateNamespace

func (a *App) CreateNamespace(ctx context.Context, ns string) error

func (*App) CredentialSet added in v0.27.0

func (a *App) CredentialSet(plugin string, secrets []string) bool

CredentialSet is whether plugin has what it needs of secrets: its own token config, or a value for one of them in rig's secrets or the environment. A plugin that asks for none is always set.

func (*App) DefaultImage

func (a *App) DefaultImage(ctx context.Context, s *spec.Service) string

func (*App) DefaultTag

func (a *App) DefaultTag(ctx context.Context, ref string) string

DefaultTag names a build: the branch (or ref) when it is short enough to read, then the time, e.g. feature-x-20261003-1907; a plain timestamp outside git or for long branch names.

func (*App) Deploy

func (a *App) Deploy(ctx context.Context, name, tag string) error

Deploy rolls out a service. A tag deploys that tag of its image from the registry without building.

func (*App) Doctor added in v0.6.0

func (a *App) Doctor(ctx context.Context) []Check

Doctor checks what this environment needs: its runtime's tools and reachability, unset ${VARS}, free ports for services not running, and every component through its own adapter.

func (*App) Down

func (a *App) Down(ctx context.Context, targets []string, out io.Writer) error

Down stops targets in reverse dependency order. With no targets it stops every app and load service: infrastructure, and services shared from another environment, stop only when named.

func (*App) EnvOverrides

func (a *App) EnvOverrides(name string) map[string]string

EnvOverrides are the variables SetEnv gave a service.

func (*App) Environment

func (a *App) Environment() *spec.Environment

func (*App) Exec

func (a *App) Exec(ctx context.Context, name string, o core.ExecOptions) error

func (*App) Guard

func (a *App) Guard() error

Guard refuses a mutating operation on a read-only environment, and on a protected one the caller did not confirm. Every change passes here (or through Writable), so readonly holds whoever calls.

func (*App) Host added in v0.26.0

func (a *App) Host() *host.Host

Host runs the project's plugins, started on first use; the engine and the components plugins serve share it.

func (*App) ImageBased

func (a *App) ImageBased() bool

ImageBased reports whether the runtime runs images (and so needs builds) rather than local processes.

func (*App) InfraApp

func (a *App) InfraApp() (*App, error)

InfraApp opens (once) the environment that runs this one's shared services; nil when there is none.

func (*App) Investigate added in v0.6.0

func (a *App) Investigate(ctx context.Context, service string, window time.Duration, more ...Probe) (*Incident, error)

func (*App) InvestigateSymptom added in v0.22.0

func (a *App) InvestigateSymptom(ctx context.Context, words []string, window time.Duration, more ...Probe) (*Incident, error)

InvestigateSymptom investigates what the user described: the first service its words name (by name, image or SERVICE_NAME), else every service.

func (*App) KeepEnv added in v0.10.0

func (a *App) KeepEnv(ctx context.Context, names []string, kv map[string]string) error

KeepEnv is SetEnv without the redeploy: the next deploy of names takes the variables.

func (*App) Kind

func (a *App) Kind(name string) (core.Kind, string, error)

Kind tells which kind a configured component is, without building it.

func (*App) KnownSecrets added in v0.6.0

func (a *App) KnownSecrets() map[string]string

KnownSecrets are the values rig knows to be secret, by name: secrets:, the ${NAME}s with a secret's name taken from the environment, and the env vars, variables and component fields named like one.

func (*App) LoadLimits

func (a *App) LoadLimits(name string) LoadLimits

func (*App) LoadResultFor added in v0.26.0

func (a *App) LoadResultFor(id, name, skip string) (*LoadResult, error)

LoadResultFor is the saved run id, or with id "last" the latest run of name before the run skip.

func (*App) LoadRunNamed added in v0.26.0

func (a *App) LoadRunNamed(name string) (*spec.LoadRun, error)

LoadRunNamed is the load: entry name, or an ad-hoc steady run of the generator name.

func (*App) LoadState

func (a *App) LoadState(ctx context.Context) (map[string]string, error)

func (*App) LoadTestRun

func (a *App) LoadTestRun(id, suite string) (*TestRun, error)

LoadTestRun reads a saved run; id "" or "last" is the newest (of suite, when given).

func (*App) Logs

func (a *App) Logs(ctx context.Context, name string, o core.LogOptions) (<-chan core.LogLine, error)

func (*App) ManifestDirs

func (a *App) ManifestDirs() []string

ManifestDirs is where this project keeps Kubernetes manifests: the project's manifests:, else the runtime's manifests option, else the project directory.

func (*App) MeasureReport

func (a *App) MeasureReport(ctx context.Context, name, source string, from, to time.Time) (*ReportResult, error)

MeasureReport runs a report's queries over [from, to] against source (default the report's own) and summarises every series they return.

func (*App) Names

func (a *App) Names(kind core.Kind) []string

Names lists configured components of a kind, sorted.

func (*App) Namespace

func (a *App) Namespace() string

Namespace is the namespace the environment works in, "" when it is not on Kubernetes.

func (*App) Namespaces

func (a *App) Namespaces(ctx context.Context) ([]string, error)

Namespaces lists the cluster's namespaces.

func (*App) NewTestRun

func (a *App) NewTestRun(suite string, o TestOptions) *TestRun

NewTestRun starts the record of a run of suite.

func (*App) Nudge

func (a *App) Nudge(ctx context.Context, name string, dir int) (float64, error)

Nudge moves a generator's rate one step up (dir > 0) or down and returns the new rate.

func (*App) Owner

func (a *App) Owner(name string) (core.Runtime, *spec.Service, error)

Owner returns the runtime that runs the named service and that environment's view of it.

func (*App) PluginChecks added in v0.26.0

func (a *App) PluginChecks() []Check

PluginChecks are the plugins this project uses that need a credential nobody has given them yet.

func (*App) PreviousBenches

func (a *App) PreviousBenches(r *TestRun) map[string]Bench

PreviousBenches are the benchmarks of the newest saved run of suite before r that has any, by package and name.

func (*App) Project

func (a *App) Project() *spec.Project

func (*App) Push added in v0.6.1

func (a *App) Push(ctx context.Context, s *spec.Service, tag string, out io.Writer) error

Push sends s's image at tag from the local Docker daemon to the environment's registry.

func (*App) Queriers

func (a *App) Queriers() map[string]core.Querier

Queriers lists every component that answers ad hoc queries, the runtime included.

func (*App) Queries

func (a *App) Queries() map[string]*spec.Query

Queries are the project's saved queries with this environment's replacing those of the same name.

func (*App) QueryNames

func (a *App) QueryNames() []string

func (*App) Reach added in v0.6.0

func (a *App) Reach(ctx context.Context, name string) error

Reach builds a component and does the cheapest read its kind has: Ping when the adapter has one. core.ErrUnsupported when the kind has nothing to reach (builders, profilers).

func (*App) Rebuild added in v0.6.0

func (a *App) Rebuild(ctx context.Context, name string, emit func(WatchEvent))

Rebuild builds a service with its builder and restarts it through its runtime: a fresh image rolled out where the runtime runs images, a restart (after a compile check, for Go) for local processes. A build that fails leaves the service running what it ran.

func (*App) Redactor added in v0.6.0

func (a *App) Redactor() *ai.Redactor

Redactor takes this project's secrets out of text bound for a model (ai.Redactor).

func (*App) RememberEnv added in v0.6.1

func (a *App) RememberEnv()

RememberEnv makes this environment the one the next `rig` opens on.

func (*App) ReportFile

func (a *App) ReportFile(name string, at time.Time) string

ReportFile is where a measured report is saved unless the caller names a file: the project's data directory, outside the repository.

func (*App) ReportNames

func (a *App) ReportNames() []string

func (*App) ReporterStarted added in v0.21.0

func (a *App) ReporterStarted(name string) (time.Time, bool)

ReporterStarted says whether report name's reporter runs, and since when.

func (*App) Resolve

func (a *App) Resolve(ctx context.Context, addr string) (string, error)

Resolve turns svc://service:port[/path] into an address reachable from here; anything else is returned as is.

func (*App) Resources

func (a *App) Resources(ctx context.Context, name string) ([]core.Resources, error)

Resources reads the requests and limits of a service's containers.

func (*App) Restart

func (a *App) Restart(ctx context.Context, name string) error

func (*App) RestoreSnapshot added in v0.6.0

func (a *App) RestoreSnapshot(ctx context.Context, comp, name string, log io.Writer) error

RestoreSnapshot puts snapshot name back into comp, replacing what it holds.

func (*App) RunLoad added in v0.26.0

func (a *App) RunLoad(ctx context.Context, name string, r *spec.LoadRun, force bool, tick func(core.LoadStatus)) (*LoadResult, error)

RunLoad drives the run's generator until its For ends or ctx does, calling tick every second, then checks the assertions and saves the result. force lets the rate exceed the generator's max.

func (*App) RunQuery

func (a *App) RunQuery(ctx context.Context, comp, text string) (core.Table, error)

RunQuery runs an ad hoc query against a component (or "runtime").

func (*App) RunSaved

func (a *App) RunSaved(ctx context.Context, name string, args map[string]string) (core.Table, error)

RunSaved runs a saved query with placeholder values.

func (*App) RunTask

func (a *App) RunTask(ctx context.Context, name string, args []string, out io.Writer) error

RunTask runs a task's steps in order with sh -c from the project directory, stopping at the first failure. svc:// addresses in a step become a host:port reachable from here, and a nested `rig` inherits this project, environment and confirmation. A NAME=value arg sets that env var for the steps (overriding any manifest var or pre-set shell env of the same name) instead of requiring it pre-set; every other arg reaches every step positionally as $1... and $RIG_ARGS.

func (*App) RunTests

func (a *App) RunTests(ctx context.Context, s *spec.TestSuite, run *TestRun, jobs []TestJob) error

RunTests runs the jobs of a suite one after another into run, stopping at ctx's end, and saves the run when done. Every job but the first keeps the results the earlier ones reported.

func (*App) Runtime

func (a *App) Runtime() core.Runtime

func (*App) SaveReport added in v0.21.0

func (a *App) SaveReport(rep *ReportResult, file string) (string, error)

SaveReport writes rep to file (default under the data directory) in the format the file's extension or the report asks for, and returns the file.

func (*App) SaveTestRun

func (a *App) SaveTestRun(r *TestRun) error

func (*App) Scale

func (a *App) Scale(ctx context.Context, name string, n int) error

func (*App) ScaleBy

func (a *App) ScaleBy(ctx context.Context, names []string, delta int, set bool) error

ScaleBy moves each service's replica count by delta (or sets it, when set is true).

func (*App) ScrapeTargets

func (a *App) ScrapeTargets(ctx context.Context, host string) ([]ScrapeTarget, error)

ScrapeTargets lists the environment's services with metrics as a Prometheus container on the docker runtime's network sees them: containers by name, local processes through host (the container's name for the host, host.docker.internal say).

func (*App) SeedData added in v0.6.0

func (a *App) SeedData(ctx context.Context, comp string, log io.Writer) error

SeedData runs comp's seed.

func (*App) Service

func (a *App) Service(name string) (*spec.Service, error)

func (*App) ServiceEnv added in v0.6.0

func (a *App) ServiceEnv(ctx context.Context, name string) (env map[string]string, overridden map[string]bool, err error)

ServiceEnv is what a service runs with: its live workload's env where the runtime reads one (Kubernetes), else rig.yaml's with the overrides on top; overridden names what SetEnv set.

func (*App) SetAutoscale

func (a *App) SetAutoscale(ctx context.Context, name string, b core.Bounds) error

SetAutoscale moves the autoscaler bounds of a service.

func (*App) SetEnv

func (a *App) SetEnv(ctx context.Context, names []string, kv map[string]string) error

SetEnv sets (an empty value removes) environment variables of services in this environment's state, so every later deploy keeps them, and redeploys the services that run so they take effect.

func (*App) SetRate

func (a *App) SetRate(ctx context.Context, name string, rps float64, force bool) error

SetRate sets a generator's rate within its max, unless force, and records it in the run state.

func (*App) SetResources

func (a *App) SetResources(ctx context.Context, name string, r core.Resources) error

SetResources changes one container's requests and limits (which restarts its pods).

func (*App) SetState

func (a *App) SetState(ctx context.Context, kv map[string]string) error

SetState merges kv into the state; an empty value deletes the key.

func (*App) SharedElsewhere

func (a *App) SharedElsewhere(name string) bool

SharedElsewhere reports whether the service runs in the infra environment rather than this one.

func (*App) Snapshots added in v0.6.0

func (a *App) Snapshots(comp string) ([]Snapshot, error)

Snapshots lists comp's snapshots, newest first.

func (*App) Source

func (a *App) Source(ctx context.Context, ref string) (string, error)

Source exports a git ref of the project's repository into the user cache (rig/src/<commit>, once per commit) and returns the directory that corresponds to the project directory inside it.

func (*App) Start

func (a *App) Start(ctx context.Context, name string) error

func (*App) StartInOrder

func (a *App) StartInOrder(ctx context.Context, names []string, wait time.Duration) error

StartInOrder starts names layer by layer in dependency order, waiting for a layer to be ready before the next: marking a whole chain and starting it never races its own dependencies.

func (*App) StartReporter added in v0.21.0

func (a *App) StartReporter(name string) (time.Time, error)

StartReporter notes now as the start of report name's window; StopReporter measures it.

func (*App) StateDir

func (a *App) StateDir() string

func (*App) Status

func (a *App) Status(ctx context.Context, name string) (core.Status, error)

func (*App) StatusAll

func (a *App) StatusAll(ctx context.Context, names []string) []core.Status

StatusAll asks for every named service, in one call per runtime when the runtime can; errors become StateUnknown rows.

func (*App) Stop

func (a *App) Stop(ctx context.Context, name string) error

func (*App) StopReporter added in v0.21.0

func (a *App) StopReporter(ctx context.Context, name, source string) (*ReportResult, error)

StopReporter measures report name from its start until now and forgets the start.

func (*App) Suite

func (a *App) Suite(name string) (*spec.TestSuite, error)

Suite is a test suite of rig.yaml by name.

func (*App) SuiteNames

func (a *App) SuiteNames() []string

SuiteNames are the test suites in rig.yaml's order.

func (*App) TagImage

func (a *App) TagImage(s *spec.Service, tag string) string

TagImage is the reference of s's image at tag in this environment's registry.

func (*App) TakeSnapshot added in v0.6.0

func (a *App) TakeSnapshot(ctx context.Context, comp, name string, log io.Writer) (Snapshot, error)

TakeSnapshot saves comp's data as name (a timestamp when ""); it changes nothing, so read-only environments can take one too.

func (*App) Targets

func (a *App) Targets(targets []string, deps bool) ([]string, error)

Targets expands names, groups and roles; unknown targets are an error.

func (*App) TaskArgChoices added in v0.5.0

func (a *App) TaskArgChoices(ctx context.Context, arg spec.TaskArg) []string

TaskArgChoices is what a task arg offers to pick from: its choices, or the services and groups, the git branches (WorkingTree first), or the hosts, of this environment.

func (*App) TaskHelp

func (a *App) TaskHelp(name string) string

TaskHelp is a task's help, or its steps' first lines when it has none.

func (*App) TaskNames

func (a *App) TaskNames() []string

func (*App) Tasks

func (a *App) Tasks() map[string]spec.Task

Tasks are the project's tasks with this environment's replacing those of the same name.

func (*App) TestRuns

func (a *App) TestRuns(suite string) []string

TestRuns are the saved runs' ids, newest first; suite "" is every suite.

func (*App) Up

func (a *App) Up(ctx context.Context, targets []string, o UpOptions) error

Up builds (when asked) and deploys targets layer by layer in dependency order, waiting for each layer to be ready before the next starts. Dependencies pulled in by the targets, and infrastructure when no target is given, are only started when not already running, never redeployed.

func (*App) UseNamespace

func (a *App) UseNamespace(ns string) error

UseNamespace makes ns this environment's namespace from now on; "" goes back to rig.yaml's.

func (*App) VarValues

func (a *App) VarValues(ctx context.Context, v *spec.DashVar) ([]string, error)

VarValues are the choices of a dashboard variable: its fixed values, or the values of its label over the series its query returns now.

func (*App) Vars

func (a *App) Vars(ctx context.Context) (map[string]Var, error)

Vars are the runtime's manifest variables: rig.yaml's, with `rig vars set` overrides from the environment's state on top.

func (*App) Wait

func (a *App) Wait(ctx context.Context, name string, timeout time.Duration) (core.Status, error)

Wait polls the service until it is ready or timeout passes.

func (*App) Watch added in v0.6.0

func (a *App) Watch(ctx context.Context, names []string, emit func(WatchEvent)) error

Watch rebuilds and restarts each named service (every app service with a build or run, when none) when its sources change, until ctx ends. Events go to emit as they happen. A failed build leaves the running service as it was. ponytail: polls file mtimes (no fsnotify in the module); fine for a service's packages, not a monorepo.

func (*App) Writable added in v0.6.0

func (a *App) Writable() error

Writable refuses any change to a read-only environment; --yes and a confirmation do not lift it.

type AssertResult added in v0.26.0

type AssertResult struct {
	Assert string `json:"assert"`
	Got    string `json:"got"`
	OK     bool   `json:"ok"`
}

type Bench

type Bench struct {
	Package string             `json:"package"`
	Name    string             `json:"name"`
	Procs   int                `json:"procs,omitempty"`
	N       int64              `json:"n"`
	Metrics map[string]float64 `json:"metrics"` // ns/op, B/op, allocs/op, MB/s and custom units
}

Bench is one benchmark result line.

type Check added in v0.6.0

type Check struct {
	Name   string      `json:"name"`
	Status CheckStatus `json:"status"`
	Detail string      `json:"detail,omitempty"`
	Fix    string      `json:"fix,omitempty"`
}

Check is one line of `rig doctor`.

type CheckStatus added in v0.6.0

type CheckStatus string
const (
	CheckOK   CheckStatus = "ok"
	CheckWarn CheckStatus = "warn"
	CheckFail CheckStatus = "fail"
)

type Evidence added in v0.6.0

type Evidence struct {
	ID      string    `json:"id"`
	Kind    string    `json:"kind"` // status, health, reach, logs, traces, metrics, alert, change
	Service string    `json:"service,omitempty"`
	At      time.Time `json:"at,omitempty"`
	Bad     bool      `json:"bad"`
	Summary string    `json:"summary"`
	Lines   []string  `json:"lines,omitempty"`
	// Blames are the services this evidence points at besides its own (a log line naming its database).
	Blames []string `json:"blames,omitempty"`
}

Evidence is one fact rig why found, cited by its ID.

type Firing

type Firing struct {
	Alert   string
	Subject string
	Value   float64
	Unit    string
	Level   Level
}

Firing is one alert over a threshold, on one subject (a node, a queue, a row of its query).

func (Firing) String

func (f Firing) String() string

type Gap added in v0.21.0

type Gap float64

Gap is a value that may be missing (NaN): JSON says null for it, which it cannot say NaN.

func (Gap) MarshalJSON added in v0.21.0

func (g Gap) MarshalJSON() ([]byte, error)

type Incident added in v0.6.0

type Incident struct {
	Service string `json:"service"`
	// Symptom is what the user described, when they said more than a service's name.
	Symptom  string     `json:"symptom,omitempty"`
	Env      string     `json:"env"`
	At       time.Time  `json:"at"`
	Window   string     `json:"window"`
	Checked  []string   `json:"checked"`
	Evidence []Evidence `json:"evidence"`
	Suspects []Suspect  `json:"suspects"`
}

Incident is what rig why gathered about one service and what it depends on.

func (*Incident) Brief added in v0.22.0

func (inc *Incident) Brief() string

Brief is one line about what was gathered: how much evidence, how much of it bad, the top suspects.

func (*Incident) Markdown added in v0.6.0

func (inc *Incident) Markdown(w io.Writer, analysis string)

Markdown writes the incident report: summary (the AI's analysis when there is one), timeline, evidence and next steps.

func (*Incident) NextSteps added in v0.6.0

func (inc *Incident) NextSteps() []string

NextSteps are rig's own suggestions for the top suspect, for when no AI answers.

func (*Incident) Prompt added in v0.6.0

func (inc *Incident) Prompt() string

Prompt is what the assistant is asked about the incident.

type Lease added in v0.26.0

type Lease struct {
	By    string    `json:"by"`
	Until time.Time `json:"until"`
	Note  string    `json:"note,omitempty"`
}

Lease holds an environment for one person: while it lasts, nobody else changes it.

type Level

type Level int
const (
	LevelOK Level = iota
	LevelWarn
	LevelCrit
)

type LoadLimits

type LoadLimits struct {
	Max  float64 `yaml:"max"`
	Step float64 `yaml:"step"`
}

type LoadResult added in v0.26.0

type LoadResult struct {
	ID         string         `json:"id"`
	Name       string         `json:"name"`
	Generator  string         `json:"generator"`
	Profile    string         `json:"profile"`
	Rate       float64        `json:"rate"`
	Started    time.Time      `json:"started"`
	Seconds    float64        `json:"seconds"`
	Sent       int64          `json:"sent"`
	Failed     int64          `json:"failed"`
	Throughput float64        `json:"throughput"`
	P50        time.Duration  `json:"p50"`
	P95        time.Duration  `json:"p95"`
	P99        time.Duration  `json:"p99"`
	Checks     []AssertResult `json:"checks,omitempty"`
}

LoadResult is one load run, saved under the state directory so later runs compare against it.

func (*LoadResult) ErrorRate added in v0.26.0

func (r *LoadResult) ErrorRate() float64

ErrorRate is the failed share of sent requests, in percent.

func (*LoadResult) Passed added in v0.26.0

func (r *LoadResult) Passed() bool

Passed is whether every assertion held.

type Local added in v0.26.0

type Local struct {
	App  *App
	Bus  *events.Bus
	Host *host.Host
	// contains filtered or unexported fields
}

Local is the Engine running in this process, over an App. ponytail: the TUI and CLI still reach App for what has no source or action yet; those calls move behind the seam as the adapters become plugins.

func NewLocal added in v0.26.0

func NewLocal(a *App, jm *jobs.Manager) *Local

NewLocal serves a; jm keeps its jobs (the TUI's own manager, so its activity view shows them).

func (*Local) Action added in v0.26.0

func (l *Local) Action(name string) (actions.Action, bool)

Action is a registered action by name: its effect, help and argument schema.

func (*Local) Actions added in v0.26.0

func (l *Local) Actions() []string

func (*Local) Catalog added in v0.26.0

func (l *Local) Catalog(context.Context) (*catalog.Catalog, error)

func (*Local) Close added in v0.26.0

func (l *Local) Close()

Close stops the plugin processes this engine started.

func (*Local) Complete added in v0.26.0

func (l *Local) Complete(context.Context, string, string, int) ([]protocol.Completion, error)

Complete has no languages until plugins bring them.

func (*Local) Decide added in v0.26.0

func (l *Local) Decide(ctx context.Context, id string, approve bool) (*protocol.RunResult, error)

func (*Local) Events added in v0.26.0

func (l *Local) Events(ctx context.Context, pattern string) (<-chan protocol.Event, error)

func (*Local) Inbox added in v0.26.0

func (l *Local) Inbox(context.Context) []inbox.Item

func (*Local) Jobs added in v0.26.0

func (l *Local) Jobs(context.Context) []*jobs.Job

func (*Local) Lease added in v0.26.0

func (l *Local) Lease() (Lease, bool)

Lease is the environment's live lease, if any.

func (*Local) Probes added in v0.26.0

func (l *Local) Probes() []Probe

Probes are the evidence the plugins' contracts add: failed pipelines and merged MRs from scm/1.

func (*Local) Provides added in v0.26.0

func (l *Local) Provides(context.Context) protocol.Provides

Provides is every source and action this engine serves, for finding them by what they do.

func (*Local) Publish added in v0.26.0

func (l *Local) Publish(ctx context.Context, rep *ReportResult, file string) error

Publish runs the report's publish: actions through policy, with ${report} and ${file} filled in.

func (*Local) Query added in v0.26.0

func (l *Local) Query(ctx context.Context, source string, args protocol.Args) (*protocol.Frame, error)

func (*Local) Resolve added in v0.26.0

func (l *Local) Resolve(ctx context.Context, ref string) (*protocol.Resolved, error)

func (*Local) Run added in v0.26.0

func (l *Local) Run(ctx context.Context, action string, args protocol.Args, o api.RunOpts) (*jobs.Job, *protocol.RunResult, error)

func (*Local) Search added in v0.26.0

func (l *Local) Search(ctx context.Context, q string) ([]protocol.Hit, error)

func (*Local) Service added in v0.26.0

func (l *Local) Service(ctx context.Context, action, name string) error

Service runs a runtime action on one service.

func (*Local) Session added in v0.26.0

func (l *Local) Session(ctx context.Context) identity.Subject

func (*Local) Stream added in v0.26.0

func (l *Local) Stream(ctx context.Context, source string, args protocol.Args) (<-chan protocol.StreamBatch, error)

Stream answers a source that only queries with one batch.

type Probe added in v0.26.0

type Probe func(ctx context.Context, window time.Duration, add func(Evidence))

Investigate gathers evidence about service and everything it depends on over the last window: state and restarts, health probes, the components they host, error lines in their logs, failed traces, firing alerts and recent changes; then ranks the likely culprits. It needs no AI. An empty service checks every service. Probe adds evidence from somewhere App cannot reach alone, such as a plugin's contract sources.

type ReportDelta added in v0.26.0

type ReportDelta struct {
	Metric string  `json:"metric"`
	Series string  `json:"series,omitempty"`
	Stat   string  `json:"stat"`
	Was    float64 `json:"was"`
	Now    float64 `json:"now"`
}

ReportDelta is one metric's stat now against the compared report.

func (ReportDelta) Change added in v0.26.0

func (d ReportDelta) Change() string

type ReportResult

type ReportResult struct {
	Name     string           `json:"name"`
	Env      string           `json:"env"`
	From     time.Time        `json:"from"`
	To       time.Time        `json:"to"`
	Stats    []string         `json:"stats"`
	Rows     []ReportRow      `json:"rows"`
	Buckets  []time.Time      `json:"buckets,omitempty"`
	Timeline []ReportTimeline `json:"timeline,omitempty"`
	Traces   []ReportTraceRow `json:"traces,omitempty"`
	Tables   []ReportTableRow `json:"tables,omitempty"`
	Tests    *ReportTests     `json:"tests,omitempty"`
	Load     *LoadResult      `json:"load,omitempty"`
	Compare  []ReportDelta    `json:"compare,omitempty"`
	// Summary is what the assistant wrote about it (ai: true); Text is the rendered template:.
	Summary string `json:"summary,omitempty"`
	Text    string `json:"text,omitempty"`
	Format  string `json:"-"`
}

ReportResult is a reports: entry measured over one window.

func (*ReportResult) Failed added in v0.26.0

func (r *ReportResult) Failed() bool

Failed says whether the report holds a failure: a failed test or a broken load assertion.

func (*ReportResult) Markdown

func (r *ReportResult) Markdown(w io.Writer)

Markdown writes the report as tables: metrics, timeline, traces, queries.

func (*ReportResult) Write added in v0.21.0

func (r *ReportResult) Write(w io.Writer, format string) error

Write writes the report as md, json or xml.

type ReportRow

type ReportRow struct {
	Metric string             `json:"metric"`
	Series string             `json:"series,omitempty"`
	Unit   string             `json:"unit,omitempty"`
	Values map[string]float64 `json:"values"`
	Err    string             `json:"err,omitempty"`
}

ReportRow is one series of one metric, summarised.

type ReportTableRow added in v0.21.0

type ReportTableRow struct {
	Title   string     `json:"title"`
	Query   string     `json:"query"`
	Columns []string   `json:"columns,omitempty"`
	Rows    [][]string `json:"rows,omitempty"`
	Total   int        `json:"total"`
	Err     string     `json:"err,omitempty"`
}

ReportTableRow is what one queries: entry returned at the end of the window.

type ReportTests added in v0.26.0

type ReportTests struct {
	Suite  string   `json:"suite"`
	Run    string   `json:"run"`
	Passed int      `json:"passed"`
	Failed int      `json:"failed"`
	Skip   int      `json:"skipped"`
	Fails  []string `json:"fails,omitempty"`
}

ReportTests is a suite's last run as a report sees it.

type ReportTimeline added in v0.21.0

type ReportTimeline struct {
	Metric string `json:"metric"`
	Series string `json:"series,omitempty"`
	Unit   string `json:"unit,omitempty"`
	Values []Gap  `json:"values"`
}

ReportTimeline is one series' average per interval of the window (the report's every:).

type ReportTraceRow added in v0.21.0

type ReportTraceRow struct {
	Title   string              `json:"title"`
	Count   int                 `json:"count"`
	Errors  int                 `json:"errors"`
	P50     time.Duration       `json:"p50_ns"`
	P95     time.Duration       `json:"p95_ns"`
	Max     time.Duration       `json:"max_ns"`
	Slowest []core.TraceSummary `json:"slowest,omitempty"`
	Err     string              `json:"err,omitempty"`
}

ReportTraceRow sums up the traces one traces: entry matched in the window.

type ScrapeTarget

type ScrapeTarget struct {
	Targets []string          `json:"targets"`
	Labels  map[string]string `json:"labels"`
}

ScrapeTarget is one entry of a Prometheus file_sd file.

type Snapshot added in v0.6.0

type Snapshot struct {
	Name string
	File string
	Size int64
	At   time.Time
}

Snapshot is one saved copy of a data component, in the environment's state dir.

type Suspect added in v0.6.0

type Suspect struct {
	Service  string   `json:"service"`
	Score    int      `json:"score"`
	Evidence []string `json:"evidence"`
}

Suspect is a service ranked by the evidence against it.

func Rank added in v0.6.0

func Rank(target string, ev []Evidence) []Suspect

Rank scores each service by the bad evidence against it: being down outweighs failing reach, which outweighs being named in another service's errors, then its own errors and restarts.

type TestCase

type TestCase struct {
	Package  string    `json:"package"`
	Name     string    `json:"name,omitempty"`
	Status   string    `json:"status"`
	Elapsed  float64   `json:"elapsed,omitempty"`
	Parallel bool      `json:"parallel,omitempty"`
	Started  time.Time `json:"started"`
	Output   []string  `json:"output,omitempty"`
}

TestCase is one package (Name "") or test as go test -json reported it.

func (*TestCase) Depth

func (c *TestCase) Depth() int

Depth is how many levels deep a test is: 1 for TestX, 2 for TestX/sub, 0 for a package.

type TestJob

type TestJob struct {
	Options TestOptions
}

TestJob is one go test invocation of a run: these options, perhaps narrowed to some tests.

func RerunFailed

func RerunFailed(r *TestRun, base TestOptions) []TestJob

RerunFailed are the jobs that run a run's failures again. Each failed test is cut back to its deepest parallel ancestor (a case that stands on its own, like one mode of an integration case), else to its top-level test, so the steps before it run too; tests cut to the same depth share a job.

type TestOptions

type TestOptions struct {
	Packages  []string      `json:"packages,omitempty"`
	Run       string        `json:"run,omitempty"`
	Skip      string        `json:"skip,omitempty"`
	Race      bool          `json:"race,omitempty"`
	Cover     bool          `json:"cover,omitempty"`
	Short     bool          `json:"short,omitempty"`
	Failfast  bool          `json:"failfast,omitempty"`
	Shuffle   bool          `json:"shuffle,omitempty"`
	Count     int           `json:"count,omitempty"`
	Parallel  int           `json:"parallel,omitempty"`
	CPU       string        `json:"cpu,omitempty"`
	Timeout   time.Duration `json:"timeout,omitempty"`
	Bench     string        `json:"bench,omitempty"`
	Benchtime string        `json:"benchtime,omitempty"`
	Benchmem  bool          `json:"benchmem,omitempty"`
}

TestOptions are the go test flags of one run; Suite fills them from rig.yaml and the caller changes them.

func Only

func Only(base TestOptions, pkg string, names ...string) TestOptions

Only narrows options to these tests of one package.

func OptionsFor

func OptionsFor(s *spec.TestSuite) TestOptions

OptionsFor is what a suite runs with unless changed.

func (TestOptions) Args

func (o TestOptions) Args(s *spec.TestSuite) []string

Args are the go test arguments for these options and the suite's fixed ones.

type TestRun

type TestRun struct {
	ID       string             `json:"id"`
	Suite    string             `json:"suite"`
	Env      string             `json:"env"`
	Options  TestOptions        `json:"options"`
	Commands [][]string         `json:"commands"`
	Started  time.Time          `json:"started"`
	Ended    time.Time          `json:"ended"`
	Err      string             `json:"err,omitempty"`
	Tests    []*TestCase        `json:"tests"`
	Benches  []Bench            `json:"benches,omitempty"`
	Coverage map[string]float64 `json:"coverage,omitempty"`
	// Stderr is what go test printed outside its JSON: build errors, mostly.
	Stderr []string `json:"stderr,omitempty"`
	// Metrics is the suite's report: measured over the run.
	Metrics *ReportResult `json:"metrics,omitempty"`
	// contains filtered or unexported fields
}

TestRun is one go test invocation (or several, for a rerun of failures at different depths) and everything it reported. It is safe to read with Read while the run goes on.

func (*TestRun) Counts

func (r *TestRun) Counts() map[string]int

Counts are the tests (not packages) per status.

func (*TestRun) Done

func (r *TestRun) Done() bool

Done reports whether the run has ended.

func (*TestRun) FailedPackages

func (r *TestRun) FailedPackages() int

FailedPackages are packages that failed on their own (a build failure, a panic in TestMain), not through a failed test.

func (*TestRun) Read

func (r *TestRun) Read(f func(*TestRun))

Read calls f with the run locked.

func (*TestRun) Summary

func (r *TestRun) Summary() string

Summary is one line about a run: counts, time, coverage.

func (*TestRun) WriteJUnit

func (r *TestRun) WriteJUnit(w io.Writer) error

WriteJUnit writes the run as JUnit XML (one testsuite per package), for CI.

func (*TestRun) WriteReport

func (r *TestRun) WriteReport(w io.Writer, failedOnly bool)

WriteReport writes a plain-text report: the summary, failures with their output, the slowest tests, benchmarks and coverage. failedOnly leaves out everything but the failures.

type UpOptions

type UpOptions struct {
	Build bool
	// Tag names the images: what builds produce, or without Build, the tag to deploy from the registry.
	Tag string
	// Ref builds from a git ref (branch, tag, commit) instead of the working tree.
	Ref    string
	NoDeps bool
	Wait   time.Duration
	// Settle is how long up watches what it deployed after the last phase: a service that turned
	// ready and then crashed (a missing config key, say) fails the up instead of passing silently.
	Settle time.Duration
	// DryRun prints the phases and what each service would get, changing nothing.
	DryRun bool
	Out    io.Writer
}

type Var

type Var struct {
	Value, From string
}

Var is a manifest variable and where its value comes from.

type ViewDef added in v0.31.0

type ViewDef struct {
	// Key is view:<name>, view:<plugin>.<name>, view:<plugin>/<contract> or view:Home
	Key   string
	Title string
	View  *view.View
	// Dir is where the view's file: and its widgets' file: props resolve
	Dir string
	// Remote is <plugin>.<view> for a view its plugin renders
	Remote  string
	Plugin  string
	Secrets []string
	// Rank is 10-13 for the dev loop's contracts, 20 for the project's views, 30 for a user's own
	Rank int
}

ViewDef is a view a UI places: from rig.yaml, a plugin's manifest or a contract a plugin serves.

func Views added in v0.31.0

func Views(a *App) []ViewDef

Views are the project's tab and command views in screen order: Home first when any view is a home tile, then the dev loop's contracts (changes, merge requests, issues, docs), the project's own, and what a user installed for themselves.

type WatchEvent added in v0.6.0

type WatchEvent struct {
	Service string
	State   string
	// Output is the build's output, on failed.
	Output string
	Err    error
	Took   time.Duration
}

WatchEvent is a step of a live rebuild: State is changed, building, restarting, ok or failed.

Jump to

Keyboard shortcuts

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