client

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 11 Imported by: 1

Documentation

Overview

Package client builds a NATS connection from typed settings.

What this package adds over nats.Connect

Three things, and they are all refusals rather than features.

Every subscription gets a bounded queue, because the client library's default of 500,000 pending messages is not a bound. NATS sheds from a full subscription queue rather than blocking the publisher — which is the right behaviour, and useless if the queue is large enough that shedding only happens once memory is already gone.

Every shed is reported, because a drop nobody counts is indistinguishable from a quiet system. The connection wires one asynchronous error handler and names the subscription that fell behind.

And a connection has exactly one target. A caller that supplies both a URL and an in-process server has said two different things, and this package refuses rather than guessing which was meant.

In-process and remote are the same code

cli, err := client.Connect(ctx, settings, cred, client.InProcess(srv))
cli, err := client.Connect(ctx, settings, cred)   // settings.URL is set

Everything published or subscribed through the result is identical. That is the whole point of the module: the decision about where the broker lives is made once, in wiring, and never leaks into the code that uses it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BucketSettings

type BucketSettings struct {
	Bucket string `mapstructure:"bucket" yaml:"bucket" json:"bucket"`

	// TTL and MaxBytes bound the bucket. At least one must be set.
	TTL      time.Duration `mapstructure:"ttl" yaml:"ttl" json:"ttl"`
	MaxBytes int64         `mapstructure:"max_bytes" yaml:"max_bytes" json:"max_bytes"`

	Memory   bool `mapstructure:"memory" yaml:"memory" json:"memory"`
	Replicas int  `mapstructure:"replicas" yaml:"replicas" json:"replicas"`

	// History is how many revisions of a key are kept. Key/value only.
	History uint8 `mapstructure:"history" yaml:"history" json:"history"`
}

BucketSettings is what a key/value bucket or an object store is created from.

type Client

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

Client is a NATS connection and the settings it was built from.

A Client built by Register has no connection until the controller starts it. That is the point: go/controls owns start order, and a client that connected during wiring would have to be wired after a server the controller has not started yet. Every method reports ErrNotConnected until then rather than dereferencing a nil connection.

func Connect

func Connect(
	ctx context.Context,
	settings gonats.ClientSettings,
	cred gonats.CredentialSource,
	opts ...Option,
) (*Client, error)

Connect builds a client from settings.

cred supplies the token. It may be nil only for an in-process server with no authentication configured — anything reachable over a network wants a credential, and a nil one there is a mistake worth failing on.

func New

func New(
	settings gonats.ClientSettings,
	cred gonats.CredentialSource,
	opts ...Option,
) (*Client, error)

New builds a client without connecting it.

Settings are validated here, so a misconfiguration fails during wiring where an operator is watching, rather than at start where it is one line in a controller's output.

func Register

func Register(
	_ context.Context,
	id string,
	controller Registrar,
	settings gonats.ClientSettings,
	cred gonats.CredentialSource,
	opts ...Option,
) (*Client, error)

Register builds a client and registers its lifecycle with the controller.

Register it AFTER the server it connects to. go/controls stops services in reverse registration order, so the client drains before the server goes away underneath it. Starts are concurrent; an in-process dial waits for the server to finish starting.

This exists because the alternative does not work. A client constructed with InProcess(srv) at wiring time asks the server for a connection immediately, and a server registered with the controller has not started yet — so the obvious wiring fails with "failed to get in-process connection".

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close drains the connection and waits for the drain to finish.

Waiting is the whole point, and an earlier version did not. nats.Conn.Drain starts a goroutine and returns immediately, so a Close built on it alone reports success while handlers are still running: the controller advances, the process exits, and the broker disconnects a client that was supposedly draining. The eventual ErrDrainTimeout arrives asynchronously, thirty seconds later, at a handler nobody is listening to any more.

The context bounds the wait, and a context without a deadline gets DefaultDrainTimeout rather than waiting for ever — otherwise the hang this method exists to prevent simply moves here.

A drain cannot finish while a handler is still running, which is the point: it is what lets a subscription complete work the broker already delivered. The cost is that a handler which never returns costs the full timeout and then an error. Measured: released beforehand, a saturated subscription drains in ~10ms; still blocked, it takes the timeout and reports "drain did not finish".

func (*Client) JetStream

func (c *Client) JetStream() (jetstream.JetStream, error)

JetStream returns the JetStream context for this connection.

Unwrapped on purpose. Consuming, publishing and every verb a stream offers belong to the caller; what this package owns is what gets *created*, which is where the refusals live. See Stream, KeyValue and ObjectStore below.

