Documentation
¶
Overview ¶
Package connectnats provides a NATS transport for connect-go v2.
The package implements version 1 of the Connect-over-NATS wire protocol, the only version 1.x speaks. The architecture is described in docs/design.md, the normative wire protocol in docs/protocol.md, and the implementation plan in docs/development-plan.md. The wire layer (frame parsing, header handling, subject mapping, end-stream messages, flow-control arithmetic), the server transport, and the client transport support unary, server-streaming, client-streaming, and bidirectional-streaming calls end to end. Unary calls are one request message and one response message; streaming calls use frames. A bidirectional stream allows one Send and one Receive to run concurrently, and CloseSend closes only the request direction: the handler may keep sending. Streaming calls of every shape use the same session, credit, and termination path. Trailing metadata travels in the end frame for streams and in the response header for unary calls, so no separate trailer frame exists.
In short, the transport has two forms. A unary RPC publishes one request on a per-procedure subject, so queue groups can balance calls across service instances, and the server answers with one message on the caller's reply inbox; there is no open/ready handshake and no per-call request inbox. A streaming RPC is a session made of two NATS subjects: one for client-to-server frames and one for server-to-client frames. Its open frame is published on the per-procedure subject, and after that all frames stay on the two per-RPC subjects, which keeps a stream pinned to the instance that accepted it. Neither side subscribes per call for either form: the client pools every response inbox under one wildcard subscription per Transport, and the server pools every request inbox under one per Service, so the subscription footprint does not grow with concurrency. Unary calls reuse the streaming message codec, compression, deadline, and cancellation rules but terminate with a single response. Keepalive is shared: one loop covers every stream of a Transport or Service, so idle streams do not each own a timer goroutine. Termination of a stream uses connect's own end-stream message shape, carrying the error verdict and the response trailer in a single frame.
Logging is opt-in: the transport is silent unless WithLogger supplies a logger, and then it records only protocol violations and handler panics.
Discovery for NATS micro tooling is also opt-in: WithMicroDiscovery publishes every mounted service on $SRV.PING, $SRV.INFO, and $SRV.STATS with the io.nats.micro.v1 schema, under the service token with "." replaced by "-" ("/acme.ping.v1.PingService/Ping" becomes "acme-ping-v1-PingService"). It adds one $SRV.> subscription per Service, derives its request, error, and timing counters from the same Metrics stream lifecycle, and leaves the wire protocol unchanged. It is a server-side capability; a Transport ignores the option.
Delivery is at-most-once: core NATS does not retransmit, so a gap in the per-direction sequence is reported as connect.CodeDataLoss, and a lost end frame leaves the caller unable to tell whether the handler ran. The transport never retries on its own and exposes no "safe to retry" signal; callers that need at-least-once delivery must use JetStream or their own idempotency keys. A unary call is one request and one response on the wire, so it has no keepalive frame to prove the server is still there: always pass a context with a deadline. Without one, a response lost after the request was published blocks Receive until the connection dies.
The default receive limit is 4 MiB, but the effective limit is min(WithReadMaxBytes, the server's max_payload), and NATS defaults max_payload to 1 MiB. NewTransport and Mount log one warning when the configured limit cannot be reached.
Index ¶
- Constants
- type ClientInfo
- type Metrics
- type MicroConfig
- type MicroServiceInfo
- type Option
- func WithCodecs(codecs ...connect.Codec) Option
- func WithCompressMinBytes(size int) Option
- func WithCompressors(compressors ...connect.Compressor) Option
- func WithHeaderMaxBytes(size int) Option
- func WithInboxPrefix(prefix string) Option
- func WithKeepalive(interval, timeout time.Duration) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMaxConcurrentCalls(limit int) Option
- func WithMetrics(metrics Metrics) Option
- func WithMicroDiscovery(config MicroConfig) Option
- func WithQueueGroup(group string) Option
- func WithReadBuffer(size int) Option
- func WithReadMaxBytes(size int) Option
- func WithSendCodec(name string) Option
- func WithSendCompression(name string) Option
- func WithSendMaxBytes(size int) Option
- func WithSendStallTimeout(timeout time.Duration) Option
- func WithStreamMaxBytes(size int) Option
- func WithSubjectPrefix(prefix string) Option
- func WithWindow(size int) Option
- type ServerInfo
- type Service
- type StreamMetrics
- type Transport
Examples ¶
Constants ¶
const ProtocolName = "nats"
ProtocolName is the value this transport reports in connect.CallInfo.Protocol. It is distinct from the HTTP transport protocol names (connect, grpc, grpcweb), so interceptors and metrics that branch on the protocol need a case for it.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ClientInfo ¶
type ClientInfo struct {
// StreamID is the token this transport generated for the call. A streaming
// client shares it with the server in the open frame; a single-message
// unary client encodes it in the response inbox.
StreamID string
// RequestSubject is the subject the client publishes requests on. A
// single-message unary call publishes to the method subject; a streaming
// call publishes to the server-assigned inbox returned in ready.
RequestSubject string
// ResponseSubject is the inbox the client subscribes to for responses.
ResponseSubject string
// ServerURL is the URL of the NATS server this transport was connected to
// when the stream opened, with any password redacted. It is a snapshot:
// after a reconnect it may name a server the call no longer uses.
ServerURL string
}
ClientInfo is the transport-specific information attached to a client-side connect.CallInfo.TransportInfo. The transport fills it when it opens the stream, before the first request is published, and it never changes afterwards.
func ClientInfoForContext ¶
func ClientInfoForContext(ctx context.Context) (*ClientInfo, bool)
ClientInfoForContext returns the ClientInfo of the current client-side call. It reports false outside a call opened by a Transport, including in server handlers and in client interceptors that run before the transport opens the stream.
To read the info after a call returns, attach the CallInfo to the context with connect.NewClientContext first, exactly as with connecthttp.ClientInfoForContext.
type Metrics ¶
type Metrics struct {
// StreamStarted runs once a stream is accepted by a service or created by
// a transport. Every StreamStarted is followed by exactly one StreamEnded.
StreamStarted func(StreamMetrics)
// StreamReady runs once when the ready handshake completes: the client
// accepted the server's ready frame, or the server published its own. The
// latency is the same value StreamEnded later reports as OpenLatency. A
// stream that ends before ready has no StreamReady callback.
StreamReady func(StreamMetrics, time.Duration)
// StreamEnded runs once when the stream releases its resources. The error
// is nil for a clean completion and the terminal error otherwise; use
// connect.CodeOf to bucket failures.
StreamEnded func(StreamMetrics, *connect.Error)
// CreditBlocked runs each time Send has to wait because the peer's receive
// window is full. A Send that only waits for the handshake does not count.
CreditBlocked func(StreamMetrics)
}
Metrics observes stream lifecycle counters. Every field is optional: a nil callback is skipped, and the zero value disables metrics.
Callbacks are invoked from stream goroutines, possibly concurrently, but never while the transport holds a stream lock. They must be fast and must not block: a callback runs before the operation that reported it returns, so blocking it stalls that operation. Calling Close or Send on the reporting stream is safe; calling a method that waits for the same stream to make progress (Receive, for example) deadlocks the caller. An active-stream gauge can be derived by pairing StreamStarted with StreamEnded.
type MicroConfig ¶
type MicroConfig struct {
// Version is the SemVer-compatible version reported for every service.
// nats micro tooling expects SemVer, but the adapter only requires a
// non-empty value. Mount returns CodeInvalidArgument when it is empty.
Version string
// Description is the human-readable description reported by $SRV.INFO.
// Empty is allowed.
Description string
// Metadata annotates every service. The map is copied; nil is reported as
// the empty object, matching nats.go/micro.
Metadata map[string]string
// Services overrides Version, Description, Metadata, and the published name
// for individual services, keyed by the service token from the procedure. A
// zero field inherits the value above; a non-nil Metadata map replaces the
// global one. A key that does not name a registered service is rejected by
// Mount.
Services map[string]MicroServiceInfo
}
MicroConfig configures the NATS micro discovery adapter for one Mount.
The adapter answers the read-only control verbs defined by nats.go/micro: $SRV.PING, $SRV.INFO, and $SRV.STATS, in the io.nats.micro.v1 response schema. Every service registered on the connect.Server passed to Mount is published; Services only overrides the identity of individual services.
Discovery is metadata, not a data path. Enabling it adds one $SRV.> subscription per Mount, leaves the v1 wire protocol untouched, and does not take part in dispatch. A deployment that also runs nats.go/micro services must not reuse a service name: both implementations would answer the same control subjects.
type MicroServiceInfo ¶
type MicroServiceInfo struct {
// Name replaces the published service name. The default is the service
// token from the procedure with every "." replaced by "-", so
// "/acme.ping.v1.PingService/Ping" publishes as "acme-ping-v1-PingService"
// and needs no configuration. That derived name is a single NATS token and
// is usually what a monitor already shows for the equivalent nats.go/micro
// service.
//
// Set Name only to shorten the label or to disambiguate a collision, since
// control subjects are $SRV.<verb>.<name>: the published name must be a
// single token (no ".", wildcard, or whitespace) and must be unique within
// the Mount.
Name string
// Version overrides MicroConfig.Version when non-empty.
Version string
// Description overrides MicroConfig.Description when non-empty.
Description string
// Metadata replaces MicroConfig.Metadata when non-nil. An empty non-nil
// map reports an empty object rather than the global metadata.
Metadata map[string]string
}
MicroServiceInfo overrides the discovery identity of one service. Zero values inherit the corresponding MicroConfig field.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a client transport or a mounted service. Options that only apply to one side are ignored by the other.
func WithCodecs ¶
WithCodecs replaces the supported codecs. The first is preferred when a client does not express a choice. Defaults to protobuf binary and JSON.
func WithCompressMinBytes ¶
WithCompressMinBytes sets the smallest payload worth compressing. Payloads below it are sent uncompressed even when an encoding is negotiated, which mirrors connect's compressMinBytes. Default 1024.
func WithCompressors ¶
func WithCompressors(compressors ...connect.Compressor) Option
WithCompressors replaces the supported compression algorithms. Compression is disabled when called with no arguments. Default gzip.
func WithHeaderMaxBytes ¶
WithHeaderMaxBytes bounds the total size of one received frame's headers: the sum of its keys and values, across every value. A frame over the limit fails the call with CodeResourceExhausted: on the server when it arrives in the open frame, on the client when it arrives in any response frame. Zero means no limit; Default 64 KiB, which bounds request and response metadata without being reached by normal RPCs.
Trailers are not affected: they travel in the end frame's payload, not in headers.
func WithInboxPrefix ¶
WithInboxPrefix sets the root of the per-RPC inbox space. It must match the prefix the NATS server uses for client inboxes, which is "_INBOX" unless custom_inbox_prefix is configured server-side. Default "_INBOX".
func WithKeepalive ¶
WithKeepalive sets how often an idle stream sends a ping and how long it waits before declaring the peer dead. Default 30s/90s.
WithKeepalive(0, 0) disables keepalive; a peer that dies silently is then detected only by the call's context or by the NATS connection closing. The keepalive state is shared per Transport and per Service: one heap and at most one goroutine cover every stream.
func WithLogger ¶
WithLogger sets the logger used for protocol violations and handler panics. A nil logger, the default, disables logging: the transport is silent on the happy path and does not log expected outcomes such as cancellation, an expired deadline, or a peer that closed its connection.
Protocol records carry stream (Connect-Stream), procedure, subject (the open subject), code, and error. Panic records carry the panic value and stack instead of code. The logger must be safe for concurrent use, as the standard library's loggers are.
func WithMaxConcurrentCalls ¶
WithMaxConcurrentCalls bounds how many RPCs one mounted service handles at once and how many streams one Transport keeps open. Excess calls fail immediately with CodeResourceExhausted rather than queueing. Default 1024; zero disables the limit.
func WithMetrics ¶
WithMetrics installs stream lifecycle callbacks. The zero Metrics value, the default, disables them. The callbacks report started and ended streams, the terminal code of each, and every Send that had to wait for the peer's receive window.
Example ¶
ExampleWithMetrics wires the optional stream callbacks. The zero Metrics value disables them, so the transport stays silent by default.
package main
import (
"connectrpc.com/connect/v2"
"github.com/chenjpu/connectnats"
)
func main() {
metrics := connectnats.Metrics{
StreamStarted: func(info connectnats.StreamMetrics) {
_ = info // count active streams by pairing with StreamEnded
},
StreamEnded: func(info connectnats.StreamMetrics, err *connect.Error) {
_ = info
_ = err // nil is a clean end; connect.CodeOf(err) buckets failures
},
CreditBlocked: func(info connectnats.StreamMetrics) {
_ = info // Send had to wait for the peer's receive window
},
}
_ = connectnats.WithMetrics(metrics)
}
Output:
func WithMicroDiscovery ¶
func WithMicroDiscovery(config MicroConfig) Option
WithMicroDiscovery publishes every mounted service on the NATS micro control subjects $SRV.PING, $SRV.INFO, and $SRV.STATS.
The adapter is disabled by default: when it is not enabled, Mount creates no $SRV subscription and no counters. Enabling it requires Version to be non-empty; Mount otherwise returns CodeInvalidArgument.
Each service is published under its service token with "." replaced by "-", so a generated "/acme.ping.v1.PingService/Ping" becomes "acme-ping-v1-PingService". MicroServiceInfo.Name overrides the label, and Mount rejects two services that would publish under one name because $SRV.PING.<name> must have one answer.
The adapter needs subscribe permission on "$SRV.>" to receive the control requests, plus publish permission for the reply subject it answers on: the monitor's inbox (usually "_INBOX.>") unless the user configures allow_responses. Answering is a plain msg.Respond publish, so subscribe permission alone leaves $SRV.PING unanswered. It is a server-side capability: a Transport ignores this option.
Statistics follow the Metrics contract: one stream is one request, whether it is unary or streaming, and only server-side streams are counted. The reported processing time is StreamMetrics.Duration, which includes queueing and transport time rather than handler CPU time alone. num_errors counts ends whose code is not Canceled, DeadlineExceeded, Unavailable, or DataLoss; Internal is counted as a business error because the transport cannot tell a handler-authored Internal from a local protocol violation. See docs/micro-adapter.md for the full mapping.
func WithQueueGroup ¶
WithQueueGroup sets the NATS queue group used by mounted services. Instances in the same group share the call load; instances in different groups each receive a copy of every open frame. Default "connectnats".
func WithReadBuffer ¶
WithReadBuffer sets the NATS subscription capacity used when the window is unlimited. Ignored otherwise. Default 1024.
func WithReadMaxBytes ¶
WithReadMaxBytes limits the decompressed size of a received message. Zero means no limit. Default 4 MiB, matching connect's HTTP transports.
The effective receive limit is min(this, conn.MaxPayload()): nats.go rejects a message larger than the server's max_payload before the peer publishes it, so a larger value here cannot be reached. NewTransport and Mount log one warning when that happens and a logger is configured; they do not fail, because the server setting may be about to change.
func WithSendCodec ¶
WithSendCodec sets the codec used by a client for its first request. The server's codec comes from the wire, so it ignores this option.
func WithSendCompression ¶
WithSendCompression sets the compression a client applies to its request payloads. Default "identity"; the response coding follows the request.
func WithSendMaxBytes ¶
WithSendMaxBytes limits the uncompressed size of a sent message. Zero means no limit.
func WithSendStallTimeout ¶
WithSendStallTimeout bounds how long a Send may wait for the peer's receive window to open. When the window stays full for the whole timeout, Send returns CodeResourceExhausted instead of blocking until the peer consumes a message or the call context ends. Zero, the default, waits indefinitely.
The limit applies to both client and server Send. It is a per-stream error, not a protocol failure: the stream stays open, and the caller decides whether to abandon it with Close or the call's context.
func WithStreamMaxBytes ¶
WithStreamMaxBytes bounds the payload bytes one stream may buffer before the application consumes them: responses waiting in a client's Receive queue and requests waiting in a server's Receive queue. Bytes are counted as they arrived on the wire, so a compressed message counts compressed and headers are not counted. A stream that would exceed the limit fails with CodeResourceExhausted and stops reading; other streams are unaffected.
The check is off by default. With the default WithWindow(16) and the default 4 MiB WithReadMaxBytes, the message-count window already caps a stream at about 64 MiB; a smaller byte budget would fail streams that connect's HTTP transports serve, because HTTP applies backpressure instead of failing. Set this option for a tighter bound, or when the count window is disabled.
With WithWindow(0) it is required: without a count window the byte budget is the only bound on pending messages.
func WithSubjectPrefix ¶
WithSubjectPrefix sets the root of the open-subject space. Default "connect.rpc".
func WithWindow ¶
WithWindow sets how many un-consumed messages this side is willing to buffer for one stream. Zero disables the count window and is intended for benchmark experiments; it requires WithStreamMaxBytes. Default 16.
type ServerInfo ¶
type ServerInfo struct {
// Subject is the method subject the call arrived on, such as
// "connect.rpc.acme.ping.v1.PingService.Ping".
Subject string
// RequestSubject is the server-assigned inbox that a streaming client
// publishes later request frames on, sent back in the ready frame
// (Connect-Request-Subject). It is empty for a single-message unary call,
// which carries its only request in the initial message.
RequestSubject string
// ResponseSubject is the inbox the service publishes responses on, taken
// from the request's reply subject.
ResponseSubject string
// StreamID identifies the call. A streaming client supplies it in
// Connect-Stream; for a single-message unary call it is derived from the
// response inbox. It is advisory: the transport does not trust it for
// routing, but it is the natural correlation key for server logs and
// traces.
StreamID string
// QueueGroup is the queue group the mounted service uses for this call,
// or empty when the service does not load-balance.
QueueGroup string
}
ServerInfo is the transport-specific information attached to a server-side connect.CallInfo.TransportInfo. It is a snapshot of the request: the service fixes it before the handler runs, and it never changes afterwards, so handlers may read it without synchronization.
The transport fills it from whichever wire form carried the call: the single message used by unary RPCs, or the open frame used by streaming RPCs.
NATS does not expose the publisher's address or identity, so there is no peer address here; the stream ID is the handle that correlates logs across both sides (protocol.md §3).
func ServerInfoForContext ¶
func ServerInfoForContext(ctx context.Context) (*ServerInfo, bool)
ServerInfoForContext returns the ServerInfo of the current server-side call. It reports false outside a call dispatched by a mounted Service, including in client interceptors and on the client side of an RPC.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is a running set of NATS subscriptions that dispatch RPCs to a connect.Server.
Mount creates one subscription per registered service, on the service's subject wildcard. Every instance sharing the queue group receives one copy of each open frame, so they split the call load; instances in different groups each receive every frame and would answer it independently.
With WithMicroDiscovery, Mount also creates one $SRV.> subscription that answers the NATS micro control verbs for every mounted service.
A Service never closes the NATS connection it was given: connections are owned by the caller and may be shared with other users.
func Mount ¶
Mount subscribes to every service registered on server and returns the running Service. The subscriptions are flushed before Mount returns, so a client may issue calls immediately.
Mount is setup-time work: server.Register must not run concurrently with it. If any subscription fails, the subscriptions already created are removed and Mount returns the error, leaving no partially mounted service behind.
Example ¶
ExampleMount builds the server half: register handlers on a connect.Server, then mount it on a NATS connection. Every instance sharing the same queue group load-balances opens of the same procedure.
package main
import (
"context"
"log"
"time"
"connectrpc.com/connect/v2"
"github.com/chenjpu/connectnats"
"github.com/nats-io/nats.go"
)
func main() {
conn, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
server := connect.NewServer()
// pingv1connect.RegisterPingServiceHandler(server, pingServer{})
service, err := connectnats.Mount(conn, server, connectnats.WithQueueGroup("ping"))
if err != nil {
log.Print(err)
return
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = service.Shutdown(ctx)
}()
}
Output:
func (*Service) Shutdown ¶
Shutdown stops accepting new RPCs and ends the ones in flight.
It removes every service subscription first, so an open frame published afterwards reaches no subscriber and the client observes NATS's no-responders status message, which maps to CodeUnavailable. Each active call is then ended with an end frame carrying CodeUnavailable, and its handler context is canceled. The end frames are flushed before Shutdown waits, so a caller that closes the connection right after it returns cannot discard them.
Shutdown waits for the handlers to return or for ctx to expire, whichever comes first. It is idempotent and safe to call concurrently: every caller waits for the same completion. It never closes the NATS connection.
Shutdown publishes no drain or goaway broadcast (ADR-020): NATS has no connection-level RPC channel, and queue groups already choose the instance, so Unavailable is the only shutdown signal a client can act on.
func (*Service) SubscriptionCount ¶
SubscriptionCount returns the number of NATS subscriptions this service owns: one request-inbox pool, plus one method subscription and one cancellation subscription per registered service. When micro discovery is enabled it also includes the single $SRV.> subscription. It is zero after Shutdown. The connection may carry subscriptions created by other users; only the ones Mount created are counted.
type StreamMetrics ¶
type StreamMetrics struct {
// StreamID is the Connect-Stream token.
StreamID string
// Procedure is the RPC procedure.
Procedure string
// StreamType is the declared stream type of the call.
StreamType connect.StreamType
// Server reports which side ran the callback: true for a mounted service,
// false for a Transport.
Server bool
// Subscriptions is the number of NATS subscriptions the reporting side owns
// when the callback runs: one response pool on a Transport, and one request
// pool plus one per service on a Service. It is not the process-wide
// connection count.
Subscriptions int
// StartedAt is when the stream was created (client) or accepted (server).
// It is set in StreamStarted and repeated in StreamEnded.
StartedAt time.Time
// Duration is the wall-clock time from StartedAt to StreamEnded. It is zero
// in StreamStarted.
Duration time.Duration
// OpenLatency is the time from StartedAt to the ready handshake: ready
// received on a client, ready published on a server. It is zero in
// StreamStarted and zero in StreamEnded when ready never completed.
OpenLatency time.Duration
// SendWait is the total time Send spent waiting for the peer's receive
// window. Waiting for ready is excluded. It is zero in StreamStarted.
SendWait time.Duration
// DroppedMessages is the number of frames this stream's bounded queue
// dropped. Pool-level drops cannot be attributed to a stream and are not
// included; the terminal error is CodeDataLoss in that case. It is zero in
// StreamStarted.
DroppedMessages int
// ProtocolErrors reports a local frame, header, or state violation that
// terminated the stream. DataLoss is excluded because it is reported
// through DroppedMessages and the terminal code; handler errors,
// cancellation, deadlines, and connection loss are also excluded. It is
// zero in StreamStarted.
ProtocolErrors int
// ReconnectFailure reports that the stream ended with CodeUnavailable while
// the NATS connection was still reconnecting. It counts failed calls, not
// reconnect attempts: a call that fails after a reconnect completed is not
// counted. It is false in StreamStarted.
ReconnectFailure bool
// PendingMessages and PendingBytes report what was still buffered and never
// consumed by the application when the stream ended. They are zero in
// StreamStarted, and zero in StreamEnded when the application drained the
// queue. PendingBytes counts payload as it arrived on the wire: compressed
// when the message was compressed, and without frame headers.
PendingMessages int
PendingBytes int
}
StreamMetrics identifies one stream in Metrics callbacks. It is an immutable snapshot taken by the transport.
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport is a connect.Transport that sends RPCs over NATS.
A Transport owns one response-inbox subscription for all of its calls: NewTransport subscribes to <inboxPrefix>.<transportToken>.*.resp and flushes it once, and every call publishes to its own token under that tree. Messages are demultiplexed by subject token, so the subscription footprint is constant in the number of concurrent calls. A Transport owns no NATS connection: the caller passes one in and keeps ownership of it, so Close and Shutdown never close the connection. A single Transport is safe for concurrent use.
A Transport does own its streams. Close ends every in-flight call and releases the pool subscription; Shutdown does the same and waits for the calls to unwind, bounded by its context. Calls ended this way report CodeCanceled, which connect's retry policy does not retry. After Close or Shutdown, NewClientStream fails with CodeCanceled until the Transport is rebuilt.
func NewTransport ¶
NewTransport returns a Transport that publishes calls over conn. The options configure codecs, compression, the receive window, size limits, and the cap on concurrently open streams; the server-only options (queue group) are ignored.
NewTransport subscribes to the response-inbox pool and flushes it before returning, so the first call cannot race the subscription. A rejected subscription is reported immediately as CodePermissionDenied (ACL) or CodeResourceExhausted (max_subscriptions) instead of surfacing later as a call that never completes.
Example ¶
ExampleNewTransport builds the client half: wrap an existing NATS connection in a Transport, then pass connect.NewClient to generated code.
package main
import (
"log"
"time"
"connectrpc.com/connect/v2"
"github.com/chenjpu/connectnats"
"github.com/nats-io/nats.go"
)
func main() {
conn, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
transport, err := connectnats.NewTransport(
conn,
connectnats.WithWindow(16),
connectnats.WithKeepalive(30*time.Second, 90*time.Second),
)
if err != nil {
log.Print(err)
return
}
client := connect.NewClient(transport)
_ = client // pingv1connect.NewPingServiceClient(client)
}
Output:
func (*Transport) Close ¶
Close ends every in-flight call and waits for their resources to be released. The NATS connection stays open and owned by the caller.
In-flight calls see CodeCanceled from Receive; a client-streaming call sees the same error from every later Receive. The pool subscription and the shared keepalive loop are released before Close returns, so the connection's subscription count falls back to its pre-call value. Close stops opening new calls but does not close the connection, which lets the caller reuse it for other transports.
Close is idempotent and safe to call concurrently; every caller waits for the same completion.
func (*Transport) NewClientStream ¶
func (t *Transport) NewClientStream(ctx context.Context, spec connect.Spec) (connect.ClientStream, error)
NewClientStream opens a client stream for spec.
The response inbox is covered by the pool subscription NewTransport already flushed, so a call only registers a token before the open frame is published. A transport already running WithMaxConcurrentCalls streams reports CodeResourceExhausted; a closed transport or a closed connection reports CodeCanceled or CodeUnavailable.
func (*Transport) Shutdown ¶
Shutdown stops opening new calls, ends the ones in flight, and waits for them to unwind or for ctx to expire, whichever comes first.
It differs from Close only in the wait: Shutdown honors ctx, so a caller that cannot block (for example a process shutdown with a fixed budget) can bound the drain. The handlers behind the ended calls are told to stop by the cancel frames, exactly as with Close; the NATS connection is never closed.
Shutdown is idempotent and safe to call concurrently. A completion that finishes at the same moment ctx expires is reported as success.
func (*Transport) SubscriptionCount ¶
SubscriptionCount returns the number of NATS subscriptions this transport owns: one response pool while it is open, and zero after Close or Shutdown. The connection may carry subscriptions created by other users; only the ones this transport created are counted.
Source Files
¶
- client_stream.go
- compression.go
- connectnats.go
- doc.go
- errors.go
- flow.go
- header.go
- keepalive.go
- log.go
- message.go
- metadata.go
- metrics.go
- micro.go
- micro_server.go
- observability.go
- semaphore.go
- server.go
- server_dispatch.go
- server_stream.go
- stall.go
- status.go
- subject.go
- transport.go
- unary.go
- unary_client.go
- unary_server.go
- wire.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package example is the parent of the example's client and server commands.
|
Package example is the parent of the example's client and server commands. |
|
client
command
Command client calls the example PingService over NATS.
|
Command client calls the example PingService over NATS. |
|
ping/v1/pingv1connect
The example package mirrors connect-go's internal example so the two can be compared side by side: one unary, one client-streaming, one server-streaming, and one bidirectional RPC.
|
The example package mirrors connect-go's internal example so the two can be compared side by side: one unary, one client-streaming, one server-streaming, and one bidirectional RPC. |
|
server
command
Command server serves the example PingService over NATS.
|
Command server serves the example PingService over NATS. |
|
internal
|
|
|
natstest
Package natstest starts in-process NATS servers for tests.
|
Package natstest starts in-process NATS servers for tests. |