pipelines

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 20 Imported by: 1 module, 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 pipelines builds configurable, retryable workflows out of Steps: external processes (Command), Go functions (FuncStep) and groups of steps that run concurrently (ConcurrentStep). A Pipeline runs its steps in order, and several pipelines can run side by side.

What happens when a step succeeds or fails is decided by a Policy: retries, callbacks and, after a failure, whether to abort, continue or rerun. A policy is set for a whole pipeline (Pipeline.Policy) or for one step (WithPolicy, WithRetry).

A Pipeline is a state machine: every finished or aborted step moves it to a State chosen by Pipeline.Transition, for instance from the step's exit code, and the jobs registered for that state (Pipeline.On) are run.

All output goes through a Logger: step output and logrus entries are queued on one channel and demultiplexed per pipeline into log files and into the tabs of a gocui terminal viewer.

ctx, log, err := pipelines.NewLogger(ctx, "logs", true)
...
err = pipelines.RunPipelinesConcurrently(ctx, []pipelines.Pipeline{build, test})
log.Close()

Index

Constants

View Source
const All = "all"

All is the stream every line is copied to: the first tab and all.log.

Variables

This section is empty.

Functions

func AcquireConfigLock

func AcquireConfigLock(ctx context.Context, symb string) error

AcquireConfigLock acquires a filesystem-based reentrant lock for symb. It blocks until the lock is acquired or the context is cancelled.

func Always added in v0.2.0

func Always(a Action) func(context.Context, Step, error) Action

Always returns an OnFailure callback that picks a whatever the error.

func CopyFile

func CopyFile(src string, dst string) error

CopyFile copies the contents of src to dst. Returns an error on failure.

func Log added in v0.2.0

func Log(ctx context.Context) *logrus.Entry

Log returns an entry for the Logger in ctx that is bound to the pipeline running in ctx, so that what it logs lands in that pipeline's tab and file. Without a Logger it falls back to logrus's standard logger.

func PipelinesDir added in v0.1.4

func PipelinesDir(ctx context.Context) string

PipelinesDir returns a pipelines directory path from the context, falling back to the PIPELINES_DIR environment variable, or $HOME/.pipelines/.

func ReleaseConfigLock

func ReleaseConfigLock(ctx context.Context, symb string) error

ReleaseConfigLock releases the filesystem-based reentrant lock for symb.

func RunPipelinesConcurrently

func RunPipelinesConcurrently(ctx context.Context, pipelines []Pipeline, opts ...RunOption) error

RunPipelinesConcurrently runs the pipelines concurrently and returns their joined errors. It runs the slice's elements in place, so that is where their State is found afterwards. The caller provides a context wired to cancellation.

func WithLockToken

func WithLockToken(ctx context.Context) context.Context

WithLockToken returns a child context that carries a fresh, unique lock token. Call this once per logical "owner" (e.g. at the top of each command handler) before passing the context to AcquireConfigLock.

Types

type Action added in v0.2.0

type Action int

Action is what happens to a step that has failed.

const (
	Abort    Action = iota // return the error: the pipeline stops (default)
	Continue               // drop the error: the pipeline carries on
	Rerun                  // run the step again with a fresh retry budget
)

type Command

type Command struct {
	Name        string
	Description string
	Environment map[string]string
	Executable  string
	Args        []string
	Options     []Option
}

Command is a Step that runs an external command.

func (*Command) AddOption

func (c *Command) AddOption(opt Option)

func (*Command) BuildArgs

func (c *Command) BuildArgs() []string

func (*Command) Execute

func (c *Command) Execute(ctx context.Context, sw *StepWriter) error

Execute runs the command with its output sent to sw. On cancellation the process is interrupted and, if it lingers, killed five seconds later.

func (*Command) HelpInfo

func (c *Command) HelpInfo() string

func (*Command) StepDescription

func (c *Command) StepDescription() string

func (*Command) StepName

func (c *Command) StepName() string

type ConcurrentStep

type ConcurrentStep struct {
	Name           string
	Description    string
	Steps          []Step
	MaxConcurrency int // sub-steps running at once; <= 0 means all of them
}

