client

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2025 License: Apache-2.0 Imports: 14 Imported by: 42

Documentation

Overview

Package client provides an interface and helpers for go-orb clients.

Package client provides an interface and helpers for go-orb clients.

Index

Constants

View Source
const ComponentType = "client"

ComponentType is the client component type name.

View Source
const MiddlewareComponentType = "middleware"

MiddlewareComponentType is returned when you call SomeMiddleware.Type().

Variables

View Source
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{
		"memory",
		"unix+grpc",
		"unix+drpc",
		"unix+http",
		"grpc",
		"drpc",
		"http",
		"grpcs",
		"http2",
		"http3",
		"https",
	}

	// DefaultPoolHosts set the number of hosts in a pool.
	DefaultPoolHosts = 64
	// DefaultPoolSize sets the connection pool size.
	// The effective pool size will be PoolHosts * PoolSize.
	DefaultPoolSize = 10
	// DefaultPoolTTL sets the connection pool ttl.
	DefaultPoolTTL = 30 * time.Minute

	// DefaultSelector is the default node selector.
	DefaultSelector = SelectRandomNode

	// 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

	// DefaultCallOptionsRetryFunc is nil, so it uses the middlewares default.
	DefaultCallOptionsRetryFunc = (RetryFunc)(nil)

	// DefaultCallOptionsRetries is 0, so it uses the middlewares default.
	DefaultCallOptionsRetries = 0

	// DefaultMaxCallRecvMsgSize is the default maximum size of the call receive message size.
	DefaultMaxCallRecvMsgSize = 10 * 1024 * 1024
	// DefaultMaxCallSendMsgSize is the default maximum size of the call send message size.
	DefaultMaxCallSendMsgSize = 10 * 1024 * 1024
)
View Source
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")
)
View Source
var ErrStreamNotSupported = errors.New("client does not support streaming")

ErrStreamNotSupported is returned when the client does not support streaming.

Middlewares contains a map of all available middlewares.

Functions

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 RegisterMemoryServer added in v0.3.0

func RegisterMemoryServer(service string, server MemoryServer)

RegisterMemoryServer registers a memory server for a service.

func Request

func Request[TResp any, TReq any](
	ctx context.Context,
	client Client,
	service string,
	endpoint string,
	req TReq,
	opts ...CallOption,
) (*TResp, error)

Request is a typesafe shortcut for making a request.

Example:

resp , err := client.Request[FooResponse](context.Background(), clientWire, "service1", "Say.Hello", fooRequest)

Response will be of type *FooResponse.

func SelectRandomNode

func SelectRandomNode(
	_ context.Context,
	_ string,
	nodes []registry.ServiceNode,
) (registry.ServiceNode, error)

SelectRandomNode selects a random node.

func UnregisterMemoryServer added in v0.3.0

func UnregisterMemoryServer(service string)

UnregisterMemoryServer unregisters a memory server for a service.

Types

type CallOption

type CallOption func(*CallOptions)

CallOption used by Call or Stream.

func WithAnyTransport

func WithAnyTransport() CallOption

WithAnyTransport enables unconfigured (any) transports.

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 WithMaxCallRecvMsgSize added in v0.3.0

func WithMaxCallRecvMsgSize(n int) CallOption

WithMaxCallRecvMsgSize sets the maximum size of the call receive message size.

func WithMaxCallSendMsgSize added in v0.3.0

func WithMaxCallSendMsgSize(n int) CallOption

WithMaxCallSendMsgSize sets the maximum size of the call send message size.

func WithMetadata added in v0.3.0

func WithMetadata(n map[string]string) CallOption

WithMetadata sets the metadata to be sent with the request.

func WithNamespace added in v0.3.0

func WithNamespace(n string) CallOption

WithNamespace sets the namespace filter.

func WithPreferredTransports

func WithPreferredTransports(n ...string) CallOption

WithPreferredTransports set's the preffered transports for this request.

func WithRegion added in v0.3.0

func WithRegion(r string) CallOption

WithRegion sets the region filter.

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 WithRetryFunc added in v0.3.0

func WithRetryFunc(fn RetryFunc) CallOption

