cell

package
v0.0.0-...-e90d087 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2024 License: Apache-2.0 Imports: 20 Imported by: 138

Documentation

Index

Constants

This section is empty.

Variables

View Source
var SimpleHealthCell = Provide(NewSimpleHealth)

Functions

func NewSimpleHealth

func NewSimpleHealth() (Health, *SimpleHealth)

func SimpleHealthCmd

func SimpleHealthCmd(h *SimpleHealth) script.Cmd

SimpleHealthCmd for showing or checking the simple module health state. Not provided as hive.ScriptCmdOut due to cyclic import issues. To include provide with: hive.ScriptCmdOut("health", SimpleHealthCmd(simpleHealth)))

Example:

# show health
health

# grep health
health 'my-module: level=OK'

Types

type AllSettings

type AllSettings map[string]any

type Cell

type Cell interface {
	// Info provides a structural summary of the cell for printing purposes.
	Info(container) Info

	// Apply the cell to the dependency graph container.
	Apply(container, rootContainer) error
}

Cell is the modular building block of the hive.

A cell can be constructed with:

  • Module(): Create a named set of cells.
  • Provide(): Provide object constructors.
  • Invoke(): Invoke a function to instantiate objects.
  • Decorate(): Decorate a set of cells to augment an object.
  • Config(): Cell providing a configuration struct.

func Config

func Config[Cfg Flagger](def Cfg) Cell

Config constructs a new config cell.

The configuration struct `T` needs to implement the Flags method that registers the flags. The structure is populated and provided via dependency injection by Hive.Run(). The underlying mechanism for populating the struct is viper's Unmarshal().

func Decorate

func Decorate(dtor any, cells ...Cell) Cell

Decorate takes a decorator function and a set of cells and returns a decorator cell.

A decorator function is a function that takes as arguments objects in the hive and returns one or more augmented objects. The cells wrapped with a decorator will be provided the returned augmented objects.

Example:

