Documentation
¶
Overview ¶
Package client provides an interface and helpers for go-orb clients.
Index ¶
- Constants
- Variables
- func BackoffExponential(_ context.Context, _ Request[any, any], attempts int) (time.Duration, error)
- func Call[TResp any, TReq any](ctx context.Context, client Client, service string, endpoint string, req TReq, ...) (*TResp, error)
- func Register(name string, factory ProviderFunc) bool
- func RetryAlways(_ context.Context, _ Request[any, any], _ int, _ error) (bool, error)
- func RetryOnTimeoutError(_ context.Context, _ Request[any, any], _ int, err error) (bool, error)
- func SelectRandomNode(_ context.Context, _ string, nodes NodeMap, preferredTransports []string, ...) (*registry.Node, error)
- type BackoffFunc
- type CallOption
- func WithAnyTransport() CallOption
- func WithBackoff(fn BackoffFunc) CallOption
- func WithConnClose() CallOption
- func WithContentType(ct string) CallOption
- func WithDialTimeout(d time.Duration) CallOption
- func WithPoolHosts(n int) CallOption
- func WithPoolSize(n int) CallOption
- func WithPoolTTL(n time.Duration) CallOption
- func WithPreferredTransports(n ...string) CallOption
- func WithRequestTimeout(d time.Duration) CallOption
- func WithResponseMetadata(n map[string]string) CallOption
- func WithRetries(i int) CallOption
- func WithRetry(fn RetryFunc) CallOption
- func WithSelector(fn SelectorFunc) CallOption
- func WithStreamTimeout(d time.Duration) CallOption
- func WithTLSConfig(n *tls.Config) CallOption
- func WithURL(n string) CallOption
- type CallOptions
- type Client
- type Config
- type ConfigType
- type Middleware
- type MiddlewareCallHandler
- type MiddlewareCallNoCodecHandler
- type MiddlewareConfig
- type MiddlewareFactory
- type NodeMap
- type Option
- func WithClientAnyTransport() Option
- func WithClientBackoff(n BackoffFunc) Option
- func WithClientConnectionTimeout(n time.Duration) Option
- func WithClientContentType(n string) Option
- func WithClientDialTimeout(n time.Duration) Option
- func WithClientMiddleware(m MiddlewareConfig) Option
- func WithClientPlugin(n string) Option
- func WithClientPoolSize(n int) Option
- func WithClientPoolTTL(n time.Duration) Option
- func WithClientPreferredTransports(n ...string) Option
- func WithClientRequestTimeout(n time.Duration) Option
- func WithClientRetries(n int) Option
- func WithClientRetry(n RetryFunc) Option
- func WithClientSelector(n SelectorFunc) Option
- func WithClientStreamTimeout(n time.Duration) Option
- func WithClientTLSConfig(n *tls.Config) Option
- type ProviderFunc
- type RawResponse
- type Request
- func (r *Request[TResp, TReq]) Call(ctx context.Context, client Client, opts ...CallOption) (resp *TResp, err error)
- func (r *Request[TResp, TReq]) Endpoint() string
- func (r *Request[TResp, TReq]) Node(ctx context.Context, opts *CallOptions) (*registry.Node, error)
- func (r *Request[TResp, TReq]) Request() TReq
- func (r *Request[TResp, TReq]) Service() string
- type Response
- type RetryFunc
- type SelectorFunc
- type Type
Constants ¶
const ComponentType = "client"
ComponentType is the client component type name.
const MiddlewareComponentType = "middleware"
MiddlewareComponentType is returned when you call SomeMiddleware.Type().
Variables ¶
var ( // DefaultClientPlugin is the default client implementation to use. DefaultClientPlugin = "orb" // DefaultConfigSection is the default config section for the client. DefaultConfigSection = "client" // DefaultContentType is the default Content-Type for calls. DefaultContentType = "application/x-protobuf" // DefaultPreferredTransports set's in which order a transport will be selected. DefaultPreferredTransports = []string{"grpc", "drpc", "http", "h2c", "http2", "http3", "https"} // DefaultPoolHosts set the number of hosts in a pool. DefaultPoolHosts = 16 // DefaultPoolSize sets the connection pool size per service. DefaultPoolSize = 100 // DefaultPoolTTL sets the connection pool ttl. DefaultPoolTTL = time.Minute // DefaultSelector is the default node selector. DefaultSelector = SelectRandomNode // DefaultBackoff is the default backoff function for retries. DefaultBackoff = BackoffExponential // DefaultRetry is the default check-for-retry function for retries. DefaultRetry = RetryOnTimeoutError // DefaultRetries is the default number of times a request is tried. DefaultRetries = 5 // DefaultDialTimeout is the default dial timeout. DefaultDialTimeout = time.Second * 5 // DefaultRequestTimeout is the default request timeout. DefaultRequestTimeout = time.Second * 30 // DefaultConnectionTimeout is the default connection timeout. DefaultConnectionTimeout = time.Second * 5 // DefaultStreamTimeout is by default a noop. DefaultStreamTimeout = time.Duration(0) // DefaultConnClose indicates whetever to close the connection after each request. DefaultConnClose = false )
var ( // ErrNoNodeFound happens we haven't found a node for the requested service. ErrNoNodeFound = errors.New("no node found for the requested service") // ErrServiceArgumentEmpty happens when the service argument is empty. ErrServiceArgumentEmpty = errors.New("service argument is empty") // ErrFailedToCreateTransport happens when we haven't found the transport requested. ErrFailedToCreateTransport = errors.New("failed to create a transport") // ErrUnknownContentType happens when you request something with a (yet) unknown content-type. ErrUnknownContentType = errors.New("unknown content-type has been requested") )
var Middlewares = container.NewMap[string, MiddlewareFactory]()
Middlewares contains a map of all available middlewares.
Functions ¶
func BackoffExponential ¶
func BackoffExponential(_ context.Context, _ Request[any, any], attempts int) (time.Duration, error)
BackoffExponential uses expentionalDo to calc the duration to wait.
func Call ¶
func Call[TResp any, TReq any]( ctx context.Context, client Client, service string, endpoint string, req TReq, opts ...CallOption, ) (*TResp, error)
Call makes a call with the client, it's a shortcut for NewRequest(...).Call(...) Example:
resp , err := client.Call[FooResponse](context.Background(), clientWire, "service1", "Say.Hello", fooRequest)
Response will be of type *FooResponse.
func Register ¶
func Register(name string, factory ProviderFunc) bool
Register makes a plugin available by the provided name. If Register is called twice with the same name, it panics.
func RetryAlways ¶
RetryAlways always retry on error.
func RetryOnTimeoutError ¶
RetryOnTimeoutError retries a request on a 408 timeout error.
func SelectRandomNode ¶
func SelectRandomNode( _ context.Context, _ string, nodes NodeMap, preferredTransports []string, anyTransport bool, ) (*registry.Node, error)
SelectRandomNode selects a random node, it tries' on preferredTransport after another, if anyTransport is true it will return transports that are not listet as well.
Types ¶
type BackoffFunc ¶
type BackoffFunc func(ctx context.Context, req Request[any, any], attempts int) (time.Duration, error)
BackoffFunc is the type for backoff funcs.
type CallOption ¶
type CallOption func(*CallOptions)
CallOption used by Call or Stream.
func WithAnyTransport ¶
func WithAnyTransport() CallOption
WithAnyTransport enables unconfigured (any) transports.
func WithBackoff ¶
func WithBackoff(fn BackoffFunc) CallOption
WithBackoff is a CallOption which overrides that which set in Options.CallOptions.
func WithConnClose ¶
func WithConnClose() CallOption
WithConnClose sets the Connection header to close.
func WithContentType ¶
func WithContentType(ct string) CallOption
WithContentType set's the call's Content-Type.
func WithDialTimeout ¶
func WithDialTimeout(d time.Duration) CallOption
WithDialTimeout is a CallOption which overrides that which set in Options.CallOptions.
func WithPoolHosts ¶
func WithPoolHosts(n int) CallOption
WithPoolHosts sets the number of hosts in a pool.
func WithPoolSize ¶
func WithPoolSize(n int) CallOption
WithPoolSize sets the connection pool size per service.
func WithPoolTTL ¶
func WithPoolTTL(n time.Duration) CallOption
WithPoolTTL sets the connection pool ttl.
func WithPreferredTransports ¶
func WithPreferredTransports(n ...string) CallOption
WithPreferredTransports set's the preffered transports for this request.
func WithRequestTimeout ¶
func WithRequestTimeout(d time.Duration) CallOption
WithRequestTimeout is a CallOption which overrides that which set in Options.CallOptions.
func WithResponseMetadata ¶
func WithResponseMetadata(n map[string]string) CallOption
WithResponseMetadata will write response Metadata into the give map.
func WithRetries ¶
func WithRetries(i int) CallOption
WithRetries sets the number of tries for a call. This CallOption overrides Options.CallOptions.
func WithRetry ¶
func WithRetry(fn RetryFunc) CallOption
WithRetry is a CallOption which overrides that which set in Options.CallOptions.
func WithSelector ¶
func WithSelector(fn SelectorFunc) CallOption
WithSelector overrides the calls SelectorFunc.
func WithStreamTimeout ¶
func WithStreamTimeout(d time.Duration) CallOption
WithStreamTimeout sets the stream timeout.
func WithTLSConfig ¶
func WithTLSConfig(n *tls.Config) CallOption
WithTLSConfig set's the clients TLS config.
func WithURL ¶
func WithURL(n string) CallOption
WithURL bypasses the registry when set. This is mainly for tests. Only <scheme>://<host:port> will be used from it.
type CallOptions ¶
type CallOptions struct {
// Used to select a codec
ContentType string
// PreferredTransports contains a list of transport names in preferred order.
PreferredTransports []string
// PoolHosts sets the number of hosts in a pool
PoolHosts int
// PoolSize sets the connection pool size per service.
PoolSize int
// PoolTTL sets the connection pool ttl.
PoolTTL time.Duration
AnyTransport bool
// Selector is the node selector.
Selector SelectorFunc
// Backoff func
Backoff BackoffFunc
// Check if retriable func
Retry RetryFunc
// Number of Call attempts
Retries int
// Transport Dial Timeout. Used for initial dial to establish a connection.
DialTimeout time.Duration
// ConnectionTimeout of one request to the server.
// Set this lower than the RequestTimeout to enable retries on connection timeout.
ConnectionTimeout time.Duration
// Request/Response timeout of entire srv.Call, for single request timeout set ConnectionTimeout.
RequestTimeout time.Duration
// Stream timeout for the stream
StreamTimeout time.Duration
// ConnClose sets the Connection: close header.
ConnClose bool
// URL bypasses the registry when set. This is mainly for tests.
// Only <scheme>://<host:port> will be used from it.
URL string
// TLS config.
TLSConfig *tls.Config
// ResponseMetadata will be written into `ResponseMetadata` when given.
ResponseMetadata map[string]string
}
CallOptions are options used to make calls to a server.
type Client ¶
type Client interface {
types.Component
// Config returns the internal config, this is for tests.
Config() Config
// With closes all transports and configures the client with the given options.
With(opts ...Option) error
ResolveService(ctx context.Context, service string, preferredTransports ...string) (NodeMap, error)
// NeedsCodec has to do node resolving and then selects the right transport for that node,
// it then has to return whatever the selected transport needs a codec or if it does encoding internaly.
NeedsCodec(ctx context.Context, req *Request[any, any], opts ...CallOption) bool
// Call with encoding on client side.
Call(ctx context.Context, req *Request[any, any], result any, opts ...CallOption) (*RawResponse, error)
// CallNoCodec is the same as Call but without encoding.
CallNoCodec(ctx context.Context, req *Request[any, any], result any, opts ...CallOption) error
}
Client is the interface for clients.
type Config ¶
type Config struct {
// Plugin selects the client implementation.
Plugin string `json:"plugin" yaml:"plugin"`
Middleware []MiddlewareConfig
// Used to select a codec
ContentType string `json:"contentType" yaml:"contentType"`
// PreferredTransports contains a list of transport names in preferred order.
PreferredTransports []string `json:"preferredTransports" yaml:"preferredTransports"`
// AnyTransport enables Transports which are not in PreferredTransports.
AnyTransport bool `json:"anyTransport" yaml:"anyTransport"`
// Connection Pool
PoolHosts int `json:"poolHosts" yaml:"poolHosts"`
PoolSize int `json:"poolSize" yaml:"poolSize"`
PoolTTL time.Duration `json:"poolTtl" yaml:"poolTtl"`
// SelectorFunc get's executed by client.SelectNode which get it's info's from client.ResolveService.
Selector SelectorFunc `json:"-" yaml:"-"`
// Backoff func
Backoff BackoffFunc `json:"-" yaml:"-"`
// Check if retriable func
Retry RetryFunc `json:"-" yaml:"-"`
// Number of Call attempts
Retries int `json:"retries" yaml:"retries"`
// Transport Dial Timeout. Used for initial dial to establish a connection.
DialTimeout time.Duration `json:"dialTimeout" yaml:"dialTimeout"`
// ConnectionTimeout of one request to the server.
// Set this lower than the RequestTimeout to enbale retries on connection timeout.
ConnectionTimeout time.Duration `json:"connectionTimeout" yaml:"connectionTimeout"`
// Request/Response timeout of entire srv.Call, for single request timeout set ConnectionTimeout.
RequestTimeout time.Duration `json:"requestTimeout" yaml:"requestTimeout"`
// Stream timeout for the stream
StreamTimeout time.Duration `json:"streamTimeout" yaml:"streamTimeout"`
// TLS config.
TLSConfig *tls.Config
}
Config are the Client options.
type ConfigType ¶
type ConfigType interface {
// contains filtered or unexported methods
}
ConfigType is used in the functional options as type to identify a registry option. It is used over a static *Config type as this way plugins can also easilty set functional options without the complication of contexts, as was done in v4. This is possible because plugins will nest the registry.Config type, and thus inherit the interface that is used to identify the registry config.
type Middleware ¶
type Middleware interface {
types.Component
Call(
next MiddlewareCallHandler,
) MiddlewareCallHandler
CallNoCodec(
next MiddlewareCallNoCodecHandler,
) MiddlewareCallNoCodecHandler
}
Middleware is the middleware for clients.
type MiddlewareCallHandler ¶
type MiddlewareCallHandler func(ctx context.Context, req *Request[any, any], opts *CallOptions) (*RawResponse, error)
MiddlewareCallHandler is the middleware handler for client.Call.
type MiddlewareCallNoCodecHandler ¶
type MiddlewareCallNoCodecHandler func(ctx context.Context, req *Request[any, any], result any, opts *CallOptions) error
MiddlewareCallNoCodecHandler is the middleware handler for client.Call without a codec in between.
type MiddlewareConfig ¶
type MiddlewareConfig struct {
Name string `json:"name" yaml:"name"`
}
MiddlewareConfig is the basic config for every middleware.
type MiddlewareFactory ¶
type MiddlewareFactory func(configSection []string, configs types.ConfigData, client Type, logger log.Logger) (Middleware, error)
MiddlewareFactory is used to create a new client Middleware.
type Option ¶
type Option func(ConfigType)
Option is a functional option type for the registry.
func WithClientAnyTransport ¶
func WithClientAnyTransport() Option
WithClientAnyTransport enables Transports which are not in PreferredTransports.
func WithClientBackoff ¶
func WithClientBackoff(n BackoffFunc) Option
WithClientBackoff overrides the clients backoff func.
func WithClientConnectionTimeout ¶
WithClientConnectionTimeout overrides the connection timeout.
func WithClientContentType ¶
WithClientContentType set's the Content-Type other than the default for this client.
func WithClientDialTimeout ¶
WithClientDialTimeout overrides the dial timeout.
func WithClientMiddleware ¶
func WithClientMiddleware(m MiddlewareConfig) Option
WithClientMiddleware appends a middleware to the client.
func WithClientPlugin ¶
WithClientPlugin set the client implementation to use.
func WithClientPoolSize ¶
WithClientPoolSize overrides the PoolSize of the client.
func WithClientPoolTTL ¶
WithClientPoolTTL overrides the PoolTTL of the client.
func WithClientPreferredTransports ¶
WithClientPreferredTransports set the order of transports.
func WithClientRequestTimeout ¶
WithClientRequestTimeout overrides the request timeout.
func WithClientRetries ¶
WithClientRetries overrides the number of retries to make.
func WithClientRetry ¶
WithClientRetry overrides the retry function.
func WithClientSelector ¶
func WithClientSelector(n SelectorFunc) Option
WithClientSelector overrides the clients selector func.
func WithClientStreamTimeout ¶
WithClientStreamTimeout overrides the stream timeout.
func WithClientTLSConfig ¶
WithClientTLSConfig set's the clients TLS config.
type ProviderFunc ¶
type ProviderFunc func( name types.ServiceName, data types.ConfigData, logger log.Logger, registry registry.Type, opts ...Option, ) (Type, error)
ProviderFunc is provider function type used by plugins to create a new client.
type RawResponse ¶
RawResponse is a internal struct to pass the transport's response with metadata and content-type around.
type Request ¶
Request is a request for Client.
func NewRequest ¶
func NewRequest[TResp any, TReq any]( service string, endpoint string, req TReq, ) *Request[TResp, TReq]
NewRequest creates a request for a service+endpoint.
Example (with call):
resp, err := client.NewRequest[FooResponse]( "service1", "Say.Hello", myRequest, ).Call(context.Background(), clientFromWire)
Response will be of type *FooResponse.
func (*Request[TResp, TReq]) Call ¶
func (r *Request[TResp, TReq]) Call(ctx context.Context, client Client, opts ...CallOption) (resp *TResp, err error)
Call forward's the Request to Client.Call() and decodes the result into resp with the type TResp.
type RetryFunc ¶
type RetryFunc func(ctx context.Context, req Request[any, any], retryCount int, err error) (bool, error)
RetryFunc is the type for a retry func. note that returning either false or a non-nil error will result in the call not being retried.
type SelectorFunc ¶
type SelectorFunc func( ctx context.Context, service string, nodes NodeMap, preferredTransports []string, anyTransport bool, ) (*registry.Node, error)
SelectorFunc get's executed by client.SelectNode which get it's info's from client.ResolveService.