touchhttp

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2024 License: Apache-2.0 Imports: 13 Imported by: 5

Documentation

Overview

Package touchhttp defines the HTTP-specific behavior for metrics within an uber/fx app which uses the touchstone package.

Bootstrapping is similar to touchstone: A Config object can be available in the enclosing fx.App that will tailor certain aspects of the metrics http.Handler.

ServerBundle and ClientBundle are prebaked, opinionated metrics for instrumenting HTTP servers and clients. They each produce middleware given a label for a particular server or client.

Example

Output:

Index

Examples

Constants

View Source
const (
	// DefaultServerCount is the default name of the counter that tracks the
	// total number of received server requests.
	DefaultServerCount = "server_request_count"

	// DefaultServerDuration is the default name of the observer that tracks
	// the total time taken by handlers to process requests.
	DefaultServerDuration = "server_request_duration_ms"

	// DefaultServerInFlight is the default name of the gauge that tracks the
	// instantaneous view of how many requests the handler is currently serving.
	DefaultServerInFlight = "server_requests_in_flight"

	// DefaultServerRequestSize is the default name of the observer that tracks the sizes
	// of requests received by handlers.
	DefaultServerRequestSize = "server_request_size"

	// DefaultClientCount is the default name of the counter that tracks the
	// total number of outgoing server requests.
	DefaultClientCount = "client_request_count"

	// DefaultClientDuration is the default name of the observer that tracks
	// the total time taken to send a request and receive a response.
	DefaultClientDuration = "client_request_duration_ms"

	// DefaultClientInFlight is the default name of the gauge that tracks the
	// instantaneous view of how many requests the client has currently pending.
	DefaultClientInFlight = "client_requests_in_flight"

	// DefaultClientRequestSize is the default name of the observer that tracks the sizes
	// of requests sent to servers.
	DefaultClientRequestSize = "client_request_size"

	// DefaultClientErrorCount is the default name of the count of total number of errors
	// (nil responses) that occurred since startup.
	DefaultClientErrorCount = "client_error_count"
)
View Source
const (
	// HTTPErrorOnError is the value allowed for Config.ErrorHandling that maps
	// to promhttp.HTTPErrorOnError.  This is also the default used when no
	// value is set.
	HTTPErrorOnError = "http"

	// ContinueOnError is the value allowed for Config.ErrorHandler that maps
	// to promhttp.ContinueOnError.
	ContinueOnError = "continue"

	// PanicOnError is the value allowed for Config.ErrorHandler that maps
	// to promhttp.PanicOnError.
	PanicOnError = "panic"
)
View Source
const (
	// CodeLabel is the metric label containing the HTTP response code.
	CodeLabel = "code"

	// MethodLabel is the metric label containing the HTTP request's method.
	MethodLabel = "method"

	// ServerLabel is the canonical metric label name containing the name of the HTTP server.
	// This label is not automatically supplied.
	ServerLabel = "server"

	// ClientLabel is the canonical metric label name containing the name of the HTTP client.
	// This label is not automatically supplied.
	ClientLabel = "client"

	// MethodUnrecognized is used when an HTTP method is not one of the
	// standard methods, as enumerated in the net/http package.
	MethodUnrecognized = "UNRECOGNIZED"
)

Variables

View Source
var (
	// ErrReservedLabelName indicates that labels supplied to build an instrumenter
	// had one or more reserved label names.
	ErrReservedLabelName = fmt.Errorf(
		"%s and %s are reserved label names and are supplied automatically",
		CodeLabel,
		MethodLabel,
	)

	// ErrInvalidLabelCount indicates that an odd number of name/value pairs were
	// passed when creating metrics.
	ErrInvalidLabelCount = errors.New("The number of label names and values must be even")
)

Functions

func NewHandlerOpts

func NewHandlerOpts(cfg Config, p fx.Printer, r prometheus.Registerer) (opts promhttp.HandlerOpts, err error)

NewHandlerOpts creates a basic HandlerOpts from an Config configuration.

func NewServerInstrumenter added in v0.1.2

func NewServerInstrumenter(namesAndValues ...string) func(ServerInstrumenterIn) (ServerInstrumenter, error)

NewServerInstrumenter produces a constructor that can be passed to fx.Provide. The returned constructor allows a ServerBundle to be injected.

Use this function when a ServerBundle has been supplied to the enclosing fx.App:

app := fx.New(
  touchstone.Provide(), // bootstrap metrics subsystem

  fx.Provide(
    // A single, global ServerInstrumenter
    touchhttp.NewServerInstrumenter(),

    // A custom label
    touchhttp.NewServerInstrumenter(
      "custom1", "value",
    ),

    // A named ServerInstrumenter with a server label
    fx.Annotated{
      Name: "servers.main",
      Target: NewServerInstrumenter(
        touchhttp.ServerLabel, "servers.main",
      ),
    },
  ),
)

