libroutine

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package libroutine runs recurring background tasks under circuit-breaker protection: Routine is the breaker, group manages one keyed loop per task, and Runner, Job and Schedule build condition-gated job chains on top of a Routine that can be fired directly, on a Schedule, or from a libbus subject.

Index

Constants

This section is empty.

Variables

View Source
var ErrAlreadyRunning = errors.New("libroutine: job is already running")

ErrAlreadyRunning is returned by Run when the Runner's job chain is already executing.

View Source
var ErrCircuitOpen = errors.New("circuit breaker is open")

ErrCircuitOpen is returned by Execute when the circuit breaker is Open.

Functions

func GetGroup

func GetGroup() *group

GetGroup returns the singleton instance of the group.

Types

type Condition added in v0.38.0

type Condition func(ctx context.Context) (bool, error)

Condition gates whether a Job's Operation runs. A nil Condition on a Job always proceeds.

type Job added in v0.38.0

type Job struct {
	// Name identifies this job in RunResult and error messages.
	Name string
	// Condition, if set, is evaluated before Operation. A false result skips
	// Operation and Next without failing the run.
	Condition Condition
	Operation Operation
	// Next, if set, runs after Operation succeeds.
	Next *Job
}

Job is one step in a chain: check Condition, run Operation, and if both succeed continue into Next. A Job is driven by a Runner.

type LoopConfig

type LoopConfig struct {
	// Key uniquely identifies the routine and prevents duplicate loops.
	Key string
	// Threshold is the number of consecutive failures before the circuit opens.
	Threshold int
	// ResetTimeout is how long the circuit stays open before half-open.
	ResetTimeout time.Duration
	// Interval is the time between executions.
	Interval time.Duration
	// Operation is the function executed periodically.
	Operation func(ctx context.Context) error
}

LoopConfig configures one managed background loop.

type Operation added in v0.38.0

type Operation func(ctx context.Context) error

Operation is the work a Job performs once its Condition allows it.

type Routine

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

Routine is a circuit breaker: it tracks failures, opens the circuit when a threshold is reached, and resets automatically after a timeout via HalfOpen.

func NewRoutine

func NewRoutine(threshold int, resetTimeout time.Duration) *Routine

NewRoutine creates a Routine that opens after threshold consecutive failures and stays Open for resetTimeout before transitioning to HalfOpen.

func (*Routine) Allow

func (rm *Routine) Allow() bool

Allow reports whether the circuit breaker permits an operation. It may transition the state from Open to HalfOpen if the reset timeout has passed.

func (*Routine) Execute

func (rm *Routine) Execute(ctx context.Context, fn func(ctx context.Context) error) error

Execute runs fn if allowed by the circuit breaker, recording the outcome.

func (*Routine) ExecuteWithRetry

func (rm *Routine) ExecuteWithRetry(ctx context.Context, interval time.Duration, iterations int, fn func(ctx context.Context) error) error

ExecuteWithRetry runs fn via Execute, retrying on failure up to iterations times with a fixed interval between attempts. It returns the last error, or the context cause if ctx is cancelled.

func (*Routine) ForceClose

func (rm *Routine) ForceClose()

ForceClose sets the circuit breaker to Closed and resets the failure count.

func (*Routine) ForceOpen

func (rm *Routine) ForceOpen()

ForceOpen sets the circuit breaker to the Open state.

func (*Routine) GetResetTimeout

func (rm *Routine) GetResetTimeout() time.Duration

GetResetTimeout returns the reset timeout duration configured for this circuit breaker.

func (*Routine) GetState

func (rm *Routine) GetState() State

GetState returns the current State of the circuit breaker.

func (*Routine) GetThreshold

func (rm *Routine) GetThreshold() int

GetThreshold returns the failure threshold configured for this circuit breaker.

func (*Routine) Loop

func (rm *Routine) Loop(ctx context.Context, interval time.Duration, triggerChan <-chan struct{}, fn func(ctx context.Context) error, errHandling func(err error))

