oversight

package module
v2.0.0-...-2b35743 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2025 License: Apache-2.0 Imports: 7 Imported by: 3

README

cirello.io/oversight/v2

Go Reference

Package oversight mimics the implementation of Erlang supervision trees.

Refer to: http://erlang.org/doc/design_principles/sup_princ.html

go get cirello.io/oversight/v2

https://pkg.go.dev/cirello.io/oversight/v2

Quickstart

var tree oversight.Tree
err := tree.Add(
	func(ctx context.Context) error {
		select {
		case <-ctx.Done():
			return nil
		case <-time.After(time.Second):
			fmt.Println(1)
		}
		return nil
	},
	oversight.Permanent(),
	oversight.Natural(),
	"childProcess",
)
if err != nil {
	log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fmt.Println(tree.Start(ctx))

Documentation

Overview

Package oversight mimics the implementation of Erlang supervision trees.

Refer to: http://erlang.org/doc/design_principles/sup_princ.html

var tree oversight.Tree
err := tree.Add(
	func(ctx context.Context) error {
		select {
		case <-ctx.Done():
			return nil
		case <-time.After(time.Second):
			fmt.Println(1)
		}
		return nil
	},
	oversight.Permanent(),
	oversight.Natural(),
	"childProcess",
)
if err != nil {
	log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fmt.Println(tree.Start(ctx))

Security Notice: there has been permanent attempts to use the name of this package to spread malware. Please refer to https://github.com/cirello-io/oversight/issues/3 for more information.

Index

Examples

Constants

View Source
const (
	DefaultMaxR = 1
	DefaultMaxT = 5 * time.Second
)

Default restart intensity expectations.

Variables

View Source
var ErrChildProcessSpecificationMissingStart = errors.New("missing start function in child process specification")

ErrChildProcessSpecificationMissingStart is returned when a child process specification is missing the start function.

View Source
var ErrInvalidConfiguration = errors.New("invalid tree configuration")

ErrInvalidConfiguration is returned when tree has invalid settings.

View Source
var ErrMissingContext = errors.New("missing context")

ErrMissingContext is returned when a nil value is passed as context

View Source
var ErrMissingRestartPolicy = errors.New("missing restart policy")

ErrMissingRestartPolicy is returned when a child process specification is missing the Restart policy.

View Source
var ErrMissingShutdownPolicy = errors.New("missing shutdown policy")

ErrMissingShutdownPolicy is returned when a child process specification is missing the Shutdown policy.

View Source
var ErrNoChildProcessLeft = errors.New("no child process left")

ErrNoChildProcessLeft means that all processes in the supervisor are done, and there is no one left to restart.

View Source
var ErrNonUniqueProcessName = errors.New("non-unique process name")

ErrNonUniqueProcessName is returned when a child process is added with a name that is already in use.

View Source
var ErrProcessNotRunning = errors.New("process not running")

ErrProcessNotRunning is returned when caller tries to terminated processes that are not running.

View Source
var ErrTooManyFailures = errors.New("too many failures")

ErrTooManyFailures means that the supervisor detected that one of the child processes has failed too much and that it decided to fully stop.

View Source
var ErrTreeNotRunning = errors.New("oversight tree is not running")

ErrTreeNotRunning is returned to Add, Terminate and Delete calls when the oversight tree is initialized but not started yet; or when at that point in time is not running anymore.

View Source
var ErrUnknownProcess = errors.New("unknown process")

ErrUnknownProcess is returned when runtime operations (like delete or terminate) failed because the process is not present.

Functions

This section is empty.

Types

type ChildProcess

type ChildProcess func(ctx context.Context) error

ChildProcess is a function that can be restarted

type ChildProcessState

type ChildProcessState string

ChildProcessState represents the current lifecycle step of the child process.

const (
	Starting ChildProcessState = ""
	Running  ChildProcessState = "running"
	Failed   ChildProcessState = "failed"
	Done     ChildProcessState = "done"
)

Child processes navigate through a sequence of states, that are atomically managed by the oversight tree to decide if child process needs to be started or not.

                         ┌─────────────────────┐
                         │                     │
                         │              ┌────────────┐
                         ▼         ┌───▶│   Failed   │
┌────────────┐    ┌────────────┐   │    └────────────┘
│  Starting  │───▶│  Running   │───┤
└────────────┘    └────────────┘   │    ┌────────────┐
                                   └───▶│    Done    │
                                        └────────────┘

type Logger

type Logger func(args ...any)

Logger defines the interface for any logging facility to be compatible with oversight trees.

type Restart

type Restart func(error) bool

Restart is a function that decides if a worker has to be restarted or not according to its returned error.

func Permanent

func Permanent() Restart

Permanent goroutine is always restarted.

func Temporary

func Temporary() Restart

Temporary goroutine is never restarted (not even when the supervisor restart strategy is rest_for_one or one_for_all and a sibling death causes the temporary process to be terminated).

func Transient

func Transient() Restart

Transient goroutine is restarted only if it terminates abnormally, that is, with any error.

type Shutdown

type Shutdown func() (context.Context, context.CancelFunc)

Shutdown defines how the oversight handles child processes hanging after they are signaled to stop.

func Natural

func Natural() Shutdown

Natural will wait until the process naturally dies.

func Timeout

func Timeout(d time.Duration) Shutdown

Timeout defines a duration of time that the oversight will wait before detaching from the winding process.

type State

type State struct {
	Name  string
	State ChildProcessState
	Stop  func()
}

State is a snapshot of the child process current state.

type Strategy

type Strategy func(t *Tree, childProcess *childProcess)

Strategy defines how the supervisor handles individual failures and tree shutdowns (best effort). The shutdown is initiated in the reverse order of the start of the child processes. The Go scheduler implementation makes it impossible to guarantee any order regarding shutdown completion.

func OneForAll

func OneForAll() Strategy

OneForAll ensures that if a child process terminates, all other child processes are terminated, and then all child processes, including the terminated one, are restarted.

func OneForOne

func OneForOne() Strategy

OneForOne ensures that if a child process terminates, only that process is restarted.

func RestForOne

func RestForOne() Strategy

RestForOne ensures that if a child process terminates, the rest of the child processes (that is, the child processes after the terminated process in start order) are terminated. Then the terminated child process and the rest of the child processes are restarted.

func SimpleOneForOne

func SimpleOneForOne() Strategy

SimpleOneForOne behaves similarly to OneForOne but it runs the stop calls asynchronously.

type Tree

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

Tree is the supervisor tree proper.

Example (SinglePermanent)

ExampleTree_singlePermanent shows how to create a static tree of permanent child processes.

var tree oversight.Tree
err := tree.Add(
	func(ctx context.Context) error {
		select {
		case <-ctx.Done():
			return nil
		case <-time.After(time.Second):
			fmt.Println(1)
		}
		return nil
	},
	oversight.Permanent(),
	oversight.Natural(),
	"childProcess",
)
if err != nil {
	log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fmt.Println(tree.Start(ctx))
Output:

1
1
too many failures

func New

func New(opts ...TreeOption) *Tree

New creates a new oversight (supervisor) tree with the applied options.

func (*Tree) Add

func (t *Tree) Add(fn ChildProcess, restart Restart, shutdown Shutdown, name string) error

Add attaches a new child process to a running oversight tree. This call must be used on running oversight trees. If the tree is halted, it is going to fail with ErrTreeNotRunning.

func (*Tree) Children

func (t *Tree) Children() []State

Children returns the current set of child processes.

func (*Tree) Delete

func (t *Tree) Delete(name string) error

Delete stops the service in the oversight tree and remove from it. If the oversight tree runs out of processes, it will terminate itself with ErrNoChildProcessLeft. This call must be used on running oversight trees, if the tree is not started yet, it is going to block. If the tree is halted, it is going to fail with ErrTreeNotRunning.

func (*Tree) Start

func (t *Tree) Start(rootCtx context.Context) error

Start ignites the supervisor tree.

func (*Tree) Terminate

func (t *Tree) Terminate(name string) error

Terminate stop the named process. Terminated child processes do not count as failures in the oversight tree restart policy. If the oversight tree runs out of processes, it will terminate itself with ErrNoChildProcessLeft. This call must be used on running oversight trees, if the tree is not started yet, it is going to block. If the tree is halted, it is going to fail with ErrTreeNotRunning.

type TreeOption

type TreeOption func(*Tree)

TreeOption are applied to change the behavior of a Tree.

func DefaultMaximumRestartIntensity

func DefaultMaximumRestartIntensity() TreeOption

DefaultMaximumRestartIntensity redefines the tolerance for failures in the supervisor tree. It defaults to 1 restart (maxR) in the preceding 5 seconds (maxT).

Refer to http://erlang.org/doc/design_principles/sup_princ.html#tuning-the-intensity-and-period

func DefaultRestartStrategy

func DefaultRestartStrategy() TreeOption

DefaultRestartStrategy redefines the supervisor behavior to use OneForOne.

func NeverHalt

func NeverHalt() TreeOption

NeverHalt will configure the oversight tree to never stop in face of failure.

func WithLogger

func WithLogger(logger Logger) TreeOption

WithLogger plugs a custom logger to the oversight tree. It assumes the logger is thread-safe.

func WithMaximumRestartIntensity

func WithMaximumRestartIntensity(maxR int, maxT time.Duration) TreeOption

WithMaximumRestartIntensity defines a custom tolerance for failures in the supervisor tree.

Refer to http://erlang.org/doc/design_principles/sup_princ.html#maximum-restart-intensity

func WithRestartStrategy

func WithRestartStrategy(strategy Strategy) TreeOption

WithRestartStrategy defines a custom restart strategy for the supervisor tree.

func WithSpecification

func WithSpecification(maxR int, maxT time.Duration, strategy Strategy) TreeOption

WithSpecification defines a custom setup to tweak restart tolerance and strategy for the instance of oversight.

Source Files

  • child_process.go
  • doc.go
  • run.go
  • strategy.go
  • tree.go
  • tree_options.go
  • tree_restart.go

Jump to

Keyboard shortcuts

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