deps

package
v0.6.70 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 20 Imported by: 5

Documentation

Overview

Package deps is how a service is composed: a tree of components, dependencies and singletons built explicitly by the author's constructor. Every node is a Scope with its own name, logger and instrumentation.

Nodes start depth-first in creation order and stop in exact reverse, so a component (and its goroutines) always stops before the dependencies it was given. Create nodes before Run; a dependency may create child nodes while it is being provided.

It does not depend on the backplane package, so contrib providers need only this one.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotReady: the dependency has not been provided (yet).
	ErrNotReady = errors.New("deps: not ready")
	// ErrClosed: the node has stopped.
	ErrClosed = errors.New("deps: closed")
)

Errors.

Functions

func SpanValue

func SpanValue[T any](
	ctx context.Context, s Scope, name string, fn func(ctx context.Context) (T, error), opts ...xtrace.SpanOption,
) (T, error)

SpanValue runs fn in a span of s and returns its value.

Types

type Component

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

Component is a named node of the author's code. Embed it:

type UserRepo struct {
    deps.Component
    pool deps.Dependency[*pgxpool.Pool]
}

A zero Component logs nowhere and traces nothing; hooking it into the lifecycle panics.

func NewComponent

func NewComponent(parent Scope, name string) Component

NewComponent creates a component under parent.

func (Component) Go

func (c Component) Go(fn func(ctx context.Context) error)

Go runs fn under the component's lifecycle.

func (Component) IsZero

func (c Component) IsZero() bool

IsZero reports whether c was not created by NewComponent.

func (Component) Log

func (c Component) Log() *xlog.Logger

Log is the component's logger.

func (Component) Meter

func (c Component) Meter() metric.Meter

Meter of the component.

func (Component) Name

func (c Component) Name() string

Name of the component.

func (Component) OnStart

func (c Component) OnStart(fn func(ctx context.Context) error)

OnStart hooks fn into the component's start.

func (Component) OnStop

func (c Component) OnStop(fn func(ctx context.Context) error)

OnStop hooks fn into the component's stop.

func (Component) Path

func (c Component) Path() string

Path of the component in the tree.

func (Component) Span

func (c Component) Span(
	ctx context.Context, name string, fn func(ctx context.Context) error, opts ...xtrace.SpanOption,
) error

Span runs fn in a span named name.

func (Component) Tracer

func (c Component) Tracer() trace.Tracer

Tracer of the component.

type Dependency

type Dependency[T any] struct {
	// contains filtered or unexported fields
}

Dependency is a required external resource: provided when its node starts (the start retries until it succeeds), part of readiness through its probe, closed at stop. Public and internal traffic starts only after every required dependency is ready and stops before they close, so Get always holds the value where handlers run.

func NewDependency

func NewDependency[T any](parent Scope, p Provider[T], opts ...Option) Dependency[T]

NewDependency adds a required dependency under parent: the start waits for it, retrying with backoff.

func Static

func Static[T any](v T) Dependency[T]

Static is a dependency that is always ready with v: tests, and values the service owns itself.

func (Dependency[T]) Err

func (d Dependency[T]) Err() error

Err is why the dependency is not ready; nil when it is.

func (Dependency[T]) Get

func (d Dependency[T]) Get() T

Get returns the value. It is set wherever handlers run: they are served only while every required dependency is ready.

func (Dependency[T]) IsZero

func (d Dependency[T]) IsZero() bool

IsZero reports whether d was not created by NewDependency or Static.

func (Dependency[T]) Ready

func (d Dependency[T]) Ready() bool

Ready reports whether the value is provided.

type DependencyOption

type DependencyOption interface {
	Option
	OptionalOption
}

DependencyOption applies to required and optional dependencies.

func Backoff

func Backoff(minDelay, maxDelay time.Duration) DependencyOption

Backoff bounds the delay between provide attempts (default 1s..30s, jittered). It panics unless 0 < minDelay <= maxDelay.

func ProbeTimeout

func ProbeTimeout(d time.Duration) DependencyOption