func (*Client) KeyValue

func (c *Client) KeyValue(ctx context.Context, s BucketSettings) (jetstream.KeyValue, error)

KeyValue creates or opens a bucket, refusing one that is unbounded.

The returned interface is upstream's, unwrapped: sixteen methods plus four supporting interfaces is a surface this module would only fall behind. Get and Put need no opinion. Creation does.

func (*Client) Liveness

func (c *Client) Liveness() error

Liveness reports whether the client can still recover.

A closed connection cannot. That is the state this probe exists for: after repeated authentication failures NATS stops reconnecting and closes, and without this the process stays healthy for ever while carrying no traffic.

func (*Client) ObjectStore

func (c *Client) ObjectStore(ctx context.Context, s BucketSettings) (jetstream.ObjectStore, error)

ObjectStore creates or opens an object store, refusing one that is unbounded.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, subject string, data []byte) error

Publish sends data on a subject.

It exists so there is one place a publish passes through. A module whose only publish path is Raw() has nowhere to put header propagation, latency and error metrics, deadlines or subject policy — each would have to be remembered at every call site instead, which is the same as not having them.

The context is how a caller asks to be told the message arrived. Give it a deadline and this waits for the server to acknowledge the buffer; give it none and it returns as soon as the client has buffered, which is NATS' own behaviour. Confirmation costs a round trip, so it is asked for rather than assumed.

func (*Client) PublishMsg

func (c *Client) PublishMsg(ctx context.Context, msg *nats.Msg) error

PublishMsg sends a message, headers included.

func (*Client) QueueSubscribe

func (c *Client) QueueSubscribe(
	subject, queue string, handler func(*nats.Msg),
) (*nats.Subscription, error)

QueueSubscribe is Subscribe with competing consumers: each message reaches exactly one member of the named queue group rather than all of them.

func (*Client) Raw

func (c *Client) Raw() *nats.Conn

Raw returns the underlying connection.

An escape hatch, and named as one. Everything reached through here bypasses this package's policy — including nats.Conn.Subscribe, which does not bound its queue — so a second caller reaching for the same thing is a request for it to become a method here instead.

It exists because wrapping JetStream's key/value and object stores would be forty-odd methods across seven interfaces, each a place to fall behind an actively developed upstream. What this module owns is construction and policy; what a consumer does with a stream afterwards is its own business.

func (*Client) Readiness

func (c *Client) Readiness() error

Readiness reports whether the client can carry traffic right now.

Reconnecting counts as not ready. The connection will recover on its own, so this is not a liveness failure — but anything asking "can I publish?" wants the answer no while it lasts.

func (*Client) Request

func (c *Client) Request(ctx context.Context, subject string, data []byte) (*nats.Msg, error)

Request sends data and waits for one reply.

The context is the deadline. NATS' own Request takes a duration; taking a context instead means a caller's existing deadline propagates rather than being restated as a number somebody has to keep in step.

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start connects. It is the controller's StartFunc.

func (*Client) Stop

func (c *Client) Stop(ctx context.Context)

Stop drains, bounded by the context. It is the controller's StopFunc.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, s StreamSettings) (jetstream.Stream, error)

Stream creates or updates a stream, refusing one that is unbounded.

This is the whole of what the module owns about JetStream, and it is the part worth owning. Every JetStream limit defaults to unlimited, and NATS' own documentation warns that this exhausts the disk — so a stream created without one is bounded by the volume rather than by anything a person chose, and the failure arrives at whatever hour the volume fills.

func (*Client) Subscribe

func (c *Client) Subscribe(subject string, handler func(*nats.Msg)) (*nats.Subscription, error)

Subscribe registers a handler and bounds its queue.

This is the only reason this method exists rather than letting callers use the connection directly: nats.Conn.Subscribe does not bound anything, and SetPendingLimits has to be called on the subscription afterwards. A consumer that forgets gets the 500,000-message default and finds out under load.

The handler form is required rather than preferred. SetPendingLimits returns ErrTypeSubscription for a channel subscription, so a bounded queue and a shed count are only available this way.

func (*Client) WaitReady added in v0.2.0

func (c *Client) WaitReady(ctx context.Context) error

WaitReady blocks until the connection is established, the context is done, or the client is stopped.

D3. Start returns once the client is *trying*, not once it has connected, so this is how a caller waits — with the budget in its own context, where its deadline already lives:

if err := cli.WaitReady(ctx); err != nil {
	return fmt.Errorf("nats: never became ready: %w", err)
}

