servicemanager

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 10 Imported by: 0

README

Service manager

service-manager is the framework's in-process supervisor. It owns factory registration, service construction, dependency ordering, readiness gates, retry/failure policy, service-scoped logging, and ordered shutdown. App owns the process-level lifecycle around it; pkg/runner owns signals and the outer deadline. See the architecture overview for how those pieces connect.

Public contract

The required Service contract is deliberately small:

type Service interface {
	Name() string
	Run(ctx context.Context) error
	Stop(ctx context.Context) error
}

Name is the map key for registration, filtering, dependency resolution, and service log scope. Names must be stable enough that a deployment configuration can refer to them through SERVICES_ENABLED.

Run is called in a managed goroutine. It must return when ctx.Done() is closed. A clean return is logged as a clean service exit; a non-nil error goes through retry/failure handling. A panic is recovered and represented as ErrServicePanic so it cannot tear down the process without context.

Stop is called after the manager cancels its run context. It receives a bounded shutdown context and should close resources, not start unbounded work. The manager logs a Stop error but has no return path for it; report only useful errors there and make cleanup idempotent.

Registration is factories, not instances

Register(name, factory) stores a ServiceFactory. It does not construct a service. Run constructs all selected factories; Commands constructs only the service named by the invoked command. That is why constructors should own configuration parsing and client setup, while package initialization should remain side-effect free.

Generated internal/pkg/services/services.gen.go calls Register for each discovered service. It is generation output, not a hand-maintained registry. Use make service-registration after modifying services.

Startup graph

resolveOrder builds a directed graph from Dependent.Dependencies() and topologically sorts it into groups. Every service in a group starts concurrently; group N+1 starts only after group N has been launched and its ready-notifying services have become ready.

database ─┐
cache ────┴─ group 0 (concurrent)
    │
api ──────── group 1
    │
worker ───── group 2

The key distinction:

  • a Dependent relationship orders launch;
  • ReadyNotifier controls when dependents may advance beyond that group.

Without ReadyNotifier, launch is treated as readiness. If api needs a database that is accepting connections—not merely a goroutine that has been scheduled—have database.Ready() return a channel and close it after the connection is established.

Missing dependency names are treated as external to this process: the manager logs a warning and skips that edge. Cycles among registered services return ErrCyclicDependency; zero selected services return ErrNoEnabledServices.

Failure policy

Retryable supplies an attempt budget and delay. The manager calls Run once plus MaxRetries() additional times; it exits a delay early when the context is cancelled. A non-positive delay retries immediately.

After the retry budget is exhausted:

  • an AllowedFailure whose IsAllowedFailure() returns true is logged and allowed to disappear;
  • every other failure is sent as the terminal error for the process.

Only the first terminal failure is delivered. Concurrent later failures are logged rather than blocking on the already-full error channel, because the first failure is already causing application shutdown. This is an intentional anti-deadlock semantic, not lost success information.

Context and logging conventions

The manager scopes every service run, command, registration log, and stop path with ctxscope.Attr("service", service.Name()). Services should keep deriving from the passed context rather than replacing it with context.Background(). That preserves cancellation plus the process-wide binary/commit fields set by cmd/main.go.

Use Add for straightforward registration in tests and AddContext when the registration log needs a caller-provided scope. Both overwrite a prior service with the same name in the in-memory service map; registering duplicate names is therefore a bug in the caller, not a supported way to run two instances.

Stop behavior

Stop cancels the run context once, then walks the resolved start groups in reverse order. It stops each group concurrently and waits for that group before moving to the preceding one. The local per-service timeout is 30 seconds.

In the normal application path, the runner supplies a shorter whole-process deadline (10 seconds by default), so services must respect the passed context promptly. The runner can return on its outer deadline even if a broken Stop implementation ignores cancellation; do not rely on the manager's timer as a way to make non-cooperative cleanup safe.

Testing this package

Tests need singleton isolation. Start each independent scenario by resetting the manager and avoid the generated global registration unless that behavior is the subject under test:

servicemanager.ResetInstance()
manager := servicemanager.GetInstance()
manager.ClearServices()
manager.Add(fakeService)

