service

package
v0.36.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 27 Imported by: 4 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package service provides ready made github.com/foomo/keel.Service implementations for running HTTP servers, goroutines and message subscriptions under a keel server.

HTTP wraps a net/http.Server; GoRoutine runs a function in one or more goroutines; Subscription runs a goflux.Subscriber. All of them implement Healthz and Close(ctx) error so they double as health probes and closers.

The package also provides constructors for keel's built-in internal HTTP services, each with a NewDefaultHTTPXxx variant using the DefaultHTTPXxx name, address and path variables:

  • NewHealthz: Kubernetes health probes (default :9400/healthz)
  • NewHTTPPrometheus: Prometheus metrics (default :9200/metrics)
  • NewHTTPPProf: pprof profiling (default localhost:6060/debug/pprof)
  • NewHTTPZap: runtime log level control (default localhost:9100/log)
  • NewHTTPViper: runtime configuration access (default localhost:9300/config)
  • NewHTTPReadme: markdown readme (default localhost:9001/readme, deprecated)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrServiceNotRunning is returned by the Healthz methods while a service is
	// not running.
	ErrServiceNotRunning = errors.New("service not running")
	// ErrServiceShutdown is the cancellation cause of a service context canceled
	// by Close.
	ErrServiceShutdown = errors.New("service shutdown")
)
View Source
var (
	DefaultHTTPHealthzName = "healthz"
	DefaultHTTPHealthzAddr = ":9400"
	DefaultHTTPHealthzPath = "/healthz"
)

Default name, address and path of the service returned by NewDefaultHTTPProbes.

View Source
var (
	// ErrUnhandledHealthzProbe is reported for a probe of an unsupported type.
	ErrUnhandledHealthzProbe = errors.New("unhandled healthz probe")
	// ErrProbeFailed is reported when a boolean probe fails on the aggregate path.
	ErrProbeFailed = errors.New("probe failed")
	// ErrLivenessProbeFailed is reported when a boolean liveness probe fails.
	ErrLivenessProbeFailed = errors.New("liveness probe failed")
	// ErrReadinessProbeFailed is reported when a boolean readiness probe fails.
	ErrReadinessProbeFailed = errors.New("readiness probe failed")
	// ErrStartupProbeFailed is reported when a boolean startup probe fails.
	ErrStartupProbeFailed = errors.New("startup probe failed")
)

Errors reported by the health probe handlers.

View Source
var (
	DefaultHTTPPProfName = "pprof"
	DefaultHTTPPProfAddr = "localhost:6060"
	DefaultHTTPPProfPath = "/debug/pprof"
)

Default name, address and path of the service returned by NewDefaultHTTPPProf.

View Source
var (
	DefaultHTTPPrometheusName = "prometheus"
	DefaultHTTPPrometheusAddr = ":9200"
	DefaultHTTPPrometheusPath = "/metrics"
)

Default name, address and path of the service returned by NewDefaultHTTPPrometheus.

View Source
var (
	DefaultHTTPReadmeName = "readme"
	DefaultHTTPReadmeAddr = "localhost:9001"
	DefaultHTTPReadmePath = "/readme"
)

Default name, address and path of the service returned by NewDefaultHTTPReadme.

View Source
var (
	DefaultHTTPViperName = "viper"
	DefaultHTTPViperAddr = "localhost:9300"
	DefaultHTTPViperPath = "/config"
)

Default name, address and path of the service returned by NewDefaultHTTPViper.

View Source
var (
	DefaultHTTPZapName = "zap"
	DefaultHTTPZapAddr = "localhost:9100"
	DefaultHTTPZapPath = "/log"
)

Default name, address and path of the service returned by NewDefaultHTTPZap.

Functions

This section is empty.

Types

type GoRoutine

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

GoRoutine is a service that runs a GoRoutineFn in one or more goroutines until it returns or the service is closed. Create it with NewGoRoutine.

func NewGoRoutine

func NewGoRoutine(l *zap.Logger, name string, handler GoRoutineFn, opts ...GoRoutineOption) *GoRoutine

NewGoRoutine returns a GoRoutine named name that runs handler. A nil l defaults to log.Logger. By default handler runs in a single goroutine.

Example
var once sync.Once
// unset for github actions
_ = os.Setenv("GITHUB_REPOSITORY", "")

svr := keel.NewServer(
	keel.WithLogger(zap.NewExample()),
	keel.WithGracefulPeriod(3*time.Second),
)

svr.AddService(
	service.NewGoRoutine(svr.Logger(), "demo", func(ctx context.Context, l *zap.Logger) error {
		for {
			// handle graceful shutdowns
			if err := ctx.Err(); errors.Is(context.Cause(ctx), service.ErrServiceShutdown) {
				l.Info("context has been canceled du to graceful shutdown")
				return nil
			} else if err != nil {
				return errors.Wrap(err, "unexpected context error")
			}

			l.Info("ping")
			time.Sleep(700 * time.Millisecond)
			once.Do(shutdown)
		}
	}),
)