It returns immediately for a client that is already connected, and promptly for one that is stopped while waiting, rather than blocking until the caller's budget expires.

Client.Readiness remains the question "is it connected right now". This one is asked once, at start-up; that one is asked for ever.

type InProcessProvider

type InProcessProvider interface {
	InProcessConn() (net.Conn, error)
}

InProcessProvider is what an embedded server offers so a client in the same process can reach it without a network hop.

Declared here rather than imported so this package does not depend on the server package — a service connecting to somebody else's cluster must not pull a broker into its binary.

type Option

type Option func(*config)

Option configures a connection.

func InProcess

func InProcess(p InProcessProvider) Option

InProcess connects to a server running in this process, bypassing TCP.

func OnError

func OnError(fn func(subject string, err error)) Option

OnError is called for every asynchronous error the connection reports, with the subject where one is known.

It MUST NOT block, for the reason given on OnShed.

Asynchronous is the important word. A publish that the server later refuses on permissions returns nil from Publish and arrives here instead, so a consumer watching only returned errors sees a successful publish that never happened. Authentication failures, subscription limits and drain timeouts arrive the same way.

func OnShed

func OnShed(fn func(Shed)) Option

OnShed is called when a subscription's queue overflows and messages are dropped.

It MUST NOT block. This and OnError run on the connection's single serial callback goroutine, ahead of the closed callback a drain waits for — so a handler that blocks here starves Close, turning every shutdown into its full timeout and leaking the dispatcher goroutine permanently.

It exists so a consumer can put the number on its own health surface. The count belongs to the subscription that fell behind, because "something shed" answers a less useful question than "which consumer is behind".

func WithDrainTimeout

func WithDrainTimeout(d time.Duration) Option

WithDrainTimeout overrides how long the client library will spend draining.

It exists mostly so a test can make the library give up first. In production the module's own bound and this one are set together and agreeing is the point; overriding one without the other reintroduces the disagreement.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger asynchronous errors are reported through.

Defaults to slog.Default() rather than to nothing. A module whose stated purpose is that a shed is never silent cannot have "report it" be opt-in: the consumer most likely to lose messages unnoticed is the one that never configured anything.

type Registrar

type Registrar interface {
	Register(id string, opts ...controls.ServiceOption)
}

Registrar is the one thing this package needs from a controller.

type Shed

type Shed struct {
	Subject string
	Queue   string
	Dropped int
}

Shed identifies a subscription that dropped messages, and how many.

Subject is the subscription's PATTERN, not the message subject — measured, because it decides whether this is safe to use as a metric label. A subscription to `tenant.*.events` reports `tenant.*.events` however many tenants publish through it, so cardinality is bounded by the number of subscriptions and no tenant identifier appears.

Queue distinguishes two subscriptions to the same pattern in different groups, which is the one thing the subject alone cannot.

type StreamSettings

type StreamSettings struct {
	Name     string   `mapstructure:"name" yaml:"name" json:"name"`
	Subjects []string `mapstructure:"subjects" yaml:"subjects" json:"subjects"`

	// MaxAge, MaxMsgs and MaxBytes bound the stream. At least one must be set.
	MaxAge   time.Duration `mapstructure:"max_age" yaml:"max_age" json:"max_age"`
	MaxMsgs  int64         `mapstructure:"max_msgs" yaml:"max_msgs" json:"max_msgs"`
	MaxBytes int64         `mapstructure:"max_bytes" yaml:"max_bytes" json:"max_bytes"`

	// Memory keeps the stream in memory, losing it on restart. The default is
	// file storage, because a stream somebody bothered to create is usually one
	// they expected to survive a deploy.
	Memory bool `mapstructure:"memory" yaml:"memory" json:"memory"`

	Replicas int `mapstructure:"replicas" yaml:"replicas" json:"replicas"`

	// Duplicates is how long the stream remembers a publish's Nats-Msg-Id, so
	// that a publish repeated within it is stored once. Unset is not "off": the
	// server picks two minutes, or MaxAge if that is shorter, or its own limit
	// if that is shorter still. The server refuses a window longer than MaxAge
	// (spec 0002).
	Duplicates time.Duration `mapstructure:"duplicates" yaml:"duplicates" json:"duplicates"`
}

StreamSettings is what a stream is created from.

A subset of jetstream.StreamConfig: the fields this module has an opinion about, plus the ones you cannot create a stream without. Anything else is reachable by updating the returned stream, which is the caller's business.

Jump to

Keyboard shortcuts

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