func Provide

func Provide() fx.Option

Provide bootstraps the promhttp environment for an uber/fx app. This function creates the following component types:

  • promhttp.HandlerOpts
  • touchhttp.Handler This is the http.Handler to use to serve prometheus metrics. It will be instrumented if Config.InstrumentMetricHandler is set to true.

Types

type ClientBundle

type ClientBundle struct {
	// Count describes the options used for the total request counter
	Count prometheus.CounterOpts

	// InFlight describes the options used for the instaneous request gauge
	InFlight prometheus.GaugeOpts

	// RequestSize describes the options for the request size observer.  A panic
	// will result if this field is not nil, a prometheus.HistogramOpts, or
	// a prometheus.SummaryOpts.
	RequestSize interface{}

	// Duration describes the options for the request duration observer.  A panic
	// will result if this field is not either a prometheus.HistogramOpts or a prometheus.SummaryOpts.
	Duration interface{}

	// ErrorCount describes the options for the error counter.
	ErrorCount prometheus.CounterOpts

	// Now is the strategy for extracting the current system time.  If unset,
	// time.Now is used.
	Now func() time.Time
}

func (ClientBundle) NewInstrumenter added in v0.1.2

func (cb ClientBundle) NewInstrumenter(namesAndValues ...string) func(*touchstone.Factory) (ClientInstrumenter, error)

NewInstrumenter creates a constructor that can be passed to fx.Provide. The returned constructor creates a ClientInstrumenter given a *touchstone.Factory.

Similar typical usage to ServerBundle.NewInstrumenter:

app := fx.New(
  touchstone.Provide(), // bootstraps the metrics environment

  fx.Provide(
    // Create a single, unnamed ClientInstrumenter with no extra labels
    touchhttp.ClientBundle{}.NewInstrumenter(),

    // Create a named ClientInstrumenter with a label identifying a particular client
    fx.Annotated{
      Name: "clients.main",
      Target: touchhttp.ClientBundle{}.NewInstrumenter(
        touchhttp.ClientLabel, "clients.main",
      ),
    },
  ),
)

type ClientInstrumenter

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

ClientInstrumenter is a clientside middleware that provides HTTP client metrics.

func (ClientInstrumenter) Then

Then is a client middleware that instruments the given client. This middleware is compatible with httpaux.

type Config

type Config struct {
	// ErrorHandling is the promhttp.HandlerErrorHandling value.  If this field
	// is unset, promhttp.HTTPErrorOnError is used.
	//
	// See: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#HandlerErrorHandling
	ErrorHandling string `json:"errorHandling" yaml:"errorHandling"`

	// DisableCompression disables compression on metrics output.
	DisableCompression bool `json:"disableCompression" yaml:"disableCompression"`

	// MaxRequestsInFlight controls the number of concurrent HTTP metrics requests.
	MaxRequestsInFlight int `json:"maxRequestsInFlight" yaml:"maxRequestsInFlight"`

	// Timeout is the time period after which the handler will return a 503.
	Timeout time.Duration `json:"timeout" yaml:"timeout"`

	// EnableOpenMetrics controls whether open metrics encoding is available
	// during content negotiation.
	EnableOpenMetrics bool `json:"enableOpenMetrics" yaml:"enableOpenMetrics"`

	// InstrumentMetricHandler indicates whether the http.Handler that renders
	// prometheus metrics will itself be decorated with metrics.
	//
	// See: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#InstrumentMetricHandler
	InstrumentMetricHandler bool `json:"instrumentMetricHandler" yaml:"instrumentMetricHandler"`
}

Config is the configuration for boostrapping the promhttp package.

type ErrorPrinter

type ErrorPrinter struct {
	fx.Printer
}

ErrorPrinter adapts an fx.Printer and allows it to be used as an error Logger for prometheus.

func (ErrorPrinter) Println

func (ep ErrorPrinter) Println(values ...interface{})

Println satisfies the promhttp.Logger interface.

type Handler

type Handler http.Handler

Handler is a type alias for http.Handler that makes dependency injection easier. The handler bootstrapped by this package will be of this type, which means injection by type will not interfere with any other http.Handler component in the application.

The promhttp.HandlerFor function is used to create this type using the handler options created from the Config type.

See: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#HandlerFor

type In