ConcurrentStep is a Step that runs its sub-steps concurrently and completes when all of them have. The first sub-step to fail cancels the others and its error is returned; wrap a sub-step with WithPolicy to retry it or to tolerate its failure.

func (*ConcurrentStep) Execute

func (cs *ConcurrentStep) Execute(ctx context.Context, sw *StepWriter) error

func (*ConcurrentStep) HelpInfo

func (cs *ConcurrentStep) HelpInfo() string

func (*ConcurrentStep) StepDescription

func (cs *ConcurrentStep) StepDescription() string

func (*ConcurrentStep) StepName

func (cs *ConcurrentStep) StepName() string

type FuncStep

type FuncStep struct {
	Name        string
	Description string
	Fn          func(ctx context.Context, sw *StepWriter) error
}

FuncStep is a Step that calls a Go function.

func (*FuncStep) Execute

func (f *FuncStep) Execute(ctx context.Context, sw *StepWriter) error

func (*FuncStep) HelpInfo

func (f *FuncStep) HelpInfo() string

func (*FuncStep) StepDescription

func (f *FuncStep) StepDescription() string

func (*FuncStep) StepName

func (f *FuncStep) StepName() string

type Logger added in v0.2.0

type Logger struct {
	*logrus.Logger
	Dir string // holds all.log and, unless Pipeline.LogDir is set, <pipeline>.log
	// contains filtered or unexported fields
}

Logger demultiplexes the log of concurrently running pipelines. Step output and logrus entries are queued on one channel and a single goroutine routes each line, by the pipeline it belongs to, to that pipeline's log file and terminal tab, as well as to All.

The embedded logrus.Logger is the front end for structured entries: level, formatter and hooks work as usual, and an entry is routed by its "pipeline" field (see Log).

func LoggerFromContext

func LoggerFromContext(ctx context.Context) *Logger

LoggerFromContext returns the Logger carried by ctx, or nil.

func NewLogger added in v0.2.0

func NewLogger(ctx context.Context, dir string, tui bool) (context.Context, *Logger, error)

NewLogger starts a Logger that stores its files in dir (default PipelinesDir) and returns it together with a context that carries it.

With tui set, the terminal becomes a gocui viewer with one tab per stream, and the returned context is cancelled when the user presses q or Ctrl-C. Otherwise the lines of All are printed to stdout.

func (*Logger) Close added in v0.2.0

func (l *Logger) Close()

Close completes the log files and, in TUI mode, keeps the viewer open until the user quits it. Call it once every pipeline has returned; entries logged afterwards go to stderr.

type Option

type Option struct {
	Short       string
	Long        string
	Description string
	HasValue    bool
	Value       string
}

Option represents a CLI flag or argument.

type Pipeline

type Pipeline struct {
	Name        string
	Description string
	Steps       []Step
	Policy      Policy // applied to every step; see WithPolicy for a single step
	LogDir      string // where <Name>.log is written; defaults to the Logger's Dir

	// State is maintained by Run. Read it from Transition, from jobs or after Run.
	State State
	// Transition picks the state that follows a step; nil means Next.
	Transition func(s State, r Result) State
	// Jobs are the steps to run, in order, whenever a step leaves the pipeline
	// in the given state. They run to completion even if the pipeline is
	// cancelled, and their failures are logged without changing the state.
	Jobs map[State][]Step
}

Pipeline is a state machine driven by its Steps, which it runs one after another. Run starts in Running. Each time a step finishes or gets aborted, Transition picks the next state from the step's Result and the Jobs of that state are run. A final state ends the run; a pipeline that is still Running after its last step becomes Succeeded.

func (*Pipeline) AddCommand

func (p *Pipeline) AddCommand(cmd Command)

func (*Pipeline) AddFunc

func (p *Pipeline) AddFunc(name, description string, fn func(ctx context.Context, sw *StepWriter) error)

func (*Pipeline) AddFuncStep

func (p *Pipeline) AddFuncStep(fs FuncStep)

func (*Pipeline) AddStep

func (p *Pipeline) AddStep(s Step)

func (*Pipeline) GetLogFilePath

func (p *Pipeline) GetLogFilePath() string

func (*Pipeline) HelpText

func (p *Pipeline) HelpText() string

func (*Pipeline) On added in v0.2.1

func (p *Pipeline) On(s State, jobs ...Step)

