lifecycle

package
v0.0.0-...-53235be Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 2 Imported by: 0

README

Lifecycle

The lifecycle package provides primitives for managing the lifecycle of application components, standardizing how long-running processes start, run, and stop.

Interfaces

Runnable

Runnable represents a long-running process that blocks until the context is canceled or a fatal error occurs. This is the core interface for the main application loop.

type Runnable interface {
    Run(ctx context.Context) error
}
Lifecycle

Lifecycle represents a component that has distinct start and stop phases. Unlike Runnable, the Start and Stop methods are expected to be non-blocking.

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

Usage

Converting Lifecycle to Runnable

The ToRunnable function adapts a Lifecycle component into a Runnable. This handles the orchestration of starting the component, waiting for the context to be canceled, and then stopping the component.

It ensures that Stop is called even if the application context is canceled, allowing for graceful shutdowns.

type MyService struct{}

func (s *MyService) Start(ctx context.Context) error {
    // Initialize resources...
    return nil
}

func (s *MyService) Stop(ctx context.Context) error {
    // Cleanup resources...
    return nil
}

func main() {
    svc := &MyService{}
    
    // Convert to Runnable with optional timeouts
    runnable := lifecycle.ToRunnable(svc, 
        lifecycle.WithStartTimeout(5*time.Second),
        lifecycle.WithStopTimeout(10*time.Second),
    )

    // Run blocks until context is done or error occurs
    if err := runnable.Run(context.Background()); err != nil {
        log.Fatal(err)
    }
}
Functional Runnable

You can also create a Runnable from a simple function using RunnableFunc:

runnable := lifecycle.RunnableFunc(func(ctx context.Context) error {
    // Do work...
    <-ctx.Done()
    return nil
})
Running Multiple Components

Runnable is designed to work seamlessly with errgroup for managing multiple concurrent processes. If any process returns an error, the context is canceled, triggering a graceful shutdown for all other processes.

func main() {
    g, ctx := errgroup.WithContext(context.Background())

    // List of components to run
    runnables := []lifecycle.Runnable{
        lifecycle.ToRunnable(&HttpServer{}),
        lifecycle.ToRunnable(&WorkerPool{}),
        lifecycle.RunnableFunc(func(ctx context.Context) error {
            // Some other background task
            return nil
        }),
    }

    for _, r := range runnables {
        r := r // capture range variable
        g.Go(func() error {
            return r.Run(ctx)
        })
    }

    if err := g.Wait(); err != nil {
        log.Fatalf("application error: %v", err)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Lifecycle

type Lifecycle interface {
	// Start starts the component.
	// This method must be non-blocking.
	// The context is used for the start operation itself (e.g., timeout), not the application lifecycle.
	Start(ctx context.Context) error

	// Stop stops the component.
	// This method must be non-blocking.
	// The context is used for the stop operation itself (e.g., timeout), not the application lifecycle.
	Stop(ctx context.Context) error
}

Lifecycle represents a component that has a distinct start and stop phase.

type Option

type Option func(*adapter)

Option configures the adapter.

func WithStartTimeout

func WithStartTimeout(timeout time.Duration) Option

WithStartTimeout sets the timeout for the Start operation.

func WithStopTimeout

func WithStopTimeout(timeout time.Duration) Option

WithStopTimeout sets the timeout for the Stop operation.

type Runnable

type Runnable interface {
	// Run starts the process.
	// The context passed to Run is the application lifecycle context.
	// Run must block until the context is canceled or a fatal error occurs.
	Run(ctx context.Context) error
}

Runnable represents a long-running process that blocks until the context is canceled or an error occurs.

func ToRunnable

func ToRunnable(l Lifecycle, opts ...Option) Runnable

ToRunnable converts a Lifecycle to a Runnable. It handles the start and stop sequence, respecting the application lifecycle context.

type RunnableFunc

type RunnableFunc func(ctx context.Context) error

RunnableFunc is a function adapter for the Runnable interface.

func (RunnableFunc) Run

func (f RunnableFunc) Run(ctx context.Context) error

Run calls f(ctx).

Jump to

Keyboard shortcuts

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