Use controlled channels for readiness, attempts, and stop observation. Cover both ordering and the absence of readiness: they are different guarantees. Run the suite through make test; the framework test workflow uses Docker and the race detector. See development for the full test/coverage contract.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrServiceNotFound    = errors.New("service not found")
	ErrNoEnabledServices  = errors.New("no enabled services")
	ErrCyclicDependency   = errors.New("cyclic dependency detected")
	ErrDependencyNotFound = errors.New("dependency not found")
	ErrMaxRetriesReached  = errors.New("max retries reached")
	ErrStopTimeout        = errors.New("service stop timed out")
	ErrServicePanic       = errors.New("service panicked")
	ErrNoCommands         = errors.New("service has no commands")
)

Functions

func ResetInstance

func ResetInstance()

Types

type AllowedFailure

type AllowedFailure interface {
	IsAllowedFailure() bool
}

AllowedFailure is optionally implemented by services whose failure should not bring down the entire service manager.

type AllowedFailureMockService

type AllowedFailureMockService struct {
	*MockService
}

func NewAllowedFailureMockService

func NewAllowedFailureMockService(
	name string,
) *AllowedFailureMockService

func (*AllowedFailureMockService) IsAllowedFailure

func (a *AllowedFailureMockService) IsAllowedFailure() bool

type Commander added in v1.0.3

type Commander interface {
	Commands() []*cobra.Command
}

Commander is optionally implemented by services that expose CLI subcommands. The returned commands are added under the service name: ./app <servicename> <subcommand>.

type Dependent

type Dependent interface {
	Dependencies() []string
}

Dependent is optionally implemented by services that must start after other services. Dependencies returns the names of services this service depends on.

type DependentMockService

type DependentMockService struct {
	*MockService
	// contains filtered or unexported fields
}

func NewDependentMockService

func NewDependentMockService(
	name string,
	deps ...string,
) *DependentMockService

func (*DependentMockService) Dependencies

func (d *DependentMockService) Dependencies() []string

type FullMockService

type FullMockService struct {
	*MockService
	// contains filtered or unexported fields
}

func NewFullMockService

func NewFullMockService(name string) *FullMockService

func (*FullMockService) Dependencies

func (f *FullMockService) Dependencies() []string

func (*FullMockService) IsAllowedFailure

func (f *FullMockService) IsAllowedFailure() bool

func (*FullMockService) MaxRetries

func (f *FullMockService) MaxRetries() int

func (*FullMockService) RetryDelay

func (f *FullMockService) RetryDelay() time.Duration

func (*FullMockService) WithAllowFailure

func (f *FullMockService) WithAllowFailure(
	v bool,
) *FullMockService

func (*FullMockService) WithDependencies

func (f *FullMockService) WithDependencies(
	deps ...string,
) *FullMockService

func (*FullMockService) WithMaxRetries

func (f *FullMockService) WithMaxRetries(
	n int,
) *FullMockService

func (*FullMockService) WithRetryDelay

func (f *FullMockService) WithRetryDelay(
	d time.Duration,
) *FullMockService

type MockService

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

func NewMockService

func NewMockService(name string) *MockService

func (*MockService) IsRunning

func (m *MockService) IsRunning() bool

func (*MockService) Name

func (m *MockService) Name() string

func (*MockService) Run

func (m *MockService) Run(ctx context.Context) error

func (*MockService) RunCount

func (m *MockService) RunCount() int

func (*MockService) Stop

func (m *MockService) Stop(_ context.Context) error

func (*MockService) WasRunCalled

func (m *MockService) WasRunCalled() bool

func (*MockService) WasStopCalled

func (m *MockService) WasStopCalled() bool

func (*MockService) WithOnRun

func (m *MockService) WithOnRun(
	fn func(),
) *MockService

func (*MockService) WithRunDelay

func (m *MockService) WithRunDelay(
	delay time.Duration,
) *MockService

func (*MockService) WithRunError

func (m *MockService) WithRunError(
	err error,
) *MockService

func (*MockService) WithRunErrors

func (m *MockService) WithRunErrors(
	errs ...error,
) *MockService

