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 ¶
- 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) 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) 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
Constants ¶
This section is empty.
Variables ¶
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) Connect ¶
Connect establishes the connection to the NATS server and JetStream context. This method returns an error if there are any issues during connection.
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. A wait for a message also ends when ctx ends. A message is acknowledged when handler returns nil. A handler that returns an error or panics leaves it unacknowledged, so that JetStream delivers it again.
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) 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 until the deadline of ctx, or for 5 seconds when ctx has none. 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 {
// QueueGroup for load balancing across multiple consumers (optional)
QueueGroup string
// MaxInFlight limits the number of unacknowledged messages
MaxInFlight int
}
ConsumeOptions configures message consumption behavior.
type JetStreamMessageHandler ¶
JetStreamMessageHandler handles a JetStream message, with ctx as for MsgHandler. An error leaves the message unacknowledged, so that JetStream delivers 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) 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
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
// 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
}
Options holds the configuration for connecting to a NATS server, including connection details and authentication settings.