On registers jobs for state s.

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context) error

Run drives the state machine until it reaches a final state and returns an error if that state is Failed or Aborted. The pipeline's log goes to the Logger in ctx, under the stream p.Name, and is complete on disk when Run returns.

type PipelineFormatter

type PipelineFormatter struct{}

PipelineFormatter is a logrus.Formatter that renders entries as

LEVL[15:04:05](pipeline)(step)(progress) message  key=value ...

where the three leading fields are shown only if the entry has them.

func (PipelineFormatter) Format

func (PipelineFormatter) Format(e *logrus.Entry) ([]byte, error)

type Policy added in v0.2.0

type Policy struct {
	// Retry is passed to retry.Do. Without retry.Attempts the step is tried once;
	// retry.OnRetry replaces the built-in "retrying" log line.
	Retry []retry.Option
	// OnSuccess is called after the step succeeded.
	OnSuccess func(ctx context.Context, s Step)
	// OnFailure is called after the step failed for good and picks the Action.
	// nil means Abort.
	OnFailure func(ctx context.Context, s Step, err error) Action
}

Policy is the control over a step's outcome. A step runs until it succeeds or its Retry budget is spent; then exactly one of the callbacks is called.

Cancellation is not a failure: once ctx is done the step is neither retried nor reported to OnFailure, and its error is returned as is.

type Result added in v0.2.1

type Result struct {
	Step     Step
	Err      error // nil on success
	ExitCode int   // 0 on success, else Err's ExitCode() (as *exec.ExitError has), or -1 if it has none
	Aborted  bool  // the step ended because the pipeline was cancelled
}

Result is how a step ended, as the pipeline sees it after the step's policies.

type RunOption

type RunOption func(*runOptions)

RunOption configures RunPipelinesConcurrently.

func ContinueOnError

func ContinueOnError() RunOption

ContinueOnError keeps the other pipelines running when one fails. By default the first failure cancels them. Either way all errors are returned.

type State added in v0.2.1

type State string

State is where a Pipeline stands. The four states below are built in; a Transition may return any other value, such as "degraded".

const (
	Running   State = "running"   // steps are being executed
	Succeeded State = "succeeded" // final: every step was executed, or a Transition ended the run early
	Failed    State = "failed"    // final: Run returns an error
	Aborted   State = "aborted"   // final: Run returns an error
)

func Next added in v0.2.1

func Next(s State, r Result) State

Next is the default Transition: an aborted step makes the pipeline Aborted, a failed one Failed, and a successful one leaves the state as it is.

func (State) Done added in v0.2.1

func (s State) Done() bool

Done reports whether s is final, which ends the run.

type Step

type Step interface {
	StepName() string
	StepDescription() string
	HelpInfo() string
	Execute(ctx context.Context, sw *StepWriter) error
}

Step is one unit of work in a Pipeline. Execute reports failure by returning an error; what happens next is decided by the Policy the step runs under.

func WithPolicy added in v0.2.0

func WithPolicy(s Step, p Policy) Step

WithPolicy wraps s so that it runs under p wherever it is placed: in a Pipeline, in a ConcurrentStep or inside another WithPolicy. An enclosing policy (such as Pipeline.Policy) only sees the error that p let through.

func WithRetry

func WithRetry(s Step, opts ...retry.Option) Step

WithRetry wraps s so that it is retried as described by opts, for example

pipelines.WithRetry(step, retry.Attempts(3), retry.Delay(time.Second), retry.DelayType(retry.FixedDelay))

type StepWriter

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

StepWriter is the output handle passed to every Execute call. It cuts what is written into lines, tags each with the names of its pipeline and step, and queues them on the Logger. It is safe for concurrent use.

func New

func New(w io.Writer) *StepWriter

New returns a StepWriter that prints its lines to w instead of a Logger, which is handy for running a Step on its own.

func (*StepWriter) Flush

func (sw *StepWriter) Flush() error

Flush emits a trailing line that was not terminated by a newline.

func (*StepWriter) Write

func (sw *StepWriter) Write(p []byte) (int, error)

Directories

Path Synopsis
example demonstrates the pipelines package.
example demonstrates the pipelines package.

Jump to

Keyboard shortcuts

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