lifecycle

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 15 Imported by: 6

Documentation

Index

Constants

View Source
const (
	// StageDefault is the default stage for actors without explicit stage.
	StageDefault = 0

	// StageReadiness is the default stage for actors with readiness probe enabled.
	// It's very high to ensure readiness-probe actors start last.
	StageReadiness = math.MaxInt - 1000
)

Variables

View Source
var DefaultSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM}
View Source
var DefaultStopEachTimeout = 5 * time.Second

DefaultStopEachTimeout is the default timeout for stopping each individual actor.

View Source
var DefaultStopTimeout = 30 * time.Second

DefaultStopTimeout is the default timeout for stopping all actors during shutdown.

View Source
var ErrNoServices = errors.New("no long-running services to serve")

ErrNoServices is returned when no long-running services are registered.

View Source
var ErrServed = errors.New("lifecycle already served")

ErrServed is returned when Serve is called.

Functions

func GetStopCause

func GetStopCause(ctx context.Context) error

func Serve

func Serve(ctx context.Context, ctors ...any) error

Serve is a convenience function that creates a new Lifecycle instance and calls Serve on it.

func SetupSignalWith

func SetupSignalWith(signals ...os.Signal) func(lc *Lifecycle) *SignalService

SetupSignalWith returns a setup function that creates and registers a signal handling service that listens for the specified signals. If no signals are provided, it defaults to SIGINT and SIGTERM. The returned function can be used with dependency injection or called directly with a Lifecycle instance.

Types

type Actor

type Actor interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

Actor defines the interface for simple actors that only need start/stop operations. Examples: configuration loaders, database migrations, one-time setup tasks.

type FuncActor

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

FuncActor wraps start and stop functions into an Actor implementation. This is useful for creating actors from simple functions without defining new types.

func NewFuncActor

func NewFuncActor(start, stop func(ctx context.Context) error) *FuncActor

NewFuncActor creates a new FuncActor with the provided start and stop functions.

func (*FuncActor) GetName

func (f *FuncActor) GetName() string

GetName returns the name of the actor.

func (*FuncActor) GetStage added in v1.2.2

func (f *FuncActor) GetStage() int

GetStage returns the stage of the actor.

func (*FuncActor) RequiresReadinessProbe added in v1.2.0

func (f *FuncActor) RequiresReadinessProbe() *ReadinessProbe

RequiresReadinessProbe returns the readiness probe if enabled via WithReadiness.

func (*FuncActor) RequiresStop added in v1.0.2

func (f *FuncActor) RequiresStop() bool

acquired resources during construction and needs cleanup regardless of whether Start is called.

func (*FuncActor) Start

func (f *FuncActor) Start(ctx context.Context) (xerr error)

Start calls the wrapped start function. If readiness probe is enabled via WithReadiness, it signals completion after start.

func (*FuncActor) Stop

func (f *FuncActor) Stop(ctx context.Context) error

Stop calls the wrapped stop function.

func (*FuncActor) WithName

func (f *FuncActor) WithName(name string) *FuncActor

WithName sets the name of the actor. If a readiness probe is enabled, its name is also updated.

func (*FuncActor) WithReadiness added in v1.2.0

func (f *FuncActor) WithReadiness() *FuncActor

WithReadiness enables a readiness probe for this actor. Note: When enabled, this actor is assigned a very high stage value (for example, close to math.MaxInt) so that it starts after most other actors. This is typically desirable because readiness/health endpoints depend on the rest of the system being up, not the other way around. If another actor must start after this one, give that actor a higher stage (but still lower than the readiness-probe stage) by using WithStage to override its default behavior. Returns the actor for method chaining.

func (*FuncActor) WithStage added in v1.2.2

func (f *FuncActor) WithStage(stage int) *FuncActor

WithStage sets the stage for the actor, overriding the default behavior. This affects the order of actor startup: lower stages start first.

type FuncService

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

FuncService runs a function in a background goroutine and implements Service interface. Useful for long-running background tasks that need to be monitored.

