healthy

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2025 License: MIT Imports: 10 Imported by: 0

README

healthy

build codecov Go Report Card

healthy provides a simple mechanism to check the health of dependencies and wait for them to become available. While fundamentally an excuse to explore synctest.Test introduced in Go 1.25 the module can simplify dependency checking in non-production scenarios such as local docker compose setups.

Getting Started

go get github.com/stevecallear/healthy@latest
err := healthy.Wait(healthy.HTTP("http://dependency:8080/healthy").Expect(http.StatusOK))

Checks

Healthy includes checks for TCP, HTTP and files. Additional checks can be added by implementing Check or providing a CheckFunc.

Metadata

Check metadata can be provided by implementing MetadataCheck or wrapping a CheckFunc with WithMetadata.

c := healthy.WithMetadata(func(ctx context.Context) error {
    // implement check
}, "type", "custom", "target", "something")

Execution

While checks can be executed directly by calling check.Healthy, they are intended to be executed as a group with multiple attempts using healthy.New(checks...).Wait(). Wait accepts a number of execution options relating to context, timeout and delay. Checks are executed until either context cancellation or timeout, specified via WithContext or WithTimeout respectively.

WithCallback accepts a callback function that is invoked for each check execution and error. The following example logs the result using slog:

healthy.Wait(
    healthy.TCP("host:8080"),
    healthy.WithCallback(func(ctx context.Context, err error) {
        args := []any{}
        for k, v := range healthy.GetContextMetadata(ctx) {
            args = append(args, k, v)
        }

        level := slog.LevelInfo
        if err != nil {
            level = slog.LevelError
            args = append(args, "err", err)
        }

        slog.Log(ctx, level, "health check result", args...)  
    }),
)

Parallel Checks

The initial implementation of the module allowed multiple checks to be executed in parallel. While convenient, this created a confused API and limited configuration for what was effectively a wrapper over errgroup.Group.

If parallel check execution is desired, then it is trivial (if a bit more verbose) to execute them using errgroup:

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

opts := healthy.JoinOptions(
    healthy.WithContext(ctx),
    healthy.WithCallback(callback),
)

g.Go(func() error {
    return healthy.Wait(healthy.TCP("host:8080"), opts)
})
g.Go(func() error {
    return healthy.Wait(healthy.HTTP("http://dependency:8080/health"), opts)
})

err := g.Wait()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fatal

func Fatal(err error) error

Fatal wraps the supplied error to indicate that it is fatal. When a check returns a fatal error retry execution will be aborted.

func IsFatal

func IsFatal(err error) bool

IsFatal returns true if the supplied error is fatal.

func SetContextMetadata added in v0.4.0

func SetContextMetadata(ctx context.Context, m Metadata) context.Context

SetContextMetadata stores the supplied Metadata in the context.

func Wait added in v0.4.0

func Wait(c Check, opts ...Option) error

Wait executes the check using the supplied options. Checks are retried until successful execution or option limits are reached.

Types

type CallbackFunc

type CallbackFunc func(ctx context.Context, err error)

CallbackFunc represents an execution callback function. The function is invoked on each health check invocation.

type Check

type Check interface {
	Healthy(ctx context.Context) error
}

Check represents a health check.

type CheckFunc

type CheckFunc func(ctx context.Context) error

CheckFunc represents a health check function.

func (CheckFunc) Healthy added in v0.3.0

func (c CheckFunc) Healthy(ctx context.Context) error

Healthy should return nil if the health check is successful.

type HTTPCheck

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

HTTPCheck represents an HTTP health check.

func HTTP

func HTTP(url string) *HTTPCheck

HTTP returns an HTTP health check.

func (*HTTPCheck) Expect

func (c *HTTPCheck) Expect(statusCode int) *HTTPCheck

Expect specifies the expected status code.

func (*HTTPCheck) Healthy

func (c *HTTPCheck) Healthy(ctx context.Context) error

Healthy returns true if the target URL returns the expected status code.

func (*HTTPCheck) Metadata added in v0.4.0

func (c *HTTPCheck) Metadata() Metadata

Metadata returns the check metadata.

func (*HTTPCheck) Timeout

func (c *HTTPCheck) Timeout(t time.Duration) *HTTPCheck

Timout specifies the HTTP client timeout.

type Metadata added in v0.4.0

type Metadata map[string]any

Metadata represents check metadata.

func GetContextMetadata added in v0.4.0

func GetContextMetadata(ctx context.Context) Metadata

GetContextMetadata returns the Metadata stored in the .

func (Metadata) Get added in v0.4.0

func (m Metadata) Get(key string) any

Get gets the metadata value.

func (Metadata) Set added in v0.4.0

func (m Metadata) Set(key string, value any)

Set sets the metadata key/value.

type MetadataCheck added in v0.4.0

type MetadataCheck interface {
	Check
	Metadata() Metadata
}

Metadata represents a check that has metadata.

func File

func File(path string) MetadataCheck

File returns a file health check. The check returns nil if the file exists.

func WithMetadata added in v0.4.0

func WithMetadata(fn CheckFunc, pairs ...any) MetadataCheck

WithMetadata wraps the CheckFunc with the supplied metadata. Metadata should be specified in key/value pairs. The function will panic if the pairs are invalid.

type Option

type Option func(*options)

Option represents an execution option.

func JoinOptions added in v0.4.2

func JoinOptions(opts ...Option) Option

JoinOptions joins the specified options to simplify re-use.

func WithCallback

func WithCallback(fn CallbackFunc) Option

WithCallback specifies the callback function to be invoked after check execution.

func WithContext

func WithContext(ctx context.Context) Option

WithContext uses the supplied context for check execution. This allows alternative context cancellations to be specified.

func WithDelay

func WithDelay(d time.Duration) Option

WithDelay specifies the retry delay between check executions. The default value is one second.

func WithJitter

func WithJitter(j time.Duration) Option

WithJitter specifies an optional maximum jitter to apply to the delay. The default value is no jitter.

func WithTimeout

func WithTimeout(t time.Duration) Option

WithTimeout specifies the retry execution timeout. Retry execution will be cancelled either on the cancellation of a supplied context or after the timeout has elapsed. The default value is 30 seconds.

type TCPCheck

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

TCPCheck represents a TCP health check.

func TCP

func TCP(addr string) *TCPCheck

TCP returns a TCP health check.

func (*TCPCheck) Healthy

func (c *TCPCheck) Healthy(ctx context.Context) error

Healtyh returns nil if a TCP connection can be established with the target address.

func (*TCPCheck) Metadata added in v0.4.0

func (c *TCPCheck) Metadata() Metadata

Metadata retuns the check metadata.

func (*TCPCheck) Timeout

func (c *TCPCheck) Timeout(t time.Duration) *TCPCheck

Timeout species the TCP dial timeout

Jump to

Keyboard shortcuts

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