Documentation
¶
Overview ¶
Package natsclient provides the NATS client factory for sqi-worker.
The worker connects over the network to the NATS server that sqi-server embeds, or to an operator-run external NATS server. The connection is configured with:
- Exponential backoff reconnection with jitter so a worker restart storm does not spike load on the server.
- Optional TLS, including mutual TLS and InsecureSkipVerify for development environments.
- Structured slog logging for all lifecycle events (connect, disconnect, reconnect, close).
Typical usage:
nc, closedCh, err := natsclient.Connect(ctx, cfg.NATS, workerID, seed, publicKey, logger)
if err != nil {
return fmt.Errorf("nats connect: %w", err)
}
defer natsclient.Drain(nc, gracePeriod, logger)
Index ¶
- func Connect(ctx context.Context, cfg workerconfig.NATSConfig, workerID string, seed []byte, ...) (*nats.Conn, <-chan struct{}, error)
- func Drain(nc *nats.Conn, gracePeriod time.Duration, logger *slog.Logger)
- func IsAuthRefusal(err error) bool
- func TLSOptions(cfg workerconfig.NATSConfig) ([]nats.Option, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Connect ¶
func Connect(ctx context.Context, cfg workerconfig.NATSConfig, workerID string, seed []byte, publicKey string, logger *slog.Logger) (*nats.Conn, <-chan struct{}, error)
Connect dials the NATS server described by cfg and returns a connected *nats.Conn and a lifecycle channel. The connection is configured for:
- MaxReconnects from cfg.MaxReconnectAttempts (-1 = unlimited).
- Exponential backoff starting at cfg.ReconnectWait, doubling each attempt, capped at protocol.MaxReconnectBackoff, with ±[protocol.ReconnectJitterFraction] randomness added so simultaneous worker restarts spread their reconnect storms.
- TLS when any of cfg.TLSCertFile, cfg.TLSKeyFile, or cfg.TLSCAFile is non-empty, or when cfg.InsecureSkipVerify is true.
A connection failure at dial time is returned as an error; a refused credential is first retried for [authRejectGrace] (see dial). After the initial connection is established, reconnect failures are handled internally with backoff until the configured max attempts are exhausted, or a refused credential has been retried for the grace, at which point the connection transitions to a closed state and the returned closedCh is closed.
Callers should select on closedCh to detect permanent disconnects that occur outside of a planned shutdown sequence.
seed and publicKey are the worker's nkey broker credential, obtained separately (see internal/worker/enroll). They are taken as parameters rather than folded into cfg so that a seed never sits in a config struct that might get logged elsewhere. An empty seed connects with no credential, which is correct on a farm that does not require worker authentication; see buildOptions for how that case is distinguished from a broker that actively rejects the connection.
workerID scopes this connection's reply inboxes to a per-worker prefix (see brokerauth.InboxPrefix). It is required whether or not a credential is present, so the connect path is identical in both modes, and it must be a single NATS subject token.
func Drain ¶
Drain gracefully closes nc by draining in-flight subscriptions and flushing any pending publishes before closing the connection. It blocks until the drain completes or gracePeriod elapses. If the grace period expires first, the connection is force-closed via nats.Conn.Close.
Drain is idempotent with respect to an already-closed connection: errors from draining a closed connection are silently ignored.
nats.Conn.Drain only starts the drain and returns at once, so Drain waits for the connection to reach the closed state itself. The worker exits right after Drain, and its last core-NATS publish, the deregister, must have left the client's buffer by then.
func IsAuthRefusal ¶ added in v0.4.0
IsAuthRefusal reports whether err is the broker refusing this connection's credential: every auth error nats.go recognizes. With IgnoreAuthErrorAbort set, one left out here would be retried silently forever.
func TLSOptions ¶ added in v0.4.0
func TLSOptions(cfg workerconfig.NATSConfig) ([]nats.Option, error)
TLSOptions returns the nats.Option(s) needed to configure TLS on the connection. It returns an empty slice when no TLS configuration is provided.
TLS is activated when any of the following are set:
- cfg.TLSCertFile / cfg.TLSKeyFile — mutual TLS client certificate
- cfg.TLSCAFile — custom CA for server cert verification
- cfg.InsecureSkipVerify — disable server cert verification
Types ¶
This section is empty.