client

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2022 License: MIT Imports: 11 Imported by: 3

Documentation

Overview

Package client provides a standard way of writing API clients. It's meant to be a drop-in replacement for an HTTPClient. Currently, it supports a way of generating Prometheus metrics when performing API calls, and a means of caching API responses for one or more endpoints.

InstrumentedClient generates Prometheus metrics when performing API calls. Currently, latency and errors are supported:

cfg = client.ClientMetrics{
	Latency: promauto.NewSummaryVec(prometheus.SummaryOpts{
		Name: "request_duration_seconds",
		Help: "Duration of API requests.",
	}, []string{"application", "request"}),
	Errors:  promauto.NewCounterVec(prometheus.CounterOpts{
		Name: "request_errors",
		Help: "Duration of API requests.",
	}, []string{"application", "request"}),

c := client.InstrumentedClient{
	Options: cfg,
	Application: "foo",
}

req, _ := http.NewRequest(http.MethodGet, url, nil)
resp, err = c.Do(req)

This will generate Prometheus metrics for every request sent by the InstrumentedClient. The application label will be as set by the InstrumentedClient object. The request will be set to the Path of the request.

Cacher caches responses to HTTP requests:

c := client.NewCacher(
	http.DefaultClient, "foo", client.Options{},
	[]client.CacheTableEntry{
		{Endpoint: "/foo"},
	},
	50*time.Millisecond, 0,
)

This creates a Cacher that will cache the response of called to any request with Path '/foo', for up to 50 msec.

Note: NewCacher will create a Caller that also generates Prometheus metrics by chaining the request to an InstrumentedClient. To avoid this, create the Cacher object directly:

c := &Cacher{
	Caller: &BaseClient{},
	Table: CacheTable{Table: cacheEntries},
	Cache: cache.New[string, []byte](cacheExpiry, cacheCleanup),

Deprecated: moved to github.com/clambin/httpclient

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseClient

type BaseClient struct {
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

BaseClient performs the actual HTTP request

func (*BaseClient) Do

func (b *BaseClient) Do(req *http.Request) (resp *http.Response, err error)

Do performs the actual HTTP request

type CacheTable

type CacheTable struct {
	Table []CacheTableEntry
	// contains filtered or unexported fields
}

CacheTable holds the Endpoints that should be cached. If Table is empty, all responses will be cached.

type CacheTableEntry

type CacheTableEntry struct {
	// Endpoint is the URL Path for requests whose responses should be cached.
	// Can be a literal path, or a regular expression. In the latter case,
	// set IsRegExp to true
	Endpoint string
	// Methods is the list of HTTP Methods for which requests the response should be cached.
	// If empty, requests for any method will be cached.
	Methods []string
	// IsRegExp indicated the Endpoint is a regular expression.
	// Note: CacheTableEntry will panic if Endpoint does not contain a valid regular expression.
	IsRegExp bool
	// Expiry indicates how long a response should be cached.
	Expiry time.Duration
	// contains filtered or unexported fields
}

CacheTableEntry contains a single endpoint that should be cached. If the Endpoint is a regular expression, IsRegExp must be set. CacheTable will then compile it when needed. CacheTable will panic if the regular expression is invalid.

type Cacher

type Cacher struct {
	Caller
	Table CacheTable
	Cache cache.Cacher[string, []byte]
}

Cacher will cache calls based in the provided CacheTable Deprecated: moved to github.com/clambin/httpclient

func NewCacher

func NewCacher(httpClient *http.Client, application string, options Options, cacheEntries []CacheTableEntry, cacheExpiry, cacheCleanup time.Duration) *Cacher

NewCacher creates a new Cacher. It will also use InstrumentedClient to measure API call performance statistics. Deprecated: moved to github.com/clambin/httpclient

func (*Cacher) Do

func (c *Cacher) Do(req *http.Request) (resp *http.Response, err error)

Do sends the request and caches the response for future use. If a (non-expired) cached response exists for the request's URL, it is returned instead.

Note: only the request's URL is used to find a cached version. Currently, it does not consider the request's method (i.e. GET/PUT/etc).

type Caller

type Caller interface {
	Do(req *http.Request) (resp *http.Response, err error)
}

Caller interface of a generic API caller

type InstrumentedClient

type InstrumentedClient struct {
	BaseClient
	Options     Options
	Application string
}

InstrumentedClient implements the Caller interface. If provided by Options, it will collect performance metrics of the API calls and record them for Prometheus to scrape. Deprecated: moved to github.com/clambin/httpclient

func (*InstrumentedClient) Do

func (c *InstrumentedClient) Do(req *http.Request) (resp *http.Response, err error)

Do implements the Caller's Do() method. It sends the request and records performance metrics of the call. Currently, it records the request's duration (i.e. latency) and error rate.

type Metrics

type Metrics struct {
	Latency *prometheus.SummaryVec // measures latency of an API call
	Errors  *prometheus.CounterVec // measures any errors returned by an API call
}

Metrics contains Prometheus metrics to capture during API calls. Each metric is expected to have two labels: the first will contain the application issuing the request. The second will contain the endpoint (i.e. Path) of the request.

func NewMetrics

func NewMetrics(namespace, subsystem string) Metrics

NewMetrics creates a standard set of Prometheus metrics to capture during API calls.

func (*Metrics) MakeLatencyTimer

func (pm *Metrics) MakeLatencyTimer(labelValues ...string) (timer *prometheus.Timer)

MakeLatencyTimer creates a prometheus.Timer to measure the duration (latency) of an API client call If no Latency metric was created, timer will be nil:

timer := pm.MakeLatencyTimer(server, endpoint)
callAPI(server, endpoint)
if timer != nil {
	timer.ObserveDuration()
}

func (*Metrics) ReportErrors

func (pm *Metrics) ReportErrors(err error, labelValues ...string)

ReportErrors measures any API client call failures:

err := callAPI(server, endpoint)
pm.ReportErrors(err)

type Options

type Options struct {
	PrometheusMetrics Metrics // Prometheus metric to record API performance metrics
}

Options contains options to alter InstrumentedClient behaviour

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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