func (*MockService) WithStopError

func (m *MockService) WithStopError(
	err error,
) *MockService

type ReadyMockService added in v1.0.2

type ReadyMockService struct {
	*MockService
	// contains filtered or unexported fields
}

func NewReadyMockService added in v1.0.2

func NewReadyMockService(
	name string,
	deps ...string,
) *ReadyMockService

func (*ReadyMockService) Dependencies added in v1.0.2

func (r *ReadyMockService) Dependencies() []string

func (*ReadyMockService) Ready added in v1.0.2

func (r *ReadyMockService) Ready() <-chan struct{}

func (*ReadyMockService) SignalReady added in v1.0.2

func (r *ReadyMockService) SignalReady()

type ReadyNotifier added in v1.0.2

type ReadyNotifier interface {
	Ready() <-chan struct{}
}

ReadyNotifier is optionally implemented by services that need to signal when they're actually ready to serve. The service manager waits for the Ready channel to close before starting dependent services. Services that don't implement this are considered ready immediately after their goroutine is launched.

type Retryable

type Retryable interface {
	MaxRetries() int
	RetryDelay() time.Duration
}

Retryable is optionally implemented by services that want automatic restart on failure. MaxRetries returns the maximum number of retry attempts (0 means no retries). RetryDelay returns the delay between retries. Use human-readable durations like 1s, 2m, 1h30m via time.Duration.

type RetryableMockService

type RetryableMockService struct {
	*MockService
	// contains filtered or unexported fields
}

func NewRetryableMockService

func NewRetryableMockService(
	name string,
	maxRetries int,
) *RetryableMockService

func (*RetryableMockService) MaxRetries

func (r *RetryableMockService) MaxRetries() int

func (*RetryableMockService) RetryDelay

func (r *RetryableMockService) RetryDelay() time.Duration

func (*RetryableMockService) WithRetryDelay

func (r *RetryableMockService) WithRetryDelay(
	d time.Duration,
) *RetryableMockService

type Service

type Service interface {
	Name() string
	Run(ctx context.Context) error
	Stop(ctx context.Context) error
}

type ServiceFactory added in v1.1.0

type ServiceFactory func() (Service, error)

ServiceFactory is a function that creates a service instance.

type ServiceManager

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

func GetInstance

func GetInstance() *ServiceManager

func (*ServiceManager) Add

func (s *ServiceManager) Add(services ...Service)

func (*ServiceManager) AddContext added in v1.3.0

func (s *ServiceManager) AddContext(ctx context.Context, services ...Service)

AddContext registers services and records their registration in ctx's scope.

func (*ServiceManager) ClearServices

func (s *ServiceManager) ClearServices()

func (*ServiceManager) Commands added in v1.0.3

func (s *ServiceManager) Commands() []*cobra.Command

Commands returns lazy cobra commands for each registered service factory. Each parent command instantiates only its own service when invoked, so ./app <service> <subcommand> doesn't trigger initialization of all services.

func (*ServiceManager) Instantiate added in v1.1.0

func (s *ServiceManager) Instantiate(
	name string,
) (Service, error)

Instantiate creates a single service by calling its factory. Used for Commander commands that need only one service.

func (*ServiceManager) Register added in v1.1.0

func (s *ServiceManager) Register(
	name string,
	factory ServiceFactory,
)

Register stores a service factory for lazy instantiation. The factory is only called when the service is actually needed (during Run or when a Commander command is invoked).

func (*ServiceManager) RegisteredNames added in v1.1.0

func (s *ServiceManager) RegisteredNames() []string

RegisteredNames returns the names of all registered service factories.

func (*ServiceManager) Run

func (s *ServiceManager) Run(ctx context.Context) error

func (*ServiceManager) Stop

func (s *ServiceManager) Stop(ctx context.Context)

type TestService

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

func NewTestService

func NewTestService(name string) *TestService

func (*TestService) Name

func (s *TestService) Name() string

func (*TestService) Run

func (s *TestService) Run(ctx context.Context) error

func (*TestService) Stop

func (s *TestService) Stop(_ context.Context) error

Jump to

Keyboard shortcuts

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