func NewFuncService

func NewFuncService(taskFunc func(ctx context.Context) error) *FuncService

NewFuncService creates a new FuncService with the provided task function.

func (*FuncService) Done

func (b *FuncService) Done() <-chan struct{}

Done returns a channel that is closed when the background task completes.

func (*FuncService) Err

func (b *FuncService) Err() error

Err returns any error that occurred during background task execution.

func (*FuncService) GetName

func (b *FuncService) GetName() string

GetName returns the name of the service.

func (*FuncService) IsStarted

func (b *FuncService) IsStarted() bool

IsStarted returns whether the service has been started

func (*FuncService) Start

func (b *FuncService) Start(_ context.Context) error

Start launches the background task in a separate goroutine.

func (*FuncService) Stop

func (b *FuncService) Stop(ctx context.Context) error

Stop cancels the background task and waits for completion.

func (*FuncService) WithName

func (b *FuncService) WithName(name string) *FuncService

WithName sets the name of the service.

func (*FuncService) WithStop

func (b *FuncService) WithStop(stop func(ctx context.Context) error) *FuncService

WithStop sets the stop function for the service.

type Lifecycle

type Lifecycle struct {
	*inject.Injector // Embedded injector for dependency management
	*FuncService
	// contains filtered or unexported fields
}

Lifecycle manages the lifecycle of multiple actor instances. It provides coordinated startup, monitoring, and cleanup of both simple actors and long-running services.

func New

func New() *Lifecycle

New creates a new Lifecycle instance with embedded injector and default stop timeout.

func Provide added in v1.1.2

func Provide(ctors ...any) (*Lifecycle, error)

Provide is a convenience function that creates a new Lifecycle instance and calls Provide on it.

func Start

func Start(ctx context.Context, ctors ...any) (*Lifecycle, error)

Start is a convenience function that creates a new Lifecycle instance, provides the constructors, and calls Start on it.

func (*Lifecycle) Add

func (lc *Lifecycle) Add(actor Actor)

Add registers an actor to the lifecycle manager. Actors are started in the order they are added and stopped in reverse order.

func (*Lifecycle) IsStarted

func (lc *Lifecycle) IsStarted() bool

IsStarted returns true if the lifecycle has been started.

func (*Lifecycle) Provide

func (lc *Lifecycle) Provide(ctors ...any) error

Provide registers constructors and tracks all non-error return types for auto-resolution. This overrides the embedded Injector's Provide method to enable auto-resolution of types.

func (*Lifecycle) RequiresReadinessProbe added in v1.1.2

func (lc *Lifecycle) RequiresReadinessProbe() *ReadinessProbe

RequiresReadinessProbe returns the readiness probe for this lifecycle. The probe is signaled when Start completes successfully. This allows parent lifecycles to wait for nested lifecycles to be ready.

func (*Lifecycle) Serve

func (lc *Lifecycle) Serve(ctx context.Context, ctors ...any) (xerr error)

Serve provides a complete lifecycle management solution. It automatically resolves all provided types, starts all actors, monitors long-running services, and ensures proper cleanup.

Process: 1. Automatically resolves all provided types with context support 2. Checks if there are long-running services to monitor 3. Starts all registered actors via internal start logic 4. Sets up automatic cleanup via defer for each started actor 5. Monitors long-running services 6. Returns when any service completes or context is cancelled

The cleanup is guaranteed to run even if any step fails, using defer to ensure each started actor is properly stopped. The ctx parameter controls the long-running monitoring process and can be used to cancel the entire operation.

func (*Lifecycle) Start

func (lc *Lifecycle) Start(ctx context.Context) (xerr error)

Start builds the context and starts the lifecycle.

func (*Lifecycle) WithLogger

func (lc *Lifecycle) WithLogger(logger *slog.Logger) *Lifecycle

WithLogger sets the logger for the lifecycle and returns the Lifecycle instance. This allows for method chaining during initialization.

func (*Lifecycle) WithName