type In struct {
	fx.In

	// Config is the prometheus configuration.  This is optional,
	// as a zero value for Config will result in a default environment.
	Config Config `optional:"true"`

	// Printer is the fx.Printer to which this package writes messages.
	// This is optional, and if unset no messages are written.
	Printer fx.Printer `optional:"true"`

	// Now is the optional current time function.  If supplied, this
	// will be used for computing metric durations.
	Now func() time.Time `optional:"true"`
}

In represents the components used by this package to bootstrap a promhttp environment. Provide uses these components.

type InvalidErrorHandlingError

type InvalidErrorHandlingError struct {
	// Value is the unrecognized Config.ErrorHandling value.
	Value string
}

InvalidErrorHandlingError is the error returned when Config.ErrorHandling is not a recognized value.

func (*InvalidErrorHandlingError) Error

func (e *InvalidErrorHandlingError) Error() string

Error satisfies the error interface.

type Labels added in v0.1.0

type Labels prometheus.Labels

Labels is a convenient extension for a prometheus.Labels that adds support for the reserved and de facto labels in this package.

The zero value for this map is usable with any of its methods.

func NewLabels added in v0.1.0

func NewLabels(code int, method string) Labels

NewLabels creates a touchhttp Labels with code and method set appropriately.

func (*Labels) SetClient added in v0.1.0

func (l *Labels) SetClient(v string)

SetClient updates this set of Labels with the given client name.

func (*Labels) SetCode added in v0.1.0

func (l *Labels) SetCode(v int)

SetCode updates this set of Labels with the given HTTP status code Passing a value outside the range of valid HTTP response code values (e.g. zero) means http.StatusOK.

func (*Labels) SetMethod added in v0.1.0

func (l *Labels) SetMethod(v string)

SetMethod updates this set of Labels with the given HTTP method. Any unrecognized methods result in MethodUnrecognized.

func (*Labels) SetServer added in v0.1.0

func (l *Labels) SetServer(v string)

SetServer updates this set of Labels with the given server name.

type ServerBundle

type ServerBundle struct {
	// Count describes the options used for the total request counter
	Count prometheus.CounterOpts

	// InFlight describes the options used for the instaneous request gauge
	InFlight prometheus.GaugeOpts

	// RequestSize describes the options for the request size observer.  If this
	// field is set, it must be either a prometheus.HistogramOpts or a prometheus.SummaryOpts.
	// The type of Opts struct will determine the type of metric created.
	RequestSize interface{}

	// Duration describes the options for the request duration observer.  If this field is
	// set, it must be either a prometheus.HistogramOpts or a prometheus.SummaryOpts.
	// The type of Opts struct will determine the type of metric created.
	Duration interface{}

	// Now is the strategy for extracting the current system time.  If unset,
	// time.Now is used.
	Now func() time.Time
}

func (ServerBundle) NewInstrumenter added in v0.1.2

func (sb ServerBundle) NewInstrumenter(namesAndValues ...string) func(*touchstone.Factory) (ServerInstrumenter, error)

NewInstrumenter creates a constructor that can be passed to fx.Provide or annotated as needed.

The namesAndValues are any extra, curried labels to apply to all the created metrics. If multiple calls to this method on the same ServerBundle instance are made, the extra label names must match though the values may differ.

If namesAndValues contatins and odd number of entries or if it contains any of the reserved label names used by this package, and error is returned by the returned constructor.

Typical usage:

app := fx.New(
  touchstone.Provide(), // bootstraps the metrics environment

  fx.Provide(
    // Create a single, unnamed ServerInstrumenter with no extra labels
    touchhttp.ServerBundle{}.NewInstrumenter(),

    // Create a named ServerInstrumenter with a label identifying a particular server
    fx.Annotated{
      Name: "servers.main",
      Target: touchhttp.ServerBundle{}.NewInstrumenter(
        touchhttp.ServerLabel, "servers.main",
      ),
    },
  ),
)

type ServerInstrumenter

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

ServerInstrumenter is a serverside middleware that provides http.Handler metrics.

func (ServerInstrumenter) Then

func (si ServerInstrumenter) Then(next http.Handler) http.Handler

Then is a server middleware that instruments the given handler. This middleware is compatible with justinas/alice and gorilla/mux.

type ServerInstrumenterIn added in v0.1.2

type ServerInstrumenterIn struct {
	fx.In

	// Factory is the required touchstone Factory instance.
	Factory *touchstone.Factory

	// Bundle is the optional ServerBundle supplied in the application.
	// If not present, the default metrics are used.
	Bundle ServerBundle `optional:"true"`
}

ServerInstrumenterIn defines the set of dependencies required to build a ServerInstrumenter.

Jump to

Keyboard shortcuts

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