Documentation
¶
Overview ¶
Package client provides a NATS JetStream client with connection management, KV buckets, Object Store buckets, streams, messaging, and OpenTelemetry spans and metrics for each call.
Index ¶
- Constants
- Variables
- func MessageContext(ctx context.Context, header nats.Header) context.Context
- type AuthOptions
- type AuthType
- type Client
- func (c *Client) Close()
- func (c *Client) Connect() error
- func (c *Client) ConnectedServerVersion() string
- func (c *Client) ConnectedURL() string
- func (c *Client) Consume(ctx context.Context, stream string, consumer string, ...) error
- func (c *Client) ConsumerCreateOrUpdate(ctx context.Context, stream string, config jetstream.ConsumerConfig) error
- func (c *Client) KVCreate(ctx context.Context, bucket string, key string, value []byte) (uint64, error)
- func (c *Client) KVCreateOrUpdate(ctx context.Context, config jetstream.KeyValueConfig) error
- func (c *Client) KVDelete(ctx context.Context, bucket string, key string) error
- func (c *Client) KVGet(ctx context.Context, bucket string, key string) (jetstream.KeyValueEntry, error)
- func (c *Client) KVKeys(ctx context.Context, bucket string, filters ...string) ([]string, error)
- func (c *Client) KVPut(ctx context.Context, bucket string, key string, value []byte) (uint64, error)
- func (c *Client) KVStatus(ctx context.Context, bucket string) (jetstream.KeyValueStatus, error)
- func (c *Client) KVUpdate(ctx context.Context, bucket string, key string, value []byte, revision uint64) (uint64, error)
- func (c *Client) KVWatch(ctx context.Context, bucket string, pattern string, opts ...jetstream.WatchOpt) (<-chan jetstream.KeyValueEntry, error)
- func (c *Client) ObjectDelete(ctx context.Context, bucket string, name string) error
- func (c *Client) ObjectGetBytes(ctx context.Context, bucket string, name string) ([]byte, error)
- func (c *Client) ObjectInfo(ctx context.Context, bucket string, name string) (*jetstream.ObjectInfo, error)
- func (c *Client) ObjectList(ctx context.Context, bucket string) ([]*jetstream.ObjectInfo, error)
- func (c *Client) ObjectPut(ctx context.Context, bucket string, meta jetstream.ObjectMeta, ...) (*jetstream.ObjectInfo, error)
- func (c *Client) ObjectPutBytes(ctx context.Context, bucket string, name string, data []byte) (*jetstream.ObjectInfo, error)
- func (c *Client) ObjectStoreCreateOrUpdate(ctx context.Context, config jetstream.ObjectStoreConfig) error
- func (c *Client) ObjectStoreStatus(ctx context.Context, bucket string) (jetstream.ObjectStoreStatus, error)
- func (c *Client) Publish(ctx context.Context, subject string, data []byte) error
- func (c *Client) PublishCore(ctx context.Context, subject string, data []byte) error
- func (c *Client) StreamCreateOrUpdate(ctx context.Context, config jetstream.StreamConfig) error
- func (c *Client) StreamGetMsg(ctx context.Context, name string, seq uint64) (*jetstream.RawStreamMsg, error)
- func (c *Client) StreamInfo(ctx context.Context, name string) (*jetstream.StreamInfo, error)
- func (c *Client) StreamLastMsg(ctx context.Context, name string, subject string) (*jetstream.RawStreamMsg, error)
- func (c *Client) StreamRead(ctx context.Context, name string, from uint64, count int) ([]jetstream.Msg, error)
- func (c *Client) Subscribe(ctx context.Context, subject string, handler MsgHandler) (*nats.Subscription, error)
- type ConsumeOptions
- type JetStreamMessageHandler
- type MsgHandler
- type NATSConnWrapper
- func (n *NATSConnWrapper) Close()
- func (n *NATSConnWrapper) Connect(url string, opts ...nats.Option) (*nats.Conn, error)
- func (n *NATSConnWrapper) ConnectedServerVersion() string
- func (n *NATSConnWrapper) ConnectedUrl() string
- func (n *NATSConnWrapper) JetStream(opts ...nats.JSOpt) (nats.JetStreamContext, error)
- func (n *NATSConnWrapper) Publish(subject string, data []byte) error
- func (n *NATSConnWrapper) PublishMsg(msg *nats.Msg) error
- func (n *NATSConnWrapper) QueueSubscribe(subject, queue string, handler nats.MsgHandler) (*nats.Subscription, error)
- func (n *NATSConnWrapper) Subscribe(subject string, handler nats.MsgHandler) (*nats.Subscription, error)
- type NATSConnector
- type Options
- type ReconnectOptions
Constants ¶
const DefaultMaxInFlight = 10
DefaultMaxInFlight is the MaxInFlight of a Consume with no options or zero.
const DefaultReconnectWait = 2 * time.Second
DefaultReconnectWait is the Wait of a ReconnectOptions that has none.
Variables ¶
var ErrConnected = errors.New("already connected: call Close first")
ErrConnected is the error of a Connect on a client that is connected.
var ErrNotConnected = errors.New("not connected: call Connect first")
ErrNotConnected is the error of a call to JetStream before Connect, or after Close.
var ErrTerminate = errors.New("terminate the message")
ErrTerminate is the error that a JetStreamMessageHandler wraps for a message that must not be delivered again, such as one that it cannot parse.
var GetJetStream = func(nc *nats.Conn) (jetstream.JetStream, error) { return jetstream.New(nc) }
GetJetStream is a public variable function wrapping jetstream.New.
Functions ¶
func MessageContext ¶ added in v1.2.0
MessageContext returns ctx with the trace context that a message carries in its headers, as Publish and PublishCore put it there. Consume and Subscribe give their handler this context already. Use it with msg.Headers() of a jetstream.Msg, or msg.Header of a *nats.Msg.
Types ¶
type AuthOptions ¶
type AuthOptions struct {
// AuthType specifies the authentication method to use (NoAuth, UserPassAuth,
// NKeyAuth, or CredsAuth).
AuthType AuthType
// Username is required for UserPassAuth and represents the NATS username.
Username string
// Password is required for UserPassAuth and represents the NATS password.
Password string
// NKeyFile is required for NKeyAuth and specifies the path to the NKEY private seed file.
// This file should contain an Ed25519 private key (starting with "S").
NKeyFile string
// CredsFile is required for CredsAuth and specifies the path to a NATS
// credentials file, such as one `nsc generate creds` writes.
CredsFile string
}
AuthOptions holds authentication-related settings for connecting to NATS.
type AuthType ¶
type AuthType int
AuthType defines the different authentication methods supported by the client.
const ( // NoAuth represents a connection with no authentication. NoAuth AuthType = iota // UserPassAuth represents authentication using a username and password. UserPassAuth // NKeyAuth represents authentication using NATS NKEYs (Ed25519 public-private key pairs). NKeyAuth // CredsAuth represents authentication with a NATS credentials file: a user // JWT signed by an account, and the user's NKEY seed. It is how a client // joins a NATS server running in operator (decentralized JWT) mode. CredsAuth )
type Client ¶
type Client struct {
// NC underlying connection.
NC NATSConnector
// ExtJS is the extended JetStream API for high-level operations (e.g. retrieving streams/consumers).
ExtJS jetstream.JetStream
// Opts configuration options used to create the client
Opts *Options
// KeyPair allows injecting a mock `nkeys.KeyPair` for testing authentication logic.
KeyPair nkeys.KeyPair
// contains filtered or unexported fields
}
Client provides an implementation for interacting with an embedded NATS server.
func (*Client) Close ¶
func (c *Client) Close()
Close closes the underlying NATS connection, and forgets the handles of the buckets and streams. Connect can then connect again.
func (*Client) Connect ¶
Connect establishes the connection to the NATS server and JetStream context. This method returns an error if there are any issues during connection.
A second Connect without a Close between returns ErrConnected, so that the first connection does not leak.
func (*Client) ConnectedServerVersion ¶
ConnectedServerVersion returns the version of the connected NATS server. Returns an empty string if not connected or the version is unavailable.
func (*Client) ConnectedURL ¶
ConnectedURL returns the URL of the NATS server the client is connected to. Returns an empty string if not connected.
func (*Client) Consume ¶ added in v1.2.0
func (c *Client) Consume( ctx context.Context, stream string, consumer string, handler JetStreamMessageHandler, opts *ConsumeOptions, ) error
Consume fetches the messages of the durable consumer on stream, and calls handler for each, until ctx ends. It handles up to MaxInFlight messages at the same time, and fetches only as many as it has room for. A wait for a message also ends when ctx ends. Consume returns only after each handler that it started has returned.
A message is acknowledged when handler returns nil. A handler that returns an error or panics makes it negatively acknowledged, so that JetStream delivers it again. An error that wraps ErrTerminate ends it.
A fetch that fails is tried again after a wait that doubles, up to fetchRetryLongest. A failure that a retry cannot fix, such as a closed connection or a consumer that is gone, ends Consume with that error.
func (*Client) ConsumerCreateOrUpdate ¶ added in v1.2.0
func (c *Client) ConsumerCreateOrUpdate( ctx context.Context, stream string, config jetstream.ConsumerConfig, ) error
ConsumerCreateOrUpdate creates the durable consumer of config on stream, or updates it to match.
func (*Client) KVCreate ¶ added in v1.2.0
func (c *Client) KVCreate( ctx context.Context, bucket string, key string, value []byte, ) (uint64, error)
KVCreate writes value to key in bucket only when the key is not there, and returns the revision. A key that is there returns jetstream.ErrKeyExists.
func (*Client) KVCreateOrUpdate ¶ added in v1.2.0
KVCreateOrUpdate creates the KV bucket of config, or updates it to match.
NATS does not allow a change of the storage type of an existing bucket. When only that differs, the bucket stays as it is, and the other settings that can change are not applied.
func (*Client) KVGet ¶
func (c *Client) KVGet( ctx context.Context, bucket string, key string, ) (jetstream.KeyValueEntry, error)
KVGet returns the entry of key in bucket. A key that is not there returns jetstream.ErrKeyNotFound.
func (*Client) KVKeys ¶
KVKeys returns the keys of bucket that match one of filters, such as "jobs.>", or each key when there is no filter. A bucket with no key returns an empty list, not an error.
func (*Client) KVPut ¶
func (c *Client) KVPut( ctx context.Context, bucket string, key string, value []byte, ) (uint64, error)
KVPut writes value to key in bucket, and returns the new revision.
func (*Client) KVStatus ¶ added in v1.2.0
KVStatus returns the status of bucket, such as its count of values and its size.
func (*Client) KVUpdate ¶ added in v1.2.0
func (c *Client) KVUpdate( ctx context.Context, bucket string, key string, value []byte, revision uint64, ) (uint64, error)
KVUpdate writes value to key in bucket only when the key is at revision, and returns the new revision.
func (*Client) KVWatch ¶ added in v1.2.0
func (c *Client) KVWatch( ctx context.Context, bucket string, pattern string, opts ...jetstream.WatchOpt, ) (<-chan jetstream.KeyValueEntry, error)
KVWatch sends each change to a key of bucket that matches pattern, such as "responses.>" or ">" for each key, on the channel that it returns. The current values come first. The watch stops, and the channel closes, when ctx ends. The span covers the start of the watch.
func (*Client) ObjectDelete ¶ added in v1.2.0
ObjectDelete deletes the object name from bucket.
func (*Client) ObjectGetBytes ¶ added in v1.2.0
ObjectGetBytes returns the content of the object name in bucket. An object that is not there returns jetstream.ErrObjectNotFound.
func (*Client) ObjectInfo ¶ added in v1.2.0
func (c *Client) ObjectInfo( ctx context.Context, bucket string, name string, ) (*jetstream.ObjectInfo, error)
ObjectInfo returns the information of the object name in bucket, such as its size and its digest, without its content.
func (*Client) ObjectList ¶ added in v1.2.0
ObjectList returns the information of each object in bucket. A bucket with no object returns an empty list, not an error.
func (*Client) ObjectPut ¶ added in v1.2.0
func (c *Client) ObjectPut( ctx context.Context, bucket string, meta jetstream.ObjectMeta, reader io.Reader, ) (*jetstream.ObjectInfo, error)
ObjectPut writes the object of meta, read from reader, to bucket.
func (*Client) ObjectPutBytes ¶ added in v1.2.0
func (c *Client) ObjectPutBytes( ctx context.Context, bucket string, name string, data []byte, ) (*jetstream.ObjectInfo, error)
ObjectPutBytes writes data as the object name to bucket.
func (*Client) ObjectStoreCreateOrUpdate ¶ added in v1.2.0
func (c *Client) ObjectStoreCreateOrUpdate( ctx context.Context, config jetstream.ObjectStoreConfig, ) error
ObjectStoreCreateOrUpdate creates the Object Store bucket of config, or updates it to match. As with KVCreateOrUpdate, a bucket whose storage type differs stays as it is.
func (*Client) ObjectStoreStatus ¶ added in v1.2.0
func (c *Client) ObjectStoreStatus( ctx context.Context, bucket string, ) (jetstream.ObjectStoreStatus, error)
ObjectStoreStatus returns the status of bucket, such as its size.
func (*Client) Publish ¶
Publish publishes data to subject in JetStream. When ctx is inside a trace, the headers of the message carry its trace context.
func (*Client) PublishCore ¶
PublishCore publishes data to subject with core NATS, not JetStream: for a message that no stream keeps, such as an enrollment request. The headers carry the trace context, as with Publish.
func (*Client) StreamCreateOrUpdate ¶ added in v1.2.0
StreamCreateOrUpdate creates the stream of config, or updates it to match. A stream whose storage type differs stays as it is.
func (*Client) StreamGetMsg ¶ added in v1.4.0
func (c *Client) StreamGetMsg( ctx context.Context, name string, seq uint64, ) (*jetstream.RawStreamMsg, error)
StreamGetMsg returns the message at seq in the stream name, read directly, with no consumer. A message that the stream no longer has, such as one past its max age, is jetstream.ErrMsgNotFound.
func (*Client) StreamInfo ¶ added in v1.2.0
StreamInfo returns the configuration and the state of the stream name, such as its count of messages and its first sequence. It asks the server each time, so the state is current.
func (*Client) StreamLastMsg ¶ added in v1.2.0
func (c *Client) StreamLastMsg( ctx context.Context, name string, subject string, ) (*jetstream.RawStreamMsg, error)
StreamLastMsg returns the last message on subject in the stream name.
func (*Client) StreamRead ¶ added in v1.2.0
func (c *Client) StreamRead( ctx context.Context, name string, from uint64, count int, ) ([]jetstream.Msg, error)
StreamRead reads up to count messages of the stream name in order, from the sequence from, or from the first message when from is 0. It waits for the messages for up to 5 seconds, and stops sooner when ctx ends. count must be 1 or more. It returns the messages that it read; when the read stopped with an error, it returns them with the error.
func (*Client) Subscribe ¶
func (c *Client) Subscribe( ctx context.Context, subject string, handler MsgHandler, ) (*nats.Subscription, error)
Subscribe calls handler for each core NATS message on subject, until the subscription is drained or unsubscribed. ctx is the base of the context of each call.
type ConsumeOptions ¶
type ConsumeOptions struct {
// MaxInFlight is the number of messages that Consume handles at the same
// time. Zero is DefaultMaxInFlight.
MaxInFlight int
}
ConsumeOptions configures message consumption behavior.
type JetStreamMessageHandler ¶
JetStreamMessageHandler handles a JetStream message, with ctx as for MsgHandler. An error makes Consume negatively acknowledge the message, so that JetStream delivers it again, after the BackOff of the consumer when it has one. An error that wraps ErrTerminate ends the message instead: JetStream does not deliver it again.
type MsgHandler ¶ added in v1.2.0
MsgHandler handles a core NATS message. ctx carries the trace of the message, so that the work of the handler is in the trace of the request that published it.
type NATSConnWrapper ¶
NATSConnWrapper is a concrete implementation of NATSConnector, wrapping a *nats.Conn.
func (*NATSConnWrapper) Close ¶
func (n *NATSConnWrapper) Close()
Close wraps the Close method of nats.Conn.
func (*NATSConnWrapper) Connect ¶
Connect establishes a connection to the NATS server with the given URL and options.
func (*NATSConnWrapper) ConnectedServerVersion ¶ added in v1.5.0
func (n *NATSConnWrapper) ConnectedServerVersion() string
ConnectedServerVersion wraps the ConnectedServerVersion method of nats.Conn. It is empty before Connect.
func (*NATSConnWrapper) ConnectedUrl ¶
func (n *NATSConnWrapper) ConnectedUrl() string
ConnectedUrl wraps the ConnectedUrl method of nats.Conn.
func (*NATSConnWrapper) JetStream ¶
func (n *NATSConnWrapper) JetStream( opts ...nats.JSOpt, ) (nats.JetStreamContext, error)
JetStream wraps the JetStream method of nats.Conn.
func (*NATSConnWrapper) Publish ¶
func (n *NATSConnWrapper) Publish( subject string, data []byte, ) error
Publish wraps the core NATS Publish method of nats.Conn.
func (*NATSConnWrapper) PublishMsg ¶ added in v1.2.0
func (n *NATSConnWrapper) PublishMsg( msg *nats.Msg, ) error
PublishMsg wraps the PublishMsg method of nats.Conn, which sends the headers of the message too.
func (*NATSConnWrapper) QueueSubscribe ¶
func (n *NATSConnWrapper) QueueSubscribe( subject, queue string, handler nats.MsgHandler, ) (*nats.Subscription, error)
QueueSubscribe wraps the QueueSubscribe method of nats.Conn.
func (*NATSConnWrapper) Subscribe ¶
func (n *NATSConnWrapper) Subscribe( subject string, handler nats.MsgHandler, ) (*nats.Subscription, error)
Subscribe wraps the Subscribe method of nats.Conn.
type NATSConnector ¶
type NATSConnector interface {
JetStream(opts ...nats.JSOpt) (nats.JetStreamContext, error)
Close()
ConnectedUrl() string
ConnectedServerVersion() string
Connect(url string, opts ...nats.Option) (*nats.Conn, error)
Subscribe(subject string, handler nats.MsgHandler) (*nats.Subscription, error)
QueueSubscribe(subject, queue string, handler nats.MsgHandler) (*nats.Subscription, error)
Publish(subject string, data []byte) error
PublishMsg(msg *nats.Msg) error
}
NATSConnector defines an interface for managing a NATS connection.
type Options ¶
type Options struct {
// Host specifies the NATS server hostname or IP address.
Host string
// Port specifies the NATS server port.
Port int
// Auth contains authentication settings for connecting to the NATS server.
Auth AuthOptions
// Name is a human-readable name for this client connection.
Name string
// TLS makes the connection use TLS, with this config: the roots it
// trusts, a client certificate, the server name. Nil connects in plain
// text, as before.
TLS *tls.Config
// Telemetry makes OpenTelemetry spans and metrics for each call to NATS
// that the client makes. A span is made only inside a trace that the
// caller started; a metric is recorded for each call. Off by default.
// See docs/client/telemetry.md.
Telemetry bool
// TracerProvider makes the spans when Telemetry is on. Nil uses the
// global provider of the application.
TracerProvider trace.TracerProvider
// MeterProvider records the metrics when Telemetry is on. Nil uses the
// global provider of the application.
MeterProvider metric.MeterProvider
// Reconnect is what the client does when the connection drops. Its zero
// value tries again forever, DefaultReconnectWait apart.
Reconnect ReconnectOptions
}
Options holds the configuration for connecting to a NATS server, including connection details and authentication settings.
type ReconnectOptions ¶ added in v1.5.0
type ReconnectOptions struct {
// MaxAttempts is the number of tries in a row after a drop. After them
// the client closes the connection, and each call fails. Zero tries
// forever, which is right for a process that runs for a long time.
MaxAttempts int
// Wait is the time between two tries. Zero is DefaultReconnectWait.
Wait time.Duration
// RetryFirstConnect makes Connect succeed when the server is not there
// yet, and try in the background as after a drop. A call before the
// connection is up waits or fails as after a drop. Without it, Connect
// returns the error of the first try, which a command that runs one
// time wants.
RetryFirstConnect bool
}
ReconnectOptions is the reconnect policy of a Client. The client logs each disconnect, each reconnect, the close of the connection, and each error that the server sends, through its logger.