ProbeTimeout bounds one probe (default: the service's health timeout for a required dependency, its health interval under ProbeOptional). It panics unless d > 0.

func ProvideTimeout

func ProvideTimeout(d time.Duration) DependencyOption

ProvideTimeout bounds one provide attempt (default 30s); a timed-out attempt is retried like a failed one. The context Provide gets ends with the attempt: a provider must not keep it. It panics unless d > 0.

type Factory

type Factory[T any] interface {
	Name() string
	Provide(ctx context.Context, s Scope) (T, error)
	Close(ctx context.Context, v T) error
}

Factory builds a singleton: a Provider without a probe.

type FuncOption

type FuncOption[T any] func(*funcProvider[T])

FuncOption configures Func.

func WithClose

func WithClose[T any](closeFn func(ctx context.Context, v T) error) FuncOption[T]

WithClose sets how the value is released.

func WithProbe

func WithProbe[T any](probe func(ctx context.Context, v T) error) FuncOption[T]

WithProbe sets the readiness probe.

type NameOption

type NameOption interface {
	Option
	OptionalOption
	SingletonOption
}

NameOption applies to dependencies and singletons.

func Name

func Name(name string) NameOption

Name overrides the provider's name: two databases of one kind.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures NewDependency.

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional is a dependency the service works without: provided in the background with retries, never part of readiness. Get reports whether it is there right now: provided and, with ProbeOptional, passing its probe.

func NewOptional

func NewOptional[T any](parent Scope, p Provider[T], opts ...OptionalOption) Optional[T]

NewOptional adds an optional dependency under parent: the start does not wait; providing retries in the background until it succeeds or the service stops. With ProbeOptional it is then probed periodically.

func StaticOptional

func StaticOptional[T any](v T) Optional[T]

StaticOptional is an optional dependency that is present with v; the zero Optional is one that is absent.

func (Optional[T]) Err

func (o Optional[T]) Err() error

Err is why the dependency is absent; nil when it is there.

func (Optional[T]) Get

func (o Optional[T]) Get() (T, bool)

Get returns the value and whether it is there right now.

func (Optional[T]) IsZero

func (o Optional[T]) IsZero() bool

IsZero reports whether o was not created by NewOptional or StaticOptional (an absent dependency).

type OptionalOption

type OptionalOption interface {
	// contains filtered or unexported methods
}

OptionalOption configures NewOptional.

func ProbeOptional

func ProbeOptional() OptionalOption

ProbeOptional probes a provided optional dependency every health interval of the service: while its probe fails, Get reports it absent and Err says why; the value is kept and comes back when the probe passes. It never enters readiness.

type Provider

type Provider[T any] interface {
	// Name is the node name, e.g. "postgres".
	Name() string
	Provide(ctx context.Context, s Scope) (T, error)
	// Probe is part of readiness while the dependency is required.
	Probe(ctx context.Context, v T) error
	Close(ctx context.Context, v T) error
}

Provider builds and serves a dependency. Contrib packages implement it once per library (config section, instrumentation, ping, close).

func Func

func Func[T any](provide func(ctx context.Context) (T, error), opts ...FuncOption[T]) Provider[T]

Func adapts plain functions into a Provider (and so a Factory). The node is named after T ("pool" for *pgxpool.Pool); rename it with deps.Name.

type Scope

type Scope interface {
	// Name of the node; Path is its place in the tree ("users/templates").
	Name() string
	Path() string
	// Log carries node=<path>.
	Log() *xlog.Logger
	Tracer() trace.Tracer
	Meter() metric.Meter
	// Span runs fn in a span of this node's tracer.
	Span(ctx context.Context, name string, fn func(ctx context.Context) error, opts ...xtrace.SpanOption) error
	// Go runs fn once the node has started, on a context cancelled when the
	// node stops; the stop waits for it. An error stops the service.
	Go(fn func(ctx context.Context) error)
	// OnStart and OnStop hook the node into the lifecycle. Stop hooks run
	// in reverse and must tolerate a start that failed half way.
	OnStart(fn func(ctx context.Context) error)
	OnStop(fn func(ctx context.Context) error)
	// contains filtered or unexported methods
}

Scope is a node of the service tree.

type Singleton

type Singleton[T any] struct {
	// contains filtered or unexported fields
}

Singleton is built on first Get and closed at stop if it was built. It is not part of readiness. Its factory must not create child nodes: it runs after the service started.

func NewSingleton

func NewSingleton[T any](parent Scope, f Factory[T], opts ...SingletonOption) Singleton[T]

NewSingleton adds a singleton under parent.

func (Singleton[T]) Get

func (s Singleton[T]) Get(ctx context.Context) (T, error)

Get builds the value once; a failed build is retried by the next Get. After stop it returns ErrClosed.

Get holds the singleton's lock while the factory runs: concurrent Gets wait for that one build and get its value (or, if it failed, try their own in turn), so a factory runs at most once at a time. A waiting Get does not watch its own ctx — a slow factory delays every caller, and the stop waits for a build under way before it closes the value; bound the factory with the ctx it is given.

func (Singleton[T]) IsZero

func (s Singleton[T]) IsZero() bool

IsZero reports whether s was not created by NewSingleton.

type SingletonOption

type SingletonOption interface {
	// contains filtered or unexported methods
}

SingletonOption configures NewSingleton.

Jump to

Keyboard shortcuts

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