svr.Run()
Output:
{"level":"info","msg":"starting keel server"}
{"level":"info","msg":"starting keel service","keel_service_type":"goroutine","keel_service_name":"demo"}
{"level":"info","msg":"ping","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0}
{"level":"info","msg":"ping","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0}
{"level":"info","msg":"keel closer closed","keel_graceful_period":3}
{"level":"info","msg":"keel closer closed: closers"}
{"level":"info","msg":"stopping keel service","keel_service_type":"goroutine","keel_service_name":"demo"}
{"level":"info","msg":"context has been canceled du to graceful shutdown","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0}
{"level":"debug","msg":"keel closer closed","keel_closer_type":"*service.GoRoutine"}
{"level":"debug","msg":"keel closer closed","keel_closer_type":"noop.TracerProvider"}
{"level":"debug","msg":"keel closer closed","keel_closer_type":"noop.MeterProvider"}
{"level":"debug","msg":"keel closer closed","keel_closer_type":"noop.LoggerProvider"}
{"level":"info","msg":"keel closer closed: complete"}
{"level":"info","msg":"keel server stopped"}

func (*GoRoutine) Close

func (s *GoRoutine) Close(ctx context.Context) error

Close cancels the handler context with cause ErrServiceShutdown and waits for all goroutines to return, returning the first non-nil handler error. ctx is not used. If called before GoRoutine.Start, Start cancels the handler context immediately.

func (*GoRoutine) Healthz

func (s *GoRoutine) Healthz() error

Healthz returns ErrServiceNotRunning unless GoRoutine.Start is in progress.

func (*GoRoutine) Name

func (s *GoRoutine) Name() string

Name returns the service name.

func (*GoRoutine) Start

func (s *GoRoutine) Start(ctx context.Context) error

Start runs the handler in the configured number of goroutines and blocks until all of them have returned. It returns the first non-nil handler error.

func (*GoRoutine) String

func (s *GoRoutine) String() string

String returns a short description used in the readme.

type GoRoutineFn

type GoRoutineFn func(ctx context.Context, l *zap.Logger) error

GoRoutineFn is the function run by a GoRoutine. ctx is canceled with cause ErrServiceShutdown when the service is closed; l is enriched with the service name and goroutine instance.

type GoRoutineOption

type GoRoutineOption func(*GoRoutine)

GoRoutineOption configures a GoRoutine in NewGoRoutine.

func GoRoutineWithParallel added in v0.30.0

func GoRoutineWithParallel(v int) GoRoutineOption

GoRoutineWithParallel sets the number of goroutines running the handler concurrently. Defaults to 1.

type HTTP

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

HTTP is a service that serves an net/http.Server. Create it with NewHTTP.

func NewDefaultHTTPPProf

func NewDefaultHTTPPProf(l *zap.Logger) *HTTP

NewDefaultHTTPPProf returns NewHTTPPProf using DefaultHTTPPProfName, DefaultHTTPPProfAddr and DefaultHTTPPProfPath.

func NewDefaultHTTPProbes

func NewDefaultHTTPProbes(l *zap.Logger, probes map[healthz.Type][]any) *HTTP

NewDefaultHTTPProbes returns NewHealthz using DefaultHTTPHealthzName, DefaultHTTPHealthzAddr and DefaultHTTPHealthzPath.

func NewDefaultHTTPPrometheus

func NewDefaultHTTPPrometheus(l *zap.Logger) *HTTP

NewDefaultHTTPPrometheus returns NewHTTPPrometheus using DefaultHTTPPrometheusName, DefaultHTTPPrometheusAddr and DefaultHTTPPrometheusPath.

func NewDefaultHTTPReadme deprecated

func NewDefaultHTTPReadme(l *zap.Logger, readmers func() []interfaces.Readmer) *HTTP

NewDefaultHTTPReadme returns NewHTTPReadme using DefaultHTTPReadmeName, DefaultHTTPReadmeAddr and DefaultHTTPReadmePath.

Deprecated: Readme support will be removed in a future release.

func NewDefaultHTTPViper

func NewDefaultHTTPViper(l *zap.Logger) *HTTP

NewDefaultHTTPViper returns NewHTTPViper for config.Config using DefaultHTTPViperName, DefaultHTTPViperAddr and DefaultHTTPViperPath.

func NewDefaultHTTPZap

func NewDefaultHTTPZap(l *zap.Logger) *HTTP

NewDefaultHTTPZap returns NewHTTPZap using DefaultHTTPZapName, DefaultHTTPZapAddr and DefaultHTTPZapPath.

func NewHTTP

func NewHTTP(l *zap.Logger, name, addr string, handler http.Handler, middlewares ...keelhttp.Middleware) *HTTP

NewHTTP returns an HTTP service named name listening on addr and serving handler wrapped in middlewares. See keelhttp.NewServer. A nil l defaults to log.Logger.

func NewHTTPPProf

func NewHTTPPProf(l *zap.Logger, name, addr, path string) *HTTP

NewHTTPPProf returns an HTTP service exposing the net/http/pprof handlers below path. The CPU profile endpoint is served by Pyroscope's pprof handler.

func NewHTTPPrometheus

func NewHTTPPrometheus(l *zap.Logger, name, addr, path string) *HTTP

NewHTTPPrometheus returns an HTTP service exposing the metrics of prometheus.DefaultGatherer on path, with OpenMetrics enabled.

func NewHTTPReadme deprecated

func NewHTTPReadme(l *zap.Logger, name, addr, path string, readmers func() []interfaces.Readmer) *HTTP

NewHTTPReadme returns an HTTP service that responds to GET requests on path with the concatenated markdown of the readmers returned by readmers.

Deprecated: Readme support will be removed in a future release.

func NewHTTPViper

func NewHTTPViper(l *zap.Logger, c *viper.Viper, name, addr, path string) *HTTP

NewHTTPViper returns an HTTP service exposing c on path. GET responds with all settings as JSON; PUT sets a single value from a {"key": ..., "value": ...} JSON body.

func NewHTTPZap

func NewHTTPZap(l *zap.Logger, name, addr, path string) *HTTP

NewHTTPZap returns an HTTP service controlling the global logger on path. GET responds with the level, disableCaller and disableStacktrace settings as JSON; PUT updates any of them from a JSON body of the same shape and responds with the resulting settings.

func NewHealthz

func NewHealthz(l *zap.Logger, name, addr, path string, probes map[healthz.Type][]any) *HTTP

NewHealthz returns an HTTP service serving health checks for probes:

Each endpoint responds 200 OK when all probes pass and 503 Service Unavailable at the first failing probe. probes is read on every request, so probes added to the map later are included.

func (*HTTP) Close

func (s *HTTP) Close(ctx context.Context) error

Close gracefully shuts down the server, bounded by ctx.

func (*HTTP) Healthz

func (s *HTTP) Healthz() error

Healthz returns ErrServiceNotRunning unless the server is listening.

func (*HTTP) Name

func (s *HTTP) Name() string

Name returns the service name.

func (*HTTP) Server added in v0.18.0

func (s *HTTP) Server() *http.Server

Server returns the underlying HTTP server.

func (*HTTP) Start

func (s *HTTP) Start(ctx context.Context) error

Start listens on the configured address and serves requests with ctx as the base request context, blocking until the server is shut down. It returns an error if the address cannot be bound or serving fails; a graceful shutdown returns nil.

func (*HTTP) String

func (s *HTTP) String() string

String returns a short description of the handler type and address used in the readme.

type Subscription added in v0.24.0

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

Subscription is a service that manages the lifecycle of a goflux subscriber. Create it with NewSubscription.

func NewSubscription added in v0.24.0

func NewSubscription[T any](
	l *zap.Logger,
	name string,
	subscriber goflux.Subscriber[T],
	subject string,
	handler goflux.Handler[T],
	opts ...SubscriptionOption[T],
) *Subscription[T]

NewSubscription returns a Subscription named name that subscribes subscriber to subject with handler. A nil l defaults to log.Logger.

func (*Subscription[T]) Close added in v0.24.0

func (s *Subscription[T]) Close(ctx context.Context) error

Close cancels the subscription context with cause ErrServiceShutdown, closes the subscriber (logging a failure) and waits for the subscription to end. ctx is not used. If called before Subscription.Start, Start cancels the subscription context immediately.

func (*Subscription[T]) Healthz added in v0.24.0

func (s *Subscription[T]) Healthz() error

Healthz returns ErrServiceNotRunning unless Subscription.Start is in progress.

func (*Subscription[T]) Name added in v0.24.0

func (s *Subscription[T]) Name() string

Name returns the service name.

func (*Subscription[T]) Start added in v0.24.0

func (s *Subscription[T]) Start(ctx context.Context) error

Start subscribes to the subject and blocks until the subscription ends, returning the error from the subscriber.

func (*Subscription[T]) String added in v0.24.0

func (s *Subscription[T]) String() string

String returns a short description of the subject used in the readme.

type SubscriptionOption added in v0.24.0

type SubscriptionOption[T any] func(*Subscription[T])

SubscriptionOption configures a Subscription in NewSubscription.

Directories

Path Synopsis
threephase module

Jump to

Keyboard shortcuts

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