Documentation
¶
Overview ¶
Package natsclient provides the NATS client factory for sqi-worker.
Unlike the server's internal/bus package — which dials a loopback embedded broker — the worker connects to a remote NATS server hosted by sqi-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, logger)
if err != nil {
return fmt.Errorf("nats connect: %w", err)
}
defer natsclient.Drain(nc, gracePeriod, logger)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Connect ¶
func Connect(ctx context.Context, cfg workerconfig.NATSConfig, 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 [maxBackoff], with ±[jitterFraction] 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. After the initial connection is established, reconnect failures are handled internally with backoff until the configured max attempts are exhausted, 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.
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.
Types ¶
This section is empty.