component

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 5 Imported by: 0

README

component

Lifecycle-managed components with ordered startup/shutdown, health checks, and lazy initialization.

Install

go get github.com/kbukum/gokit

Quick Start

package main

import (
    "context"
    "fmt"
    "github.com/kbukum/gokit/component"
)

func main() {
    registry := component.NewRegistry()

    // Create a lazy component
    comp := component.NewBaseLazyComponent("cache", func(ctx context.Context) error {
        fmt.Println("initializing cache...")
        return nil
    }).WithHealthCheck(func(ctx context.Context) error {
        return nil // health check logic
    }).WithCloser(func() error {
        fmt.Println("closing cache")
        return nil
    })

    registry.Register(comp)

    ctx := context.Background()
    registry.StartAll(ctx)  // starts in registration order
    defer registry.StopAll(ctx)  // stops in reverse order

    // Check health
    for _, h := range registry.HealthAll(ctx) {
        fmt.Printf("%s: %s\n", h.Name, h.Status)
    }
}

Key Types & Functions

Name Description
Component Interface: Name(), Start(), Stop(), Health()
ComponentHealth Health status with name, status, message
Registry Manages component lifecycle with deterministic ordering
BaseLazyComponent Thread-safe lazy initialization wrapper
NewRegistry() Create component registry
StartAll() / StopAll() / HealthAll() Batch lifecycle operations

⬅ Back to main README

Documentation

Overview

Package component defines the core interfaces for lifecycle-managed infrastructure services in gokit.

Components represent services that require initialization, startup, shutdown, and health monitoring. They are registered with the bootstrap package for automatic lifecycle management.

Interfaces

  • Component: Core lifecycle interface (Init/Start/Stop)
  • HealthChecker: Health status reporting
  • Describable: Bootstrap summary descriptions

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseLazyComponent

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

BaseLazyComponent provides thread-safe lazy initialization for components that defer expensive setup until first use.

func NewBaseLazyComponent

func NewBaseLazyComponent(name string, initializer func(context.Context) error) *BaseLazyComponent

NewBaseLazyComponent creates a lazy component with the given initializer.

func (*BaseLazyComponent) Close

func (b *BaseLazyComponent) Close() error

Close shuts down the component and marks it as uninitialized.

func (*BaseLazyComponent) HealthCheck

func (b *BaseLazyComponent) HealthCheck(ctx context.Context) error

HealthCheck verifies the component is initialized and optionally runs a custom check.

func (*BaseLazyComponent) Initialize

func (b *BaseLazyComponent) Initialize(ctx context.Context) error

Initialize performs thread-safe lazy initialization using double-check locking.

func (*BaseLazyComponent) IsInitialized

func (b *BaseLazyComponent) IsInitialized() bool

IsInitialized returns whether the component has been successfully initialized.

func (*BaseLazyComponent) Name

func (b *BaseLazyComponent) Name() string

Name returns the component name.

func (*BaseLazyComponent) WithCloser

func (b *BaseLazyComponent) WithCloser(fn func() error) *BaseLazyComponent

WithCloser sets a custom close function.

func (*BaseLazyComponent) WithHealthCheck

func (b *BaseLazyComponent) WithHealthCheck(fn func(context.Context) error) *BaseLazyComponent

WithHealthCheck sets a custom health check function.

type Component

type Component interface {
	// Name returns the unique name of the component for registration.
	Name() string

	// Start initializes and starts the component.
	Start(ctx context.Context) error

	// Stop gracefully shuts down the component and releases resources.
	Stop(ctx context.Context) error

	// Health returns the current health status of the component.
	Health(ctx context.Context) Health
}

Component represents a lifecycle-managed infrastructure component. Each infrastructure module (database, redis, kafka, etc.) implements this interface.

type Describable

type Describable interface {
	Describe() Description
}

Describable is optionally implemented by Components to provide startup summary information for the bootstrap display.

When a component implements this interface, the bootstrap system automatically includes it in the infrastructure section of the startup summary — no manual TrackInfrastructure calls needed.

type Description

type Description struct {
	// Name is the human-readable display name (e.g., "HTTP Server", "PostgreSQL").
	// If empty, the component's Name() is used.
	Name string
	// Type categorizes the component: "database", "server", "kafka", "redis", etc.
	Type string
	// Details is a human-readable one-liner shown in the startup summary.
	// Examples: "localhost:5432 pool=25/5", "localhost:6379 db=0 pool=10"
	Details string
	// Port is the primary port, 0 if not applicable.
	Port int
}

Description holds summary information for the bootstrap display. Components that implement Describable return this to self-report what they are and how they're configured.

type Health

type Health struct {
	Name    string       `json:"name"`
	Status  HealthStatus `json:"status"`
	Message string       `json:"message,omitempty"`
}

Health holds health information for a component.

type HealthStatus

type HealthStatus string

HealthStatus represents the health state of a component.

const (
	StatusHealthy   HealthStatus = "healthy"
	StatusUnhealthy HealthStatus = "unhealthy"
	StatusDegraded  HealthStatus = "degraded"
)

type Registry

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

Registry manages component lifecycle with deterministic ordering. Components are started in registration order and stopped in reverse order.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new component registry.

func (*Registry) All

func (r *Registry) All() []Component

All returns all registered components in registration order.

func (*Registry) Get

func (r *Registry) Get(name string) Component

Get returns a registered component by name, or nil if not found.

func (*Registry) HealthAll

func (r *Registry) HealthAll(ctx context.Context) []Health

HealthAll returns health status for all registered components.

func (*Registry) Register

func (r *Registry) Register(c Component) error

Register adds a component to the registry. Components are started in the order they are registered, so register dependencies first.

func (*Registry) StartAll

func (r *Registry) StartAll(ctx context.Context) error

StartAll starts all components in registration order.

func (*Registry) StopAll

func (r *Registry) StopAll(ctx context.Context) error

StopAll gracefully stops all components in reverse registration order.

type Route

type Route struct {
	Method  string
	Path    string
	Handler string
}

Route holds a single HTTP route for the startup summary.

type RouteProvider

type RouteProvider interface {
	Routes() []Route
}

RouteProvider is optionally implemented by server components to auto-report registered HTTP routes for the startup summary.

Jump to

Keyboard shortcuts

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