selecthost

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package selecthost handles host discovery via DNS SRV records, keeps track of healthy and selects the most optimal host for use.

An HTTP Transport is provided which simplifies using this package with any http client.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSelectHost is the root error for all SelectHost errors
	ErrSelectHost = errors.New("SelectHost Error")
	// ErrSelectorStopped is returned when waiting for a host but the selector has been stopped.
	ErrSelectorStopped = fmt.Errorf("%w: selector stopped", ErrSelectHost)
	// ErrHostNotFound is returned when a host is not able to be determined.
	ErrHostNotFound = fmt.Errorf("%w: no host found", ErrSelectHost)
	// ErrWaitTimedout is returned when waiting for a host to be discovered.
	ErrWaitTimedout = fmt.Errorf("%w: timed out waiting for host", ErrSelectHost)
	// ErrDiscoveryTimeout is returned when the discovery process takes longer than configured timeout.
	ErrDiscoveryTimeout = fmt.Errorf("%w: discovery process timed out: %w", ErrSelectHost, context.DeadlineExceeded)
	// ErrHostCheckTimedout is returned when the host check process takes longer than configured timeout.
	ErrHostCheckTimedout = fmt.Errorf("%w: host check timed out: %w", ErrSelectHost, context.DeadlineExceeded)
)
View Source
var (
	// ErrHostRemoved is set on a host if it no longer exists in the discovered hosts.
	ErrHostRemoved = fmt.Errorf("%w: host removed", ErrSelectHost)
)
View Source
var (
	// ErrUnexpectedStatusCode is returned when a check request doesn't have 2xx status code.
	ErrUnexpectedStatusCode = fmt.Errorf("%w: unexpected status code", ErrSelectHost)
)

Functions

func JoinHostPort

func JoinHostPort(host string, port string) string

JoinHostPort combines host and port into a network address of the form "host:port". If host contains a colon, as found in literal IPv6 addresses, then JoinHostPort returns "[host]:port". If port is not defined, port is left out.

func NewTransport

func NewTransport(selector *Selector, base http.RoundTripper) http.RoundTripper

NewTransport initialized a new Transport with the provided selector and base transport. If base is nil, the default http transport is used.

Types

type Host

type Host interface {
	ID() string
	Record() net.SRV
	Host() string
	Port() string

	Before(h2 Host) bool

	LastCheck() Results
	AverageDuration() time.Duration
	Err() error
	// contains filtered or unexported methods
}

Host is an individual host entry.

func ParseHost

func ParseHost(selector *Selector, host string) (Host, error)

ParseHost parses the provided host allowing for a host without a port and returns a new Host.

type Hosts

type Hosts []Host

Hosts is a collection of [Host]s.

func (Hosts) Len

func (h Hosts) Len() int

Len implement sort.Interface.

func (Hosts) Less

func (h Hosts) Less(i, j int) bool

Less implements sort.Interface.

func (Hosts) Swap

func (h Hosts) Swap(i, j int)

Swap implement sort.Interface.

type Option

type Option func(s *Selector) error

Option defines a selector option.

func CheckConcurrency

func CheckConcurrency(count int) Option

CheckConcurrency defines the number of hosts which may be checked simultaneously. Default: 5

func CheckCount

func CheckCount(count int) Option

CheckCount defines how many checks to run on an endpoint. Default: 5

func CheckDelay

func CheckDelay(delay time.Duration) Option

CheckDelay specifies how long to wait between subsequent checks for the same host. Default: 200ms

func CheckInterval

func CheckInterval(interval time.Duration) Option

CheckInterval specifies how frequently to run host checks. Default: 1m.

func CheckPath

func CheckPath(path string) Option

CheckPath sets the request path for checks.

func CheckScheme

func CheckScheme(scheme string) Option

CheckScheme sets the uri scheme. Default is http unless discovered port is 443, https will be used then.

func CheckTimeout

func CheckTimeout(timeout time.Duration) Option

CheckTimeout defines the maximum time an individual check request can take. Default: 2s

func DiscoveryInterval

func DiscoveryInterval(interval time.Duration) Option

DiscoveryInterval specifies the interval at which SRV records will be rediscovered. Default: 15m

func Fallback

func Fallback(host string) Option

Fallback specifies a fallback host if no hosts are discovered or all hosts are currently failing.

func Logger

func Logger(logger *zap.SugaredLogger) Option

Logger sets the logger.

func Optional

func Optional() Option

Optional if no SRV record is found, the target (or fallback address) is used instead. The discovery process continues to run in the chance that SRV records are added at a later point.

func Prefer

func Prefer(host string) Option

Prefer specifies a preferred host. If the host is not discovered or has an error it will not be used.

func Quick

func Quick() Option

Quick will select the fallback address immediately on startup instead of waiting for the discovery process to complete.

type Results

type Results struct {
	Time          time.Time
	Host          Host
	Checks        uint
	TotalDuration time.Duration
	Errors        []error
}

Results holds host check results.

func (Results) Average

func (r Results) Average() time.Duration

Average returns the average duration of all checks run on host.

type Selector

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

Selector handles discovering SRV records, periodically polling and selecting the fastest responding endpoint.

func NewSelector

func NewSelector(target, service, protocol string, options ...Option) (*Selector, error)

NewSelector creates a new selector service handler. The target provided is automatically registered as the default fallback address.

func (*Selector) GetHost

func (s *Selector) GetHost(ctx context.Context) (Host, error)

GetHost returns the active host. If the selector has not been started before, the selector is initialized. This method will block until a host is selected, initialization timeout is reached or the context is canceled.

func (*Selector) Start

func (s *Selector) Start()

Start initializes the selector discovery and checking handlers.

func (*Selector) Stop

func (s *Selector) Stop()

Stop cleans up the service.

func (*Selector) Target

func (s *Selector) Target() string

Target returns the SRV target.

type Transport

type Transport struct {
	Selector *Selector
	Base     http.RoundTripper
}

Transport implements http.RoundTripper handles switching the request host to a discovered host.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper. If the request host matches the selector service's target, the host is replaced with the selected host address. If the request does not match, the base transport is called for the request instead.

When the selected host is used, if the result from the base transport returns an error, the selected host is marked as having that error and a new host is immediately selected. The request however is not retried, instead the requestor must retry when appropriate.

Hosts marked with an error will get cleared upon the next successful host check cycle.

Jump to

Keyboard shortcuts

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