Loop runs fn via Execute immediately, then on every interval tick or triggerChan signal, until ctx is cancelled. errHandling is called with each error, including ErrCircuitOpen.

func (*Routine) MarkFailure

func (rm *Routine) MarkFailure()

MarkFailure records a failed operation, tripping the circuit to Open once the threshold is reached or a HalfOpen test fails.

func (*Routine) MarkSuccess

func (rm *Routine) MarkSuccess()

MarkSuccess resets the circuit breaker after a successful call.

type RunResult added in v0.38.0

type RunResult struct {
	Name     string
	Skipped  bool
	Err      error
	Duration time.Duration
	// Next is the chained job's result, set only when Next was run.
	Next *RunResult
}

RunResult reports the outcome of running a Job, including its chain.

func (*RunResult) Failed added in v0.38.0

func (r *RunResult) Failed() bool

Failed reports whether this result or any later in its chain errored.

type Runner added in v0.38.0

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

Runner drives one Job's execution through a dedicated Routine, with a single-flight guard so a slow run is never overlapped by its own next trigger. It is safe for concurrent use.

func NewRunner added in v0.38.0

func NewRunner(job *Job, threshold int, resetTimeout time.Duration, opts ...RunnerOption) *Runner

NewRunner returns a Runner for job, protected by a Routine constructed with threshold and resetTimeout. The job chain is not started.

func (*Runner) Run added in v0.38.0

func (r *Runner) Run(ctx context.Context) (*RunResult, error)

Run executes the job chain synchronously through the Runner's Routine. It returns a nil result with ErrAlreadyRunning or ErrCircuitOpen when the chain is already executing or the circuit is open.

func (*Runner) Running added in v0.38.0

func (r *Runner) Running() bool

Running reports whether the job chain is currently executing.

func (*Runner) StartSchedule added in v0.38.0

func (r *Runner) StartSchedule(ctx context.Context, sched Schedule)

StartSchedule runs r.Trigger each time sched fires, until ctx is cancelled. It returns immediately, and a tick that lands mid-run is dropped rather than queued.

func (*Runner) SubscribeMessenger added in v0.38.0

func (r *Runner) SubscribeMessenger(ctx context.Context, bus libbus.Messenger, subject string) (libbus.Subscription, error)

SubscribeMessenger triggers r every time a message is published to subject on bus. The subscription is torn down when ctx is done, or earlier via the returned Subscription.

func (*Runner) Trigger added in v0.38.0

func (r *Runner) Trigger(ctx context.Context)

Trigger launches Run in a background goroutine, silently dropping the request if the chain is already running or the circuit is open.

type RunnerOption added in v0.38.0

type RunnerOption func(*Runner)

RunnerOption configures a Runner at construction.

func WithResultHook added in v0.38.0

func WithResultHook(fn func(*RunResult)) RunnerOption

WithResultHook registers fn to be called with the RunResult of every run that actually executed the job. fn is called synchronously and must not block.

func WithTracker added in v0.38.0

func WithTracker(tracker libtracker.ActivityTracker) RunnerOption

WithTracker wires an ActivityTracker to observe every Run. Without it, a Runner uses libtracker.NoopTracker.

type Schedule added in v0.38.0

type Schedule interface {
	Next(t time.Time) time.Time
}

Schedule computes the next run time after t. It is interface-compatible with robfig/cron/v3's cron.Schedule.

func Every added in v0.38.0

func Every(d time.Duration) Schedule

Every returns a Schedule that fires at a fixed interval.

type State

type State int

State represents the operational state of the Routine (circuit breaker).

const (
	// Closed allows operations to execute and counts failures.
	Closed State = iota
	// Open prevents operations from executing, until a timeout moves it to HalfOpen.
	Open
	// HalfOpen allows a single test operation: success closes the circuit, failure reopens it.
	HalfOpen
)

func (State) String

func (s State) String() string

String returns a human-readable representation of the State.

Jump to

Keyboard shortcuts

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