func (lc *Lifecycle) WithName(name string) *Lifecycle

WithName sets the name for the lifecycle. Also updates the readiness probe name.

func (*Lifecycle) WithStop

func (lc *Lifecycle) WithStop(stop func(ctx context.Context) error) *Lifecycle

WithStop is not supported for Lifecycle.

func (*Lifecycle) WithStopEachTimeout

func (lc *Lifecycle) WithStopEachTimeout(timeout time.Duration) *Lifecycle

WithStopEachTimeout sets the timeout duration for stopping each individual actor.

func (*Lifecycle) WithStopTimeout

func (lc *Lifecycle) WithStopTimeout(timeout time.Duration) *Lifecycle

WithStopTimeout sets the global timeout duration for stopping all actors during shutdown.

type Named

type Named interface {
	GetName() string
}

Named defines an optional interface for actors that can provide a human-readable name. This is useful for logging and debugging purposes.

type ReadinessProbe added in v1.1.2

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

ReadinessProbe is a simple readiness probe that can be used to signal when the application is ready to serve traffic.

func NewReadinessProbe added in v1.1.2

func NewReadinessProbe() *ReadinessProbe

NewReadinessProbe creates a new readiness probe.

func (*ReadinessProbe) Done added in v1.1.2

func (rp *ReadinessProbe) Done() <-chan struct{}

Done returns a channel that is closed when the readiness probe is signaled.

func (*ReadinessProbe) Error added in v1.1.2

func (rp *ReadinessProbe) Error() error

Error returns the error that caused the readiness probe to fail, or nil if successful.

func (*ReadinessProbe) GetName added in v1.2.2

func (rp *ReadinessProbe) GetName() string

GetName returns the name of the readiness probe.

func (*ReadinessProbe) Signal added in v1.1.2

func (rp *ReadinessProbe) Signal(err error)

Signal signals the completion of readiness check. Pass nil error to indicate success, or non-nil error to indicate failure.

func (*ReadinessProbe) WithName added in v1.2.2

func (rp *ReadinessProbe) WithName(name string) *ReadinessProbe

WithName sets the name of the readiness probe for logging and debugging.

type RequiresReadinessProbe added in v1.1.2

type RequiresReadinessProbe interface {
	RequiresReadinessProbe() *ReadinessProbe
}

RequiresReadinessProbe is an interface for types that provide a readiness probe. Actors implementing this interface will have their probes collected and waited on during lifecycle startup.

type RequiresStop added in v1.0.2

type RequiresStop interface {
	RequiresStop() bool
}

RequiresStop defines an interface for actors that need cleanup even if their Start method is not called. This is useful for actors that acquire resources during construction and need cleanup regardless of whether Start is called.

type Service

type Service interface {
	Actor
	Done() <-chan struct{} // Signals when the service has completed or failed
	Err() error            // Returns any error that caused the service to stop
}

Service defines the interface for long-running services that can signal completion. Examples: HTTP servers, gRPC servers, message queue consumers, background workers.

type SignalService

type SignalService struct {
	*FuncService
}

SignalService is a specialized service for handling OS signals. This provides a distinct type for dependency injection while reusing FuncService functionality.

func NewSignalService

func NewSignalService(signals ...os.Signal) *SignalService

NewSignalService creates a new SignalService that listens for SIGINT and SIGTERM.

func SetupSignal

func SetupSignal(lc *Lifecycle) *SignalService

SetupSignal creates and registers a signal handling service that listens for SIGINT and SIGTERM. Returns a SignalService that will complete when a signal is received.

func (*SignalService) WithName

func (s *SignalService) WithName(name string) *SignalService

WithName sets the name for the signal service.

func (*SignalService) WithStop

func (s *SignalService) WithStop(stop func(ctx context.Context) error) *SignalService

WithStop is not supported for SignalService.

type Staged added in v1.2.2

type Staged interface {
	GetStage() int
}

Staged defines an optional interface for actors that can specify their execution stage

Jump to

Keyboard shortcuts

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