WithRetryFunc is a CallOption which overrides the retry function.

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

	// Allow any transport in any order.
	AnyTransport bool

	// Selector is the node selector.
	Selector SelectorFunc
	// Check if retriable func
	RetryFunc 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

	// Metadata to be sent with the request.
	Metadata map[string]string

	// ResponseMetadata will be written into `ResponseMetadata` when given.
	ResponseMetadata map[string]string

	// MaxCallRecvMsgSize is the maximum size of the call receive message size.
	MaxCallRecvMsgSize int

	// MaxCallSendMsgSize is the maximum size of the call send message size.
	MaxCallSendMsgSize int

	// Namespace registry filter.
	Namespace string

	// Region registry filter.
	Region 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

	// SelectService selects a service node.
	// Returns:
	// - address
	// - transport
	// - error
	SelectService(ctx context.Context, service string, opts ...CallOption) (string, string, error)

	// Request does the actual call.
	Request(ctx context.Context, service string, endpoint string, req any, result any, opts ...CallOption) error

	// Stream creates a streaming client to the specified service endpoint.
	Stream(ctx context.Context, service string, endpoint string, opts ...CallOption) (StreamIface[any, any], 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   config.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:"-"`

	// Transport Dial Timeout. Used for initial dial to establish a connection.
	DialTimeout config.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 config.Duration `json:"connectionTimeout" yaml:"connectionTimeout"`
	// Request/Response timeout of entire srv.Call, for single request timeout set ConnectionTimeout.
	RequestTimeout config.Duration `json:"requestTimeout" yaml:"requestTimeout"`
	// Stream timeout for the stream
	StreamTimeout config.Duration `json:"streamTimeout" yaml:"streamTimeout"`
	// TLS config.
	TLSConfig *tls.Config

	// Namespace registry filter.
	Namespace string `json:"namespace" yaml:"namespace"`

	// Region registry filter.
	Region string `json:"region" yaml:"region"`
}

Config are the Client options.

func NewConfig

func NewConfig(opts ...Option) Config

NewConfig generates a new config with all the defaults.

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 MemoryServer added in v0.3.0

type MemoryServer interface {
	// Request does the actual call.
	Request(ctx context.Context, infos RequestInfos, req any, result any, opts *CallOptions) error

	// Stream creates a streaming client to the specified service endpoint.
	Stream(ctx context.Context, infos RequestInfos, opts *CallOptions) (StreamIface[any, any], error)
}

MemoryServer is the interface that a memory server has to implement to be accepted by the client.

func ResolveMemoryServer added in v0.3.0

func ResolveMemoryServer(service string) (MemoryServer, error)

ResolveMemoryServer resolves a memory server for a service.

type Middleware

type Middleware interface {
	types.Component

	Request(
		next MiddlewareRequestHandler,
	) MiddlewareRequestHandler
}

Middleware is the middleware for clients.

type MiddlewareConfig

type MiddlewareConfig struct {
	Name string `json:"name" yaml:"name"`
}

MiddlewareConfig is the basic config for every middleware.

type MiddlewareFactory

type MiddlewareFactory func(config map[string]any, client Type, logger log.Logger) (Middleware, error)

MiddlewareFactory is used to create a new client Middleware.

type MiddlewareRequestHandler added in v0.3.0

type MiddlewareRequestHandler func(ctx context.Context, service string, endpoint string, req any, result any, opts *CallOptions) error

MiddlewareRequestHandler is the middleware handler for client.Request without a codec in between.

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 WithClientConnectionTimeout

func WithClientConnectionTimeout(n time.Duration) Option

WithClientConnectionTimeout overrides the connection timeout.

func WithClientContentType

func WithClientContentType(n string) Option

WithClientContentType set's the Content-Type other than the default for this client.

func WithClientDialTimeout

func WithClientDialTimeout(n time.Duration) Option

WithClientDialTimeout overrides the dial timeout.

func WithClientMiddleware

func WithClientMiddleware(m MiddlewareConfig) Option

WithClientMiddleware appends a middleware to the client.

func WithClientNamespace added in v0.3.0

func WithClientNamespace(n string) Option

WithClientNamespace sets the namespace filter.

func WithClientPlugin

func WithClientPlugin(n string) Option

WithClientPlugin set the client implementation to use.

func WithClientPoolHosts added in v0.3.0

func WithClientPoolHosts(n int) Option

WithClientPoolHosts overrides the PoolHosts of the client.

func WithClientPoolSize

func WithClientPoolSize(n int) Option

WithClientPoolSize overrides the PoolSize of the client.

func WithClientPoolTTL

func WithClientPoolTTL(n time.Duration) Option

WithClientPoolTTL overrides the PoolTTL of the client.

func WithClientPreferredTransports

func WithClientPreferredTransports(n ...string) Option

WithClientPreferredTransports set the order of transports.

func WithClientRegion added in v0.3.0

func WithClientRegion(r string) Option

WithClientRegion sets the region filter.

func WithClientRequestTimeout

func WithClientRequestTimeout(n time.Duration) Option

WithClientRequestTimeout overrides the request timeout.

func WithClientSelector

func WithClientSelector(n SelectorFunc) Option

WithClientSelector overrides the clients selector func.

func WithClientStreamTimeout

func WithClientStreamTimeout(n time.Duration) Option

WithClientStreamTimeout overrides the stream timeout.

func WithClientTLSConfig

func WithClientTLSConfig(n *tls.Config) Option

WithClientTLSConfig set's the clients TLS config.

type ProviderFunc

type ProviderFunc func(
	configData map[string]any,
	components *types.Components,
	logger log.Logger,
	registry registry.Type,
	opts ...Option,
) (Type, error)

ProviderFunc is provider function type used by plugins to create a new client.

type RequestInfos added in v0.3.0

type RequestInfos struct {
	Service   string
	Endpoint  string
	Transport string
	Address   string
}

RequestInfos contains the request infos.

func RequestInfo added in v0.3.0

func RequestInfo(ctx context.Context) (RequestInfos, bool)

RequestInfo returns the request infos from the context.

type RequestInfosKey added in v0.3.0

type RequestInfosKey struct{}

RequestInfosKey is the key for the request infos in the context.

type RetryFunc

type RetryFunc func(ctx context.Context, err error, options *CallOptions) (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 []registry.ServiceNode,
) (registry.ServiceNode, error)

SelectorFunc get's executed by client.SelectNode which get it's info's from client.ResolveService.

type StreamAdapter added in v0.3.0

type StreamAdapter[TReq any, TResp any] struct {
	// contains filtered or unexported fields
}

StreamAdapter is an adapter that maps between StreamIface with generic types (any, any) and StreamIface with specific types (TReq, TResp).

func (*StreamAdapter[TReq, TResp]) Close added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) Close() error

Close closes the stream.

func (*StreamAdapter[TReq, TResp]) CloseSend added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) CloseSend() error

CloseSend closes the send side of the stream.

func (*StreamAdapter[TReq, TResp]) Context added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) Context() context.Context

Context returns the context for the stream.

func (*StreamAdapter[TReq, TResp]) Endpoint added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) Endpoint() string

Endpoint returns the Endpoint from the request.

func (*StreamAdapter[TReq, TResp]) Recv added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) Recv(msg TResp) error

Recv receives a message from the stream.

func (*StreamAdapter[TReq, TResp]) Send added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) Send(msg TReq) error

Send sends a message to the stream.

func (*StreamAdapter[TReq, TResp]) Service added in v0.3.0

func (s *StreamAdapter[TReq, TResp]) Service() string

Service returns the Service from the request.

type StreamIface added in v0.3.0

type StreamIface[TReq any, TResp any] interface {
	// Send sends a message to the stream.
	Send(msg TReq) error

	// Recv receives a message from the stream.
	Recv(msg TResp) error

	// Close closes the stream.
	Close() error

	// CloseSend closes the send direction of the stream but allows receiving responses.
	CloseSend() error

	// Context returns the context for the stream.
	Context() context.Context
}

StreamIface is the interface for handling streaming operations.

func NewStreamAdapter added in v0.3.0

func NewStreamAdapter[TReq any, TResp any](
	stream StreamIface[any, any],
	service string,
	endpoint string,
	client Client,
) StreamIface[TReq, TResp]

NewStreamAdapter creates a new stream adapter.

func Stream added in v0.3.0

func Stream[TReq any, TResp any](
	ctx context.Context,
	c Client,
	service, endpoint string,
	opts ...CallOption,
) (StreamIface[TReq, TResp], error)

Stream is a helper function to create a new stream with the given service and endpoint.

type Type

type Type struct {
	Client
}

Type is the client type it is returned when you use ProvideClient which selects a client to use based on the plugin configuration.

func New added in v0.3.0

func New(
	configData map[string]any,
	components *types.Components,
	logger log.Logger,
	registry registry.Type,
	opts ...Option,
) (Type, error)

New creates a new client instance with the implementation from cfg.Plugin.

func Provide

func Provide(
	svcCtx *cli.ServiceContextWithConfig,
	components *types.Components,
	logger log.Logger,
	reg registry.Type,
	opts ...Option) (Type, error)

Provide creates a new client instance with the implementation from cfg.Plugin.

func ProvideNoOpts added in v0.3.0

func ProvideNoOpts(
	svcCtx *cli.ServiceContextWithConfig,
	components *types.Components,
	logger log.Logger,
	reg registry.Type,
) (Type, error)

ProvideNoOpts provides a new client without options.

Jump to

Keyboard shortcuts

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