cell.Decorate(
	func(e Example) Example {
		return e.WithMoreMagic()
	},
	cell.Invoke(func(e Example) {
		// e now has more magic
	},
)

func DecorateAll

func DecorateAll(dtor any) Cell

DecorateAll takes a decorator function and applies the decoration globally.

Example:

	cell.Module(
	  "my-app",
	  "My application",
	    foo.Cell, // provides foo.Foo
	    bar.Cell,

       // Wrap 'foo.Foo' everywhere, including inside foo.Cell.
	   cell.DecorateAll(
	     func(f foo.Foo) foo.Foo {
	       return myFooWrapper{f}
	     },
	   ),
	)

func Group

func Group(cells ...Cell) Cell

Group a set of cells. Unlike Module(), Group() does not create a new scope.

func Invoke

func Invoke(funcs ...any) Cell

Invoke constructs a cell for invoke functions. The invoke functions are executed when the hive is started to instantiate all objects via the constructors.

func Module

func Module(id, description string, cells ...Cell) Cell

Module creates a scoped set of cells with a given identifier.

The id and description will be included in the object dump (hive.PrintObjects). The id must be lower-case, at most 30 characters and only contain [a-z0-9-_]. The description can contain [a-zA-Z0-9_- ] and must be shorter than 80 characters.

As the description will be shown alongside the id, it should not repeat the id, but rather expand on it, for example;

endpoint-manager: Manages and provides access to endpoints
^- id             ^- description

Private constructors with a module (ProvidePrivate) are only accessible within this module and its sub-modules.

func Provide

func Provide(ctors ...any) Cell

Provide constructs a new cell with the given constructors. Constructor is any function that takes zero or more parameters and returns one or more values and optionally an error. For example, the following forms are accepted:

func() A
func(A, B, C) (D, error).

If the constructor depends on a type that is not provided by any constructor the hive will fail to run with an error pointing at the missing type.

A constructor can also take as parameter a structure of parameters annotated with `cell.In`, or return a struct annotated with `cell.Out`:

type params struct {
	cell.In
	Flower *Flower
	Sun *Sun
}

type out struct {
	cell.Out
	Honey *Honey
	Nectar *Nectar
}

func newBee(params) (out, error)

func ProvidePrivate

func ProvidePrivate(ctors ...any) Cell

ProvidePrivate is like Provide, but the constructed objects are only available within the module it is defined and nested modules.

type DecodeHooks

type DecodeHooks []mapstructure.DecodeHookFunc

type DefaultLifecycle

type DefaultLifecycle struct {
	LogThreshold time.Duration
	// contains filtered or unexported fields
}

DefaultLifecycle lifecycle implements a simple lifecycle management that conforms to Lifecycle. It is exported for use in applications that have nested lifecycles (e.g. operator).

func NewDefaultLifecycle

func NewDefaultLifecycle(hooks []HookInterface, numStarted int, logThreshold time.Duration) *DefaultLifecycle

func (*DefaultLifecycle) Append

func (lc *DefaultLifecycle) Append(hook HookInterface)

func (*DefaultLifecycle) PrintHooks

func (lc *DefaultLifecycle) PrintHooks()

func (*DefaultLifecycle) Start

func (lc *DefaultLifecycle) Start(log *slog.Logger, ctx context.Context) error

func (*DefaultLifecycle) Stop

func (lc *DefaultLifecycle) Stop(log *slog.Logger, ctx context.Context) error

type Flagger

type Flagger interface {
	// Flags registers the configuration options as command-line flags.
	//
	// By convention a flag name matches the field name
	// if they're the same under case-insensitive comparison when dashes are
	// removed. E.g. "my-config-flag" matches field "MyConfigFlag". The
	// correspondence to the flag can be also specified with the mapstructure
	// tag: MyConfigFlag `mapstructure:"my-config-flag"`.
	//
	// Exported fields that are not found from the viper settings will cause
	// hive.Run() to fail. Unexported fields are ignored.
	//
	// See https://pkg.go.dev/github.com/mitchellh/mapstructure for more info.
	Flags(*pflag.FlagSet)
}

Flagger is implemented by configuration structs to provide configuration for a cell.

type FullModuleID

type FullModuleID []string

FullModuleID is the fully qualified module identifier, e.g. the concat of nested module ids, e.g. "agent.controlplane.endpoint-manager". Provided in the module's scope.

func (FullModuleID) String

func (f FullModuleID) String() string

type Health

type Health interface {
	// OK declares that a Module has achieved a desired state and has not entered
	// any unexpected or incorrect states.
	// Modules should only declare themselves as 'OK' once they have stabilized,
	// rather than during their initial state. This should be left to be reported
	// as the default "unknown" to denote that the module has not reached a "ready"
	// health state.
	OK(status string)

	// Stopped reports that a module has completed, and will no longer report any
	// health status.
	// Implementations should differentiate that a stopped module may also be OK or Degraded.
	// Stopping a reporting should only affect future updates.
	Stopped(reason string)

	// Degraded declares that a module has entered a degraded state.
	// This means that it may have failed to provide it's intended services, or
	// to perform it's desired task.
	Degraded(reason string, err error)

	// NewScope constructs a new scoped health reporter.
	NewScope(name string) Health

	// Close closes this health scope and removes it. This is distinct from
	// 'Stopped' in that after closing the health status will disappear completely.
	Close()
}

Health provides a method of declaring a Modules health status.

The interface is meant to be used with "ModuleDecorator" to inject it into the scope of modules.

Implementation for health reporting is not included with the Hive library.

type Hook

type Hook struct {
	OnStart func(HookContext) error
	OnStop  func(HookContext) error
}

Hook is a pair of start and stop callbacks. Both are optional. They're paired up to make sure that on failed start all corresponding stop hooks are executed.

func (Hook) Start

func (h Hook) Start(ctx HookContext) error

func (Hook) Stop

func (h Hook) Stop(ctx HookContext) error

type HookContext

type HookContext context.Context

HookContext is a context passed to a lifecycle hook that is cancelled in case of timeout. Hooks that perform long blocking operations directly in the start or stop function (e.g. connecting to external services to initialize) must abort any such operation if this context is cancelled.

type HookInterface

type HookInterface interface {
	Start(HookContext) error
	Stop(HookContext) error
}

HookInterface wraps the Start and Stop methods that can be appended to an application lifecycle.

type In

type In = dig.In

In when embedded into a struct used as constructor parameter makes the exported values of that struct become dependency injected values. In other words, it allows moving a long list of constructor parameters into a struct.

Struct fields can be annotated with `optional:"true"` to make the dependency optional. If the type is not found in the dependency graph, the value is set to the zero value.

See https://pkg.go.dev/go.uber.org/dig#In for more information.

type Info

type Info interface {
	Print(indent int, w *InfoPrinter)
}

Info provides a simple way of printing cells hierarchically in textual form.

type InfoLeaf

type InfoLeaf string

func (InfoLeaf) Print

func (l InfoLeaf) Print(indent int, w *InfoPrinter)

type InfoNode

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

func NewInfoNode

func NewInfoNode(header string) *InfoNode

func (*InfoNode) Add

func (n *InfoNode) Add(child Info)

func (*InfoNode) AddLeaf

func (n *InfoNode) AddLeaf(format string, args ...any)

func (*InfoNode) Print

func (n *InfoNode) Print(indent int, w *InfoPrinter)

type InfoPrinter

type InfoPrinter struct {
	io.Writer
	// contains filtered or unexported fields
}

func NewInfoPrinter

func NewInfoPrinter() *InfoPrinter

type InfoStruct

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

func (*InfoStruct) Print

func (n *InfoStruct) Print(indent int, w *InfoPrinter)

type InvokerList

type InvokerList interface {
	AppendInvoke(func(*slog.Logger, time.Duration) error)
}

type Level

type Level string

Level denotes what kind an update is.

const (
	// StatusUnknown is the default status of a Module, prior to it reporting
	// any status.
	// All created
	StatusUnknown Level = "Unknown"

	// StatusStopped is the status of a Module that has completed, further updates
	// will not be processed.
	StatusStopped Level = "Stopped"

	// StatusDegraded is the status of a Module that has entered a degraded state.
	StatusDegraded Level = "Degraded"

	// StatusOK is the status of a Module that has achieved a desired state.
	StatusOK Level = "OK"
)

type Lifecycle

type Lifecycle interface {
	Append(HookInterface)

	Start(*slog.Logger, context.Context) error
	Stop(*slog.Logger, context.Context) error
	PrintHooks()
}

Lifecycle enables cells to register start and stop hooks, either from a constructor or an invoke function.

type ModuleDecorator

type ModuleDecorator any

ModuleDecorator is the optional decorator function used for each module to provide or replace objects in each module's scope. Supplied with [hive.Options] field 'ModuleDecorators'.

This can be used to provide module-specific instances of objects application wide, similar to how *slog.Logger is provided by default.

type ModuleDecorators

type ModuleDecorators []ModuleDecorator

type ModuleID

type ModuleID string

ModuleID is the module identifier. Provided in the module's scope.

type ModulePrivateProvider

type ModulePrivateProvider any

type ModulePrivateProviders

type ModulePrivateProviders []ModulePrivateProvider

type Out

type Out = dig.Out

Out when embedded into a struct that is returned by a constructor will make the values in the struct become objects in the dependency graph instead of the struct itself.

See https://pkg.go.dev/go.uber.org/dig#Out for more information.

type RootLogger

type RootLogger *slog.Logger

RootLogger is the unscoped logger without any attrs added to it.

type SimpleHealth

type SimpleHealth struct {
	Scope  string
	Level  Level
	Status string
	Error  error
	// contains filtered or unexported fields
}

func (*SimpleHealth) Close

func (h *SimpleHealth) Close()

func (*SimpleHealth) Degraded

func (h *SimpleHealth) Degraded(reason string, err error)

Degraded implements cell.Health.

func (*SimpleHealth) GetChild

func (h *SimpleHealth) GetChild(fullName string) *SimpleHealth

func (*SimpleHealth) NewScope

func (h *SimpleHealth) NewScope(name string) Health

NewScope implements cell.Health.

func (*SimpleHealth) OK

func (h *SimpleHealth) OK(status string)

OK implements cell.Health.

func (*SimpleHealth) Stopped

func (h *SimpleHealth) Stopped(reason string)

Stopped implements cell.Health.

Jump to

Keyboard shortcuts

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