Debian Codegraph @

nats.go

raw
1 // Copyright 2012-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // A Go client for the NATS messaging system (https://nats.io).
15 package nats
16
17 import (
18 "bufio"
19 "bytes"
20 "crypto/tls"
21 "crypto/x509"
22 "encoding/base64"
23 "encoding/json"
24 "errors"
25 "fmt"
26 "io"
27 "maps"
28 "math/rand"
29 "net"
30 "net/http"
31 "net/textproto"
32 "net/url"
33 "os"
34 "path/filepath"
35 "regexp"
36 "runtime"
37 "slices"
38 "strconv"
39 "strings"
40 "sync"
41 "sync/atomic"
42 "syscall"
43 "time"
44
45 "github.com/nats-io/nkeys"
46 "github.com/nats-io/nuid"
47
48 "github.com/nats-io/nats.go/util"
49 )
50
51 // Default Constants
52 const (
53 Version = "1.54.0"
54 DefaultURL = "nats://127.0.0.1:4222"
55 DefaultPort = 4222
56 DefaultMaxReconnect = 60
57 DefaultReconnectWait = 2 * time.Second
58 DefaultReconnectJitter = 100 * time.Millisecond
59 DefaultReconnectJitterTLS = time.Second
60 DefaultTimeout = 2 * time.Second
61 DefaultPingInterval = 2 * time.Minute
62 DefaultMaxPingOut = 2
63 DefaultMaxChanLen = 64 * 1024 // 64k
64 DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB
65 DefaultWriteBufSize = defaultBufSize
66 RequestChanLen = 8
67 DefaultDrainTimeout = 30 * time.Second
68 DefaultFlusherTimeout = time.Minute
69 LangString = "go"
70 )
71
72 const (
73 // STALE_CONNECTION is for detection and proper handling of stale connections.
74 STALE_CONNECTION = "stale connection"
75
76 // PERMISSIONS_ERR is for when nats server subject authorization has failed.
77 PERMISSIONS_ERR = "permissions violation"
78
79 // AUTHORIZATION_ERR is for when nats server user authorization has failed.
80 AUTHORIZATION_ERR = "authorization violation"
81
82 // AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired.
83 AUTHENTICATION_EXPIRED_ERR = "user authentication expired"
84
85 // AUTHENTICATION_REVOKED_ERR is for when user authorization has been revoked.
86 AUTHENTICATION_REVOKED_ERR = "user authentication revoked"
87
88 // ACCOUNT_AUTHENTICATION_EXPIRED_ERR is for when nats server account authorization has expired.
89 ACCOUNT_AUTHENTICATION_EXPIRED_ERR = "account authentication expired"
90
91 // MAX_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit.
92 MAX_CONNECTIONS_ERR = "maximum connections exceeded"
93
94 // MAX_ACCOUNT_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit on the account.
95 MAX_ACCOUNT_CONNECTIONS_ERR = `maximum account active connections exceeded`
96
97 // MAX_SUBSCRIPTIONS_ERR is for when nats server denies the connection due to server subscriptions limit.
98 MAX_SUBSCRIPTIONS_ERR = "maximum subscriptions exceeded"
99 )
100
101 // Errors
102 var (
103 ErrConnectionClosed = errors.New("nats: connection closed")
104 ErrConnectionDraining = errors.New("nats: connection draining")
105 ErrDrainTimeout = errors.New("nats: draining connection timed out")
106 ErrConnectionReconnecting = errors.New("nats: connection reconnecting")
107 ErrSecureConnRequired = errors.New("nats: secure connection required")
108 ErrSecureConnWanted = errors.New("nats: secure connection not available")
109 ErrBadSubscription = errors.New("nats: invalid subscription")
110 ErrTypeSubscription = errors.New("nats: invalid subscription type")
111 ErrBadSubject = errors.New("nats: invalid subject")
112 ErrBadQueueName = errors.New("nats: invalid queue name")
113 ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped")
114 ErrTimeout = errors.New("nats: timeout")
115 ErrBadTimeout = errors.New("nats: timeout invalid")
116 ErrAuthorization = errors.New("nats: authorization violation")
117 ErrAuthExpired = errors.New("nats: authentication expired")
118 ErrAuthRevoked = errors.New("nats: authentication revoked")
119 ErrPermissionViolation = errors.New("nats: permissions violation")
120 ErrAccountAuthExpired = errors.New("nats: account authentication expired")
121 ErrNoServers = errors.New("nats: no servers available for connection")
122 ErrJsonParse = errors.New("nats: connect message, json parse error")
123 ErrChanArg = errors.New("nats: argument needs to be a channel type")
124 ErrMaxPayload = errors.New("nats: maximum payload exceeded")
125 ErrMaxMessages = errors.New("nats: maximum messages delivered")
126 ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription")
127 ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed")
128 ErrClientCertOrRootCAsRequired = errors.New("nats: at least one of certCB or rootCAsCB must be set")
129 ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received")
130 ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded")
131 ErrInvalidConnection = errors.New("nats: invalid connection")
132 ErrInvalidMsg = errors.New("nats: invalid message or message nil")
133 ErrInvalidArg = errors.New("nats: invalid argument")
134 ErrInvalidContext = errors.New("nats: invalid context")
135 ErrNoDeadlineContext = errors.New("nats: context requires a deadline")
136 ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server")
137 ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server")
138 ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler")
139 ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler")
140 ErrNoUserCB = errors.New("nats: user callback not defined")
141 ErrNkeyAndUser = errors.New("nats: user callback and nkey defined")
142 ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server")
143 ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION)
144 ErrTokenAlreadySet = errors.New("nats: token and token handler both set")
145 ErrUserInfoAlreadySet = errors.New("nats: cannot set user info callback and user/pass")
146 ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection")
147 ErrMsgNoReply = errors.New("nats: message does not have a reply")
148 ErrClientIPNotSupported = errors.New("nats: client IP not supported by this server")
149 ErrDisconnected = errors.New("nats: server is disconnected")
150 ErrHeadersNotSupported = errors.New("nats: headers not supported by this server")
151 ErrBadHeaderMsg = errors.New("nats: message could not decode headers")
152 ErrNoResponders = errors.New("nats: no responders available for request")
153 ErrMaxConnectionsExceeded = errors.New("nats: server maximum connections exceeded")
154 ErrMaxAccountConnectionsExceeded = errors.New("nats: maximum account active connections exceeded")
155 ErrConnectionNotTLS = errors.New("nats: connection is not tls")
156 ErrTLS = errors.New("nats: tls error")
157 ErrMaxSubscriptionsExceeded = errors.New("nats: server maximum subscriptions exceeded")
158 ErrWebSocketHeadersAlreadySet = errors.New("nats: websocket connection headers already set")
159 ErrServerNotInPool = errors.New("nats: selected server is not in the pool")
160 ErrMixingWebsocketSchemes = errors.New("nats: mixing of websocket and non websocket URLs is not allowed")
161 )
162
163 // GetDefaultOptions returns default configuration options for the client.
164 func GetDefaultOptions() Options {
165 return Options{
166 AllowReconnect: true,
167 MaxReconnect: DefaultMaxReconnect,
168 ReconnectWait: DefaultReconnectWait,
169 ReconnectJitter: DefaultReconnectJitter,
170 ReconnectJitterTLS: DefaultReconnectJitterTLS,
171 Timeout: DefaultTimeout,
172 PingInterval: DefaultPingInterval,
173 MaxPingsOut: DefaultMaxPingOut,
174 SubChanLen: DefaultMaxChanLen,
175 ReconnectBufSize: DefaultReconnectBufSize,
176 DrainTimeout: DefaultDrainTimeout,
177 FlusherTimeout: DefaultFlusherTimeout,
178 }
179 }
180
181 // Deprecated: Use GetDefaultOptions() instead.
182 // DefaultOptions is not safe for use by multiple clients.
183 // For details see #308.
184 var DefaultOptions = GetDefaultOptions()
185
186 // Status represents the state of the connection.
187 type Status int
188
189 const (
190 DISCONNECTED = Status(iota)
191 CONNECTED
192 CLOSED
193 RECONNECTING
194 CONNECTING
195 DRAINING_SUBS
196 DRAINING_PUBS
197 )
198
199 func (s Status) String() string {
200 switch s {
201 case DISCONNECTED:
202 return "DISCONNECTED"
203 case CONNECTED:
204 return "CONNECTED"
205 case CLOSED:
206 return "CLOSED"
207 case RECONNECTING:
208 return "RECONNECTING"
209 case CONNECTING:
210 return "CONNECTING"
211 case DRAINING_SUBS:
212 return "DRAINING_SUBS"
213 case DRAINING_PUBS:
214 return "DRAINING_PUBS"
215 }
216 return "unknown status"
217 }
218
219 // ConnHandler is used for asynchronous events such as
220 // disconnected and closed connections.
221 type ConnHandler func(*Conn)
222
223 // ConnErrHandler is used to process asynchronous events like
224 // disconnected connection with the error (if any).
225 type ConnErrHandler func(*Conn, error)
226
227 // ErrHandler is used to process asynchronous errors encountered
228 // while processing inbound messages.
229 type ErrHandler func(*Conn, *Subscription, error)
230
231 // UserJWTHandler is used to fetch and return the account signed
232 // JWT for this user.
233 type UserJWTHandler func() (string, error)
234
235 // TLSCertHandler is used to fetch and return tls certificate.
236 type TLSCertHandler func() (tls.Certificate, error)
237
238 // RootCAsHandler is used to fetch and return a set of root certificate
239 // authorities that clients use when verifying server certificates.
240 type RootCAsHandler func() (*x509.CertPool, error)
241
242 // SignatureHandler is used to sign a nonce from the server while
243 // authenticating with nkeys. The user should sign the nonce and
244 // return the raw signature. The client will base64 encode this to
245 // send to the server.
246 type SignatureHandler func([]byte) ([]byte, error)
247
248 // AuthTokenHandler is used to generate a new token.
249 type AuthTokenHandler func() string
250
251 // UserInfoCB is used to pass the username and password when establishing a connection.
252 type UserInfoCB func() (string, string)
253
254 // ReconnectDelayHandler is used to get from the user the desired
255 // delay the library should pause before attempting to reconnect
256 // again. Note that this is invoked after the library tried the
257 // whole list of URLs and failed to reconnect.
258 type ReconnectDelayHandler func(attempts int) time.Duration
259
260 // WebSocketHeadersHandler is an optional callback handler for generating token used for WebSocket connections.
261 type WebSocketHeadersHandler func() (http.Header, error)
262
263 // ReconnectToServerHandler is used to determine the server to reconnect to during
264 // the reconnection process. The handler receives a snapshot of available servers
265 // in the pool and should return a pointer to one of the servers from the provided
266 // slice and a delay before attempting the connection.
267 //
268 // Return values:
269 // - *Server: The server to connect to. Must be a pointer to an element from the
270 // provided servers slice. If the returned server is not in the pool, the library
271 // will fire ReconnectErrCB with ErrServerNotInPool and fall back to default
272 // server selection.
273 // - time.Duration: The delay before attempting the connection. If zero, the
274 // connection attempt is made immediately. If non-zero, the library sleeps
275 // for exactly that duration before attempting.
276 //
277 // MaxReconnect limits are enforced automatically: servers exceeding the configured
278 // MaxReconnect attempts are removed from the pool before the handler is called.
279 // To disable this limit, set MaxReconnect to a negative value.
280 type ReconnectToServerHandler func([]Server, ServerInfo) (*Server, time.Duration)
281
282 // asyncCB is used to preserve order for async callbacks.
283 type asyncCB struct {
284 f func()
285 next *asyncCB
286 }
287
288 type asyncCallbacksHandler struct {
289 mu sync.Mutex
290 cond *sync.Cond
291 head *asyncCB
292 tail *asyncCB
293 }
294
295 // Option is a function on the options for a connection.
296 type Option func(*Options) error
297
298 // CustomDialer can be used to specify any dialer, not necessarily a
299 // *net.Dialer. A CustomDialer may also implement `SkipTLSHandshake() bool`
300 // in order to skip the TLS handshake in case not required.
301 type CustomDialer interface {
302 Dial(network, address string) (net.Conn, error)
303 }
304
305 type InProcessConnProvider interface {
306 InProcessConn() (net.Conn, error)
307 }
308
309 // Options can be used to create a customized connection.
310 type Options struct {
311 // Url represents a single NATS server url to which the client
312 // will be connecting. If the Servers option is also set, it
313 // then becomes the first server in the Servers array.
314 Url string
315
316 // InProcessServer represents a NATS server running within the
317 // same process. If this is set then we will attempt to connect
318 // to the server directly rather than using external TCP conns.
319 InProcessServer InProcessConnProvider
320
321 // Servers is a configured set of servers which this client
322 // will use when attempting to connect.
323 Servers []string
324
325 // NoRandomize configures whether we will randomize the
326 // server pool.
327 NoRandomize bool
328
329 // NoEcho configures whether the server will echo back messages
330 // that are sent on this connection if we also have matching subscriptions.
331 // Note this is supported on servers >= version 1.2. Proto 1 or greater.
332 NoEcho bool
333
334 // Name is an optional name label which will be sent to the server
335 // on CONNECT to identify the client.
336 Name string
337
338 // Verbose signals the server to send an OK ack for commands
339 // successfully processed by the server.
340 Verbose bool
341
342 // Pedantic signals the server whether it should be doing further
343 // validation of subjects.
344 Pedantic bool
345
346 // Secure enables TLS secure connections that skip server
347 // verification by default. NOT RECOMMENDED.
348 Secure bool
349
350 // TLSConfig is a custom TLS configuration to use for secure
351 // transports.
352 TLSConfig *tls.Config
353
354 // TLSCertCB is used to fetch and return custom tls certificate.
355 TLSCertCB TLSCertHandler
356
357 // TLSHandshakeFirst is used to instruct the library perform
358 // the TLS handshake right after the connect and before receiving
359 // the INFO protocol from the server. If this option is enabled
360 // but the server is not configured to perform the TLS handshake
361 // first, the connection will fail.
362 TLSHandshakeFirst bool
363
364 // RootCAsCB is used to fetch and return a set of root certificate
365 // authorities that clients use when verifying server certificates.
366 RootCAsCB RootCAsHandler
367
368 // AllowReconnect enables reconnection logic to be used when we
369 // encounter a disconnect from the current server.
370 AllowReconnect bool
371
372 // MaxReconnect sets the number of reconnect attempts that will be
373 // tried before giving up. If negative, then it will never give up
374 // trying to reconnect.
375 // Defaults to 60.
376 MaxReconnect int
377
378 // ReconnectWait sets the time to back off after attempting a reconnect
379 // to a server that we were already connected to previously.
380 // Defaults to 2s.
381 ReconnectWait time.Duration
382
383 // CustomReconnectDelayCB is invoked after the library tried every
384 // URL in the server list and failed to reconnect. It passes to the
385 // user the current number of attempts. This function returns the
386 // amount of time the library will sleep before attempting to reconnect
387 // again. It is strongly recommended that this value contains some
388 // jitter to prevent all connections to attempt reconnecting at the same time.
389 CustomReconnectDelayCB ReconnectDelayHandler
390
391 // ReconnectJitter sets the upper bound for a random delay added to
392 // ReconnectWait during a reconnect when no TLS is used.
393 // Defaults to 100ms.
394 ReconnectJitter time.Duration
395
396 // ReconnectJitterTLS sets the upper bound for a random delay added to
397 // ReconnectWait during a reconnect when TLS is used.
398 // Defaults to 1s.
399 ReconnectJitterTLS time.Duration
400
401 // Timeout sets the timeout for a Dial operation on a connection.
402 // Defaults to 2s.
403 Timeout time.Duration
404
405 // DrainTimeout sets the timeout for a drain operation to complete.
406 // Defaults to 30s.
407 DrainTimeout time.Duration
408
409 // FlusherTimeout is the maximum time to wait for write operations
410 // to the underlying connection to complete (including the flusher loop).
411 // Defaults to 1m.
412 FlusherTimeout time.Duration
413
414 // ReconnectOnFlusherError, when set to true, causes the client to
415 // trigger a reconnect if the background flusher fails to write to the
416 // underlying connection for any reason (timeout, broken pipe,
417 // connection reset, EOF etc.).
418 //
419 // This is an advanced option. Most applications do not need to enable
420 // it: the server-side stale connection detection (via PingInterval /
421 // MaxPingsOut) and the read loop's own error handling will eventually
422 // notice a dead connection and the client will reconnect. Enable this
423 // only if you need faster recovery from a stalled or broken TCP write
424 // — for example, in latency-sensitive setups where waiting for a ping
425 // timeout is unacceptable.
426 //
427 // Messages buffered at the time of the error are lost, as they are
428 // with any flusher write error. The purpose of this option is to
429 // limit the blast radius by preventing further messages from being
430 // buffered into a potentially corrupted connection, not to recover
431 // the in-flight data.
432 //
433 // When triggered, the standard DisconnectErrHandler and
434 // ReconnectHandler callbacks are invoked as with any other reconnect.
435 // The first reconnect attempt bypasses the configured ReconnectWait
436 // so that recovery is as fast as possible; if that attempt fails,
437 // subsequent attempts obey the normal backoff.
438 //
439 // Defaults to false.
440 ReconnectOnFlusherError bool
441
442 // PingInterval is the period at which the client will be sending ping
443 // commands to the server, disabled if 0 or negative.
444 // Defaults to 2m.
445 PingInterval time.Duration
446
447 // MaxPingsOut is the maximum number of pending ping commands that can
448 // be awaiting a response before raising an ErrStaleConnection error.
449 // Defaults to 2.
450 MaxPingsOut int
451
452 // ClosedCB sets the closed handler that is called when a client will
453 // no longer be connected.
454 ClosedCB ConnHandler
455
456 // DisconnectedCB sets the disconnected handler that is called
457 // whenever the connection is disconnected.
458 // Will not be called if DisconnectedErrCB is set
459 // Deprecated. Use DisconnectedErrCB which passes error that caused
460 // the disconnect event.
461 DisconnectedCB ConnHandler
462
463 // DisconnectedErrCB sets the disconnected error handler that is called
464 // whenever the connection is disconnected.
465 // Disconnected error could be nil, for instance when user explicitly closes the connection.
466 // DisconnectedCB will not be called if DisconnectedErrCB is set
467 DisconnectedErrCB ConnErrHandler
468
469 // ConnectedCB sets the connected handler called when the initial connection
470 // is established. It is not invoked on successful reconnects - for reconnections,
471 // use ReconnectedCB. ConnectedCB can be used in conjunction with RetryOnFailedConnect
472 // to detect whether the initial connect was successful.
473 ConnectedCB ConnHandler
474
475 // ReconnectedCB sets the reconnected handler called whenever
476 // the connection is successfully reconnected.
477 ReconnectedCB ConnHandler
478
479 // DiscoveredServersCB sets the callback that is invoked whenever a new
480 // server has joined the cluster.
481 DiscoveredServersCB ConnHandler
482
483 // AsyncErrorCB sets the async error handler (e.g. slow consumer errors)
484 AsyncErrorCB ErrHandler
485
486 // ReconnectErrCB sets the callback that is invoked whenever a
487 // reconnect attempt fails.
488 ReconnectErrCB ConnErrHandler
489
490 // ReconnectToServerCB is called before reconnection attempt.
491 // It is used to determine the server to reconnect to out of
492 // the list of available servers.
493 // If a reconnect attempt is not successful, this callback will
494 // be called again before the next attempt.
495 ReconnectToServerCB ReconnectToServerHandler
496
497 // ReconnectBufSize is the size of the backing bufio during reconnect.
498 // Once this has been exhausted publish operations will return an error.
499 // Defaults to 8388608 bytes (8MB).
500 ReconnectBufSize int
501
502 // SubChanLen is the size of the buffered channel used between the socket
503 // goroutine and the message delivery for SyncSubscriptions.
504 // NOTE: This does not affect AsyncSubscriptions which are
505 // dictated by PendingLimits().
506 // Defaults to 65536.
507 SubChanLen int
508
509 // UserJWT sets the callback handler that will fetch a user's JWT.
510 UserJWT UserJWTHandler
511
512 // Nkey sets the public nkey that will be used to authenticate
513 // when connecting to the server. UserJWT and Nkey are mutually exclusive
514 // and if defined, UserJWT will take precedence.
515 Nkey string
516
517 // SignatureCB designates the function used to sign the nonce
518 // presented from the server.
519 SignatureCB SignatureHandler
520
521 // User sets the username to be used when connecting to the server.
522 User string
523
524 // Password sets the password to be used when connecting to a server.
525 Password string
526
527 // UserInfo sets the callback handler that will fetch the username and password.
528 UserInfo UserInfoCB
529
530 // Token sets the token to be used when connecting to a server.
531 Token string
532
533 // TokenHandler designates the function used to generate the token
534 // used when connecting to a server.
535 TokenHandler AuthTokenHandler
536
537 // Dialer allows a custom net.Dialer when forming connections.
538 // Deprecated: should use CustomDialer instead.
539 Dialer *net.Dialer
540
541 // AllowMultipathTCP controls MPTCP for connections made with Dialer.
542 // A nil value leaves Go's default unchanged. If MPTCP is unavailable,
543 // the dialer falls back to TCP. This option does not affect CustomDialer.
544 AllowMultipathTCP *bool
545
546 // CustomDialer allows to specify a custom dialer (not necessarily
547 // a *net.Dialer).
548 CustomDialer CustomDialer
549
550 // UseOldRequestStyle forces the old method of Requests that utilize
551 // a new Inbox and a new Subscription for each request.
552 UseOldRequestStyle bool
553
554 // NoCallbacksAfterClientClose allows preventing the invocation of
555 // callbacks after Close() is called. Client won't receive notifications
556 // when Close is invoked by user code. Default is to invoke the callbacks.
557 NoCallbacksAfterClientClose bool
558
559 // LameDuckModeHandler sets the callback to invoke when the server notifies
560 // the connection that it entered lame duck mode, that is, going to
561 // gradually disconnect all its connections before shutting down. This is
562 // often used in deployments when upgrading NATS Servers.
563 LameDuckModeHandler ConnHandler
564
565 // RetryOnFailedConnect sets the connection in reconnecting state right
566 // away if it can't connect to a server in the initial set. The
567 // MaxReconnect and ReconnectWait options are used for this process,
568 // similarly to when an established connection is disconnected.
569 // If a ReconnectHandler is set, it will be invoked on the first
570 // successful reconnect attempt (if the initial connect fails),
571 // and if a ClosedHandler is set, it will be invoked if
572 // it fails to connect (after exhausting the MaxReconnect attempts).
573 RetryOnFailedConnect bool
574
575 // For websocket connections, indicates to the server that the connection
576 // supports compression. If the server does too, then data will be compressed.
577 Compression bool
578
579 // For websocket connections, adds a path to connections url.
580 // This is useful when connecting to NATS behind a proxy.
581 ProxyPath string
582
583 // InboxPrefix allows the default _INBOX prefix to be customized
584 InboxPrefix string
585
586 // IgnoreAuthErrorAbort - if set to true, client opts out of the default connect behavior of aborting
587 // subsequent reconnect attempts if server returns the same auth error twice (regardless of reconnect policy).
588 IgnoreAuthErrorAbort bool
589
590 // SkipHostLookup skips the DNS lookup for the server hostname.
591 SkipHostLookup bool
592
593 // PermissionErrOnSubscribe - if set to true, the client will return ErrPermissionViolation
594 // from SubscribeSync if the server returns a permissions error for a subscription.
595 // Defaults to false.
596 PermissionErrOnSubscribe bool
597
598 // WebSocketConnectionHeaders is an optional http request headers to be sent with the WebSocket request.
599 WebSocketConnectionHeaders http.Header
600
601 // WebSocketConnectionHeadersHandler is an optional callback handler for generating token used for WebSocket connections.
602 WebSocketConnectionHeadersHandler WebSocketHeadersHandler
603
604 // SkipSubjectValidation will disable publish subject validation.
605 // NOTE: This is not recommended in general, as the performance gain is minimal
606 // and may lead to breaking protocol.
607 SkipSubjectValidation bool
608
609 // IgnoreDiscoveredServers will disable adding advertised server URLs
610 // from INFO messages to the server pool.
611 IgnoreDiscoveredServers bool
612
613 // WriteBufferSize is an advanced option that sets the flush threshold
614 // of the write buffer used to batch outgoing data before writing to
615 // the underlying connection. In most cases, the default value should
616 // not be changed. A smaller buffer reduces the amount of data that
617 // can be lost on blocked writes but may significantly reduce throughput.
618 // Defaults to 32768 bytes (32KB).
619 WriteBufferSize int
620 }
621
622 const (
623 // Scratch storage for assembling protocol headers
624 scratchSize = 512
625
626 // The size of the bufio reader/writer on top of the socket.
627 defaultBufSize = 32768
628
629 // The buffered size of the flush "kick" channel
630 flushChanSize = 1
631
632 // Default server pool size
633 srvPoolSize = 4
634
635 // NUID size
636 nuidSize = 22
637
638 // Default ports used if none is specified in given URL(s)
639 defaultWSPortString = "80"
640 defaultWSSPortString = "443"
641 defaultPortString = "4222"
642 )
643
644 // A Conn represents a bare connection to a nats-server.
645 // It can send and receive []byte payloads.
646 // The connection is safe to use in multiple Go routines concurrently.
647 type Conn struct {
648 // Keep all members for which we use atomic at the beginning of the
649 // struct and make sure they are all 64bits (or use padding if necessary).
650 // atomic.* functions crash on 32bit machines if operand is not aligned
651 // at 64bit. See https://github.com/golang/go/issues/599
652 Statistics
653 mu sync.RWMutex
654 // Opts holds the configuration of the Conn.
655 // Modifying the configuration of a running Conn is a race.
656 Opts Options
657 wg sync.WaitGroup
658 srvPool []*Server
659 current *Server
660 urls map[string]struct{} // Keep track of all known URLs (used by processInfo)
661 conn net.Conn
662 bw *natsWriter
663 br *natsReader
664 fch chan struct{}
665 info ServerInfo
666 // subsMu protects subs, ssid and the sid of every Subscription in subs,
667 // so that a subscription and the id it is registered under always stay
668 // in sync.
669 //
670 // The lock ordering for a connection is nc.mu -> nc.subsMu -> sub.mu:
671 // each of these may be acquired while holding any of the ones to its
672 // left, and none of them may be acquired while holding one to its
673 // right.
674 ssid int64
675 subsMu sync.RWMutex
676 subs map[int64]*Subscription
677 ach *asyncCallbacksHandler
678 pongs []chan struct{}
679 scratch [scratchSize]byte
680 status Status
681 statListeners map[Status]map[chan Status]struct{}
682 initc bool // true if the connection is performing the initial connect
683 err error
684 ps *parseState
685 ptmr *time.Timer
686 pout int
687 ar bool // abort reconnect
688 rqch chan struct{}
689 ws bool // true if a websocket connection
690
691 // New style response handler
692 respSub string // The wildcard subject
693 respSubPrefix string // the wildcard prefix including trailing .
694 respSubLen int // the length of the wildcard prefix excluding trailing .
695 respMux *Subscription // A single response subscription
696 respMap map[string]chan *Msg // Request map for the response msg channels
697 respRand *rand.Rand // Used for generating suffix
698
699 // Msg filters for testing.
700 // Protected by subsMu
701 filters map[string]msgFilter
702 }
703
704 type natsReader struct {
705 r io.Reader
706 buf []byte
707 off int
708 n int
709 }
710
711 type natsWriter struct {
712 w io.Writer
713 bufs []byte
714 limit int
715 pending *bytes.Buffer
716 plimit int
717 }
718
719 // Subscription represents interest in a given subject.
720 type Subscription struct {
721 mu sync.Mutex
722
723 // Key under which this subscription is registered in conn.subs.
724 // Protected by conn.subsMu, not by the mutex above.
725 sid int64
726
727 // Subject that represents this subscription. This can be different
728 // than the received subject inside a Msg if this is a wildcard.
729 Subject string
730
731 // Optional queue group name. If present, all subscriptions with the
732 // same name will form a distributed queue, and each message will
733 // only be processed by one member of the group.
734 Queue string
735
736 // For holding information about a JetStream consumer.
737 jsi *jsSub
738
739 delivered uint64
740 max uint64
741 conn *Conn
742 mcb MsgHandler
743 mch chan *Msg
744 errCh chan (error)
745 closed bool
746 sc bool
747 connClosed bool
748 draining bool
749 status SubStatus
750 statListeners map[chan SubStatus][]SubStatus
751 permissionsErr error
752
753 // Type of Subscription
754 typ SubscriptionType
755
756 // Async linked list
757 pHead *Msg
758 pTail *Msg
759 pCond *sync.Cond
760 pDone func(subject string)
761
762 // Pending stats, async subscriptions, high-speed etc.
763 pMsgs int
764 pBytes int
765 pMsgsMax int
766 pBytesMax int
767 pMsgsLimit int
768 pBytesLimit int
769 dropped int
770 }
771
772 // Status represents the state of the connection.
773 type SubStatus int
774
775 const (
776 SubscriptionActive = SubStatus(iota)
777 SubscriptionDraining
778 SubscriptionClosed
779 SubscriptionSlowConsumer
780 )
781
782 func (s SubStatus) String() string {
783 switch s {
784 case SubscriptionActive:
785 return "Active"
786 case SubscriptionDraining:
787 return "Draining"
788 case SubscriptionClosed:
789 return "Closed"
790 case SubscriptionSlowConsumer:
791 return "SlowConsumer"
792 }
793 return "unknown status"
794 }
795
796 // Msg represents a message delivered by NATS. This structure is used
797 // by Subscribers and PublishMsg().
798 //
799 // # Types of Acknowledgements
800 //
801 // In case using JetStream, there are multiple ways to ack a Msg:
802 //
803 // // Acknowledgement that a message has been processed.
804 // msg.Ack()
805 //
806 // // Negatively acknowledges a message.
807 // msg.Nak()
808 //
809 // // Terminate a message so that it is not redelivered further.
810 // msg.Term()
811 //
812 // // Signal the server that the message is being worked on and reset redelivery timer.
813 // msg.InProgress()
814 type Msg struct {
815 Subject string
816 Reply string
817 Header Header
818 Data []byte
819 Sub *Subscription
820 // Internal
821 next *Msg
822 wsz int
823 barrier *barrierInfo
824 ackd uint32
825 }
826
827 // Compares two msgs, ignores sub but checks all other public fields.
828 func (m *Msg) Equal(msg *Msg) bool {
829 if m == msg {
830 return true
831 }
832 if m == nil || msg == nil {
833 return false
834 }
835 if m.Subject != msg.Subject || m.Reply != msg.Reply {
836 return false
837 }
838 if !bytes.Equal(m.Data, msg.Data) {
839 return false
840 }
841 if len(m.Header) != len(msg.Header) {
842 return false
843 }
844 for k, v := range m.Header {
845 val, ok := msg.Header[k]
846 if !ok || len(v) != len(val) {
847 return false
848 }
849 for i, hdr := range v {
850 if hdr != val[i] {
851 return false
852 }
853 }
854 }
855 return true
856 }
857
858 // Size returns a message size in bytes.
859 func (m *Msg) Size() int {
860 if m.wsz != 0 {
861 return m.wsz
862 }
863 hdr, _ := m.headerBytes()
864 return len(m.Subject) + len(m.Reply) + len(hdr) + len(m.Data)
865 }
866
867 func (m *Msg) headerBytes() ([]byte, error) {
868 var hdr []byte
869 if len(m.Header) == 0 {
870 return hdr, nil
871 }
872
873 // Validate the keys and calculate an upper bound for the total encoded
874 // size.
875 //
876 // The size calculation may not be exact if any values contain
877 // leading/trailing whitespace (as those will be trimmed later), but a
878 // slight over-estimation here is more preferable than an under-estimation
879 // (which could lead to unnecessary memory allocations).
880 //
881 // We don't perform any special validation on header values because we
882 // consider all strings to be valid values (including Unicode strings,
883 // special characters, etc.).
884 hdrSize := len(hdrLine) + len(crlf)
885 for k, vs := range m.Header {
886 if !isHeaderKeyValid(k) {
887 return nil, ErrBadHeaderMsg
888 }
889 for _, v := range vs {
890 hdrSize += len(k) + len(v) + 4 // 4 is for the colon, space, CR, and LF
891 }
892 }
893
894 // NOTE: bytes.Buffer.WriteString() returns an error because bytes.Buffer
895 // is intended to be a valid implementation of the io.StringWriter interface.
896 // This implementation cannot actually fail in practice, so it is safe to
897 // ignore write errors here.
898 var b bytes.Buffer
899 b.Grow(hdrSize)
900 _, _ = b.WriteString(hdrLine)
901 for k, vs := range m.Header {
902 for _, v := range vs {
903 _, _ = b.WriteString(k)
904 _, _ = b.WriteString(": ")
905 writeHeaderValue(&b, v)
906 _, _ = b.WriteString(crlf)
907 }
908 }
909 _, _ = b.WriteString(crlf)
910
911 return b.Bytes(), nil
912 }
913
914 // asciiSet is a 256-byte lookup table for fast ASCII character membership testing.
915 // This implementation mirrors the one Go uses internally for many string operations,
916 // including strings.Contains().
917 //
918 // References:
919 // - https://github.com/golang/go/blob/master/src/strings/strings.go
920 type asciiSet [256]bool
921
922 func (as *asciiSet) MatchesString(s string) bool {
923
924 // Implementation note: Our high level strategy is to compare each byte in
925 // 's' with the corresponding entry in 'as'. If the entry is 'true', the
926 // character is valid, so we can move forward with the next byte in 's'. If
927 // the entry in 'as' is 'false', the character is invalid, so we can bail
928 // out.
929 //
930 // Benchmarking shows there to be some benefit to manually unrolling the
931 // loop (up to ~35% faster in some cases), so that's what we've done here.
932
933 i := 0
934
935 // Process the string in batches of 8 bytes
936 for ; i <= len(s)-8; i += 8 {
937 if !as[s[i]] {
938 return false
939 }
940 if !as[s[i+1]] {
941 return false
942 }
943 if !as[s[i+2]] {
944 return false
945 }
946 if !as[s[i+3]] {
947 return false
948 }
949 if !as[s[i+4]] {
950 return false
951 }
952 if !as[s[i+5]] {
953 return false
954 }
955 if !as[s[i+6]] {
956 return false
957 }
958 if !as[s[i+7]] {
959 return false
960 }
961 }
962
963 // Handle any remaining bytes at the end of the string
964 for ; i < len(s); i++ {
965 if !as[s[i]] {
966 return false
967 }
968 }
969 return true
970 }
971
972 // The asciiSet that represents valid header keys can be precalculated and
973 // cached since it will never change during the lifetime of the application.
974 var validHeaderKeyChars = makeValidHeaderKeyAsciiSet()
975
976 func makeValidHeaderKeyAsciiSet() asciiSet {
977
978 // ADR-4 specifies that header keys must be printable ASCII characters
979 // (e.g. those in the range [33, 126]), except for colons. This
980 // implementation is very slightly stricter, as it disallows several
981 // additional special characters.
982 const forbiddenChars = "\"()/,:;<=>?@[\\]{}"
983
984 var as asciiSet
985 for i := rune(33); i <= rune(126); i++ {
986 if !strings.ContainsRune(forbiddenChars, i) {
987 as[i] = true
988 }
989 }
990 return as
991 }
992
993 func isHeaderKeyValid(k string) bool {
994 return len(k) > 0 && validHeaderKeyChars.MatchesString(k)
995 }
996
997 var headerValueNewlineReplacer = strings.NewReplacer("\r", " ", "\n", " ")
998
999 func writeHeaderValue(buffer *bytes.Buffer, value string) {
1000
1001 // ADR-4 specifies that header values must be ASCII characters (except for
1002 // '\r' or '\n'), however the Go implementation is slightly more lenient
1003 // to maintain backwards compatibility with older versions of the library.
1004 // We allow arbitrary UTF-8 strings to be used as values and deliberately
1005 // sanitize '\r' and '\n' characters by replacing them with spaces.
1006
1007 // NOTE: It is safe to ignore the error returned by WriteString because
1008 // we're writing to a bytes.Buffer object, and that implementation never
1009 // returns an error.
1010 _, _ = headerValueNewlineReplacer.WriteString(buffer, textproto.TrimString(value))
1011 }
1012
1013 type barrierInfo struct {
1014 refs int64
1015 f func()
1016 }
1017
1018 // Tracks various stats received and sent on this connection,
1019 // including counts for messages and bytes.
1020 type Statistics struct {
1021 InMsgs uint64
1022 OutMsgs uint64
1023 InBytes uint64
1024 OutBytes uint64
1025 Reconnects uint64
1026 }
1027
1028 // Server represents a server in the pool of servers that the client can connect to.
1029 type Server struct {
1030 URL *url.URL
1031 Reconnects int
1032 didConnect bool
1033 lastErr error
1034 isImplicit bool
1035 tlsName string
1036 }
1037
1038 func (s Server) clone() Server {
1039 c := s
1040 if s.URL != nil {
1041 u := *s.URL
1042 c.URL = &u
1043 }
1044 return c
1045 }
1046
1047 // ServerInfo represents the information about the server that is sent in the INFO protocol message.
1048 type ServerInfo struct {
1049 ID string `json:"server_id"`
1050 Name string `json:"server_name"`
1051 Proto int `json:"proto"`
1052 Version string `json:"version"`
1053 Host string `json:"host"`
1054 Port int `json:"port"`
1055 Headers bool `json:"headers"`
1056 AuthRequired bool `json:"auth_required,omitempty"`
1057 TLSRequired bool `json:"tls_required,omitempty"`
1058 TLSAvailable bool `json:"tls_available,omitempty"`
1059 MaxPayload int64 `json:"max_payload"`
1060 CID uint64 `json:"client_id,omitempty"`
1061 ClientIP string `json:"client_ip,omitempty"`
1062 Nonce string `json:"nonce,omitempty"`
1063 Cluster string `json:"cluster,omitempty"`
1064 ConnectURLs []string `json:"connect_urls,omitempty"`
1065 LameDuckMode bool `json:"ldm,omitempty"`
1066 // JetStream indicates whether the server has JetStream enabled.
1067 JetStream bool `json:"jetstream,omitempty"`
1068 // IsSystemAccount indicates whether the connected client's account
1069 // is the system account.
1070 IsSystemAccount bool `json:"acc_is_sys,omitempty"`
1071 // JSApiLevel is the JetStream API level advertised by the server.
1072 // Requires nats-server v2.12.0 or later; older servers will report 0.
1073 JSApiLevel int `json:"api_lvl,omitempty"`
1074 Domain string `json:"domain,omitempty"`
1075 }
1076
1077 const (
1078 // clientProtoZero is the original client protocol from 2009.
1079 // http://nats.io/documentation/internals/nats-protocol/
1080 /* clientProtoZero */ _ = iota
1081 // clientProtoInfo signals a client can receive more then the original INFO block.
1082 // This can be used to update clients on other cluster members, etc.
1083 clientProtoInfo
1084 )
1085
1086 type connectInfo struct {
1087 Verbose bool `json:"verbose"`
1088 Pedantic bool `json:"pedantic"`
1089 UserJWT string `json:"jwt,omitempty"`
1090 Nkey string `json:"nkey,omitempty"`
1091 Signature string `json:"sig,omitempty"`
1092 User string `json:"user,omitempty"`
1093 Pass string `json:"pass,omitempty"`
1094 Token string `json:"auth_token,omitempty"`
1095 TLS bool `json:"tls_required"`
1096 Name string `json:"name"`
1097 Lang string `json:"lang"`
1098 Version string `json:"version"`
1099 Protocol int `json:"protocol"`
1100 Echo bool `json:"echo"`
1101 Headers bool `json:"headers"`
1102 NoResponders bool `json:"no_responders"`
1103 }
1104
1105 // MsgHandler is a callback function that processes messages delivered to
1106 // asynchronous subscribers.
1107 type MsgHandler func(msg *Msg)
1108
1109 // Connect will attempt to connect to the NATS system.
1110 // The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222
1111 // Comma separated arrays are also supported, e.g. urlA, urlB.
1112 // Options start with the defaults but can be overridden.
1113 // To connect to a NATS Server's websocket port, use the `ws` or `wss` scheme, such as
1114 // `ws://localhost:8080`. Note that websocket schemes cannot be mixed with others (nats/tls).
1115 func Connect(url string, options ...Option) (*Conn, error) {
1116 opts := GetDefaultOptions()
1117 opts.Servers = processUrlString(url)
1118 for _, opt := range options {
1119 if opt != nil {
1120 if err := opt(&opts); err != nil {
1121 return nil, err
1122 }
1123 }
1124 }
1125 return opts.Connect()
1126 }
1127
1128 // Options that can be passed to Connect.
1129
1130 // Name is an Option to set the client name.
1131 func Name(name string) Option {
1132 return func(o *Options) error {
1133 o.Name = name
1134 return nil
1135 }
1136 }
1137
1138 // InProcessServer is an Option that will try to establish a connection to a NATS server
1139 // running within the process instead of dialing via TCP.
1140 func InProcessServer(server InProcessConnProvider) Option {
1141 return func(o *Options) error {
1142 o.InProcessServer = server
1143 return nil
1144 }
1145 }
1146
1147 // Secure is an Option to enable TLS secure connections that skip server verification by default.
1148 // Pass a TLS Configuration for proper TLS.
1149 // A TLS Configuration using InsecureSkipVerify should NOT be used in a production setting.
1150 func Secure(tls ...*tls.Config) Option {
1151 return func(o *Options) error {
1152 o.Secure = true
1153 // Use of variadic just simplifies testing scenarios. We only take the first one.
1154 if len(tls) > 1 {
1155 return ErrMultipleTLSConfigs
1156 }
1157 if len(tls) == 1 {
1158 o.TLSConfig = tls[0]
1159 }
1160 return nil
1161 }
1162 }
1163
1164 // ClientTLSConfig is an Option to set the TLS configuration for secure
1165 // connections. It can be used to e.g. set TLS config with cert and root CAs
1166 // from memory. For simple use case of loading cert and CAs from file,
1167 // ClientCert and RootCAs options are more convenient.
1168 // If Secure is not already set this will set it as well.
1169 func ClientTLSConfig(certCB TLSCertHandler, rootCAsCB RootCAsHandler) Option {
1170 return func(o *Options) error {
1171 o.Secure = true
1172
1173 if certCB == nil && rootCAsCB == nil {
1174 return ErrClientCertOrRootCAsRequired
1175 }
1176
1177 // Smoke test the callbacks to fail early
1178 // if they are not valid.
1179 if certCB != nil {
1180 if _, err := certCB(); err != nil {
1181 return err
1182 }
1183 }
1184 if rootCAsCB != nil {
1185 if _, err := rootCAsCB(); err != nil {
1186 return err
1187 }
1188 }
1189 if o.TLSConfig == nil {
1190 o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
1191 }
1192 o.TLSCertCB = certCB
1193 o.RootCAsCB = rootCAsCB
1194 return nil
1195 }
1196 }
1197
1198 // RootCAs is a helper option to provide the RootCAs pool from a list of filenames.
1199 // If Secure is not already set this will set it as well.
1200 func RootCAs(file ...string) Option {
1201 return func(o *Options) error {
1202 rootCAsCB := func() (*x509.CertPool, error) {
1203 pool := x509.NewCertPool()
1204 for _, f := range file {
1205 rootPEM, err := os.ReadFile(f)
1206 if err != nil || rootPEM == nil {
1207 return nil, fmt.Errorf("nats: error loading or parsing rootCA file: %w", err)
1208 }
1209 ok := pool.AppendCertsFromPEM(rootPEM)
1210 if !ok {
1211 return nil, fmt.Errorf("nats: failed to parse root certificate from %q", f)
1212 }
1213 }
1214 return pool, nil
1215 }
1216 if o.TLSConfig == nil {
1217 o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
1218 }
1219 if _, err := rootCAsCB(); err != nil {
1220 return err
1221 }
1222 o.RootCAsCB = rootCAsCB
1223 o.Secure = true
1224 return nil
1225 }
1226 }
1227
1228 // ClientCert is a helper option to provide the client certificate from a file.
1229 // If Secure is not already set this will set it as well.
1230 func ClientCert(certFile, keyFile string) Option {
1231 return func(o *Options) error {
1232 tlsCertCB := func() (tls.Certificate, error) {
1233 cert, err := tls.LoadX509KeyPair(certFile, keyFile)
1234 if err != nil {
1235 return tls.Certificate{}, fmt.Errorf("nats: error loading client certificate: %w", err)
1236 }
1237 cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
1238 if err != nil {
1239 return tls.Certificate{}, fmt.Errorf("nats: error parsing client certificate: %w", err)
1240 }
1241 return cert, nil
1242 }
1243 if o.TLSConfig == nil {
1244 o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
1245 }
1246 if _, err := tlsCertCB(); err != nil {
1247 return err
1248 }
1249 o.TLSCertCB = tlsCertCB
1250 o.Secure = true
1251 return nil
1252 }
1253 }
1254
1255 // NoReconnect is an Option to turn off reconnect behavior.
1256 func NoReconnect() Option {
1257 return func(o *Options) error {
1258 o.AllowReconnect = false
1259 return nil
1260 }
1261 }
1262
1263 // DontRandomize is an Option to turn off randomizing the server pool.
1264 func DontRandomize() Option {
1265 return func(o *Options) error {
1266 o.NoRandomize = true
1267 return nil
1268 }
1269 }
1270
1271 // NoEcho is an Option to turn off messages echoing back from a server.
1272 // Note this is supported on servers >= version 1.2. Proto 1 or greater.
1273 func NoEcho() Option {
1274 return func(o *Options) error {
1275 o.NoEcho = true
1276 return nil
1277 }
1278 }
1279
1280 // ReconnectWait is an Option to set the wait time between reconnect attempts.
1281 // Defaults to 2s.
1282 func ReconnectWait(t time.Duration) Option {
1283 return func(o *Options) error {
1284 o.ReconnectWait = t
1285 return nil
1286 }
1287 }
1288
1289 // MaxReconnects is an Option to set the maximum number of reconnect attempts.
1290 // If negative, it will never stop trying to reconnect.
1291 // Defaults to 60.
1292 func MaxReconnects(max int) Option {
1293 return func(o *Options) error {
1294 o.MaxReconnect = max
1295 return nil
1296 }
1297 }
1298
1299 // ReconnectJitter is an Option to set the upper bound of a random delay added ReconnectWait.
1300 // Defaults to 100ms and 1s, respectively.
1301 func ReconnectJitter(jitter, jitterForTLS time.Duration) Option {
1302 return func(o *Options) error {
1303 o.ReconnectJitter = jitter
1304 o.ReconnectJitterTLS = jitterForTLS
1305 return nil
1306 }
1307 }
1308
1309 // CustomReconnectDelay is an Option to set the CustomReconnectDelayCB option.
1310 // See CustomReconnectDelayCB Option for more details.
1311 func CustomReconnectDelay(cb ReconnectDelayHandler) Option {
1312 return func(o *Options) error {
1313 o.CustomReconnectDelayCB = cb
1314 return nil
1315 }
1316 }
1317
1318 // ReconnectToServer is an Option to set a custom server selection callback
1319 // for reconnection attempts. The callback receives a snapshot of available
1320 // servers and must return a server from the pool to connect to and a delay
1321 // duration before attempting the connection.
1322 //
1323 // See ReconnectToServerHandler for detailed documentation and usage examples.
1324 func ReconnectToServer(cb ReconnectToServerHandler) Option {
1325 return func(o *Options) error {
1326 o.ReconnectToServerCB = cb
1327 return nil
1328 }
1329 }
1330
1331 // PingInterval is an Option to set the period for client ping commands.
1332 // Defaults to 2m.
1333 func PingInterval(t time.Duration) Option {
1334 return func(o *Options) error {
1335 o.PingInterval = t
1336 return nil
1337 }
1338 }
1339
1340 // MaxPingsOutstanding is an Option to set the maximum number of ping requests
1341 // that can go unanswered by the server before closing the connection.
1342 // Defaults to 2.
1343 func MaxPingsOutstanding(max int) Option {
1344 return func(o *Options) error {
1345 o.MaxPingsOut = max
1346 return nil
1347 }
1348 }
1349
1350 // ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
1351 // Defaults to 8388608 bytes (8MB). It can be disabled by setting it to -1.
1352 func ReconnectBufSize(size int) Option {
1353 return func(o *Options) error {
1354 o.ReconnectBufSize = size
1355 return nil
1356 }
1357 }
1358
1359 // WriteBufferSize is an advanced option that sets the flush threshold
1360 // of the write buffer used to batch outgoing data before writing to
1361 // the underlying connection. In most cases, the default value should
1362 // not be changed. A smaller buffer reduces the amount of data that
1363 // can be lost on blocked writes but may significantly reduce throughput.
1364 // Defaults to 32768 bytes (32KB).
1365 func WriteBufferSize(size int) Option {
1366 return func(o *Options) error {
1367 o.WriteBufferSize = size
1368 return nil
1369 }
1370 }
1371
1372 // Timeout is an Option to set the timeout for Dial on a connection.
1373 // Defaults to 2s.
1374 func Timeout(t time.Duration) Option {
1375 return func(o *Options) error {
1376 o.Timeout = t
1377 return nil
1378 }
1379 }
1380
1381 // FlusherTimeout is an Option to set the write (and flush) timeout on a connection.
1382 func FlusherTimeout(t time.Duration) Option {
1383 return func(o *Options) error {
1384 o.FlusherTimeout = t
1385 return nil
1386 }
1387 }
1388
1389 // ReconnectOnFlusherError is an Option to automatically trigger a
1390 // reconnect when the background flusher hits any write error. See
1391 // [Options.ReconnectOnFlusherError] for details. This is an
1392 // advanced option and is usually not required.
1393 func ReconnectOnFlusherError() Option {
1394 return func(o *Options) error {
1395 o.ReconnectOnFlusherError = true
1396 return nil
1397 }
1398 }
1399
1400 // DrainTimeout is an Option to set the timeout for draining a connection.
1401 // Defaults to 30s.
1402 func DrainTimeout(t time.Duration) Option {
1403 return func(o *Options) error {
1404 o.DrainTimeout = t
1405 return nil
1406 }
1407 }
1408
1409 // DisconnectErrHandler is an Option to set the disconnected error handler.
1410 func DisconnectErrHandler(cb ConnErrHandler) Option {
1411 return func(o *Options) error {
1412 o.DisconnectedErrCB = cb
1413 return nil
1414 }
1415 }
1416
1417 // DisconnectHandler is an Option to set the disconnected handler.
1418 // Deprecated: Use DisconnectErrHandler.
1419 func DisconnectHandler(cb ConnHandler) Option {
1420 return func(o *Options) error {
1421 o.DisconnectedCB = cb
1422 return nil
1423 }
1424 }
1425
1426 // ConnectHandler is an Option to set the connected handler.
1427 func ConnectHandler(cb ConnHandler) Option {
1428 return func(o *Options) error {
1429 o.ConnectedCB = cb
1430 return nil
1431 }
1432 }
1433
1434 // ReconnectHandler is an Option to set the reconnected handler.
1435 func ReconnectHandler(cb ConnHandler) Option {
1436 return func(o *Options) error {
1437 o.ReconnectedCB = cb
1438 return nil
1439 }
1440 }
1441
1442 // ReconnectErrHandler is an Option to set the reconnect error handler.
1443 func ReconnectErrHandler(cb ConnErrHandler) Option {
1444 return func(o *Options) error {
1445 o.ReconnectErrCB = cb
1446 return nil
1447 }
1448 }
1449
1450 // ClosedHandler is an Option to set the closed handler.
1451 func ClosedHandler(cb ConnHandler) Option {
1452 return func(o *Options) error {
1453 o.ClosedCB = cb
1454 return nil
1455 }
1456 }
1457
1458 // DiscoveredServersHandler is an Option to set the new servers handler.
1459 func DiscoveredServersHandler(cb ConnHandler) Option {
1460 return func(o *Options) error {
1461 o.DiscoveredServersCB = cb
1462 return nil
1463 }
1464 }
1465
1466 // ErrorHandler is an Option to set the async error handler.
1467 func ErrorHandler(cb ErrHandler) Option {
1468 return func(o *Options) error {
1469 o.AsyncErrorCB = cb
1470 return nil
1471 }
1472 }
1473
1474 // UserInfo is an Option to set the username and password to
1475 // use when not included directly in the URLs.
1476 func UserInfo(user, password string) Option {
1477 return func(o *Options) error {
1478 o.User = user
1479 o.Password = password
1480 return nil
1481 }
1482 }
1483
1484 func UserInfoHandler(cb UserInfoCB) Option {
1485 return func(o *Options) error {
1486 o.UserInfo = cb
1487 return nil
1488 }
1489 }
1490
1491 // Token is an Option to set the token to use
1492 // when a token is not included directly in the URLs
1493 // and when a token handler is not provided.
1494 func Token(token string) Option {
1495 return func(o *Options) error {
1496 if o.TokenHandler != nil {
1497 return ErrTokenAlreadySet
1498 }
1499 o.Token = token
1500 return nil
1501 }
1502 }
1503
1504 // TokenHandler is an Option to set the token handler to use
1505 // when a token is not included directly in the URLs
1506 // and when a token is not set.
1507 func TokenHandler(cb AuthTokenHandler) Option {
1508 return func(o *Options) error {
1509 if o.Token != "" {
1510 return ErrTokenAlreadySet
1511 }
1512 o.TokenHandler = cb
1513 return nil
1514 }
1515 }
1516
1517 // UserCredentials is a convenience function that takes a filename
1518 // for a user's JWT and a filename for the user's private Nkey seed.
1519 func UserCredentials(userOrChainedFile string, seedFiles ...string) Option {
1520 userCB := func() (string, error) {
1521 return userFromFile(userOrChainedFile)
1522 }
1523 var keyFile string
1524 if len(seedFiles) > 0 {
1525 keyFile = seedFiles[0]
1526 } else {
1527 keyFile = userOrChainedFile
1528 }
1529 sigCB := func(nonce []byte) ([]byte, error) {
1530 return sigHandler(nonce, keyFile)
1531 }
1532 return UserJWT(userCB, sigCB)
1533 }
1534
1535 // UserCredentialBytes is a convenience function that takes the JWT and seed
1536 // values as byte slices. This allows passing credentials directly from memory
1537 // or environment variables without needing to write them to disk.
1538 func UserCredentialBytes(userOrChainedFileBytes []byte, seedFiles ...[]byte) Option {
1539 userCB := func() (string, error) {
1540 return nkeys.ParseDecoratedJWT(userOrChainedFileBytes)
1541 }
1542
1543 var seedBytes []byte
1544 if len(seedFiles) > 0 {
1545 seedBytes = seedFiles[0]
1546 } else {
1547 seedBytes = userOrChainedFileBytes
1548 }
1549
1550 sigCB := func(nonce []byte) ([]byte, error) {
1551 kp, err := nkeys.ParseDecoratedNKey(seedBytes)
1552 if err != nil {
1553 return nil, fmt.Errorf("unable to extract key pair from bytes: %w", err)
1554 }
1555 defer kp.Wipe()
1556
1557 sig, _ := kp.Sign(nonce)
1558 return sig, nil
1559 }
1560
1561 return UserJWT(userCB, sigCB)
1562 }
1563
1564 // UserJWTAndSeed is a convenience function that takes the JWT and seed
1565 // values as strings.
1566 func UserJWTAndSeed(jwt string, seed string) Option {
1567 userCB := func() (string, error) {
1568 return jwt, nil
1569 }
1570
1571 sigCB := func(nonce []byte) ([]byte, error) {
1572 kp, err := nkeys.FromSeed([]byte(seed))
1573 if err != nil {
1574 return nil, fmt.Errorf("unable to extract key pair from seed: %w", err)
1575 }
1576 // Wipe our key on exit.
1577 defer kp.Wipe()
1578
1579 sig, _ := kp.Sign(nonce)
1580 return sig, nil
1581 }
1582
1583 return UserJWT(userCB, sigCB)
1584 }
1585
1586 // UserJWT will set the callbacks to retrieve the user's JWT and
1587 // the signature callback to sign the server nonce. This an the Nkey
1588 // option are mutually exclusive.
1589 func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option {
1590 return func(o *Options) error {
1591 if userCB == nil {
1592 return ErrNoUserCB
1593 }
1594 if sigCB == nil {
1595 return ErrUserButNoSigCB
1596 }
1597 // Smoke test the user callback to ensure it is setup properly
1598 // when processing options.
1599 if _, err := userCB(); err != nil {
1600 return err
1601 }
1602
1603 o.UserJWT = userCB
1604 o.SignatureCB = sigCB
1605 return nil
1606 }
1607 }
1608
1609 // Nkey will set the public Nkey and the signature callback to
1610 // sign the server nonce.
1611 func Nkey(pubKey string, sigCB SignatureHandler) Option {
1612 return func(o *Options) error {
1613 o.Nkey = pubKey
1614 o.SignatureCB = sigCB
1615 if pubKey != "" && sigCB == nil {
1616 return ErrNkeyButNoSigCB
1617 }
1618 return nil
1619 }
1620 }
1621
1622 // SyncQueueLen will set the maximum queue len for the internal
1623 // channel used for SubscribeSync().
1624 // Defaults to 65536.
1625 func SyncQueueLen(max int) Option {
1626 return func(o *Options) error {
1627 o.SubChanLen = max
1628 return nil
1629 }
1630 }
1631
1632 // Dialer is an Option to set the dialer which will be used when
1633 // attempting to establish a connection.
1634 // Deprecated: Should use CustomDialer instead.
1635 func Dialer(dialer *net.Dialer) Option {
1636 return func(o *Options) error {
1637 o.Dialer = dialer
1638 return nil
1639 }
1640 }
1641
1642 // MultipathTCP is an Option to enable or disable MPTCP for connections made
1643 // with the default dialer or a net.Dialer supplied through Dialer. If the
1644 // option is not specified, the dialer's existing setting or Go's default is
1645 // used. If MPTCP is unavailable, the dialer falls back to TCP. CustomDialer
1646 // takes precedence.
1647 func MultipathTCP(enabled bool) Option {
1648 return func(o *Options) error {
1649 o.AllowMultipathTCP = &enabled
1650 return nil
1651 }
1652 }
1653
1654 // SetCustomDialer is an Option to set a custom dialer which will be
1655 // used when attempting to establish a connection. If both Dialer
1656 // and CustomDialer are specified, CustomDialer takes precedence.
1657 func SetCustomDialer(dialer CustomDialer) Option {
1658 return func(o *Options) error {
1659 o.CustomDialer = dialer
1660 return nil
1661 }
1662 }
1663
1664 // UseOldRequestStyle is an Option to force usage of the old Request style.
1665 func UseOldRequestStyle() Option {
1666 return func(o *Options) error {
1667 o.UseOldRequestStyle = true
1668 return nil
1669 }
1670 }
1671
1672 // NoCallbacksAfterClientClose is an Option to disable callbacks when user code
1673 // calls Close(). If close is initiated by any other condition, callbacks
1674 // if any will be invoked.
1675 func NoCallbacksAfterClientClose() Option {
1676 return func(o *Options) error {
1677 o.NoCallbacksAfterClientClose = true
1678 return nil
1679 }
1680 }
1681
1682 // LameDuckModeHandler sets the callback to invoke when the server notifies
1683 // the connection that it entered lame duck mode, that is, going to
1684 // gradually disconnect all its connections before shutting down. This is
1685 // often used in deployments when upgrading NATS Servers.
1686 func LameDuckModeHandler(cb ConnHandler) Option {
1687 return func(o *Options) error {
1688 o.LameDuckModeHandler = cb
1689 return nil
1690 }
1691 }
1692
1693 // RetryOnFailedConnect sets the connection in reconnecting state right away
1694 // if it can't connect to a server in the initial set.
1695 // See RetryOnFailedConnect option for more details.
1696 func RetryOnFailedConnect(retry bool) Option {
1697 return func(o *Options) error {
1698 o.RetryOnFailedConnect = retry
1699 return nil
1700 }
1701 }
1702
1703 // Compression is an Option to indicate if this connection supports
1704 // compression. Currently only supported for Websocket connections.
1705 func Compression(enabled bool) Option {
1706 return func(o *Options) error {
1707 o.Compression = enabled
1708 return nil
1709 }
1710 }
1711
1712 // ProxyPath sets a path added to every WebSocket connection URL. This is
1713 // useful when NATS is behind a reverse proxy that routes by path. Unlike a
1714 // path in the connect URL, ProxyPath is also applied to server-discovered
1715 // URLs (which are bare host:port). Use ProxyPath for clustered setups
1716 // behind a proxy, so the client can connect to discovered servers on
1717 // failover. When set, it overrides any path in the connection URL.
1718 func ProxyPath(path string) Option {
1719 return func(o *Options) error {
1720 o.ProxyPath = path
1721 return nil
1722 }
1723 }
1724
1725 // CustomInboxPrefix configures the request + reply inbox prefix
1726 func CustomInboxPrefix(p string) Option {
1727 return func(o *Options) error {
1728 if p == "" || strings.Contains(p, ">") || strings.Contains(p, "*") || strings.HasSuffix(p, ".") {
1729 return errors.New("nats: invalid custom prefix")
1730 }
1731 o.InboxPrefix = p
1732 return nil
1733 }
1734 }
1735
1736 // IgnoreAuthErrorAbort opts out of the default connect behavior of aborting
1737 // subsequent reconnect attempts if server returns the same auth error twice.
1738 func IgnoreAuthErrorAbort() Option {
1739 return func(o *Options) error {
1740 o.IgnoreAuthErrorAbort = true
1741 return nil
1742 }
1743 }
1744
1745 // SkipHostLookup is an Option to skip the host lookup when connecting to a server.
1746 func SkipHostLookup() Option {
1747 return func(o *Options) error {
1748 o.SkipHostLookup = true
1749 return nil
1750 }
1751 }
1752
1753 func PermissionErrOnSubscribe(enabled bool) Option {
1754 return func(o *Options) error {
1755 o.PermissionErrOnSubscribe = enabled
1756 return nil
1757 }
1758 }
1759
1760 // TLSHandshakeFirst is an Option to perform the TLS handshake first, that is
1761 // before receiving the INFO protocol. This requires the server to also be
1762 // configured with such option, otherwise the connection will fail.
1763 func TLSHandshakeFirst() Option {
1764 return func(o *Options) error {
1765 o.TLSHandshakeFirst = true
1766 o.Secure = true
1767 return nil
1768 }
1769 }
1770
1771 // WebSocketConnectionHeaders sets a fixed set of HTTP headers that will be
1772 // sent during the WebSocket connection handshake.
1773 // This option is mutually exclusive with WebSocketConnectionHeadersHandler;
1774 // if a headers handler has already been configured, it returns
1775 // ErrWebSocketHeadersAlreadySet.
1776 func WebSocketConnectionHeaders(headers http.Header) Option {
1777 return func(o *Options) error {
1778 if o.WebSocketConnectionHeadersHandler != nil {
1779 return ErrWebSocketHeadersAlreadySet
1780 }
1781 o.WebSocketConnectionHeaders = headers
1782 return nil
1783 }
1784 }
1785
1786 // WebSocketConnectionHeadersHandler registers a callback used to supply HTTP
1787 // headers for the WebSocket connection handshake.
1788 // This option is mutually exclusive with WebSocketConnectionHeaders; if
1789 // non-empty static headers have already been configured, it returns
1790 // ErrWebSocketHeadersAlreadySet.
1791 func WebSocketConnectionHeadersHandler(cb WebSocketHeadersHandler) Option {
1792 return func(o *Options) error {
1793 if len(o.WebSocketConnectionHeaders) != 0 {
1794 return ErrWebSocketHeadersAlreadySet
1795 }
1796 o.WebSocketConnectionHeadersHandler = cb
1797 return nil
1798 }
1799 }
1800
1801 // SkipSubjectValidation is an Option to skip subject validation when
1802 // publishing messages.
1803 // By default, subject validation is performed to ensure that subjects
1804 // are valid according to NATS subject syntax (no spaces newlines and tabs).
1805 // NOTE: It is not recommended to use this option as the performance gain
1806 // is minimal and disabling subject validation can lead to breaking protocol
1807 // rules.
1808 func SkipSubjectValidation() Option {
1809 return func(o *Options) error {
1810 o.SkipSubjectValidation = true
1811 return nil
1812 }
1813 }
1814
1815 // IgnoreDiscoveredServers is an Option to disable adding advertised
1816 // server URLs from INFO messages to the server pool.
1817 func IgnoreDiscoveredServers() Option {
1818 return func(o *Options) error {
1819 o.IgnoreDiscoveredServers = true
1820 return nil
1821 }
1822 }
1823
1824 // Handler processing
1825
1826 // SetDisconnectHandler will set the disconnect event handler.
1827 // Deprecated: Use SetDisconnectErrHandler
1828 func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) {
1829 if nc == nil {
1830 return
1831 }
1832 nc.mu.Lock()
1833 defer nc.mu.Unlock()
1834 nc.Opts.DisconnectedCB = dcb
1835 }
1836
1837 // SetDisconnectErrHandler will set the disconnect event handler.
1838 func (nc *Conn) SetDisconnectErrHandler(dcb ConnErrHandler) {
1839 if nc == nil {
1840 return
1841 }
1842 nc.mu.Lock()
1843 defer nc.mu.Unlock()
1844 nc.Opts.DisconnectedErrCB = dcb
1845 }
1846
1847 // DisconnectErrHandler will return the disconnect event handler.
1848 func (nc *Conn) DisconnectErrHandler() ConnErrHandler {
1849 if nc == nil {
1850 return nil
1851 }
1852 nc.mu.Lock()
1853 defer nc.mu.Unlock()
1854 return nc.Opts.DisconnectedErrCB
1855 }
1856
1857 // SetReconnectHandler will set the reconnect event handler.
1858 func (nc *Conn) SetReconnectHandler(rcb ConnHandler) {
1859 if nc == nil {
1860 return
1861 }
1862 nc.mu.Lock()
1863 defer nc.mu.Unlock()
1864 nc.Opts.ReconnectedCB = rcb
1865 }
1866
1867 // ReconnectHandler will return the reconnect event handler.
1868 func (nc *Conn) ReconnectHandler() ConnHandler {
1869 if nc == nil {
1870 return nil
1871 }
1872 nc.mu.Lock()
1873 defer nc.mu.Unlock()
1874 return nc.Opts.ReconnectedCB
1875 }
1876
1877 // SetDiscoveredServersHandler will set the discovered servers handler.
1878 func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
1879 if nc == nil {
1880 return
1881 }
1882 nc.mu.Lock()
1883 defer nc.mu.Unlock()
1884 nc.Opts.DiscoveredServersCB = dscb
1885 }
1886
1887 // DiscoveredServersHandler will return the discovered servers handler.
1888 func (nc *Conn) DiscoveredServersHandler() ConnHandler {
1889 if nc == nil {
1890 return nil
1891 }
1892 nc.mu.Lock()
1893 defer nc.mu.Unlock()
1894 return nc.Opts.DiscoveredServersCB
1895 }
1896
1897 // SetClosedHandler will set the closed event handler.
1898 func (nc *Conn) SetClosedHandler(cb ConnHandler) {
1899 if nc == nil {
1900 return
1901 }
1902 nc.mu.Lock()
1903 defer nc.mu.Unlock()
1904 nc.Opts.ClosedCB = cb
1905 }
1906
1907 // ClosedHandler will return the closed event handler.
1908 func (nc *Conn) ClosedHandler() ConnHandler {
1909 if nc == nil {
1910 return nil
1911 }
1912 nc.mu.Lock()
1913 defer nc.mu.Unlock()
1914 return nc.Opts.ClosedCB
1915 }
1916
1917 // SetErrorHandler will set the async error handler.
1918 func (nc *Conn) SetErrorHandler(cb ErrHandler) {
1919 if nc == nil {
1920 return
1921 }
1922 nc.mu.Lock()
1923 defer nc.mu.Unlock()
1924 nc.Opts.AsyncErrorCB = cb
1925 }
1926
1927 // ErrorHandler will return the async error handler.
1928 func (nc *Conn) ErrorHandler() ErrHandler {
1929 if nc == nil {
1930 return nil
1931 }
1932 nc.mu.Lock()
1933 defer nc.mu.Unlock()
1934 return nc.Opts.AsyncErrorCB
1935 }
1936
1937 // Process the url string argument to Connect.
1938 // Return an array of urls, even if only one.
1939 func processUrlString(url string) []string {
1940 urls := strings.Split(url, ",")
1941 var j int
1942 for _, s := range urls {
1943 u := strings.TrimSuffix(strings.TrimSpace(s), "/")
1944 if len(u) > 0 {
1945 urls[j] = u
1946 j++
1947 }
1948 }
1949 return urls[:j]
1950 }
1951
1952 // Connect will attempt to connect to a NATS server with multiple options.
1953 func (o Options) Connect() (*Conn, error) {
1954 nc := &Conn{Opts: o}
1955
1956 // Some default options processing.
1957 if nc.Opts.MaxPingsOut == 0 {
1958 nc.Opts.MaxPingsOut = DefaultMaxPingOut
1959 }
1960 // Allow old default for channel length to work correctly.
1961 if nc.Opts.SubChanLen == 0 {
1962 nc.Opts.SubChanLen = DefaultMaxChanLen
1963 }
1964 // Default ReconnectBufSize
1965 if nc.Opts.ReconnectBufSize == 0 {
1966 nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
1967 }
1968 // Default WriteBufferSize
1969 if nc.Opts.WriteBufferSize <= 0 {
1970 nc.Opts.WriteBufferSize = DefaultWriteBufSize
1971 }
1972 // Ensure that Timeout is not 0
1973 if nc.Opts.Timeout == 0 {
1974 nc.Opts.Timeout = DefaultTimeout
1975 }
1976
1977 // Check first for user jwt callback being defined and nkey.
1978 if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
1979 return nil, ErrNkeyAndUser
1980 }
1981
1982 // Check if we have an nkey but no signature callback defined.
1983 if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
1984 return nil, ErrNkeyButNoSigCB
1985 }
1986
1987 // Allow custom Dialer for connecting using a timeout by default
1988 if nc.Opts.Dialer == nil {
1989 nc.Opts.Dialer = &net.Dialer{
1990 Timeout: nc.Opts.Timeout,
1991 }
1992 }
1993
1994 // If the TLSHandshakeFirst option is specified, make sure that
1995 // the Secure boolean is true.
1996 if nc.Opts.TLSHandshakeFirst {
1997 nc.Opts.Secure = true
1998 }
1999
2000 if err := nc.setupServerPool(); err != nil {
2001 return nil, err
2002 }
2003
2004 // Create the async callback handler.
2005 nc.ach = &asyncCallbacksHandler{}
2006 nc.ach.cond = sync.NewCond(&nc.ach.mu)
2007
2008 // Set a default error handler that will print to stderr.
2009 if nc.Opts.AsyncErrorCB == nil {
2010 nc.Opts.AsyncErrorCB = defaultErrHandler
2011 }
2012
2013 // Create reader/writer
2014 nc.newReaderWriter()
2015
2016 // Spin up the async cb dispatcher before connect so it's ready
2017 // to handle callbacks, especially when RetryOnFailedConnect is used
2018 // and initial connection fails.
2019 go nc.ach.asyncCBDispatcher()
2020
2021 connectionEstablished, err := nc.connect()
2022 if err != nil {
2023 nc.ach.close()
2024 return nil, err
2025 }
2026
2027 if connectionEstablished {
2028 if connectedCB := nc.Opts.ConnectedCB; connectedCB != nil {
2029 nc.ach.push(func() { connectedCB(nc) })
2030 }
2031 }
2032
2033 return nc, nil
2034 }
2035
2036 func defaultErrHandler(nc *Conn, sub *Subscription, err error) {
2037 var cid uint64
2038 if nc != nil {
2039 nc.mu.RLock()
2040 cid = nc.info.CID
2041 nc.mu.RUnlock()
2042 }
2043 var errStr string
2044 if sub != nil {
2045 var subject string
2046 sub.mu.Lock()
2047 if sub.jsi != nil {
2048 subject = sub.jsi.psubj
2049 } else {
2050 subject = sub.Subject
2051 }
2052 sub.mu.Unlock()
2053 errStr = fmt.Sprintf("%s on connection [%d] for subscription on %q\n", err.Error(), cid, subject)
2054 } else {
2055 errStr = fmt.Sprintf("%s on connection [%d]\n", err.Error(), cid)
2056 }
2057 os.Stderr.WriteString(errStr)
2058 }
2059
2060 const (
2061 _CRLF_ = "\r\n"
2062 _EMPTY_ = ""
2063 _SPC_ = " "
2064 _PUB_P_ = "PUB "
2065 _HPUB_P_ = "HPUB "
2066 )
2067
2068 var _CRLF_BYTES_ = []byte(_CRLF_)
2069
2070 const (
2071 _OK_OP_ = "+OK"
2072 _ERR_OP_ = "-ERR"
2073 _PONG_OP_ = "PONG"
2074 _INFO_OP_ = "INFO"
2075 )
2076
2077 const (
2078 connectProto = "CONNECT %s" + _CRLF_
2079 pingProto = "PING" + _CRLF_
2080 pongProto = "PONG" + _CRLF_
2081 subProto = "SUB %s %s %d" + _CRLF_
2082 unsubProto = "UNSUB %d %s" + _CRLF_
2083 okProto = _OK_OP_ + _CRLF_
2084 )
2085
2086 // Return the currently selected server
2087 func (nc *Conn) currentServer() (int, *Server) {
2088 for i, s := range nc.srvPool {
2089 if s == nil {
2090 continue
2091 }
2092 if s == nc.current {
2093 return i, s
2094 }
2095 }
2096 return -1, nil
2097 }
2098
2099 // Pop the current server and put onto the end of the list. Select head of list as long
2100 // as number of reconnect attempts under MaxReconnect.
2101 func (nc *Conn) selectNextServer() (*Server, error) {
2102 i, s := nc.currentServer()
2103 if i < 0 {
2104 return nil, ErrNoServers
2105 }
2106 sp := nc.srvPool
2107 num := len(sp)
2108 copy(sp[i:num-1], sp[i+1:num])
2109 maxReconnect := nc.Opts.MaxReconnect
2110 if maxReconnect < 0 || s.Reconnects < maxReconnect {
2111 nc.srvPool[num-1] = s
2112 } else {
2113 nc.srvPool = sp[0 : num-1]
2114 }
2115 if len(nc.srvPool) <= 0 {
2116 nc.current = nil
2117 return nil, ErrNoServers
2118 }
2119 nc.current = nc.srvPool[0]
2120 return nc.srvPool[0], nil
2121 }
2122
2123 // Will assign the correct server to nc.current
2124 func (nc *Conn) pickServer() error {
2125 nc.current = nil
2126 if len(nc.srvPool) <= 0 {
2127 return ErrNoServers
2128 }
2129
2130 for _, s := range nc.srvPool {
2131 if s != nil {
2132 nc.current = s
2133 return nil
2134 }
2135 }
2136 return ErrNoServers
2137 }
2138
2139 const tlsScheme = "tls"
2140
2141 // Create the server pool using the options given.
2142 // We will place a Url option first, followed by any
2143 // Server Options. We will randomize the server pool unless
2144 // the NoRandomize flag is set.
2145 func (nc *Conn) setupServerPool() error {
2146 nc.srvPool = make([]*Server, 0, srvPoolSize)
2147 nc.urls = make(map[string]struct{}, srvPoolSize)
2148
2149 // Create srv objects from each url string in nc.Opts.Servers
2150 // and add them to the pool.
2151 for _, urlString := range nc.Opts.Servers {
2152 if err := nc.addURLToPool(urlString, false, false); err != nil {
2153 return err
2154 }
2155 }
2156
2157 // Randomize if allowed to
2158 if !nc.Opts.NoRandomize {
2159 nc.shufflePool(0)
2160 }
2161
2162 // Normally, if this one is set, Options.Servers should not be,
2163 // but we always allowed that, so continue to do so.
2164 if nc.Opts.Url != _EMPTY_ {
2165 // Add to the end of the array
2166 if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil {
2167 return err
2168 }
2169 // Then swap it with first to guarantee that Options.Url is tried first.
2170 last := len(nc.srvPool) - 1
2171 if last > 0 {
2172 nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0]
2173 }
2174 } else if len(nc.srvPool) <= 0 {
2175 // Place default URL if pool is empty.
2176 if err := nc.addURLToPool(DefaultURL, false, false); err != nil {
2177 return err
2178 }
2179 }
2180
2181 // Check for Scheme hint to move to TLS mode.
2182 for _, srv := range nc.srvPool {
2183 if srv.URL.Scheme == tlsScheme || srv.URL.Scheme == wsSchemeTLS {
2184 // FIXME(dlc), this is for all in the pool, should be case by case.
2185 nc.Opts.Secure = true
2186 if nc.Opts.TLSConfig == nil {
2187 nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
2188 }
2189 }
2190 }
2191
2192 return nc.pickServer()
2193 }
2194
2195 // Helper function to return scheme
2196 func (nc *Conn) connScheme() string {
2197 if nc.ws {
2198 if nc.Opts.Secure {
2199 return wsSchemeTLS
2200 }
2201 return wsScheme
2202 }
2203 if nc.Opts.Secure {
2204 return tlsScheme
2205 }
2206 return "nats"
2207 }
2208
2209 // Return true iff u.Hostname() is an IP address.
2210 func hostIsIP(u *url.URL) bool {
2211 return net.ParseIP(u.Hostname()) != nil
2212 }
2213
2214 // parseServerURL parses a server URL string into a Server struct.
2215 // It handles scheme defaults and port defaults. Does not validate websocket consistency.
2216 // Returns the parsed Server and whether it's a websocket URL.
2217 func (nc *Conn) parseServerURL(sURL string, implicit, saveTLSName bool) (*Server, error) {
2218 if !strings.Contains(sURL, "://") {
2219 sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL)
2220 }
2221 var (
2222 u *url.URL
2223 err error
2224 )
2225 for i := 0; i < 2; i++ {
2226 u, err = url.Parse(sURL)
2227 if err != nil {
2228 return nil, err
2229 }
2230 if u.Port() != "" {
2231 break
2232 }
2233 // In case given URL is of the form "localhost:", just add
2234 // the port number at the end, otherwise, add ":4222".
2235 if sURL[len(sURL)-1] != ':' {
2236 sURL += ":"
2237 }
2238 switch u.Scheme {
2239 case wsScheme:
2240 sURL += defaultWSPortString
2241 case wsSchemeTLS:
2242 sURL += defaultWSSPortString
2243 default:
2244 sURL += defaultPortString
2245 }
2246 }
2247
2248 var tlsName string
2249 if implicit {
2250 curl := nc.current.URL
2251 // Check to see if we do not have a url.User but current connected
2252 // url does. If so copy over.
2253 if u.User == nil && curl.User != nil {
2254 u.User = curl.User
2255 }
2256 // We are checking to see if we have a secure connection and are
2257 // adding an implicit server that just has an IP. If so we will remember
2258 // the current hostname we are connected to.
2259 if saveTLSName && hostIsIP(u) {
2260 tlsName = curl.Hostname()
2261 }
2262 }
2263
2264 s := &Server{URL: u, isImplicit: implicit, tlsName: tlsName}
2265 return s, nil
2266 }
2267
2268 // addURLToPool adds an entry to the server pool
2269 func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error {
2270 s, err := nc.parseServerURL(sURL, implicit, saveTLSName)
2271 if err != nil {
2272 return err
2273 }
2274
2275 // We don't support mix and match of websocket and non websocket URLs.
2276 // If this is the first URL, then we accept and switch the global state
2277 // to websocket. After that, we will know how to reject mixed URLs.
2278 isWS := isWebsocketScheme(s.URL)
2279 if len(nc.srvPool) == 0 {
2280 nc.ws = isWS
2281 } else if isWS != nc.ws {
2282 return ErrMixingWebsocketSchemes
2283 }
2284
2285 nc.srvPool = append(nc.srvPool, s)
2286 nc.urls[s.URL.Host] = struct{}{}
2287 return nil
2288 }
2289
2290 // shufflePool swaps randomly elements in the server pool
2291 // The `offset` value indicates that the shuffling should start at
2292 // this offset and leave the elements from [0..offset) intact.
2293 func (nc *Conn) shufflePool(offset int) {
2294 if len(nc.srvPool) <= offset+1 {
2295 return
2296 }
2297 source := rand.NewSource(time.Now().UnixNano())
2298 r := rand.New(source)
2299 for i := offset; i < len(nc.srvPool); i++ {
2300 j := offset + r.Intn(i+1-offset)
2301 nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i]
2302 }
2303 }
2304
2305 func (nc *Conn) newReaderWriter() {
2306 nc.br = &natsReader{
2307 buf: make([]byte, defaultBufSize),
2308 off: -1,
2309 }
2310 nc.bw = &natsWriter{
2311 limit: nc.Opts.WriteBufferSize,
2312 plimit: nc.Opts.ReconnectBufSize,
2313 }
2314 }
2315
2316 func (nc *Conn) bindToNewConn() {
2317 bw := nc.bw
2318 bw.w, bw.bufs = nc.newWriter(), nil
2319 br := nc.br
2320 br.r, br.n, br.off = nc.conn, 0, -1
2321 }
2322
2323 func (nc *Conn) newWriter() io.Writer {
2324 var w io.Writer = nc.conn
2325 if nc.Opts.FlusherTimeout > 0 {
2326 w = &timeoutWriter{conn: nc.conn, timeout: nc.Opts.FlusherTimeout}
2327 }
2328 return w
2329 }
2330
2331 func (w *natsWriter) appendString(str string) error {
2332 return w.appendBufs([]byte(str))
2333 }
2334
2335 func (w *natsWriter) appendBufs(bufs ...[]byte) error {
2336 for _, buf := range bufs {
2337 if len(buf) == 0 {
2338 continue
2339 }
2340 if w.pending != nil {
2341 w.pending.Write(buf)
2342 } else {
2343 w.bufs = append(w.bufs, buf...)
2344 }
2345 }
2346 if w.pending == nil && len(w.bufs) >= w.limit {
2347 return w.flush()
2348 }
2349 return nil
2350 }
2351
2352 func (w *natsWriter) writeDirect(strs ...string) error {
2353 for _, str := range strs {
2354 if _, err := w.w.Write([]byte(str)); err != nil {
2355 return err
2356 }
2357 }
2358 return nil
2359 }
2360
2361 func (w *natsWriter) flush() error {
2362 // If a pending buffer is set, we don't flush. Code that needs to
2363 // write directly to the socket, by-passing buffers during (re)connect,
2364 // will use the writeDirect() API.
2365 if w.pending != nil {
2366 return nil
2367 }
2368 // Do not skip calling w.w.Write() here if len(w.bufs) is 0 because
2369 // the actual writer (if websocket for instance) may have things
2370 // to do such as sending control frames, etc..
2371 _, err := w.w.Write(w.bufs)
2372 w.bufs = w.bufs[:0]
2373 return err
2374 }
2375
2376 func (w *natsWriter) buffered() int {
2377 if w.pending != nil {
2378 return w.pending.Len()
2379 }
2380 return len(w.bufs)
2381 }
2382
2383 func (w *natsWriter) switchToPending() {
2384 w.pending = new(bytes.Buffer)
2385 }
2386
2387 func (w *natsWriter) flushPendingBuffer() error {
2388 if w.pending == nil || w.pending.Len() == 0 {
2389 return nil
2390 }
2391 _, err := w.w.Write(w.pending.Bytes())
2392 // Reset the pending buffer at this point because we don't want
2393 // to take the risk of sending duplicates or partials.
2394 w.pending.Reset()
2395 return err
2396 }
2397
2398 func (w *natsWriter) atLimitIfUsingPending() bool {
2399 if w.pending == nil {
2400 return false
2401 }
2402 return w.pending.Len() >= w.plimit
2403 }
2404
2405 func (w *natsWriter) doneWithPending() {
2406 w.pending = nil
2407 }
2408
2409 // Notify the reader that we are done with the connect, where "read" operations
2410 // happen synchronously and under the connection lock. After this point, "read"
2411 // will be happening from the read loop, without the connection lock.
2412 //
2413 // Note: this runs under the connection lock.
2414 func (r *natsReader) doneWithConnect() {
2415 if wsr, ok := r.r.(*websocketReader); ok {
2416 wsr.doneWithConnect()
2417 }
2418 }
2419
2420 func (r *natsReader) Read() ([]byte, error) {
2421 if r.off >= 0 {
2422 off := r.off
2423 r.off = -1
2424 return r.buf[off:r.n], nil
2425 }
2426 var err error
2427 r.n, err = r.r.Read(r.buf)
2428 return r.buf[:r.n], err
2429 }
2430
2431 func (r *natsReader) ReadString(delim byte) (string, error) {
2432 var s string
2433 build_string:
2434 // First look if we have something in the buffer
2435 if r.off >= 0 {
2436 i := bytes.IndexByte(r.buf[r.off:r.n], delim)
2437 if i >= 0 {
2438 end := r.off + i + 1
2439 s += string(r.buf[r.off:end])
2440 r.off = end
2441 if r.off >= r.n {
2442 r.off = -1
2443 }
2444 return s, nil
2445 }
2446 // We did not find the delim, so will have to read more.
2447 s += string(r.buf[r.off:r.n])
2448 r.off = -1
2449 }
2450 if _, err := r.Read(); err != nil {
2451 return s, err
2452 }
2453 r.off = 0
2454 goto build_string
2455 }
2456
2457 // createConn will connect to the server and wrap the appropriate
2458 // bufio structures. It will do the right thing when an existing
2459 // connection is in place.
2460 func (nc *Conn) createConn() (err error) {
2461 if nc.Opts.Timeout < 0 {
2462 return ErrBadTimeout
2463 }
2464 if _, cur := nc.currentServer(); cur == nil {
2465 return ErrNoServers
2466 }
2467
2468 // If we have a reference to an in-process server then establish a
2469 // connection using that.
2470 if nc.Opts.InProcessServer != nil {
2471 conn, err := nc.Opts.InProcessServer.InProcessConn()
2472 if err != nil {
2473 return fmt.Errorf("failed to get in-process connection: %w", err)
2474 }
2475 nc.conn = conn
2476 nc.bindToNewConn()
2477 return nil
2478 }
2479
2480 // We will auto-expand host names if they resolve to multiple IPs
2481 hosts := []string{}
2482 u := nc.current.URL
2483
2484 if !nc.Opts.SkipHostLookup && net.ParseIP(u.Hostname()) == nil {
2485 addrs, _ := net.LookupHost(u.Hostname())
2486 for _, addr := range addrs {
2487 hosts = append(hosts, net.JoinHostPort(addr, u.Port()))
2488 }
2489 }
2490 // Fall back to what we were given.
2491 if len(hosts) == 0 {
2492 hosts = append(hosts, u.Host)
2493 }
2494
2495 // CustomDialer takes precedence. If not set, use Opts.Dialer which
2496 // is set to a default *net.Dialer (in Connect()) if not explicitly
2497 // set by the user.
2498 dialer := nc.Opts.CustomDialer
2499 if dialer == nil {
2500 // We will copy and shorten the timeout if we have multiple hosts to try.
2501 copyDialer := *nc.Opts.Dialer
2502 copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts))
2503 if nc.Opts.AllowMultipathTCP != nil {
2504 copyDialer.SetMultipathTCP(*nc.Opts.AllowMultipathTCP)
2505 }
2506 dialer = &copyDialer
2507 }
2508
2509 if len(hosts) > 1 && !nc.Opts.NoRandomize {
2510 rand.Shuffle(len(hosts), func(i, j int) {
2511 hosts[i], hosts[j] = hosts[j], hosts[i]
2512 })
2513 }
2514 for _, host := range hosts {
2515 nc.conn, err = dialer.Dial("tcp", host)
2516 if err == nil {
2517 break
2518 }
2519 }
2520 if err != nil {
2521 return err
2522 }
2523
2524 // If scheme starts with "ws" then branch out to websocket code.
2525 if isWebsocketScheme(u) {
2526 return nc.wsInitHandshake(u)
2527 }
2528
2529 // Reset reader/writer to this new TCP connection
2530 nc.bindToNewConn()
2531 return nil
2532 }
2533
2534 type skipTLSDialer interface {
2535 SkipTLSHandshake() bool
2536 }
2537
2538 // makeTLSConn will wrap an existing Conn using TLS
2539 func (nc *Conn) makeTLSConn() error {
2540 if nc.Opts.CustomDialer != nil {
2541 // we do nothing when asked to skip the TLS wrapper
2542 sd, ok := nc.Opts.CustomDialer.(skipTLSDialer)
2543 if ok && sd.SkipTLSHandshake() {
2544 return nil
2545 }
2546 }
2547 // Allow the user to configure their own tls.Config structure.
2548 tlsCopy := &tls.Config{}
2549 if nc.Opts.TLSConfig != nil {
2550 tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig)
2551 }
2552 if nc.Opts.TLSCertCB != nil {
2553 cert, err := nc.Opts.TLSCertCB()
2554 if err != nil {
2555 return err
2556 }
2557 tlsCopy.Certificates = []tls.Certificate{cert}
2558 }
2559 if nc.Opts.RootCAsCB != nil {
2560 rootCAs, err := nc.Opts.RootCAsCB()
2561 if err != nil {
2562 return err
2563 }
2564 tlsCopy.RootCAs = rootCAs
2565 }
2566 // If its blank we will override it with the current host
2567 if tlsCopy.ServerName == _EMPTY_ {
2568 if nc.current.tlsName != _EMPTY_ {
2569 tlsCopy.ServerName = nc.current.tlsName
2570 } else {
2571 h, _, _ := net.SplitHostPort(nc.current.URL.Host)
2572 tlsCopy.ServerName = h
2573 }
2574 }
2575 nc.conn = tls.Client(nc.conn, tlsCopy)
2576 conn := nc.conn.(*tls.Conn)
2577 if err := conn.Handshake(); err != nil {
2578 return fmt.Errorf("%w: %w", ErrTLS, err)
2579 }
2580 nc.bindToNewConn()
2581 return nil
2582 }
2583
2584 // TLSConnectionState retrieves the state of the TLS connection to the server
2585 func (nc *Conn) TLSConnectionState() (tls.ConnectionState, error) {
2586 if !nc.isConnected() {
2587 return tls.ConnectionState{}, ErrDisconnected
2588 }
2589
2590 nc.mu.RLock()
2591 conn := nc.conn
2592 nc.mu.RUnlock()
2593
2594 tc, ok := conn.(*tls.Conn)
2595 if !ok {
2596 return tls.ConnectionState{}, ErrConnectionNotTLS
2597 }
2598
2599 return tc.ConnectionState(), nil
2600 }
2601
2602 // waitForExits will wait for all socket watcher Go routines to
2603 // be shutdown before proceeding.
2604 func (nc *Conn) waitForExits() {
2605 // Kick old flusher forcefully.
2606 select {
2607 case nc.fch <- struct{}{}:
2608 default:
2609 }
2610
2611 // Wait for any previous go routines.
2612 nc.wg.Wait()
2613 }
2614
2615 // ForceReconnect forces a reconnect attempt to the server.
2616 // This is a non-blocking call and will start the reconnect
2617 // process without waiting for it to complete.
2618 //
2619 // If the connection is already in the process of reconnecting,
2620 // this call will force an immediate reconnect attempt (bypassing
2621 // the current reconnect delay).
2622 func (nc *Conn) ForceReconnect() error {
2623 nc.mu.Lock()
2624 defer nc.mu.Unlock()
2625
2626 if nc.isClosed() {
2627 return ErrConnectionClosed
2628 }
2629 if nc.isReconnecting() {
2630 // if we're already reconnecting, force a reconnect attempt
2631 // even if we're in the middle of a backoff
2632 if nc.rqch != nil {
2633 close(nc.rqch)
2634 nc.rqch = nil
2635 }
2636 return nil
2637 }
2638
2639 // Clear any queued pongs
2640 nc.clearPendingFlushCalls()
2641
2642 // Clear any queued and blocking requests.
2643 nc.clearPendingRequestCalls()
2644
2645 // Stop ping timer if set.
2646 nc.stopPingTimer()
2647
2648 // flush any pending data and switch to pending mode to buffer new outgoing
2649 // data until we reconnect and can flush it.
2650 nc.bw.flush()
2651 nc.bw.switchToPending()
2652 nc.conn.Close()
2653
2654 nc.changeConnStatus(RECONNECTING)
2655 go nc.doReconnect(nil, true)
2656 return nil
2657 }
2658
2659 // ConnectedUrl reports the connected server's URL
2660 func (nc *Conn) ConnectedUrl() string {
2661 if nc == nil {
2662 return _EMPTY_
2663 }
2664
2665 nc.mu.RLock()
2666 defer nc.mu.RUnlock()
2667
2668 if nc.status != CONNECTED {
2669 return _EMPTY_
2670 }
2671 return nc.current.URL.String()
2672 }
2673
2674 // ConnectedUrlRedacted reports the connected server's URL with passwords redacted
2675 func (nc *Conn) ConnectedUrlRedacted() string {
2676 if nc == nil {
2677 return _EMPTY_
2678 }
2679
2680 nc.mu.RLock()
2681 defer nc.mu.RUnlock()
2682
2683 if nc.status != CONNECTED {
2684 return _EMPTY_
2685 }
2686 return nc.current.URL.Redacted()
2687 }
2688
2689 // ConnectedAddr returns the connected server's IP
2690 func (nc *Conn) ConnectedAddr() string {
2691 if nc == nil {
2692 return _EMPTY_
2693 }
2694
2695 nc.mu.RLock()
2696 defer nc.mu.RUnlock()
2697
2698 if nc.status != CONNECTED {
2699 return _EMPTY_
2700 }
2701 return nc.conn.RemoteAddr().String()
2702 }
2703
2704 // LocalAddr returns the local network address of the connection
2705 func (nc *Conn) LocalAddr() string {
2706 if nc == nil {
2707 return _EMPTY_
2708 }
2709
2710 nc.mu.RLock()
2711 defer nc.mu.RUnlock()
2712
2713 if nc.status != CONNECTED {
2714 return _EMPTY_
2715 }
2716 return nc.conn.LocalAddr().String()
2717 }
2718
2719 // ConnectedServerId reports the connected server's Id
2720 func (nc *Conn) ConnectedServerId() string {
2721 if nc == nil {
2722 return _EMPTY_
2723 }
2724
2725 nc.mu.RLock()
2726 defer nc.mu.RUnlock()
2727
2728 if nc.status != CONNECTED {
2729 return _EMPTY_
2730 }
2731 return nc.info.ID
2732 }
2733
2734 // ConnectedServerName reports the connected server's name
2735 func (nc *Conn) ConnectedServerName() string {
2736 if nc == nil {
2737 return _EMPTY_
2738 }
2739
2740 nc.mu.RLock()
2741 defer nc.mu.RUnlock()
2742
2743 if nc.status != CONNECTED {
2744 return _EMPTY_
2745 }
2746 return nc.info.Name
2747 }
2748
2749 // ConnectedDomain reports the connected server's domain
2750 func (nc *Conn) ConnectedDomain() string {
2751 if nc == nil {
2752 return _EMPTY_
2753 }
2754
2755 nc.mu.RLock()
2756 defer nc.mu.RUnlock()
2757
2758 if nc.status != CONNECTED {
2759 return _EMPTY_
2760 }
2761 return nc.info.Domain
2762 }
2763
2764 var semVerRe = regexp.MustCompile(`\Av?([0-9]+)\.?([0-9]+)?\.?([0-9]+)?`)
2765
2766 func versionComponents(version string) (major, minor, patch int, err error) {
2767 m := semVerRe.FindStringSubmatch(version)
2768 if m == nil {
2769 return 0, 0, 0, errors.New("invalid semver")
2770 }
2771 major, err = strconv.Atoi(m[1])
2772 if err != nil {
2773 return -1, -1, -1, err
2774 }
2775 minor, err = strconv.Atoi(m[2])
2776 if err != nil {
2777 return -1, -1, -1, err
2778 }
2779 patch, err = strconv.Atoi(m[3])
2780 if err != nil {
2781 return -1, -1, -1, err
2782 }
2783 return major, minor, patch, err
2784 }
2785
2786 // Check for minimum server requirement.
2787 func (nc *Conn) serverMinVersion(major, minor, patch int) bool {
2788 smajor, sminor, spatch, _ := versionComponents(nc.ConnectedServerVersion())
2789 if smajor < major || (smajor == major && sminor < minor) || (smajor == major && sminor == minor && spatch < patch) {
2790 return false
2791 }
2792 return true
2793 }
2794
2795 // ConnectedServerVersion reports the connected server's version as a string
2796 func (nc *Conn) ConnectedServerVersion() string {
2797 if nc == nil {
2798 return _EMPTY_
2799 }
2800
2801 nc.mu.RLock()
2802 defer nc.mu.RUnlock()
2803
2804 if nc.status != CONNECTED {
2805 return _EMPTY_
2806 }
2807 return nc.info.Version
2808 }
2809
2810 // ConnectedClusterName reports the connected server's cluster name if any
2811 func (nc *Conn) ConnectedClusterName() string {
2812 if nc == nil {
2813 return _EMPTY_
2814 }
2815
2816 nc.mu.RLock()
2817 defer nc.mu.RUnlock()
2818
2819 if nc.status != CONNECTED {
2820 return _EMPTY_
2821 }
2822 return nc.info.Cluster
2823 }
2824
2825 // ConnectedServerJetStream reports whether the connected server has
2826 // JetStream enabled and, if so, its API level. The API level is
2827 // advertised by nats-server v2.12.0 or later; older servers will
2828 // report 0 even when JetStream is enabled.
2829 func (nc *Conn) ConnectedServerJetStream() (bool, int) {
2830 if nc == nil {
2831 return false, 0
2832 }
2833
2834 nc.mu.RLock()
2835 defer nc.mu.RUnlock()
2836
2837 if nc.status != CONNECTED {
2838 return false, 0
2839 }
2840 return nc.info.JetStream, nc.info.JSApiLevel
2841 }
2842
2843 // IsSystemAccount reports whether the connected client's account
2844 // is the system account.
2845 func (nc *Conn) IsSystemAccount() bool {
2846 if nc == nil {
2847 return false
2848 }
2849
2850 nc.mu.RLock()
2851 defer nc.mu.RUnlock()
2852
2853 if nc.status != CONNECTED {
2854 return false
2855 }
2856 return nc.info.IsSystemAccount
2857 }
2858
2859 // Low level setup for structs, etc
2860 func (nc *Conn) setup() {
2861 nc.subs = make(map[int64]*Subscription)
2862 nc.pongs = make([]chan struct{}, 0, 8)
2863
2864 nc.fch = make(chan struct{}, flushChanSize)
2865 nc.rqch = make(chan struct{})
2866
2867 // Setup scratch outbound buffer for PUB/HPUB
2868 pub := nc.scratch[:len(_HPUB_P_)]
2869 copy(pub, _HPUB_P_)
2870 }
2871
2872 // tlsHandshakeEOF wraps an error with context when it occurs right after
2873 // a completed TLS handshake, which typically indicates the remote side
2874 // rejected the client certificate (e.g. an mTLS proxy like nginx).
2875 // Depending on timing, the error may be io.EOF (read from closed conn)
2876 // or a "broken pipe"/"connection reset" (write to closed conn).
2877 func (nc *Conn) tlsHandshakeEOF(err error) error {
2878 tlsConn, ok := nc.conn.(*tls.Conn)
2879 if !ok || !tlsConn.ConnectionState().HandshakeComplete {
2880 return err
2881 }
2882 if errors.Is(err, io.EOF) || isConnClosedError(err) {
2883 return fmt.Errorf("%w: connection closed by remote after TLS handshake: %w", ErrTLS, err)
2884 }
2885 return err
2886 }
2887
2888 // isConnClosedError reports whether the error indicates the remote
2889 // side closed the connection (broken pipe or connection reset).
2890 // NOTE: On Windows, connection resets use WSAECONNRESET which may not
2891 // match syscall.ECONNRESET. In that case, the error will not be
2892 // detected here but will still be returned unwrapped by the caller.
2893 func isConnClosedError(err error) bool {
2894 return errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET)
2895 }
2896
2897 // Process a connected connection and initialize properly.
2898 func (nc *Conn) processConnectInit() error {
2899 // Set our deadline for the whole connect process
2900 nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
2901 defer nc.conn.SetDeadline(time.Time{})
2902
2903 // Set our status to connecting.
2904 nc.changeConnStatus(CONNECTING)
2905
2906 // If we need to have a TLS connection and want the TLS handshake to occur
2907 // first, do it now.
2908 if nc.Opts.Secure && nc.Opts.TLSHandshakeFirst {
2909 if err := nc.makeTLSConn(); err != nil {
2910 return err
2911 }
2912 }
2913
2914 // Process the INFO protocol received from the server
2915 err := nc.processExpectedInfo()
2916 if err != nil {
2917 return nc.tlsHandshakeEOF(err)
2918 }
2919
2920 // Send the CONNECT protocol along with the initial PING protocol.
2921 // Wait for the PONG response (or any error that we get from the server).
2922 err = nc.sendConnect()
2923 if err != nil {
2924 return nc.tlsHandshakeEOF(err)
2925 }
2926
2927 // Reset the number of PING sent out
2928 nc.pout = 0
2929
2930 // Start or reset Timer
2931 if nc.Opts.PingInterval > 0 {
2932 if nc.ptmr == nil {
2933 nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
2934 } else {
2935 nc.ptmr.Reset(nc.Opts.PingInterval)
2936 }
2937 }
2938
2939 // Start the readLoop and flusher go routines, we will wait on both on a reconnect event.
2940 nc.wg.Add(2)
2941 go nc.readLoop()
2942 go nc.flusher()
2943
2944 // Notify the reader that we are done with the connect handshake, where
2945 // reads were done synchronously and under the connection lock.
2946 nc.br.doneWithConnect()
2947
2948 return nil
2949 }
2950
2951 // Main connect function. Will connect to the nats-server.
2952 func (nc *Conn) connect() (bool, error) {
2953 var err error
2954 var connectionEstablished bool
2955
2956 // Create actual socket connection
2957 // For first connect we walk all servers in the pool and try
2958 // to connect immediately.
2959 nc.mu.Lock()
2960 defer nc.mu.Unlock()
2961 nc.initc = true
2962 // The pool may change inside the loop iteration due to INFO protocol.
2963 for i := 0; i < len(nc.srvPool); i++ {
2964 nc.current = nc.srvPool[i]
2965
2966 if err = nc.createConn(); err == nil {
2967 // This was moved out of processConnectInit() because
2968 // that function is now invoked from doReconnect() too.
2969 nc.setup()
2970
2971 err = nc.processConnectInit()
2972
2973 if err == nil {
2974 nc.current.didConnect = true
2975 nc.current.Reconnects = 0
2976 nc.current.lastErr = nil
2977 break
2978 } else {
2979 nc.mu.Unlock()
2980 nc.close(DISCONNECTED, false, err)
2981 nc.mu.Lock()
2982 // Do not reset nc.current here since it would prevent
2983 // RetryOnFailedConnect to work should this be the last server
2984 // to try before starting doReconnect().
2985 }
2986 } else {
2987 // Cancel out default connection refused, will trigger the
2988 // No servers error conditional
2989 if strings.Contains(err.Error(), "connection refused") {
2990 err = nil
2991 }
2992 }
2993 }
2994
2995 if err == nil && nc.status != CONNECTED {
2996 err = ErrNoServers
2997 }
2998
2999 if err == nil {
3000 connectionEstablished = true
3001 nc.initc = false
3002 } else if nc.Opts.RetryOnFailedConnect {
3003 nc.setup()
3004 nc.changeConnStatus(RECONNECTING)
3005 nc.bw.switchToPending()
3006 go nc.doReconnect(err, false)
3007 err = nil
3008 } else {
3009 nc.current = nil
3010 }
3011
3012 return connectionEstablished, err
3013 }
3014
3015 // This will check to see if the connection should be
3016 // secure. This can be dictated from either end and should
3017 // only be called after the INIT protocol has been received.
3018 func (nc *Conn) checkForSecure() error {
3019 // Check to see if we need to engage TLS
3020 o := nc.Opts
3021
3022 // Check for mismatch in setups
3023 if o.Secure && !nc.info.TLSRequired && !nc.info.TLSAvailable {
3024 return ErrSecureConnWanted
3025 } else if nc.info.TLSRequired && !o.Secure {
3026 // Switch to Secure since server needs TLS.
3027 o.Secure = true
3028 }
3029
3030 if o.Secure {
3031 // If TLS handshake first is true, we have already done
3032 // the handshake, so we are done here.
3033 if o.TLSHandshakeFirst {
3034 return nil
3035 }
3036 // Need to rewrap with bufio
3037 if err := nc.makeTLSConn(); err != nil {
3038 return err
3039 }
3040 }
3041 return nil
3042 }
3043
3044 // processExpectedInfo will look for the expected first INFO message
3045 // sent when a connection is established. The lock should be held entering.
3046 func (nc *Conn) processExpectedInfo() error {
3047 c := &control{}
3048
3049 // Read the protocol
3050 err := nc.readOp(c)
3051 if err != nil {
3052 return err
3053 }
3054
3055 // The nats protocol should send INFO first always.
3056 if c.op != _INFO_OP_ {
3057 return ErrNoInfoReceived
3058 }
3059
3060 // Parse the protocol
3061 if err := nc.processInfo(c.args); err != nil {
3062 return err
3063 }
3064
3065 if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
3066 return ErrNkeysNotSupported
3067 }
3068
3069 // For websocket connections, we already switched to TLS if need be,
3070 // so we are done here.
3071 if nc.ws {
3072 return nil
3073 }
3074
3075 return nc.checkForSecure()
3076 }
3077
3078 // Sends a protocol control message by queuing into the bufio writer
3079 // and kicking the flush Go routine. These writes are protected.
3080 func (nc *Conn) sendProto(proto string) {
3081 nc.mu.Lock()
3082 nc.bw.appendString(proto)
3083 nc.kickFlusher()
3084 nc.mu.Unlock()
3085 }
3086
3087 // Generate a connect protocol message, issuing user/password if
3088 // applicable. The lock is assumed to be held upon entering.
3089 func (nc *Conn) connectProto() (string, error) {
3090 o := nc.Opts
3091 var nkey, sig, user, pass, token, ujwt string
3092 u := nc.current.URL.User
3093 if u != nil {
3094 // if no password, assume username is authToken
3095 if _, ok := u.Password(); !ok {
3096 token = u.Username()
3097 } else {
3098 user = u.Username()
3099 pass, _ = u.Password()
3100 }
3101 } else {
3102 // Take from options (possibly all empty strings)
3103 user = o.User
3104 pass = o.Password
3105 token = o.Token
3106 nkey = o.Nkey
3107
3108 if nc.Opts.UserInfo != nil {
3109 if user != _EMPTY_ || pass != _EMPTY_ {
3110 return _EMPTY_, ErrUserInfoAlreadySet
3111 }
3112 user, pass = nc.Opts.UserInfo()
3113 }
3114 }
3115
3116 // Look for user jwt.
3117 if o.UserJWT != nil {
3118 if jwt, err := o.UserJWT(); err != nil {
3119 return _EMPTY_, err
3120 } else {
3121 ujwt = jwt
3122 }
3123 if nkey != _EMPTY_ {
3124 return _EMPTY_, ErrNkeyAndUser
3125 }
3126 }
3127
3128 if ujwt != _EMPTY_ || nkey != _EMPTY_ {
3129 if o.SignatureCB == nil {
3130 if ujwt == _EMPTY_ {
3131 return _EMPTY_, ErrNkeyButNoSigCB
3132 }
3133 return _EMPTY_, ErrUserButNoSigCB
3134 }
3135 sigraw, err := o.SignatureCB([]byte(nc.info.Nonce))
3136 if err != nil {
3137 return _EMPTY_, fmt.Errorf("error signing nonce: %w", err)
3138 }
3139 sig = base64.RawURLEncoding.EncodeToString(sigraw)
3140 }
3141
3142 if nc.Opts.TokenHandler != nil {
3143 if token != _EMPTY_ {
3144 return _EMPTY_, ErrTokenAlreadySet
3145 }
3146 token = nc.Opts.TokenHandler()
3147 }
3148
3149 // If our server does not support headers then we can't do them or no responders.
3150 hdrs := nc.info.Headers
3151 cinfo := connectInfo{
3152 o.Verbose, o.Pedantic, ujwt, nkey, sig, user, pass, token,
3153 o.Secure, o.Name, LangString, Version, clientProtoInfo, !o.NoEcho, hdrs, hdrs,
3154 }
3155
3156 b, err := json.Marshal(cinfo)
3157 if err != nil {
3158 return _EMPTY_, ErrJsonParse
3159 }
3160
3161 // Check if NoEcho is set and we have a server that supports it.
3162 if o.NoEcho && nc.info.Proto < 1 {
3163 return _EMPTY_, ErrNoEchoNotSupported
3164 }
3165
3166 return fmt.Sprintf(connectProto, b), nil
3167 }
3168
3169 // normalizeErr removes the prefix -ERR, trim spaces and remove the quotes.
3170 func normalizeErr(line string) string {
3171 s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))
3172 s = strings.TrimLeft(strings.TrimRight(s, "'"), "'")
3173 return s
3174 }
3175
3176 // natsProtoErr represents an -ERR protocol message sent by the server.
3177 type natsProtoErr struct {
3178 description string
3179 }
3180
3181 func (nerr *natsProtoErr) Error() string {
3182 return fmt.Sprintf("nats: %s", nerr.description)
3183 }
3184
3185 func (nerr *natsProtoErr) Is(err error) bool {
3186 return strings.ToLower(nerr.Error()) == err.Error()
3187 }
3188
3189 // Send a connect protocol message to the server, issue user/password if
3190 // applicable. Will wait for a flush to return from the server for error
3191 // processing.
3192 func (nc *Conn) sendConnect() error {
3193 // Construct the CONNECT protocol string
3194 cProto, err := nc.connectProto()
3195 if err != nil {
3196 if !nc.initc {
3197 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
3198 nc.ach.push(func() { asyncErrorCB(nc, nil, err) })
3199 }
3200 }
3201 return err
3202 }
3203
3204 // Write the protocol and PING directly to the underlying writer.
3205 if err := nc.bw.writeDirect(cProto, pingProto); err != nil {
3206 return err
3207 }
3208
3209 // We don't want to read more than we need here, otherwise
3210 // we would need to transfer the excess read data to the readLoop.
3211 // Since in normal situations we just are looking for a PONG\r\n,
3212 // reading byte-by-byte here is ok.
3213 proto, err := nc.readProto()
3214 if err != nil {
3215 if !nc.initc {
3216 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
3217 nc.ach.push(func() { asyncErrorCB(nc, nil, err) })
3218 }
3219 }
3220 return err
3221 }
3222
3223 // If opts.Verbose is set, handle +OK
3224 if nc.Opts.Verbose && proto == okProto {
3225 // Read the rest now...
3226 proto, err = nc.readProto()
3227 if err != nil {
3228 if !nc.initc {
3229 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
3230 nc.ach.push(func() { asyncErrorCB(nc, nil, err) })
3231 }
3232 }
3233 return err
3234 }
3235 }
3236
3237 // We expect a PONG
3238 if proto != pongProto {
3239 // But it could be something else, like -ERR
3240
3241 // Since we no longer use ReadLine(), trim the trailing "\r\n"
3242 proto = strings.TrimRight(proto, "\r\n")
3243
3244 // If it's a server error...
3245 if strings.HasPrefix(proto, _ERR_OP_) {
3246 // Remove -ERR, trim spaces and quotes, and convert to lower case.
3247 proto = normalizeErr(proto)
3248
3249 // Check if this is an auth error
3250 if authErr := checkAuthError(strings.ToLower(proto)); authErr != nil {
3251 // This will schedule an async error if we are in reconnect,
3252 // and keep track of the auth error for the current server.
3253 // If we have got the same error twice, this sets nc.ar to true to
3254 // indicate that the reconnect should be aborted (will be checked
3255 // in doReconnect()).
3256 nc.processAuthError(authErr)
3257 }
3258 return &natsProtoErr{proto}
3259 }
3260
3261 // Notify that we got an unexpected protocol.
3262 return fmt.Errorf("nats: expected '%s', got '%s'", _PONG_OP_, proto)
3263 }
3264
3265 // This is where we are truly connected.
3266 nc.changeConnStatus(CONNECTED)
3267
3268 return nil
3269 }
3270
3271 // reads a protocol line.
3272 func (nc *Conn) readProto() (string, error) {
3273 return nc.br.ReadString('\n')
3274 }
3275
3276 // A control protocol line.
3277 type control struct {
3278 op, args string
3279 }
3280
3281 // Read a control line and process the intended op.
3282 func (nc *Conn) readOp(c *control) error {
3283 line, err := nc.readProto()
3284 if err != nil {
3285 return err
3286 }
3287 parseControl(line, c)
3288 return nil
3289 }
3290
3291 // Parse a control line from the server.
3292 func parseControl(line string, c *control) {
3293 toks := strings.SplitN(line, _SPC_, 2)
3294 if len(toks) == 1 {
3295 c.op = strings.TrimSpace(toks[0])
3296 c.args = _EMPTY_
3297 } else if len(toks) == 2 {
3298 c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
3299 } else {
3300 c.op = _EMPTY_
3301 }
3302 }
3303
3304 // flushReconnectPendingItems will push the pending items that were
3305 // gathered while we were in a RECONNECTING state to the socket.
3306 func (nc *Conn) flushReconnectPendingItems() error {
3307 return nc.bw.flushPendingBuffer()
3308 }
3309
3310 // Stops the ping timer if set.
3311 // Connection lock is held on entry.
3312 func (nc *Conn) stopPingTimer() {
3313 if nc.ptmr != nil {
3314 nc.ptmr.Stop()
3315 }
3316 }
3317
3318 // Try to reconnect using the option parameters.
3319 // This function assumes we are allowed to reconnect.
3320 func (nc *Conn) doReconnect(err error, forceReconnect bool) {
3321 // We want to make sure we have the other watchers shutdown properly
3322 // here before we proceed past this point.
3323 nc.waitForExits()
3324
3325 // FIXME(dlc) - We have an issue here if we have
3326 // outstanding flush points (pongs) and they were not
3327 // sent out, but are still in the pipe.
3328
3329 // Hold the lock manually and release where needed below,
3330 // can't do defer here.
3331 nc.mu.Lock()
3332
3333 // Clear any errors.
3334 nc.err = nil
3335
3336 // Perform appropriate callback if needed for a disconnect.
3337 // DisconnectedErrCB has priority over deprecated DisconnectedCB
3338 if !nc.initc {
3339 if disconnectedErrCB := nc.Opts.DisconnectedErrCB; disconnectedErrCB != nil {
3340 nc.ach.push(func() { disconnectedErrCB(nc, err) })
3341 } else if disconnectedCB := nc.Opts.DisconnectedCB; disconnectedCB != nil {
3342 nc.ach.push(func() { disconnectedCB(nc) })
3343 }
3344 } else if nc.Opts.RetryOnFailedConnect && nc.initc && err != nil {
3345 // For initial connection failure with RetryOnFailedConnect,
3346 // report the error via ReconnectErrCB if available
3347 if nc.Opts.ReconnectErrCB != nil {
3348 nc.ach.push(func() { nc.Opts.ReconnectErrCB(nc, err) })
3349 }
3350 }
3351
3352 // This is used to wait on go routines exit if we start them in the loop
3353 // but an error occurs after that.
3354 waitForGoRoutines := false
3355 var rt *time.Timer
3356 // Channel used to kick routine out of sleep when conn is closed.
3357 rqch := nc.rqch
3358
3359 // if rqch is nil, we need to set it up to signal
3360 // the reconnect loop to reconnect immediately
3361 // this means that `ForceReconnect` was called
3362 // before entering doReconnect
3363 if rqch == nil {
3364 rqch = make(chan struct{})
3365 close(rqch)
3366 }
3367
3368 // Counter that is increased when the whole list of servers has been tried.
3369 var wlf int
3370
3371 var jitter time.Duration
3372 var rw time.Duration
3373 // If a custom reconnect delay handler is set, this takes precedence.
3374 crd := nc.Opts.CustomReconnectDelayCB
3375 if crd == nil {
3376 rw = nc.Opts.ReconnectWait
3377 // TODO: since we sleep only after the whole list has been tried, we can't
3378 // rely on individual *srv to know if it is a TLS or non-TLS url.
3379 // We have to pick which type of jitter to use, for now, we use these hints:
3380 jitter = nc.Opts.ReconnectJitter
3381 if nc.Opts.Secure || nc.Opts.TLSConfig != nil {
3382 jitter = nc.Opts.ReconnectJitterTLS
3383 }
3384 }
3385
3386 for i := 0; len(nc.srvPool) > 0; {
3387 var err error
3388 var cur *Server
3389 var callbackDelay time.Duration
3390 var useCallbackDelay bool
3391
3392 if nc.Opts.ReconnectToServerCB != nil {
3393 // Enforce MaxReconnect limits before calling the callback
3394 maxReconnect := nc.Opts.MaxReconnect
3395 if maxReconnect >= 0 {
3396 // Remove servers that have exceeded MaxReconnect attempts
3397 filtered := make([]*Server, 0, len(nc.srvPool))
3398 for _, srv := range nc.srvPool {
3399 if srv != nil && srv.Reconnects < maxReconnect {
3400 filtered = append(filtered, srv)
3401 }
3402 }
3403 nc.srvPool = filtered
3404 }
3405
3406 // Check if we still have servers after filtering
3407 if len(nc.srvPool) == 0 {
3408 nc.err = ErrNoServers
3409 break
3410 }
3411
3412 // Copy server values to avoid caller modifying internal state
3413 srvVals := make([]Server, len(nc.srvPool))
3414 for idx, srv := range nc.srvPool {
3415 if srv != nil {
3416 srvVals[idx] = srv.clone()
3417 }
3418 }
3419
3420 var selectedSrv *Server
3421 selectedSrv, callbackDelay = nc.Opts.ReconnectToServerCB(srvVals, nc.info)
3422 if selectedSrv != nil {
3423 idx := slices.IndexFunc(nc.srvPool, func(srv *Server) bool {
3424 return srv != nil && srv.URL.String() == selectedSrv.URL.String()
3425 })
3426 if idx != -1 {
3427 cur = nc.srvPool[idx]
3428 nc.current = cur
3429 useCallbackDelay = true
3430 } else if reconnectErrCB := nc.Opts.ReconnectErrCB; reconnectErrCB != nil {
3431 nc.ach.push(func() { reconnectErrCB(nc, ErrServerNotInPool) })
3432 }
3433 }
3434 }
3435
3436 var doSleep bool
3437 if cur == nil {
3438 cur, err = nc.selectNextServer()
3439 if err != nil {
3440 nc.err = err
3441 break
3442 }
3443 doSleep = i+1 >= len(nc.srvPool) && !forceReconnect
3444 }
3445
3446 forceReconnect = false
3447 nc.mu.Unlock()
3448
3449 if useCallbackDelay {
3450 if callbackDelay > 0 {
3451 i = 0
3452 if rt == nil {
3453 rt = time.NewTimer(callbackDelay)
3454 } else {
3455 rt.Reset(callbackDelay)
3456 }
3457 select {
3458 case <-rqch:
3459 rt.Stop()
3460 nc.mu.Lock()
3461 nc.rqch = make(chan struct{})
3462 nc.mu.Unlock()
3463 case <-rt.C:
3464 }
3465 } else {
3466 runtime.Gosched()
3467 }
3468 } else if !doSleep {
3469 i++
3470 // Release the lock to give a chance to a concurrent nc.Close() to break the loop.
3471 runtime.Gosched()
3472 } else {
3473 i = 0
3474 var st time.Duration
3475 if crd != nil {
3476 wlf++
3477 st = crd(wlf)
3478 } else {
3479 st = rw
3480 if jitter > 0 {
3481 st += time.Duration(rand.Int63n(int64(jitter)))
3482 }
3483 }
3484 if rt == nil {
3485 rt = time.NewTimer(st)
3486 } else {
3487 rt.Reset(st)
3488 }
3489 select {
3490 case <-rqch:
3491 rt.Stop()
3492
3493 // we need to reset the rqch channel to avoid
3494 // closing a closed channel in the next iteration
3495 nc.mu.Lock()
3496 nc.rqch = make(chan struct{})
3497 nc.mu.Unlock()
3498 case <-rt.C:
3499 }
3500 }
3501 // If the readLoop, etc.. go routines were started, wait for them to complete.
3502 if waitForGoRoutines {
3503 nc.waitForExits()
3504 waitForGoRoutines = false
3505 }
3506 nc.mu.Lock()
3507
3508 // Check if we have been closed first.
3509 if nc.isClosed() {
3510 break
3511 }
3512
3513 // Mark that we tried a reconnect
3514 cur.Reconnects++
3515
3516 // Try to create a new connection
3517 err = nc.createConn()
3518 // Not yet connected, retry...
3519 // Continue to hold the lock
3520 if err != nil {
3521 // Perform appropriate callback for a failed connection attempt.
3522 if reconnectErrCB := nc.Opts.ReconnectErrCB; reconnectErrCB != nil {
3523 nc.ach.push(func() { reconnectErrCB(nc, err) })
3524 }
3525 nc.err = nil
3526 continue
3527 }
3528
3529 // We are reconnected
3530 nc.Reconnects++
3531
3532 // Process connect logic
3533 if nc.err = nc.processConnectInit(); nc.err != nil {
3534 // Check if we should abort reconnect. If so, break out
3535 // of the loop and connection will be closed.
3536 if nc.ar {
3537 break
3538 }
3539 nc.changeConnStatus(RECONNECTING)
3540 continue
3541 }
3542
3543 // Clear possible lastErr under the connection lock after
3544 // a successful processConnectInit().
3545 nc.current.lastErr = nil
3546
3547 // Clear out server stats for the server we connected to..
3548 cur.didConnect = true
3549 cur.Reconnects = 0
3550
3551 // Send existing subscription state
3552 nc.resendSubscriptions()
3553
3554 // Now send off and clear pending buffer
3555 nc.err = nc.flushReconnectPendingItems()
3556 if nc.err != nil {
3557 nc.changeConnStatus(RECONNECTING)
3558 // Stop the ping timer (if set)
3559 nc.stopPingTimer()
3560 // Since processConnectInit() returned without error, the
3561 // go routines were started, so wait for them to return
3562 // on the next iteration (after releasing the lock).
3563 waitForGoRoutines = true
3564 continue
3565 }
3566
3567 // Done with the pending buffer
3568 nc.bw.doneWithPending()
3569
3570 // Queue up the correct callback. If we are in initial connect state
3571 // (using retry on failed connect), we will call the ConnectedCB,
3572 // otherwise the ReconnectedCB.
3573 if reconnectedCB := nc.Opts.ReconnectedCB; reconnectedCB != nil && !nc.initc {
3574 nc.ach.push(func() { reconnectedCB(nc) })
3575 } else if connectedCB := nc.Opts.ConnectedCB; connectedCB != nil && nc.initc {
3576 nc.ach.push(func() { connectedCB(nc) })
3577 }
3578
3579 // If we are here with a retry on failed connect, indicate that the
3580 // initial connect is now complete.
3581 nc.initc = false
3582
3583 // Release lock here, we will return below.
3584 nc.mu.Unlock()
3585
3586 // Make sure to flush everything
3587 nc.Flush()
3588
3589 return
3590 }
3591
3592 // Call into close.. We have no servers left..
3593 if nc.err == nil {
3594 nc.err = ErrNoServers
3595 }
3596 nc.mu.Unlock()
3597 nc.close(CLOSED, true, nil)
3598 }
3599
3600 // processOpErr handles errors from reading or parsing the protocol.
3601 // The lock should not be held entering this function. If forceReconnect
3602 // is true, the first reconnect attempt will bypass the configured
3603 // ReconnectWait; subsequent attempts still obey the normal backoff.
3604 func (nc *Conn) processOpErr(err error, forceReconnect bool) bool {
3605 nc.mu.Lock()
3606 defer nc.mu.Unlock()
3607 if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
3608 return false
3609 }
3610
3611 if nc.Opts.AllowReconnect && nc.status == CONNECTED {
3612 // Set our new status
3613 nc.changeConnStatus(RECONNECTING)
3614 // Stop ping timer if set
3615 nc.stopPingTimer()
3616 if nc.conn != nil {
3617 nc.conn.Close()
3618 nc.conn = nil
3619 }
3620
3621 // Create pending buffer before reconnecting.
3622 nc.bw.switchToPending()
3623
3624 // Clear any queued pongs, e.g. pending flush calls.
3625 nc.clearPendingFlushCalls()
3626
3627 go nc.doReconnect(err, forceReconnect)
3628 return false
3629 }
3630
3631 nc.changeConnStatus(DISCONNECTED)
3632 nc.err = err
3633 return true
3634 }
3635
3636 // dispatch is responsible for calling any async callbacks
3637 func (ac *asyncCallbacksHandler) asyncCBDispatcher() {
3638 for {
3639 ac.mu.Lock()
3640 // Protect for spurious wakeups. We should get out of the
3641 // wait only if there is an element to pop from the list.
3642 for ac.head == nil {
3643 ac.cond.Wait()
3644 }
3645 cur := ac.head
3646 ac.head = cur.next
3647 if cur == ac.tail {
3648 ac.tail = nil
3649 }
3650 ac.mu.Unlock()
3651
3652 // This signals that the dispatcher has been closed and all
3653 // previous callbacks have been dispatched.
3654 if cur.f == nil {
3655 return
3656 }
3657 // Invoke callback outside of handler's lock
3658 cur.f()
3659 }
3660 }
3661
3662 // Add the given function to the tail of the list and
3663 // signals the dispatcher.
3664 func (ac *asyncCallbacksHandler) push(f func()) {
3665 ac.pushOrClose(f, false)
3666 }
3667
3668 // Signals that we are closing...
3669 func (ac *asyncCallbacksHandler) close() {
3670 ac.pushOrClose(nil, true)
3671 }
3672
3673 // Add the given function to the tail of the list and
3674 // signals the dispatcher.
3675 func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) {
3676 ac.mu.Lock()
3677 defer ac.mu.Unlock()
3678 // Make sure that library is not calling push with nil function,
3679 // since this is used to notify the dispatcher that it should stop.
3680 if !close && f == nil {
3681 panic("pushing a nil callback")
3682 }
3683 cb := &asyncCB{f: f}
3684 if ac.tail != nil {
3685 ac.tail.next = cb
3686 } else {
3687 ac.head = cb
3688 }
3689 ac.tail = cb
3690 if close {
3691 ac.cond.Broadcast()
3692 } else {
3693 ac.cond.Signal()
3694 }
3695 }
3696
3697 // readLoop() will sit on the socket reading and processing the
3698 // protocol from the server. It will dispatch appropriately based
3699 // on the op type.
3700 func (nc *Conn) readLoop() {
3701 // Release the wait group on exit
3702 defer nc.wg.Done()
3703
3704 // Create a parseState if needed.
3705 nc.mu.Lock()
3706 if nc.ps == nil {
3707 nc.ps = &parseState{}
3708 }
3709 conn := nc.conn
3710 br := nc.br
3711 nc.mu.Unlock()
3712
3713 if conn == nil {
3714 return
3715 }
3716
3717 for {
3718 buf, err := br.Read()
3719 if err == nil {
3720 // With websocket, it is possible that there is no error but
3721 // also no buffer returned (either WS control message or read of a
3722 // partial compressed message). We could call parse(buf) which
3723 // would ignore an empty buffer, but simply go back to top of the loop.
3724 if len(buf) == 0 {
3725 continue
3726 }
3727 err = nc.parse(buf)
3728 }
3729 if err != nil {
3730 if shouldClose := nc.processOpErr(err, false); shouldClose {
3731 nc.close(CLOSED, true, nil)
3732 }
3733 break
3734 }
3735 }
3736 // Clear the parseState here..
3737 nc.mu.Lock()
3738 nc.ps = nil
3739 nc.mu.Unlock()
3740 }
3741
3742 // waitForMsgs waits on the conditional shared with readLoop and processMsg.
3743 // It is used to deliver messages to asynchronous subscribers.
3744 func (nc *Conn) waitForMsgs(s *Subscription) {
3745 var closed bool
3746 var delivered, max uint64
3747
3748 // Used to account for adjustments to sub.pBytes when we wrap back around.
3749 msgLen := -1
3750
3751 for {
3752 s.mu.Lock()
3753 // Do accounting for last msg delivered here so we only lock once
3754 // and drain state trips after callback has returned.
3755 if msgLen >= 0 {
3756 s.pMsgs--
3757 s.pBytes -= msgLen
3758 msgLen = -1
3759 if s.jsi != nil && s.jsi.resetPending {
3760 s.tryResetOrderedConsumer()
3761 }
3762 }
3763
3764 if s.pHead == nil && !s.closed {
3765 s.pCond.Wait()
3766 }
3767 // Pop the msg off the list
3768 m := s.pHead
3769 if m != nil {
3770 s.pHead = m.next
3771 if s.pHead == nil {
3772 s.pTail = nil
3773 }
3774 if m.barrier != nil {
3775 s.mu.Unlock()
3776 if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
3777 m.barrier.f()
3778 }
3779 continue
3780 }
3781 msgLen = len(m.Data)
3782 }
3783 mcb := s.mcb
3784 max = s.max
3785 closed = s.closed
3786 var fcReply string
3787 if !s.closed {
3788 s.delivered++
3789 delivered = s.delivered
3790 if s.jsi != nil {
3791 fcReply = s.checkForFlowControlResponse()
3792 }
3793 }
3794 s.mu.Unlock()
3795
3796 // Respond to flow control if applicable
3797 if fcReply != _EMPTY_ {
3798 nc.Publish(fcReply, nil)
3799 }
3800
3801 if closed {
3802 break
3803 }
3804
3805 // Deliver the message.
3806 if m != nil && (max == 0 || delivered <= max) {
3807 mcb(m)
3808 }
3809 // If we have hit the max for delivered msgs, remove sub.
3810 if max > 0 && delivered >= max {
3811 nc.mu.Lock()
3812 nc.removeSub(s)
3813 nc.mu.Unlock()
3814 break
3815 }
3816 }
3817 // Check for barrier messages
3818 s.mu.Lock()
3819 for m := s.pHead; m != nil; m = s.pHead {
3820 if m.barrier != nil {
3821 s.mu.Unlock()
3822 if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
3823 m.barrier.f()
3824 }
3825 s.mu.Lock()
3826 }
3827 s.pHead = m.next
3828 }
3829 // Now check for pDone
3830 done := s.pDone
3831 s.mu.Unlock()
3832
3833 if done != nil {
3834 done(s.Subject)
3835 }
3836 }
3837
3838 // Used for debugging and simulating loss for certain tests.
3839 // Return what is to be used. If we return nil the message will be dropped.
3840 type msgFilter func(m *Msg) *Msg
3841
3842 // processMsg is called by parse and will place the msg on the
3843 // appropriate channel/pending queue for processing. If the channel is full,
3844 // or the pending queue is over the pending limits, the connection is
3845 // considered a slow consumer.
3846 func (nc *Conn) processMsg(data []byte) {
3847 // Stats
3848 atomic.AddUint64(&nc.InMsgs, 1)
3849 atomic.AddUint64(&nc.InBytes, uint64(len(data)))
3850
3851 // Don't lock the connection to avoid server cutting us off if the
3852 // flusher is holding the connection lock, trying to send to the server
3853 // that is itself trying to send data to us.
3854 nc.subsMu.RLock()
3855 sub := nc.subs[nc.ps.ma.sid]
3856 var mf msgFilter
3857 if nc.filters != nil {
3858 mf = nc.filters[string(nc.ps.ma.subject)]
3859 }
3860 nc.subsMu.RUnlock()
3861
3862 if sub == nil {
3863 return
3864 }
3865
3866 // Copy them into string
3867 subj := string(nc.ps.ma.subject)
3868 reply := string(nc.ps.ma.reply)
3869
3870 // Doing message create outside of the sub's lock to reduce contention.
3871 // It's possible that we end-up not using the message, but that's ok.
3872
3873 // FIXME(dlc): Need to copy, should/can do COW?
3874 msgPayload := data
3875 if !nc.ps.msgCopied {
3876 msgPayload = make([]byte, len(data))
3877 copy(msgPayload, data)
3878 }
3879
3880 // Check if we have headers encoded here.
3881 var h Header
3882 var err error
3883 var ctrlMsg bool
3884 var ctrlType int
3885 var fcReply string
3886 var ordSeqs orderedSeqs
3887
3888 if nc.ps.ma.hdr > 0 {
3889 hbuf := msgPayload[:nc.ps.ma.hdr]
3890 msgPayload = msgPayload[nc.ps.ma.hdr:]
3891 h, err = DecodeHeadersMsg(hbuf)
3892 if err != nil {
3893 // We will pass the message through but send async error.
3894 nc.mu.Lock()
3895 nc.err = ErrBadHeaderMsg
3896 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
3897 nc.ach.push(func() { asyncErrorCB(nc, sub, ErrBadHeaderMsg) })
3898 }
3899 nc.mu.Unlock()
3900 }
3901 }
3902
3903 // FIXME(dlc): Should we recycle these containers?
3904 m := &Msg{
3905 Subject: subj,
3906 Reply: reply,
3907 Header: h,
3908 Data: msgPayload,
3909 Sub: sub,
3910 wsz: len(data) + len(subj) + len(reply),
3911 }
3912
3913 // Check for message filters.
3914 if mf != nil {
3915 if m = mf(m); m == nil {
3916 // Drop message.
3917 return
3918 }
3919 }
3920
3921 sub.mu.Lock()
3922
3923 // Check if closed.
3924 if sub.closed {
3925 sub.mu.Unlock()
3926 return
3927 }
3928
3929 // Skip flow control messages in case of using a JetStream context.
3930 jsi := sub.jsi
3931 if jsi != nil {
3932 // There has to be a header for it to be a control message.
3933 if h != nil {
3934 ctrlMsg, ctrlType = isJSControlMessage(m)
3935 if ctrlMsg && ctrlType == jsCtrlHB {
3936 // Check if the heartbeat has a "Consumer Stalled" header, if
3937 // so, the value is the FC reply to send a nil message to.
3938 // We will send it at the end of this function.
3939 fcReply = m.Header.Get(consumerStalledHdr)
3940 }
3941 }
3942 }
3943
3944 // Skip processing if this is a control message and
3945 // if not a pull consumer heartbeat. For pull consumers,
3946 // heartbeats have to be handled on per request basis.
3947 if !ctrlMsg || (jsi != nil && jsi.pull) {
3948 var chanSubCheckFC bool
3949 // Subscription internal stats (applicable only for non ChanSubscription's)
3950 if sub.typ != ChanSubscription {
3951 sub.pMsgs++
3952 if sub.pMsgs > sub.pMsgsMax {
3953 sub.pMsgsMax = sub.pMsgs
3954 }
3955 sub.pBytes += len(m.Data)
3956 if sub.pBytes > sub.pBytesMax {
3957 sub.pBytesMax = sub.pBytes
3958 }
3959
3960 // Check for a Slow Consumer
3961 if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) ||
3962 (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit) {
3963 goto slowConsumer
3964 }
3965 } else if jsi != nil {
3966 chanSubCheckFC = true
3967 }
3968
3969 // Must run here, between the reservation above and the delivery below.
3970 // See checkOrderedDelivery.
3971 if jsi != nil && jsi.ordered {
3972 var action jsMsgAction
3973 action, ordSeqs = sub.checkOrderedDelivery(m)
3974 switch action {
3975 case jsMsgDrop:
3976 goto slowConsumer
3977 case jsMsgDropGap:
3978 sub.mu.Unlock()
3979 return
3980 }
3981 }
3982
3983 // We have two modes of delivery. One is the channel, used by channel
3984 // subscribers and syncSubscribers, the other is a linked list for async.
3985 if sub.mch != nil {
3986 select {
3987 case sub.mch <- m:
3988 // For ChanSubscribe, track delivered count here
3989 if sub.typ == ChanSubscription {
3990 sub.delivered++
3991 }
3992 default:
3993 goto slowConsumer
3994 }
3995 } else {
3996 // Push onto the async pList
3997 if sub.pHead == nil {
3998 sub.pHead = m
3999 sub.pTail = m
4000 if sub.pCond != nil {
4001 sub.pCond.Signal()
4002 }
4003 } else {
4004 sub.pTail.next = m
4005 sub.pTail = m
4006 }
4007 }
4008 if jsi != nil {
4009 sub.commitOrderedMsg(ordSeqs)
4010 // Store the ACK metadata from the message to
4011 // compare later on with the received heartbeat.
4012 sub.trackSequences(m.Reply)
4013 if chanSubCheckFC {
4014 // For ChanSubscription, since we can't call this when a message
4015 // is "delivered" (since user is pull from their own channel),
4016 // we have a go routine that does this check, however, we do it
4017 // also here to make it much more responsive. The go routine is
4018 // really to avoid stalling when there is no new messages coming.
4019 fcReply = sub.checkForFlowControlResponse()
4020 }
4021 }
4022 } else if ctrlType == jsCtrlFC && m.Reply != _EMPTY_ {
4023 // This is a flow control message.
4024 // We will schedule the send of the FC reply once we have delivered the
4025 // DATA message that was received before this flow control message, which
4026 // has sequence `jsi.fciseq`. However, it is possible that this message
4027 // has already been delivered, in that case, we need to send the FC reply now.
4028 if sub.getJSDelivered() >= jsi.fciseq {
4029 fcReply = m.Reply
4030 } else {
4031 // Schedule a reply after the previous message is delivered.
4032 sub.scheduleFlowControlResponse(m.Reply)
4033 }
4034 }
4035
4036 // Clear any SlowConsumer status.
4037 if sub.sc {
4038 sub.changeSubStatus(SubscriptionActive)
4039 }
4040 sub.sc = false
4041 sub.mu.Unlock()
4042
4043 if fcReply != _EMPTY_ {
4044 nc.Publish(fcReply, nil)
4045 }
4046
4047 // Handle control heartbeat messages.
4048 if ctrlMsg && ctrlType == jsCtrlHB && m.Reply == _EMPTY_ {
4049 nc.checkForSequenceMismatch(m, sub, jsi)
4050 }
4051
4052 // Check if we need to auto-unsubscribe for chan subscriptions
4053 if sub.typ == ChanSubscription && sub.max > 0 && !ctrlMsg {
4054 sub.mu.Lock()
4055 if sub.delivered >= sub.max {
4056 sub.mu.Unlock()
4057 nc.mu.Lock()
4058 nc.removeSub(sub)
4059 nc.mu.Unlock()
4060 } else {
4061 sub.mu.Unlock()
4062 }
4063 }
4064
4065 return
4066
4067 slowConsumer:
4068 // ordSeqs is deliberately not committed here: leaving the tracker behind is
4069 // what makes the next message register as a gap and get refetched.
4070 // Except for the consumer's first message: with nothing delivered yet the
4071 // tracker has no position, and a reset would resume from the start of the
4072 // stream rather than from where the consumer was told to start.
4073 if jsi != nil && jsi.ordered && jsi.sseq == 0 && ordSeqs.dseq == 1 {
4074 jsi.sseq = ordSeqs.sseq - 1
4075 }
4076 sub.dropped++
4077 sc := !sub.sc
4078 sub.sc = true
4079 // Undo stats from above
4080 sub.releaseReserved(m)
4081 if sc {
4082 sub.changeSubStatus(SubscriptionSlowConsumer)
4083 sub.mu.Unlock()
4084 // Now we need connection's lock and we may end-up in the situation
4085 // that we were trying to avoid, except that in this case, the client
4086 // is already experiencing client-side slow consumer situation.
4087 nc.mu.Lock()
4088 nc.err = ErrSlowConsumer
4089 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
4090 nc.ach.push(func() { asyncErrorCB(nc, sub, ErrSlowConsumer) })
4091 }
4092 nc.mu.Unlock()
4093 } else {
4094 sub.mu.Unlock()
4095 }
4096 }
4097
4098 // releaseReserved undoes the pending accounting reserved for m earlier in
4099 // processMsg. pMsgsMax/pBytesMax are deliberately left alone: they are
4100 // high-water marks of what was reserved. Lock must be held.
4101 func (sub *Subscription) releaseReserved(m *Msg) {
4102 if sub.typ != ChanSubscription {
4103 sub.pMsgs--
4104 sub.pBytes -= len(m.Data)
4105 }
4106 }
4107
4108 var (
4109 permissionsRe = regexp.MustCompile(`Subscription to "(\S+)"`)
4110 permissionsQueueRe = regexp.MustCompile(`using queue "(\S+)"`)
4111 )
4112
4113 // processTransientError is called when the server signals a non terminal error
4114 // which does not close the connection or trigger a reconnect.
4115 // This will trigger the async error callback if set.
4116 // These errors include the following:
4117 // - permissions violation on publish or subscribe
4118 // - maximum subscriptions exceeded
4119 func (nc *Conn) processTransientError(err error) {
4120 nc.mu.Lock()
4121 nc.err = err
4122 if errors.Is(err, ErrPermissionViolation) {
4123 matches := permissionsRe.FindStringSubmatch(err.Error())
4124 if len(matches) >= 2 {
4125 queueMatches := permissionsQueueRe.FindStringSubmatch(err.Error())
4126 var q string
4127 if len(queueMatches) >= 2 {
4128 q = queueMatches[1]
4129 }
4130 subject := matches[1]
4131 nc.subsMu.RLock()
4132 for _, sub := range nc.subs {
4133 if sub.Subject == subject && sub.Queue == q && sub.permissionsErr == nil {
4134 sub.mu.Lock()
4135 if sub.errCh != nil {
4136 sub.errCh <- err
4137 }
4138 sub.permissionsErr = err
4139 sub.mu.Unlock()
4140 }
4141 }
4142 nc.subsMu.RUnlock()
4143 }
4144 }
4145 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
4146 nc.ach.push(func() { asyncErrorCB(nc, nil, err) })
4147 }
4148 nc.mu.Unlock()
4149 }
4150
4151 // processAuthError generally processing for auth errors. We want to do retries
4152 // unless we get the same error again. This allows us for instance to swap credentials
4153 // and have the app reconnect, but if nothing is changing we should bail.
4154 // This function will return true if the connection should be closed, false otherwise.
4155 // Connection lock is held on entry
4156 func (nc *Conn) processAuthError(err error) bool {
4157 nc.err = err
4158 if !nc.initc {
4159 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
4160 nc.ach.push(func() { asyncErrorCB(nc, nil, err) })
4161 }
4162 }
4163 // We should give up if we tried twice on this server and got the
4164 // same error. This behavior can be modified using IgnoreAuthErrorAbort.
4165 if nc.current.lastErr == err && !nc.Opts.IgnoreAuthErrorAbort {
4166 nc.ar = true
4167 } else {
4168 nc.current.lastErr = err
4169 }
4170 return nc.ar
4171 }
4172
4173 // flusher is a separate Go routine that will process flush requests for the write
4174 // bufio. This allows coalescing of writes to the underlying socket.
4175 func (nc *Conn) flusher() {
4176 // Release the wait group
4177 defer nc.wg.Done()
4178
4179 // snapshot the bw and conn since they can change from underneath of us.
4180 nc.mu.Lock()
4181 bw := nc.bw
4182 conn := nc.conn
4183 fch := nc.fch
4184 nc.mu.Unlock()
4185
4186 if conn == nil || bw == nil {
4187 return
4188 }
4189
4190 for {
4191 if _, ok := <-fch; !ok {
4192 return
4193 }
4194 nc.mu.Lock()
4195
4196 // Check to see if we should bail out.
4197 if !nc.isConnected() || nc.isConnecting() || conn != nc.conn {
4198 nc.mu.Unlock()
4199 return
4200 }
4201 if bw.buffered() > 0 {
4202 if err := bw.flush(); err != nil {
4203 if nc.err == nil {
4204 nc.err = err
4205 }
4206 if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil {
4207 nc.ach.push(func() { asyncErrorCB(nc, nil, err) })
4208 }
4209 if nc.Opts.ReconnectOnFlusherError {
4210 nc.mu.Unlock()
4211 if shouldClose := nc.processOpErr(err, true); shouldClose {
4212 nc.close(CLOSED, true, nil)
4213 }
4214 return
4215 }
4216 }
4217 }
4218 nc.mu.Unlock()
4219 }
4220 }
4221
4222 // processPing will send an immediate pong protocol response to the
4223 // server. The server uses this mechanism to detect dead clients.
4224 func (nc *Conn) processPing() {
4225 nc.sendProto(pongProto)
4226 }
4227
4228 // processPong is used to process responses to the client's ping
4229 // messages. We use pings for the flush mechanism as well.
4230 func (nc *Conn) processPong() {
4231 var ch chan struct{}
4232
4233 nc.mu.Lock()
4234 if len(nc.pongs) > 0 {
4235 ch = nc.pongs[0]
4236 nc.pongs = append(nc.pongs[:0], nc.pongs[1:]...)
4237 }
4238 nc.pout = 0
4239 nc.mu.Unlock()
4240 if ch != nil {
4241 ch <- struct{}{}
4242 }
4243 }
4244
4245 // processOK is a placeholder for processing OK messages.
4246 func (nc *Conn) processOK() {
4247 // do nothing
4248 }
4249
4250 // processInfo is used to parse the info messages sent
4251 // from the server.
4252 // This function may update the server pool.
4253 func (nc *Conn) processInfo(info string) error {
4254 if info == _EMPTY_ {
4255 return nil
4256 }
4257 var ncInfo ServerInfo
4258 if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
4259 return err
4260 }
4261
4262 // Copy content into connection's info structure.
4263 nc.info = ncInfo
4264 // The array could be empty/not present on initial connect,
4265 // if advertise is disabled on that server, or servers that
4266 // did not include themselves in the async INFO protocol.
4267 // If empty, do not remove the implicit servers from the pool.
4268 if len(nc.info.ConnectURLs) == 0 || nc.Opts.IgnoreDiscoveredServers {
4269 if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil {
4270 nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) })
4271 }
4272 return nil
4273 }
4274 // Note about pool randomization: when the pool was first created,
4275 // it was randomized (if allowed). We keep the order the same (removing
4276 // implicit servers that are no longer sent to us). New URLs are sent
4277 // to us in no specific order so don't need extra randomization.
4278 hasNew := false
4279 // This is what we got from the server we are connected to.
4280 urls := nc.info.ConnectURLs
4281 // Transform that to a map for easy lookups
4282 tmp := make(map[string]struct{}, len(urls))
4283 for _, curl := range urls {
4284 tmp[curl] = struct{}{}
4285 }
4286 // Walk the pool and removed the implicit servers that are no longer in the
4287 // given array/map
4288 sp := nc.srvPool
4289 for i := 0; i < len(sp); i++ {
4290 srv := sp[i]
4291 curl := srv.URL.Host
4292 // Check if this URL is in the INFO protocol
4293 _, inInfo := tmp[curl]
4294 // Remove from the temp map so that at the end we are left with only
4295 // new (or restarted) servers that need to be added to the pool.
4296 delete(tmp, curl)
4297 // Keep servers that were set through Options, but also the one that
4298 // we are currently connected to (even if it is a discovered server).
4299 if !srv.isImplicit || srv.URL == nc.current.URL {
4300 continue
4301 }
4302 if !inInfo {
4303 // Remove from server pool. Keep current order.
4304 copy(sp[i:], sp[i+1:])
4305 nc.srvPool = sp[:len(sp)-1]
4306 sp = nc.srvPool
4307 i--
4308 }
4309 }
4310 // Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
4311 saveTLS := nc.current != nil && !hostIsIP(nc.current.URL)
4312
4313 // If there are any left in the tmp map, these are new (or restarted) servers
4314 // and need to be added to the pool.
4315 for curl := range tmp {
4316 // Before adding, check if this is a new (as in never seen) URL.
4317 // This is used to figure out if we invoke the DiscoveredServersCB
4318 if _, present := nc.urls[curl]; !present {
4319 hasNew = true
4320 }
4321 nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
4322 }
4323 if hasNew {
4324 // Randomize the pool if allowed but leave the first URL in place.
4325 if !nc.Opts.NoRandomize {
4326 nc.shufflePool(1)
4327 }
4328 if !nc.initc {
4329 if discoveredServersCB := nc.Opts.DiscoveredServersCB; discoveredServersCB != nil {
4330 nc.ach.push(func() { discoveredServersCB(nc) })
4331 }
4332 }
4333 }
4334 if !nc.initc && ncInfo.LameDuckMode {
4335 if lameDuckModeHandler := nc.Opts.LameDuckModeHandler; lameDuckModeHandler != nil {
4336 nc.ach.push(func() { lameDuckModeHandler(nc) })
4337 }
4338 }
4339 return nil
4340 }
4341
4342 // processAsyncInfo does the same than processInfo, but is called
4343 // from the parser. Calls processInfo under connection's lock
4344 // protection.
4345 func (nc *Conn) processAsyncInfo(info []byte) {
4346 nc.mu.Lock()
4347 // Ignore errors, we will simply not update the server pool...
4348 nc.processInfo(string(info))
4349 nc.mu.Unlock()
4350 }
4351
4352 // LastError reports the last error encountered via the connection.
4353 // It can be used reliably within ClosedCB in order to find out reason
4354 // why connection was closed for example.
4355 func (nc *Conn) LastError() error {
4356 if nc == nil {
4357 return ErrInvalidConnection
4358 }
4359 nc.mu.RLock()
4360 err := nc.err
4361 nc.mu.RUnlock()
4362 return err
4363 }
4364
4365 // Check if the given error string is an auth error, and if so returns
4366 // the corresponding ErrXXX error, nil otherwise
4367 func checkAuthError(e string) error {
4368 if strings.HasPrefix(e, AUTHORIZATION_ERR) {
4369 return ErrAuthorization
4370 }
4371 if strings.HasPrefix(e, AUTHENTICATION_EXPIRED_ERR) {
4372 return ErrAuthExpired
4373 }
4374 if strings.HasPrefix(e, AUTHENTICATION_REVOKED_ERR) {
4375 return ErrAuthRevoked
4376 }
4377 if strings.HasPrefix(e, ACCOUNT_AUTHENTICATION_EXPIRED_ERR) {
4378 return ErrAccountAuthExpired
4379 }
4380 return nil
4381 }
4382
4383 // processErr processes any error messages from the server and
4384 // sets the connection's LastError.
4385 func (nc *Conn) processErr(ie string) {
4386 // Trim, remove quotes
4387 ne := normalizeErr(ie)
4388 // convert to lower case.
4389 e := strings.ToLower(ne)
4390
4391 var close bool
4392
4393 // FIXME(dlc) - process Slow Consumer signals special.
4394 if e == STALE_CONNECTION {
4395 close = nc.processOpErr(ErrStaleConnection, false)
4396 } else if e == MAX_CONNECTIONS_ERR {
4397 close = nc.processOpErr(ErrMaxConnectionsExceeded, false)
4398 } else if e == MAX_ACCOUNT_CONNECTIONS_ERR {
4399 close = nc.processOpErr(ErrMaxAccountConnectionsExceeded, false)
4400 } else if strings.HasPrefix(e, PERMISSIONS_ERR) {
4401 nc.processTransientError(fmt.Errorf("%w: %s", ErrPermissionViolation, ne))
4402 } else if strings.HasPrefix(e, MAX_SUBSCRIPTIONS_ERR) {
4403 nc.processTransientError(ErrMaxSubscriptionsExceeded)
4404 } else if authErr := checkAuthError(e); authErr != nil {
4405 nc.mu.Lock()
4406 close = nc.processAuthError(authErr)
4407 nc.mu.Unlock()
4408 } else {
4409 close = true
4410 nc.mu.Lock()
4411 nc.err = errors.New("nats: " + ne)
4412 nc.mu.Unlock()
4413 }
4414 if close {
4415 nc.close(CLOSED, true, nil)
4416 }
4417 }
4418
4419 // kickFlusher will send a bool on a channel to kick the
4420 // flush Go routine to flush data to the server.
4421 func (nc *Conn) kickFlusher() {
4422 if nc.bw != nil {
4423 select {
4424 case nc.fch <- struct{}{}:
4425 default:
4426 }
4427 }
4428 }
4429
4430 // Publish publishes the data argument to the given subject. The data
4431 // argument is left untouched and needs to be correctly interpreted on
4432 // the receiver.
4433 func (nc *Conn) Publish(subj string, data []byte) error {
4434 return nc.publish(subj, _EMPTY_, false, nil, data)
4435 }
4436
4437 // Header represents the optional Header for a NATS message,
4438 // based on the implementation of http.Header.
4439 type Header map[string][]string
4440
4441 // Add adds the key, value pair to the header. It is case-sensitive
4442 // and appends to any existing values associated with key.
4443 func (h Header) Add(key, value string) {
4444 h[key] = append(h[key], value)
4445 }
4446
4447 // Set sets the header entries associated with key to the single
4448 // element value. It is case-sensitive and replaces any existing
4449 // values associated with key.
4450 func (h Header) Set(key, value string) {
4451 h[key] = []string{value}
4452 }
4453
4454 // Get gets the first value associated with the given key.
4455 // It is case-sensitive.
4456 func (h Header) Get(key string) string {
4457 if h == nil {
4458 return _EMPTY_
4459 }
4460 if v := h[key]; v != nil {
4461 return v[0]
4462 }
4463 return _EMPTY_
4464 }
4465
4466 // Values returns all values associated with the given key.
4467 // It is case-sensitive.
4468 func (h Header) Values(key string) []string {
4469 return h[key]
4470 }
4471
4472 // Del deletes the values associated with a key.
4473 // It is case-sensitive.
4474 func (h Header) Del(key string) {
4475 delete(h, key)
4476 }
4477
4478 // NewMsg creates a message for publishing that will use headers.
4479 func NewMsg(subject string) *Msg {
4480 return &Msg{
4481 Subject: subject,
4482 Header: make(Header),
4483 }
4484 }
4485
4486 const (
4487 hdrLine = "NATS/1.0\r\n"
4488 crlf = "\r\n"
4489 hdrPreEnd = len(hdrLine) - len(crlf)
4490 statusHdr = "Status"
4491 descrHdr = "Description"
4492 lastConsumerSeqHdr = "Nats-Last-Consumer"
4493 lastStreamSeqHdr = "Nats-Last-Stream"
4494 consumerStalledHdr = "Nats-Consumer-Stalled"
4495 noResponders = "503"
4496 noMessagesSts = "404"
4497 reqTimeoutSts = "408"
4498 jetStream409Sts = "409"
4499 controlMsg = "100"
4500 statusLen = 3 // e.g. 20x, 40x, 50x
4501 )
4502
4503 // DecodeHeadersMsg will decode and headers.
4504 func DecodeHeadersMsg(data []byte) (Header, error) {
4505 br := bufio.NewReaderSize(bytes.NewReader(data), 128)
4506 tp := textproto.NewReader(br)
4507 l, err := tp.ReadLine()
4508 if err != nil || len(l) < hdrPreEnd || l[:hdrPreEnd] != hdrLine[:hdrPreEnd] {
4509 return nil, ErrBadHeaderMsg
4510 }
4511
4512 mh, err := readMIMEHeader(tp)
4513 if err != nil {
4514 return nil, err
4515 }
4516
4517 // Check if we have an inlined status.
4518 if len(l) > hdrPreEnd {
4519 var description string
4520 status := strings.TrimSpace(l[hdrPreEnd:])
4521 if len(status) < statusLen {
4522 return nil, ErrBadHeaderMsg
4523 }
4524 if len(status) > statusLen {
4525 description = strings.TrimSpace(status[statusLen:])
4526 status = status[:statusLen]
4527 }
4528 mh.Add(statusHdr, status)
4529 if len(description) > 0 {
4530 mh.Add(descrHdr, description)
4531 }
4532 }
4533 return Header(mh), nil
4534 }
4535
4536 // readMIMEHeader returns a MIMEHeader that preserves the
4537 // original case of the MIME header, based on the implementation
4538 // of textproto.ReadMIMEHeader.
4539 //
4540 // https://golang.org/pkg/net/textproto/#Reader.ReadMIMEHeader
4541 func readMIMEHeader(tp *textproto.Reader) (textproto.MIMEHeader, error) {
4542 m := make(textproto.MIMEHeader)
4543 for {
4544 kv, err := tp.ReadLine()
4545 if len(kv) == 0 {
4546 return m, err
4547 }
4548
4549 // Process key fetching original case.
4550 i := strings.IndexByte(kv, ':')
4551 if i < 0 {
4552 return nil, ErrBadHeaderMsg
4553 }
4554 key := kv[:i]
4555 if key == "" {
4556 // Skip empty keys.
4557 continue
4558 }
4559 i++
4560 for i < len(kv) && (kv[i] == ' ' || kv[i] == '\t') {
4561 i++
4562 }
4563 m[key] = append(m[key], kv[i:])
4564 if err != nil {
4565 return m, err
4566 }
4567 }
4568 }
4569
4570 // PublishMsg publishes the Msg structure, which includes the
4571 // Subject, an optional Reply and an optional Data field.
4572 func (nc *Conn) PublishMsg(m *Msg) error {
4573 if m == nil {
4574 return ErrInvalidMsg
4575 }
4576 hdr, err := m.headerBytes()
4577 if err != nil {
4578 return err
4579 }
4580 validateReply := m.Reply != _EMPTY_
4581 return nc.publish(m.Subject, m.Reply, validateReply, hdr, m.Data)
4582 }
4583
4584 // PublishRequest will perform a Publish() expecting a response on the
4585 // reply subject. Use Request() for automatically waiting for a response
4586 // inline.
4587 func (nc *Conn) PublishRequest(subj, reply string, data []byte) error {
4588 return nc.publish(subj, reply, true, nil, data)
4589 }
4590
4591 // Used for handrolled Itoa
4592 const digits = "0123456789"
4593
4594 // validateSubject checks if the subject contains characters that break the NATS protocol.
4595 // Uses an adaptive algorithm: manual loop for short subjects (< 16 chars) and
4596 // SIMD-optimized strings.IndexByte for longer subjects.
4597 func validateSubject(subj string) error {
4598 if subj == "" {
4599 return ErrBadSubject
4600 }
4601
4602 // Adaptive threshold based on benchmark data showing crossover at ~15-20 characters.
4603 const lengthThreshold = 16
4604
4605 if len(subj) < lengthThreshold {
4606 // Fast path for short subjects (< 16 chars)
4607 // Short-circuit on non-control characters.
4608 for i := range len(subj) {
4609 c := subj[i]
4610 if c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
4611 return ErrBadSubject
4612 }
4613 }
4614 return nil
4615 }
4616
4617 // Optimized path for long subjects (>= 16 chars)
4618 // Uses SIMD-optimized strings.IndexByte (processes 16+ bytes per instruction)
4619 if strings.IndexByte(subj, ' ') >= 0 ||
4620 strings.IndexByte(subj, '\t') >= 0 ||
4621 strings.IndexByte(subj, '\r') >= 0 ||
4622 strings.IndexByte(subj, '\n') >= 0 {
4623 return ErrBadSubject
4624 }
4625 return nil
4626 }
4627
4628 // publish is the internal function to publish messages to a nats-server.
4629 // Sends a protocol data message by queuing into the bufio writer
4630 // and kicking the flush go routine. These writes should be protected.
4631 func (nc *Conn) publish(subj, reply string, validateReply bool, hdr, data []byte) error {
4632 if nc == nil {
4633 return ErrInvalidConnection
4634 }
4635 if !nc.Opts.SkipSubjectValidation {
4636 if err := validateSubject(subj); err != nil {
4637 return err
4638 }
4639 if validateReply {
4640 if err := validateSubject(reply); err != nil {
4641 return ErrBadSubject
4642 }
4643 }
4644 } else if subj == _EMPTY_ {
4645 return ErrBadSubject
4646 }
4647 nc.mu.Lock()
4648
4649 // Check if headers attempted to be sent to server that does not support them.
4650 if len(hdr) > 0 && !nc.info.Headers {
4651 nc.mu.Unlock()
4652 return ErrHeadersNotSupported
4653 }
4654
4655 if nc.isClosed() {
4656 nc.mu.Unlock()
4657 return ErrConnectionClosed
4658 }
4659
4660 if nc.isDrainingPubs() {
4661 nc.mu.Unlock()
4662 return ErrConnectionDraining
4663 }
4664
4665 // Proactively reject payloads over the threshold set by server.
4666 msgSize := int64(len(data) + len(hdr))
4667 // Skip this check if we are not yet connected (RetryOnFailedConnect)
4668 if !nc.initc && msgSize > nc.info.MaxPayload {
4669 nc.mu.Unlock()
4670 return ErrMaxPayload
4671 }
4672
4673 // Check if we are reconnecting, and if so check if
4674 // we have exceeded our reconnect outbound buffer limits.
4675 if nc.bw.atLimitIfUsingPending() {
4676 nc.mu.Unlock()
4677 return ErrReconnectBufExceeded
4678 }
4679
4680 var mh []byte
4681 if hdr != nil {
4682 mh = nc.scratch[:len(_HPUB_P_)]
4683 } else {
4684 mh = nc.scratch[1:len(_HPUB_P_)]
4685 }
4686 mh = append(mh, subj...)
4687 mh = append(mh, ' ')
4688 if reply != "" {
4689 mh = append(mh, reply...)
4690 mh = append(mh, ' ')
4691 }
4692
4693 // We could be smarter here, but simple loop is ok,
4694 // just avoid strconv in fast path.
4695 // FIXME(dlc) - Find a better way here.
4696 // msgh = strconv.AppendInt(msgh, int64(len(data)), 10)
4697 // go 1.14 some values strconv faster, may be able to switch over.
4698
4699 var b [12]byte
4700 i := len(b)
4701
4702 if hdr != nil {
4703 if len(hdr) > 0 {
4704 for l := len(hdr); l > 0; l /= 10 {
4705 i--
4706 b[i] = digits[l%10]
4707 }
4708 } else {
4709 i--
4710 b[i] = digits[0]
4711 }
4712 mh = append(mh, b[i:]...)
4713 mh = append(mh, ' ')
4714 // reset for below.
4715 i = len(b)
4716 }
4717
4718 if msgSize > 0 {
4719 for l := msgSize; l > 0; l /= 10 {
4720 i--
4721 b[i] = digits[l%10]
4722 }
4723 } else {
4724 i--
4725 b[i] = digits[0]
4726 }
4727
4728 mh = append(mh, b[i:]...)
4729 mh = append(mh, _CRLF_...)
4730
4731 if err := nc.bw.appendBufs(mh, hdr, data, _CRLF_BYTES_); err != nil {
4732 nc.mu.Unlock()
4733 return err
4734 }
4735
4736 nc.OutMsgs++
4737 nc.OutBytes += uint64(len(data) + len(hdr))
4738
4739 if len(nc.fch) == 0 {
4740 nc.kickFlusher()
4741 }
4742 nc.mu.Unlock()
4743 return nil
4744 }
4745
4746 // respHandler is the global response handler. It will look up
4747 // the appropriate channel based on the last token and place
4748 // the message on the channel if possible.
4749 func (nc *Conn) respHandler(m *Msg) {
4750 nc.mu.Lock()
4751
4752 // Just return if closed.
4753 if nc.isClosed() {
4754 nc.mu.Unlock()
4755 return
4756 }
4757
4758 var mch chan *Msg
4759
4760 // Grab mch
4761 rt := nc.respToken(m.Subject)
4762 if rt != _EMPTY_ {
4763 mch = nc.respMap[rt]
4764 // Delete the key regardless, one response only.
4765 delete(nc.respMap, rt)
4766 } else if len(nc.respMap) == 1 {
4767 // If the server has rewritten the subject, the response token (rt)
4768 // will not match (could be the case with JetStream). If that is the
4769 // case and there is a single entry, use that.
4770 for k, v := range nc.respMap {
4771 mch = v
4772 delete(nc.respMap, k)
4773 break
4774 }
4775 }
4776 nc.mu.Unlock()
4777
4778 // Don't block, let Request timeout instead, mch is
4779 // buffered and we should delete the key before a
4780 // second response is processed.
4781 select {
4782 case mch <- m:
4783 default:
4784 return
4785 }
4786 }
4787
4788 // Helper to setup and send new request style requests. Return the chan to receive the response.
4789 func (nc *Conn) createNewRequestAndSend(subj string, hdr, data []byte) (chan *Msg, string, error) {
4790 nc.mu.Lock()
4791 // Create new literal Inbox and map to a chan msg.
4792 mch := make(chan *Msg, RequestChanLen)
4793 respInbox := nc.newRespInbox()
4794 token := respInbox[nc.respSubLen:]
4795
4796 nc.respMap[token] = mch
4797 if nc.respMux == nil {
4798 // Create the response subscription we will use for all new style responses.
4799 // This will be on an _INBOX with an additional terminal token. The subscription
4800 // will be on a wildcard.
4801 s, err := nc.subscribeLocked(nc.respSub, _EMPTY_, nc.respHandler, nil, nil, false, nil)
4802 if err != nil {
4803 nc.mu.Unlock()
4804 return nil, token, err
4805 }
4806 nc.respMux = s
4807 }
4808 nc.mu.Unlock()
4809
4810 if err := nc.publish(subj, respInbox, false, hdr, data); err != nil {
4811 return nil, token, err
4812 }
4813
4814 return mch, token, nil
4815 }
4816
4817 // RequestMsg will send a request payload including optional headers and deliver
4818 // the response message, or an error, including a timeout if no message was received properly.
4819 func (nc *Conn) RequestMsg(msg *Msg, timeout time.Duration) (*Msg, error) {
4820 if msg == nil {
4821 return nil, ErrInvalidMsg
4822 }
4823 hdr, err := msg.headerBytes()
4824 if err != nil {
4825 return nil, err
4826 }
4827
4828 return nc.request(msg.Subject, hdr, msg.Data, timeout)
4829 }
4830
4831 // Request will send a request payload and deliver the response message,
4832 // or an error, including a timeout if no message was received properly.
4833 func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
4834 return nc.request(subj, nil, data, timeout)
4835 }
4836
4837 func (nc *Conn) useOldRequestStyle() bool {
4838 nc.mu.RLock()
4839 r := nc.Opts.UseOldRequestStyle
4840 nc.mu.RUnlock()
4841 return r
4842 }
4843
4844 func (nc *Conn) request(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
4845 if nc == nil {
4846 return nil, ErrInvalidConnection
4847 }
4848
4849 var m *Msg
4850 var err error
4851
4852 if nc.useOldRequestStyle() {
4853 m, err = nc.oldRequest(subj, hdr, data, timeout)
4854 } else {
4855 m, err = nc.newRequest(subj, hdr, data, timeout)
4856 }
4857
4858 // Check for no responder status.
4859 if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
4860 m, err = nil, ErrNoResponders
4861 }
4862 return m, err
4863 }
4864
4865 func (nc *Conn) newRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
4866 mch, token, err := nc.createNewRequestAndSend(subj, hdr, data)
4867 if err != nil {
4868 return nil, err
4869 }
4870
4871 t := globalTimerPool.Get(timeout)
4872 defer globalTimerPool.Put(t)
4873
4874 var ok bool
4875 var msg *Msg
4876
4877 select {
4878 case msg, ok = <-mch:
4879 if !ok {
4880 return nil, ErrConnectionClosed
4881 }
4882 case <-t.C:
4883 nc.mu.Lock()
4884 delete(nc.respMap, token)
4885 nc.mu.Unlock()
4886 return nil, ErrTimeout
4887 }
4888
4889 return msg, nil
4890 }
4891
4892 // oldRequest will create an Inbox and perform a Request() call
4893 // with the Inbox reply and return the first reply received.
4894 // This is optimized for the case of multiple responses.
4895 func (nc *Conn) oldRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
4896 inbox := nc.NewInbox()
4897 ch := make(chan *Msg, RequestChanLen)
4898
4899 s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, nil, true, nil)
4900 if err != nil {
4901 return nil, err
4902 }
4903 s.AutoUnsubscribe(1)
4904 defer s.Unsubscribe()
4905
4906 err = nc.publish(subj, inbox, false, hdr, data)
4907 if err != nil {
4908 return nil, err
4909 }
4910
4911 return s.NextMsg(timeout)
4912 }
4913
4914 // InboxPrefix is the prefix for all inbox subjects.
4915 const (
4916 InboxPrefix = "_INBOX."
4917 inboxPrefixLen = len(InboxPrefix)
4918 replySuffixLen = 8 // Gives us 62^8
4919 rdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
4920 base = 62
4921 )
4922
4923 // NewInbox will return an inbox string which can be used for directed replies from
4924 // subscribers. These are guaranteed to be unique, but can be shared and subscribed
4925 // to by others.
4926 func NewInbox() string {
4927 var b [inboxPrefixLen + nuidSize]byte
4928 pres := b[:inboxPrefixLen]
4929 copy(pres, InboxPrefix)
4930 ns := b[inboxPrefixLen:]
4931 copy(ns, nuid.Next())
4932 return string(b[:])
4933 }
4934
4935 // Create a new inbox that is prefix aware.
4936 func (nc *Conn) NewInbox() string {
4937 if nc.Opts.InboxPrefix == _EMPTY_ {
4938 return NewInbox()
4939 }
4940
4941 var sb strings.Builder
4942 sb.Grow(len(nc.Opts.InboxPrefix) + 1 + nuidSize)
4943 sb.WriteString(nc.Opts.InboxPrefix)
4944 sb.WriteByte('.')
4945 sb.WriteString(nuid.Next())
4946 return sb.String()
4947 }
4948
4949 // Function to init new response structures.
4950 func (nc *Conn) initNewResp() {
4951 nc.respSubPrefix = fmt.Sprintf("%s.", nc.NewInbox())
4952 nc.respSubLen = len(nc.respSubPrefix)
4953 nc.respSub = fmt.Sprintf("%s*", nc.respSubPrefix)
4954 nc.respMap = make(map[string]chan *Msg)
4955 nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
4956 }
4957
4958 // newRespInbox creates a new literal response subject
4959 // that will trigger the mux subscription handler.
4960 // Lock should be held.
4961 func (nc *Conn) newRespInbox() string {
4962 if nc.respMap == nil {
4963 nc.initNewResp()
4964 }
4965
4966 var sb strings.Builder
4967 sb.Grow(nc.respSubLen + replySuffixLen)
4968 sb.WriteString(nc.respSubPrefix)
4969
4970 rn := nc.respRand.Int63()
4971 for i := 0; i < replySuffixLen; i++ {
4972 sb.WriteByte(rdigits[rn%base])
4973 rn /= base
4974 }
4975
4976 return sb.String()
4977 }
4978
4979 // NewRespInbox is the new format used for _INBOX.
4980 func (nc *Conn) NewRespInbox() string {
4981 nc.mu.Lock()
4982 s := nc.newRespInbox()
4983 nc.mu.Unlock()
4984 return s
4985 }
4986
4987 // respToken will return the last token of a literal response inbox
4988 // which we use for the message channel lookup. This needs to verify the subject
4989 // prefix matches to protect itself against the server changing the subject.
4990 // Lock should be held.
4991 func (nc *Conn) respToken(respInbox string) string {
4992 if token, found := strings.CutPrefix(respInbox, nc.respSubPrefix); found {
4993 return token
4994 }
4995 return ""
4996 }
4997
4998 // Subscribe will express interest in the given subject. The subject
4999 // can have wildcards.
5000 // There are two type of wildcards: * for partial, and > for full.
5001 // A subscription on subject time.*.east would receive messages sent to time.us.east and time.eu.east.
5002 // A subscription on subject time.us.> would receive messages sent to
5003 // time.us.east and time.us.east.atlanta, while time.us.* would only match time.us.east
5004 // since it can't match more than one token.
5005 // Messages will be delivered to the associated MsgHandler.
5006 func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) {
5007 return nc.subscribe(subj, _EMPTY_, cb, nil, nil, false, nil)
5008 }
5009
5010 // ChanSubscribe will express interest in the given subject and place
5011 // all messages received on the channel.
5012 // You should not close the channel until sub.Unsubscribe() has been called.
5013 func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error) {
5014 return nc.subscribe(subj, _EMPTY_, nil, ch, nil, false, nil)
5015 }
5016
5017 // ChanQueueSubscribe will express interest in the given subject.
5018 // All subscribers with the same queue name will form the queue group
5019 // and only one member of the group will be selected to receive any given message,
5020 // which will be placed on the channel.
5021 // You should not close the channel until sub.Unsubscribe() has been called.
5022 // Note: This is the same than QueueSubscribeSyncWithChan.
5023 func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error) {
5024 return nc.subscribe(subj, group, nil, ch, nil, false, nil)
5025 }
5026
5027 // SubscribeSync will express interest on the given subject. Messages will
5028 // be received synchronously using Subscription.NextMsg().
5029 func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) {
5030 if nc == nil {
5031 return nil, ErrInvalidConnection
5032 }
5033 mch := make(chan *Msg, nc.Opts.SubChanLen)
5034 var errCh chan error
5035 if nc.Opts.PermissionErrOnSubscribe {
5036 errCh = make(chan error, 100)
5037 }
5038 return nc.subscribe(subj, _EMPTY_, nil, mch, errCh, true, nil)
5039 }
5040
5041 // QueueSubscribe creates an asynchronous queue subscriber on the given subject.
5042 // All subscribers with the same queue name will form the queue group and
5043 // only one member of the group will be selected to receive any given
5044 // message asynchronously.
5045 func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
5046 return nc.subscribe(subj, queue, cb, nil, nil, false, nil)
5047 }
5048
5049 // QueueSubscribeSync creates a synchronous queue subscriber on the given
5050 // subject. All subscribers with the same queue name will form the queue
5051 // group and only one member of the group will be selected to receive any
5052 // given message synchronously using Subscription.NextMsg().
5053 func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) {
5054 mch := make(chan *Msg, nc.Opts.SubChanLen)
5055 var errCh chan error
5056 if nc.Opts.PermissionErrOnSubscribe {
5057 errCh = make(chan error, 100)
5058 }
5059 return nc.subscribe(subj, queue, nil, mch, errCh, true, nil)
5060 }
5061
5062 // QueueSubscribeSyncWithChan will express interest in the given subject.
5063 // All subscribers with the same queue name will form the queue group
5064 // and only one member of the group will be selected to receive any given message,
5065 // which will be placed on the channel.
5066 // You should not close the channel until sub.Unsubscribe() has been called.
5067 // Note: This is the same than ChanQueueSubscribe.
5068 func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error) {
5069 return nc.subscribe(subj, queue, nil, ch, nil, false, nil)
5070 }
5071
5072 // badSubject will do quick test on whether a subject is acceptable.
5073 // Spaces are not allowed and all tokens should be > 0 in len.
5074 func badSubject(subj string) bool {
5075 if strings.ContainsAny(subj, " \t\r\n") {
5076 return true
5077 }
5078 tokens := strings.Split(subj, ".")
5079 for _, t := range tokens {
5080 if len(t) == 0 {
5081 return true
5082 }
5083 }
5084 return false
5085 }
5086
5087 // badQueue will check a queue name for whitespace.
5088 func badQueue(qname string) bool {
5089 return strings.ContainsAny(qname, " \t\r\n")
5090 }
5091
5092 // subscribe is the internal subscribe function that indicates interest in a subject.
5093 func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, errCh chan (error), isSync bool, js *jsSub) (*Subscription, error) {
5094 if nc == nil {
5095 return nil, ErrInvalidConnection
5096 }
5097 nc.mu.Lock()
5098 defer nc.mu.Unlock()
5099 return nc.subscribeLocked(subj, queue, cb, ch, errCh, isSync, js)
5100 }
5101
5102 func (nc *Conn) subscribeLocked(subj, queue string, cb MsgHandler, ch chan *Msg, errCh chan (error), isSync bool, js *jsSub) (*Subscription, error) {
5103 if nc == nil {
5104 return nil, ErrInvalidConnection
5105 }
5106 if badSubject(subj) {
5107 return nil, ErrBadSubject
5108 }
5109 if queue != _EMPTY_ && badQueue(queue) {
5110 return nil, ErrBadQueueName
5111 }
5112
5113 // Check for some error conditions.
5114 if nc.isClosed() {
5115 return nil, ErrConnectionClosed
5116 }
5117 if nc.isDraining() {
5118 return nil, ErrConnectionDraining
5119 }
5120
5121 if cb == nil && ch == nil {
5122 return nil, ErrBadSubscription
5123 }
5124
5125 sub := &Subscription{
5126 Subject: subj,
5127 Queue: queue,
5128 mcb: cb,
5129 conn: nc,
5130 jsi: js,
5131 }
5132 // Set pending limits.
5133 if ch != nil {
5134 sub.pMsgsLimit = cap(ch)
5135 } else {
5136 sub.pMsgsLimit = DefaultSubPendingMsgsLimit
5137 }
5138 sub.pBytesLimit = DefaultSubPendingBytesLimit
5139
5140 // If we have an async callback, start up a sub specific
5141 // Go routine to deliver the messages.
5142 var sr bool
5143 if cb != nil {
5144 sub.typ = AsyncSubscription
5145 sub.pCond = sync.NewCond(&sub.mu)
5146 sr = true
5147 } else if !isSync {
5148 sub.typ = ChanSubscription
5149 sub.mch = ch
5150 } else { // Sync Subscription
5151 sub.typ = SyncSubscription
5152 sub.mch = ch
5153 sub.errCh = errCh
5154 }
5155
5156 nc.subsMu.Lock()
5157 nc.ssid++
5158 sid := nc.ssid
5159 sub.sid = sid
5160 nc.subs[sid] = sub
5161 nc.subsMu.Unlock()
5162
5163 // Let's start the go routine now that it is fully setup and registered.
5164 if sr {
5165 go nc.waitForMsgs(sub)
5166 }
5167
5168 // We will send these for all subs when we reconnect
5169 // so that we can suppress here if reconnecting.
5170 if !nc.isReconnecting() {
5171 nc.bw.appendString(fmt.Sprintf(subProto, subj, queue, sid))
5172 nc.kickFlusher()
5173 }
5174
5175 sub.changeSubStatus(SubscriptionActive)
5176 return sub, nil
5177 }
5178
5179 // NumSubscriptions returns active number of subscriptions.
5180 func (nc *Conn) NumSubscriptions() int {
5181 nc.subsMu.RLock()
5182 defer nc.subsMu.RUnlock()
5183 return len(nc.subs)
5184 }
5185
5186 // Lock for nc should be held here upon entry
5187 func (nc *Conn) removeSub(s *Subscription) {
5188 nc.subsMu.Lock()
5189 delete(nc.subs, s.sid)
5190 nc.subsMu.Unlock()
5191 s.mu.Lock()
5192 defer s.mu.Unlock()
5193 // Release callers on NextMsg for SyncSubscription only
5194 if s.mch != nil && s.typ == SyncSubscription {
5195 close(s.mch)
5196 }
5197 s.mch = nil
5198
5199 // If JS subscription then stop HB timer.
5200 if jsi := s.jsi; jsi != nil {
5201 if jsi.hbc != nil {
5202 jsi.hbc.Stop()
5203 jsi.hbc = nil
5204 }
5205 if jsi.csfct != nil {
5206 jsi.csfct.Stop()
5207 jsi.csfct = nil
5208 }
5209 }
5210
5211 if s.typ != AsyncSubscription {
5212 done := s.pDone
5213 if done != nil {
5214 done(s.Subject)
5215 }
5216 }
5217 // Mark as invalid
5218 s.closed = true
5219 s.changeSubStatus(SubscriptionClosed)
5220 if s.pCond != nil {
5221 s.pCond.Broadcast()
5222 }
5223 }
5224
5225 // SubscriptionType is the type of the Subscription.
5226 type SubscriptionType int
5227
5228 // The different types of subscription types.
5229 const (
5230 AsyncSubscription = SubscriptionType(iota)
5231 SyncSubscription
5232 ChanSubscription
5233 NilSubscription
5234 PullSubscription
5235 )
5236
5237 // Type returns the type of Subscription.
5238 func (s *Subscription) Type() SubscriptionType {
5239 if s == nil {
5240 return NilSubscription
5241 }
5242 s.mu.Lock()
5243 defer s.mu.Unlock()
5244 // Pull subscriptions are really a SyncSubscription and we want this
5245 // type to be set internally for all delivered messages management, etc..
5246 // So check when to return PullSubscription to the user.
5247 if s.jsi != nil && s.jsi.pull {
5248 return PullSubscription
5249 }
5250 return s.typ
5251 }
5252
5253 // IsValid returns a boolean indicating whether the subscription
5254 // is still active. This will return false if the subscription has
5255 // already been closed.
5256 func (s *Subscription) IsValid() bool {
5257 if s == nil {
5258 return false
5259 }
5260 s.mu.Lock()
5261 defer s.mu.Unlock()
5262 return s.conn != nil && !s.closed
5263 }
5264
5265 // Drain will remove interest but continue callbacks until all messages
5266 // have been processed.
5267 //
5268 // For a JetStream subscription, if the library has created the JetStream
5269 // consumer, the library will send a DeleteConsumer request to the server
5270 // when the drain operation completes. If a failure occurs when deleting
5271 // the JetStream consumer, an error will be reported to the asynchronous
5272 // error callback.
5273 // If you do not wish the JetStream consumer to be automatically deleted,
5274 // ensure that the consumer is not created by the library, which means
5275 // create the consumer with AddConsumer and bind to this consumer.
5276 func (s *Subscription) Drain() error {
5277 if s == nil {
5278 return ErrBadSubscription
5279 }
5280 s.mu.Lock()
5281 conn := s.conn
5282 s.mu.Unlock()
5283 if conn == nil {
5284 return ErrBadSubscription
5285 }
5286 return conn.unsubscribe(s, 0, true)
5287 }
5288
5289 // IsDraining returns a boolean indicating whether the subscription
5290 // is being drained.
5291 // This will return false if the subscription has already been closed.
5292 func (s *Subscription) IsDraining() bool {
5293 if s == nil {
5294 return false
5295 }
5296 s.mu.Lock()
5297 defer s.mu.Unlock()
5298 return s.draining
5299 }
5300
5301 // StatusChanged returns a channel on which given list of subscription status
5302 // changes will be sent. If no status is provided, all status changes will be sent.
5303 // Available statuses are SubscriptionActive, SubscriptionDraining, SubscriptionClosed,
5304 // and SubscriptionSlowConsumer.
5305 // The returned channel will be closed when the subscription is closed.
5306 func (s *Subscription) StatusChanged(statuses ...SubStatus) <-chan SubStatus {
5307 if len(statuses) == 0 {
5308 statuses = []SubStatus{SubscriptionActive, SubscriptionDraining, SubscriptionClosed, SubscriptionSlowConsumer}
5309 }
5310 ch := make(chan SubStatus, 10)
5311 s.mu.Lock()
5312 defer s.mu.Unlock()
5313
5314 if s.status == SubscriptionClosed {
5315 if slices.Contains(statuses, SubscriptionClosed) {
5316 ch <- SubscriptionClosed
5317 }
5318 close(ch)
5319 return ch
5320 }
5321
5322 for _, status := range statuses {
5323 s.registerStatusChangeListener(status, ch)
5324 // initial status
5325 if status == s.status {
5326 ch <- status
5327 }
5328 }
5329 return ch
5330 }
5331
5332 // registerStatusChangeListener registers a channel waiting for a specific status change event.
5333 // Status change events are non-blocking - if no receiver is waiting for the status change,
5334 // it will not be sent on the channel. Closed channels are ignored.
5335 // Lock should be held entering.
5336 func (s *Subscription) registerStatusChangeListener(status SubStatus, ch chan SubStatus) {
5337 if s.statListeners == nil {
5338 s.statListeners = make(map[chan SubStatus][]SubStatus)
5339 }
5340 if _, ok := s.statListeners[ch]; !ok {
5341 s.statListeners[ch] = make([]SubStatus, 0)
5342 }
5343 s.statListeners[ch] = append(s.statListeners[ch], status)
5344 }
5345
5346 // sendStatusEvent sends subscription status event to all channels.
5347 // If there is no listener, sendStatusEvent
5348 // will not block. Lock should be held entering.
5349 func (s *Subscription) sendStatusEvent(status SubStatus) {
5350 for ch, statuses := range s.statListeners {
5351 if !slices.Contains(statuses, status) {
5352 continue
5353 }
5354 // only send event if someone's listening
5355 select {
5356 case ch <- status:
5357 default:
5358 }
5359 }
5360 // After sending SubscriptionClosed status to all listeners,
5361 // close all channels and clear the map to prevent future
5362 // sends to closed channels that could cause panics
5363 if status == SubscriptionClosed {
5364 for ch := range s.statListeners {
5365 close(ch)
5366 }
5367 s.statListeners = nil
5368 }
5369 }
5370
5371 // changeSubStatus changes subscription status and sends events
5372 // to all listeners. Lock should be held entering.
5373 func (s *Subscription) changeSubStatus(status SubStatus) {
5374 if s == nil {
5375 return
5376 }
5377 s.sendStatusEvent(status)
5378 s.status = status
5379 }
5380
5381 // Unsubscribe will remove interest in the given subject.
5382 //
5383 // For a JetStream subscription, if the library has created the JetStream
5384 // consumer, it will send a DeleteConsumer request to the server (if the
5385 // unsubscribe itself was successful). If the delete operation fails, the
5386 // error will be returned.
5387 // If you do not wish the JetStream consumer to be automatically deleted,
5388 // ensure that the consumer is not created by the library, which means
5389 // create the consumer with AddConsumer and bind to this consumer (using
5390 // the nats.Bind() option).
5391 func (s *Subscription) Unsubscribe() error {
5392 if s == nil {
5393 return ErrBadSubscription
5394 }
5395 s.mu.Lock()
5396 conn := s.conn
5397 closed := s.closed
5398 dc := s.jsi != nil && s.jsi.dc
5399 s.mu.Unlock()
5400 if conn == nil || conn.IsClosed() {
5401 return ErrConnectionClosed
5402 }
5403 if closed {
5404 return ErrBadSubscription
5405 }
5406 if conn.IsDraining() {
5407 return ErrConnectionDraining
5408 }
5409 err := conn.unsubscribe(s, 0, false)
5410 if err == nil && dc {
5411 err = s.deleteConsumer()
5412 }
5413 return err
5414 }
5415
5416 // checkDrained will watch for a subscription to be fully drained
5417 // and then remove it.
5418 func (nc *Conn) checkDrained(sub *Subscription) {
5419 if nc == nil || sub == nil {
5420 return
5421 }
5422 defer func() {
5423 sub.mu.Lock()
5424 defer sub.mu.Unlock()
5425 sub.draining = false
5426 }()
5427
5428 // This allows us to know that whatever we have in the client pending
5429 // is correct and the server will not send additional information.
5430 nc.Flush()
5431
5432 sub.mu.Lock()
5433 // For JS subscriptions, check if we are going to delete the
5434 // JS consumer when drain completes.
5435 dc := sub.jsi != nil && sub.jsi.dc
5436 sub.mu.Unlock()
5437
5438 // Once we are here we just wait for Pending to reach 0 or
5439 // any other state to exit this go routine.
5440 for {
5441 // check connection is still valid.
5442 if nc.IsClosed() {
5443 return
5444 }
5445
5446 // Check subscription state
5447 sub.mu.Lock()
5448 conn := sub.conn
5449 closed := sub.closed
5450 pMsgs := sub.pMsgs
5451 sub.mu.Unlock()
5452
5453 if conn == nil || closed || pMsgs == 0 {
5454 nc.mu.Lock()
5455 nc.removeSub(sub)
5456 nc.mu.Unlock()
5457 if dc {
5458 if err := sub.deleteConsumer(); err != nil {
5459 nc.mu.Lock()
5460 if errCB := nc.Opts.AsyncErrorCB; errCB != nil {
5461 nc.ach.push(func() { errCB(nc, sub, err) })
5462 }
5463 nc.mu.Unlock()
5464 }
5465 }
5466 return
5467 }
5468
5469 time.Sleep(100 * time.Millisecond)
5470 }
5471 }
5472
5473 // AutoUnsubscribe will issue an automatic Unsubscribe that is
5474 // processed by the server when max messages have been received.
5475 // This can be useful when sending a request to an unknown number
5476 // of subscribers.
5477 func (s *Subscription) AutoUnsubscribe(max int) error {
5478 if s == nil {
5479 return ErrBadSubscription
5480 }
5481 s.mu.Lock()
5482 conn := s.conn
5483 closed := s.closed
5484 s.mu.Unlock()
5485 if conn == nil || closed {
5486 return ErrBadSubscription
5487 }
5488 return conn.unsubscribe(s, max, false)
5489 }
5490
5491 // SetClosedHandler will set the closed handler for when a subscription
5492 // is closed (either unsubscribed or drained).
5493 func (s *Subscription) SetClosedHandler(handler func(subject string)) {
5494 s.mu.Lock()
5495 s.pDone = handler
5496 s.mu.Unlock()
5497 }
5498
5499 // unsubscribe performs the low level unsubscribe to the server.
5500 // Use Subscription.Unsubscribe()
5501 func (nc *Conn) unsubscribe(sub *Subscription, max int, drainMode bool) error {
5502 var maxStr string
5503 if max > 0 {
5504 sub.mu.Lock()
5505 sub.max = uint64(max)
5506 if sub.delivered < sub.max {
5507 maxStr = strconv.Itoa(max)
5508 }
5509 sub.mu.Unlock()
5510 }
5511
5512 nc.mu.Lock()
5513 // ok here, but defer is expensive
5514 defer nc.mu.Unlock()
5515
5516 if nc.isClosed() {
5517 return ErrConnectionClosed
5518 }
5519
5520 nc.subsMu.RLock()
5521 s := nc.subs[sub.sid]
5522 nc.subsMu.RUnlock()
5523 // Already unsubscribed
5524 if s == nil {
5525 return nil
5526 }
5527
5528 if maxStr == _EMPTY_ && !drainMode {
5529 nc.removeSub(s)
5530 }
5531
5532 if drainMode {
5533 s.mu.Lock()
5534 s.draining = true
5535 sub.changeSubStatus(SubscriptionDraining)
5536 s.mu.Unlock()
5537 go nc.checkDrained(sub)
5538 }
5539
5540 // We will send these for all subs when we reconnect
5541 // so that we can suppress here.
5542 if !nc.isReconnecting() {
5543 // Deliberately re-read the sid: in the AutoUnsubscribe case removeSub
5544 // is skipped, so an ordered consumer reset may have swapped it since
5545 // the lookup above and the max has to apply to what the server knows.
5546 nc.subsMu.RLock()
5547 sid := s.sid
5548 nc.subsMu.RUnlock()
5549 nc.bw.appendString(fmt.Sprintf(unsubProto, sid, maxStr))
5550 nc.kickFlusher()
5551 }
5552
5553 // For JetStream subscriptions cancel the attached context if there is any.
5554 var cancel func()
5555 sub.mu.Lock()
5556 jsi := sub.jsi
5557 if jsi != nil {
5558 cancel = jsi.cancel
5559 jsi.cancel = nil
5560 }
5561 sub.mu.Unlock()
5562 if cancel != nil {
5563 cancel()
5564 }
5565
5566 return nil
5567 }
5568
5569 // NextMsg will return the next message available to a synchronous subscriber
5570 // or block until one is available. An error is returned if the subscription is invalid (ErrBadSubscription),
5571 // the connection is closed (ErrConnectionClosed), the timeout is reached (ErrTimeout),
5572 // or if there were no responders (ErrNoResponders) when used in the context of a request/reply.
5573 func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
5574 if s == nil {
5575 return nil, ErrBadSubscription
5576 }
5577
5578 s.mu.Lock()
5579 err := s.validateNextMsgState(false)
5580 if err != nil {
5581 s.mu.Unlock()
5582 return nil, err
5583 }
5584
5585 // snapshot
5586 mch := s.mch
5587 s.mu.Unlock()
5588
5589 var ok bool
5590 var msg *Msg
5591
5592 // If something is available right away, let's optimize that case.
5593 select {
5594 case msg, ok = <-mch:
5595 if !ok {
5596 return nil, s.getNextMsgErr()
5597 }
5598 if err := s.processNextMsgDelivered(msg); err != nil {
5599 return nil, err
5600 } else {
5601 return msg, nil
5602 }
5603 default:
5604 }
5605
5606 // If we are here a message was not immediately available, so lets loop
5607 // with a timeout.
5608
5609 t := globalTimerPool.Get(timeout)
5610 defer globalTimerPool.Put(t)
5611
5612 if s.errCh != nil {
5613 select {
5614 case msg, ok = <-mch:
5615 if !ok {
5616 return nil, s.getNextMsgErr()
5617 }
5618 if err := s.processNextMsgDelivered(msg); err != nil {
5619 return nil, err
5620 }
5621 case err := <-s.errCh:
5622 return nil, err
5623 case <-t.C:
5624 return nil, ErrTimeout
5625 }
5626 } else {
5627 select {
5628 case msg, ok = <-mch:
5629 if !ok {
5630 return nil, s.getNextMsgErr()
5631 }
5632 if err := s.processNextMsgDelivered(msg); err != nil {
5633 return nil, err
5634 }
5635 case <-t.C:
5636 return nil, ErrTimeout
5637 }
5638 }
5639
5640 return msg, nil
5641 }
5642
5643 // nextMsgNoTimeout works similarly to Subscription.NextMsg() but will not
5644 // time out. It is only used internally for non-timeout subscription iterator.
5645 func (s *Subscription) nextMsgNoTimeout() (*Msg, error) {
5646 if s == nil {
5647 return nil, ErrBadSubscription
5648 }
5649
5650 s.mu.Lock()
5651 err := s.validateNextMsgState(false)
5652 if err != nil {
5653 s.mu.Unlock()
5654 return nil, err
5655 }
5656
5657 // snapshot
5658 mch := s.mch
5659 s.mu.Unlock()
5660
5661 var ok bool
5662 var msg *Msg
5663
5664 // If something is available right away, let's optimize that case.
5665 select {
5666 case msg, ok = <-mch:
5667 if !ok {
5668 return nil, s.getNextMsgErr()
5669 }
5670 if err := s.processNextMsgDelivered(msg); err != nil {
5671 return nil, err
5672 } else {
5673 return msg, nil
5674 }
5675 default:
5676 }
5677
5678 if s.errCh != nil {
5679 select {
5680 case msg, ok = <-mch:
5681 if !ok {
5682 return nil, s.getNextMsgErr()
5683 }
5684 if err := s.processNextMsgDelivered(msg); err != nil {
5685 return nil, err
5686 }
5687 case err := <-s.errCh:
5688 return nil, err
5689 }
5690 } else {
5691 msg, ok = <-mch
5692 if !ok {
5693 return nil, s.getNextMsgErr()
5694 }
5695 if err := s.processNextMsgDelivered(msg); err != nil {
5696 return nil, err
5697 }
5698 }
5699
5700 return msg, nil
5701 }
5702
5703 // validateNextMsgState checks whether the subscription is in a valid
5704 // state to call NextMsg and be delivered another message synchronously.
5705 // This should be called while holding the lock.
5706 func (s *Subscription) validateNextMsgState(pullSubInternal bool) error {
5707 if s.connClosed {
5708 return ErrConnectionClosed
5709 }
5710 if s.mch == nil {
5711 if s.max > 0 && s.delivered >= s.max {
5712 return ErrMaxMessages
5713 } else if s.closed {
5714 return ErrBadSubscription
5715 }
5716 }
5717 if s.mcb != nil {
5718 return ErrSyncSubRequired
5719 }
5720 // if this subscription previously had a permissions error
5721 // and no reconnect has been attempted, return the permissions error
5722 // since the subscription does not exist on the server
5723 if s.conn.Opts.PermissionErrOnSubscribe && s.permissionsErr != nil {
5724 return s.permissionsErr
5725 }
5726 if s.sc {
5727 s.changeSubStatus(SubscriptionActive)
5728 s.sc = false
5729 return ErrSlowConsumer
5730 }
5731 // Unless this is from an internal call, reject use of this API.
5732 // Users should use Fetch() instead.
5733 if !pullSubInternal && s.jsi != nil && s.jsi.pull {
5734 return ErrTypeSubscription
5735 }
5736 return nil
5737 }
5738
5739 // This is called when the sync channel has been closed.
5740 // The error returned will be either connection or subscription
5741 // closed depending on what caused NextMsg() to fail.
5742 func (s *Subscription) getNextMsgErr() error {
5743 s.mu.Lock()
5744 defer s.mu.Unlock()
5745 if s.connClosed {
5746 return ErrConnectionClosed
5747 }
5748 return ErrBadSubscription
5749 }
5750
5751 // processNextMsgDelivered takes a message and applies the needed
5752 // accounting to the stats from the subscription, returning an
5753 // error in case we have the maximum number of messages have been
5754 // delivered already. It should not be called while holding the lock.
5755 func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
5756 s.mu.Lock()
5757 nc := s.conn
5758 max := s.max
5759
5760 var fcReply string
5761 // Update some stats.
5762 s.delivered++
5763 delivered := s.delivered
5764 if s.jsi != nil {
5765 fcReply = s.checkForFlowControlResponse()
5766 }
5767
5768 if s.typ == SyncSubscription {
5769 s.pMsgs--
5770 s.pBytes -= len(msg.Data)
5771 }
5772 if s.jsi != nil && s.jsi.resetPending {
5773 s.tryResetOrderedConsumer()
5774 }
5775 s.mu.Unlock()
5776
5777 if fcReply != _EMPTY_ {
5778 nc.Publish(fcReply, nil)
5779 }
5780
5781 if max > 0 {
5782 if delivered > max {
5783 return ErrMaxMessages
5784 }
5785 // Remove subscription if we have reached max.
5786 if delivered == max {
5787 nc.mu.Lock()
5788 nc.removeSub(s)
5789 nc.mu.Unlock()
5790 }
5791 }
5792 if len(msg.Data) == 0 && msg.Header.Get(statusHdr) == noResponders {
5793 return ErrNoResponders
5794 }
5795
5796 return nil
5797 }
5798
5799 // Queued returns the number of queued messages in the client for this subscription.
5800 //
5801 // Deprecated: Use Pending()
5802 func (s *Subscription) QueuedMsgs() (int, error) {
5803 m, _, err := s.Pending()
5804 return int(m), err
5805 }
5806
5807 // Pending returns the number of queued messages and queued bytes in the client for this subscription.
5808 func (s *Subscription) Pending() (int, int, error) {
5809 if s == nil {
5810 return -1, -1, ErrBadSubscription
5811 }
5812 s.mu.Lock()
5813 defer s.mu.Unlock()
5814 if s.conn == nil || s.closed {
5815 return -1, -1, ErrBadSubscription
5816 }
5817 if s.typ == ChanSubscription {
5818 return -1, -1, ErrTypeSubscription
5819 }
5820 return s.pMsgs, s.pBytes, nil
5821 }
5822
5823 // MaxPending returns the maximum number of queued messages and queued bytes seen so far.
5824 func (s *Subscription) MaxPending() (int, int, error) {
5825 if s == nil {
5826 return -1, -1, ErrBadSubscription
5827 }
5828 s.mu.Lock()
5829 defer s.mu.Unlock()
5830 if s.conn == nil || s.closed {
5831 return -1, -1, ErrBadSubscription
5832 }
5833 if s.typ == ChanSubscription {
5834 return -1, -1, ErrTypeSubscription
5835 }
5836 return s.pMsgsMax, s.pBytesMax, nil
5837 }
5838
5839 // ClearMaxPending resets the maximums seen so far.
5840 func (s *Subscription) ClearMaxPending() error {
5841 if s == nil {
5842 return ErrBadSubscription
5843 }
5844 s.mu.Lock()
5845 defer s.mu.Unlock()
5846 if s.conn == nil || s.closed {
5847 return ErrBadSubscription
5848 }
5849 if s.typ == ChanSubscription {
5850 return ErrTypeSubscription
5851 }
5852 s.pMsgsMax, s.pBytesMax = 0, 0
5853 return nil
5854 }
5855
5856 // Pending Limits
5857 const (
5858 // DefaultSubPendingMsgsLimit will be 500k msgs.
5859 DefaultSubPendingMsgsLimit = 500_000
5860 // DefaultSubPendingBytesLimit is 64MB
5861 DefaultSubPendingBytesLimit = 64 * 1024 * 1024
5862 )
5863
5864 // PendingLimits returns the current limits for this subscription.
5865 // If no error is returned, a negative value indicates that the
5866 // given metric is not limited.
5867 func (s *Subscription) PendingLimits() (int, int, error) {
5868 if s == nil {
5869 return -1, -1, ErrBadSubscription
5870 }
5871 s.mu.Lock()
5872 defer s.mu.Unlock()
5873 if s.conn == nil || s.closed {
5874 return -1, -1, ErrBadSubscription
5875 }
5876 if s.typ == ChanSubscription {
5877 return -1, -1, ErrTypeSubscription
5878 }
5879 return s.pMsgsLimit, s.pBytesLimit, nil
5880 }
5881
5882 // SetPendingLimits sets the limits for pending msgs and bytes for this subscription.
5883 // Zero is not allowed. Any negative value means that the given metric is not limited.
5884 func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error {
5885 if s == nil {
5886 return ErrBadSubscription
5887 }
5888 s.mu.Lock()
5889 defer s.mu.Unlock()
5890 if s.conn == nil || s.closed {
5891 return ErrBadSubscription
5892 }
5893 if s.typ == ChanSubscription {
5894 return ErrTypeSubscription
5895 }
5896 if msgLimit == 0 || bytesLimit == 0 {
5897 return ErrInvalidArg
5898 }
5899 s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit
5900 return nil
5901 }
5902
5903 // Delivered returns the number of delivered messages for this subscription.
5904 func (s *Subscription) Delivered() (int64, error) {
5905 if s == nil {
5906 return -1, ErrBadSubscription
5907 }
5908 s.mu.Lock()
5909 defer s.mu.Unlock()
5910 if s.conn == nil || s.closed {
5911 return -1, ErrBadSubscription
5912 }
5913 return int64(s.delivered), nil
5914 }
5915
5916 // Dropped returns the number of known dropped messages for this subscription.
5917 // This will correspond to messages dropped by violations of PendingLimits. If
5918 // the server declares the connection a SlowConsumer, this number may not be
5919 // valid.
5920 func (s *Subscription) Dropped() (int, error) {
5921 if s == nil {
5922 return -1, ErrBadSubscription
5923 }
5924 s.mu.Lock()
5925 defer s.mu.Unlock()
5926 if s.conn == nil || s.closed {
5927 return -1, ErrBadSubscription
5928 }
5929 return s.dropped, nil
5930 }
5931
5932 // Respond allows a convenient way to respond to requests in service based subscriptions.
5933 func (m *Msg) Respond(data []byte) error {
5934 if m == nil || m.Sub == nil {
5935 return ErrMsgNotBound
5936 }
5937 if m.Reply == "" {
5938 return ErrMsgNoReply
5939 }
5940 m.Sub.mu.Lock()
5941 nc := m.Sub.conn
5942 m.Sub.mu.Unlock()
5943 // No need to check the connection here since the call to publish will do all the checking.
5944 return nc.Publish(m.Reply, data)
5945 }
5946
5947 // RespondMsg allows a convenient way to respond to requests in service based subscriptions that might include headers
5948 func (m *Msg) RespondMsg(msg *Msg) error {
5949 if m == nil || m.Sub == nil {
5950 return ErrMsgNotBound
5951 }
5952 if m.Reply == "" {
5953 return ErrMsgNoReply
5954 }
5955 msg.Subject = m.Reply
5956 m.Sub.mu.Lock()
5957 nc := m.Sub.conn
5958 m.Sub.mu.Unlock()
5959 // No need to check the connection here since the call to publish will do all the checking.
5960 return nc.PublishMsg(msg)
5961 }
5962
5963 // FIXME: This is a hack
5964 // removeFlushEntry is needed when we need to discard queued up responses
5965 // for our pings as part of a flush call. This happens when we have a flush
5966 // call outstanding and we call close.
5967 func (nc *Conn) removeFlushEntry(ch chan struct{}) bool {
5968 nc.mu.Lock()
5969 defer nc.mu.Unlock()
5970 if nc.pongs == nil {
5971 return false
5972 }
5973 for i, c := range nc.pongs {
5974 if c == ch {
5975 nc.pongs[i] = nil
5976 return true
5977 }
5978 }
5979 return false
5980 }
5981
5982 // The lock must be held entering this function.
5983 func (nc *Conn) sendPing(ch chan struct{}) {
5984 nc.pongs = append(nc.pongs, ch)
5985 nc.bw.appendString(pingProto)
5986 // Flush in place.
5987 nc.bw.flush()
5988 }
5989
5990 // This will fire periodically and send a client origin
5991 // ping to the server. Will also check that we have received
5992 // responses from the server.
5993 func (nc *Conn) processPingTimer() {
5994 nc.mu.Lock()
5995
5996 if nc.status != CONNECTED {
5997 nc.mu.Unlock()
5998 return
5999 }
6000
6001 // Check for violation
6002 nc.pout++
6003 if nc.pout > nc.Opts.MaxPingsOut {
6004 nc.mu.Unlock()
6005 if shouldClose := nc.processOpErr(ErrStaleConnection, false); shouldClose {
6006 nc.close(CLOSED, true, nil)
6007 }
6008 return
6009 }
6010
6011 nc.sendPing(nil)
6012 nc.ptmr.Reset(nc.Opts.PingInterval)
6013 nc.mu.Unlock()
6014 }
6015
6016 // FlushTimeout allows a Flush operation to have an associated timeout.
6017 func (nc *Conn) FlushTimeout(timeout time.Duration) (err error) {
6018 if nc == nil {
6019 return ErrInvalidConnection
6020 }
6021 if timeout <= 0 {
6022 return ErrBadTimeout
6023 }
6024
6025 nc.mu.Lock()
6026 if nc.isClosed() {
6027 nc.mu.Unlock()
6028 return ErrConnectionClosed
6029 }
6030 t := globalTimerPool.Get(timeout)
6031 defer globalTimerPool.Put(t)
6032
6033 // Create a buffered channel to prevent chan send to block
6034 // in processPong() if this code here times out just when
6035 // PONG was received.
6036 ch := make(chan struct{}, 1)
6037 nc.sendPing(ch)
6038 nc.mu.Unlock()
6039
6040 select {
6041 case _, ok := <-ch:
6042 if !ok {
6043 err = ErrConnectionClosed
6044 } else {
6045 close(ch)
6046 }
6047 case <-t.C:
6048 err = ErrTimeout
6049 }
6050
6051 if err != nil {
6052 nc.removeFlushEntry(ch)
6053 }
6054 return
6055 }
6056
6057 // RTT calculates the round trip time between this client and the server.
6058 func (nc *Conn) RTT() (time.Duration, error) {
6059 if nc.IsClosed() {
6060 return 0, ErrConnectionClosed
6061 }
6062 if nc.IsReconnecting() {
6063 return 0, ErrDisconnected
6064 }
6065 start := time.Now()
6066 if err := nc.FlushTimeout(10 * time.Second); err != nil {
6067 return 0, err
6068 }
6069 return time.Since(start), nil
6070 }
6071
6072 // Flush will perform a round trip to the server and return when it
6073 // receives the internal reply.
6074 func (nc *Conn) Flush() error {
6075 return nc.FlushTimeout(10 * time.Second)
6076 }
6077
6078 // Buffered will return the number of bytes buffered to be sent to the server.
6079 // FIXME(dlc) take into account disconnected state.
6080 func (nc *Conn) Buffered() (int, error) {
6081 nc.mu.RLock()
6082 defer nc.mu.RUnlock()
6083 if nc.isClosed() || nc.bw == nil {
6084 return -1, ErrConnectionClosed
6085 }
6086 return nc.bw.buffered(), nil
6087 }
6088
6089 // resendSubscriptions will send our subscription state back to the
6090 // server. Used in reconnects
6091 func (nc *Conn) resendSubscriptions() {
6092 // Since we are going to send protocols to the server, we don't want to
6093 // be holding the subsMu lock (which is used in processMsg). So copy
6094 // the subscriptions in a temporary map, keyed by sid as nc.subs is.
6095 nc.subsMu.RLock()
6096 subs := maps.Clone(nc.subs)
6097 nc.subsMu.RUnlock()
6098 for sid, s := range subs {
6099 adjustedMax := uint64(0)
6100 s.mu.Lock()
6101 // when resending subscriptions, the permissions error should be cleared
6102 // since the user may have fixed the permissions issue
6103 s.permissionsErr = nil
6104 if s.max > 0 {
6105 if s.delivered < s.max {
6106 adjustedMax = s.max - s.delivered
6107 }
6108 // adjustedMax could be 0 here if the number of delivered msgs
6109 // reached the max, if so unsubscribe.
6110 if adjustedMax == 0 {
6111 s.mu.Unlock()
6112 nc.bw.writeDirect(fmt.Sprintf(unsubProto, sid, _EMPTY_))
6113 continue
6114 }
6115 }
6116 subj, queue := s.Subject, s.Queue
6117 s.mu.Unlock()
6118
6119 nc.bw.writeDirect(fmt.Sprintf(subProto, subj, queue, sid))
6120 if adjustedMax > 0 {
6121 maxStr := strconv.Itoa(int(adjustedMax))
6122 nc.bw.writeDirect(fmt.Sprintf(unsubProto, sid, maxStr))
6123 }
6124 }
6125 }
6126
6127 // This will clear any pending flush calls and release pending calls.
6128 // Lock is assumed to be held by the caller.
6129 func (nc *Conn) clearPendingFlushCalls() {
6130 // Clear any queued pongs, e.g. pending flush calls.
6131 for _, ch := range nc.pongs {
6132 if ch != nil {
6133 close(ch)
6134 }
6135 }
6136 nc.pongs = nil
6137 }
6138
6139 // This will clear any pending Request calls.
6140 // Lock is assumed to be held by the caller.
6141 func (nc *Conn) clearPendingRequestCalls() {
6142 for key, ch := range nc.respMap {
6143 if ch != nil {
6144 close(ch)
6145 delete(nc.respMap, key)
6146 }
6147 }
6148 }
6149
6150 // Low level close call that will do correct cleanup and set
6151 // desired status. Also controls whether user defined callbacks
6152 // will be triggered. The lock should not be held entering this
6153 // function. This function will handle the locking manually.
6154 func (nc *Conn) close(status Status, doCBs bool, err error) {
6155 nc.mu.Lock()
6156 if nc.isClosed() {
6157 nc.status = status
6158 nc.mu.Unlock()
6159 return
6160 }
6161 nc.status = CLOSED
6162
6163 // Kick the Go routines so they fall out.
6164 nc.kickFlusher()
6165
6166 // If the reconnect timer is waiting between a reconnect attempt,
6167 // this will kick it out.
6168 if nc.rqch != nil {
6169 close(nc.rqch)
6170 nc.rqch = nil
6171 }
6172
6173 // Clear any queued pongs, e.g. pending flush calls.
6174 nc.clearPendingFlushCalls()
6175
6176 // Clear any queued and blocking Requests.
6177 nc.clearPendingRequestCalls()
6178
6179 // Stop ping timer if set.
6180 nc.stopPingTimer()
6181 nc.ptmr = nil
6182
6183 // Need to close and set TCP conn to nil if reconnect loop has stopped,
6184 // otherwise we would incorrectly invoke Disconnect handler (if set)
6185 // down below.
6186 if nc.ar && nc.conn != nil {
6187 nc.conn.Close()
6188 nc.conn = nil
6189 } else if nc.conn != nil {
6190 // Go ahead and make sure we have flushed the outbound
6191 nc.bw.flush()
6192 defer nc.conn.Close()
6193 }
6194
6195 // Close sync subscriber channels and release any
6196 // pending NextMsg() calls.
6197 nc.subsMu.Lock()
6198 for _, s := range nc.subs {
6199 s.mu.Lock()
6200
6201 // Release callers on NextMsg for SyncSubscription only
6202 if s.mch != nil && s.typ == SyncSubscription {
6203 close(s.mch)
6204 }
6205 s.mch = nil
6206
6207 // Call closed handler for non-AsyncSubscription types (AsyncSubscription handlers
6208 // are called by waitForMsgs when it exits)
6209 var done func(string)
6210 if s.typ != AsyncSubscription && s.pDone != nil {
6211 done = s.pDone
6212 }
6213
6214 // Mark as invalid, for signaling to waitForMsgs
6215 s.closed = true
6216 // Mark connection closed in subscription
6217 s.connClosed = true
6218 // If we have an async subscription, signals it to exit
6219 if s.typ == AsyncSubscription && s.pCond != nil {
6220 s.pCond.Signal()
6221 }
6222
6223 s.mu.Unlock()
6224
6225 // Call the closed handler outside the lock to avoid potential deadlocks
6226 if done != nil {
6227 done(s.Subject)
6228 }
6229 }
6230 nc.subs = nil
6231 nc.subsMu.Unlock()
6232
6233 nc.changeConnStatus(status)
6234
6235 // Perform appropriate callback if needed for a disconnect.
6236 if doCBs {
6237 if nc.conn != nil {
6238 if disconnectedErrCB := nc.Opts.DisconnectedErrCB; disconnectedErrCB != nil {
6239 nc.ach.push(func() { disconnectedErrCB(nc, err) })
6240 } else if disconnectedCB := nc.Opts.DisconnectedCB; disconnectedCB != nil {
6241 nc.ach.push(func() { disconnectedCB(nc) })
6242 }
6243 }
6244 if closedCB := nc.Opts.ClosedCB; closedCB != nil {
6245 nc.ach.push(func() { closedCB(nc) })
6246 }
6247 }
6248 // If this is terminal, then we have to notify the asyncCB handler that
6249 // it can exit once all async callbacks have been dispatched.
6250 if status == CLOSED {
6251 nc.ach.close()
6252 }
6253 nc.mu.Unlock()
6254 }
6255
6256 // Close will close the connection to the server. This call will release
6257 // all blocking calls, such as Flush() and NextMsg()
6258 func (nc *Conn) Close() {
6259 if nc != nil {
6260 // This will be a no-op if the connection was not websocket.
6261 // We do this here as opposed to inside close() because we want
6262 // to do this only for the final user-driven close of the client.
6263 // Otherwise, we would need to change close() to pass a boolean
6264 // indicating that this is the case.
6265 nc.wsClose()
6266 nc.close(CLOSED, !nc.Opts.NoCallbacksAfterClientClose, nil)
6267 }
6268 }
6269
6270 // IsClosed tests if a Conn has been closed.
6271 func (nc *Conn) IsClosed() bool {
6272 nc.mu.RLock()
6273 defer nc.mu.RUnlock()
6274 return nc.isClosed()
6275 }
6276
6277 // IsReconnecting tests if a Conn is reconnecting.
6278 func (nc *Conn) IsReconnecting() bool {
6279 nc.mu.RLock()
6280 defer nc.mu.RUnlock()
6281 return nc.isReconnecting()
6282 }
6283
6284 // IsConnected tests if a Conn is connected.
6285 func (nc *Conn) IsConnected() bool {
6286 nc.mu.RLock()
6287 defer nc.mu.RUnlock()
6288 return nc.isConnected()
6289 }
6290
6291 // drainConnection will run in a separate Go routine and will
6292 // flush all publishes and drain all active subscriptions.
6293 func (nc *Conn) drainConnection() {
6294 // Snapshot subs list.
6295 nc.mu.Lock()
6296
6297 // Check again here if we are in a state to not process.
6298 if nc.isClosed() {
6299 nc.mu.Unlock()
6300 return
6301 }
6302 if nc.isConnecting() || nc.isReconnecting() {
6303 nc.mu.Unlock()
6304 // Move to closed state.
6305 nc.Close()
6306 return
6307 }
6308
6309 nc.subsMu.RLock()
6310 subs := make([]*Subscription, 0, len(nc.subs))
6311 for _, s := range nc.subs {
6312 if s == nc.respMux {
6313 // Skip since might be in use while messages
6314 // are being processed (can miss responses).
6315 continue
6316 }
6317 subs = append(subs, s)
6318 }
6319 nc.subsMu.RUnlock()
6320 errCB := nc.Opts.AsyncErrorCB
6321 drainWait := nc.Opts.DrainTimeout
6322 respMux := nc.respMux
6323 nc.mu.Unlock()
6324
6325 // for pushing errors with context.
6326 pushErr := func(err error) {
6327 nc.mu.Lock()
6328 nc.err = err
6329 if errCB != nil {
6330 nc.ach.push(func() { errCB(nc, nil, err) })
6331 }
6332 nc.mu.Unlock()
6333 }
6334
6335 // Do subs first, skip request handler if present.
6336 for _, s := range subs {
6337 if err := s.Drain(); err != nil {
6338 // We will notify about these but continue.
6339 pushErr(err)
6340 }
6341 }
6342
6343 // Wait for the subscriptions to drop to zero.
6344 timeout := time.Now().Add(drainWait)
6345 var min int
6346 if respMux != nil {
6347 min = 1
6348 } else {
6349 min = 0
6350 }
6351 for time.Now().Before(timeout) {
6352 if nc.NumSubscriptions() == min {
6353 break
6354 }
6355 time.Sleep(10 * time.Millisecond)
6356 }
6357
6358 // In case there was a request/response handler
6359 // then need to call drain at the end.
6360 if respMux != nil {
6361 if err := respMux.Drain(); err != nil {
6362 // We will notify about these but continue.
6363 pushErr(err)
6364 }
6365 for time.Now().Before(timeout) {
6366 if nc.NumSubscriptions() == 0 {
6367 break
6368 }
6369 time.Sleep(10 * time.Millisecond)
6370 }
6371 }
6372
6373 // Check if we timed out.
6374 if nc.NumSubscriptions() != 0 {
6375 pushErr(ErrDrainTimeout)
6376 }
6377
6378 // Flip State
6379 nc.mu.Lock()
6380 nc.changeConnStatus(DRAINING_PUBS)
6381 nc.mu.Unlock()
6382
6383 // Do publish drain via Flush() call.
6384 err := nc.FlushTimeout(5 * time.Second)
6385 if err != nil {
6386 pushErr(err)
6387 }
6388
6389 // Move to closed state.
6390 nc.Close()
6391 }
6392
6393 // Drain will put a connection into a drain state. All subscriptions will
6394 // immediately be put into a drain state. Upon completion, the publishers
6395 // will be drained and can not publish any additional messages. Upon draining
6396 // of the publishers, the connection will be closed. Use the ClosedCB
6397 // option to know when the connection has moved from draining to closed.
6398 //
6399 // See note in Subscription.Drain for JetStream subscriptions.
6400 func (nc *Conn) Drain() error {
6401 nc.mu.Lock()
6402 if nc.isClosed() {
6403 nc.mu.Unlock()
6404 return ErrConnectionClosed
6405 }
6406 if nc.isConnecting() || nc.isReconnecting() {
6407 nc.mu.Unlock()
6408 nc.Close()
6409 return ErrConnectionReconnecting
6410 }
6411 if nc.isDraining() {
6412 nc.mu.Unlock()
6413 return nil
6414 }
6415 nc.changeConnStatus(DRAINING_SUBS)
6416 go nc.drainConnection()
6417 nc.mu.Unlock()
6418
6419 return nil
6420 }
6421
6422 // IsDraining tests if a Conn is in the draining state.
6423 func (nc *Conn) IsDraining() bool {
6424 nc.mu.RLock()
6425 defer nc.mu.RUnlock()
6426 return nc.isDraining()
6427 }
6428
6429 // caller must lock
6430 func (nc *Conn) getServers(implicitOnly bool) []string {
6431 poolSize := len(nc.srvPool)
6432 servers := make([]string, 0)
6433 for i := 0; i < poolSize; i++ {
6434 if implicitOnly && !nc.srvPool[i].isImplicit {
6435 continue
6436 }
6437 url := nc.srvPool[i].URL
6438 servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
6439 }
6440 return servers
6441 }
6442
6443 // Servers returns the list of known server urls, including additional
6444 // servers discovered after a connection has been established. If
6445 // authentication is enabled, use UserInfo or Token when connecting with
6446 // these urls.
6447 func (nc *Conn) Servers() []string {
6448 nc.mu.RLock()
6449 defer nc.mu.RUnlock()
6450 return nc.getServers(false)
6451 }
6452
6453 // DiscoveredServers returns only the server urls that have been discovered
6454 // after a connection has been established. If authentication is enabled,
6455 // use UserInfo or Token when connecting with these urls.
6456 func (nc *Conn) DiscoveredServers() []string {
6457 nc.mu.RLock()
6458 defer nc.mu.RUnlock()
6459 return nc.getServers(true)
6460 }
6461
6462 // Status returns the current state of the connection.
6463 func (nc *Conn) Status() Status {
6464 nc.mu.RLock()
6465 defer nc.mu.RUnlock()
6466 return nc.status
6467 }
6468
6469 // Test if Conn has been closed Lock is assumed held.
6470 func (nc *Conn) isClosed() bool {
6471 return nc.status == CLOSED
6472 }
6473
6474 // Test if Conn is in the process of connecting
6475 func (nc *Conn) isConnecting() bool {
6476 return nc.status == CONNECTING
6477 }
6478
6479 // Test if Conn is being reconnected.
6480 func (nc *Conn) isReconnecting() bool {
6481 return nc.status == RECONNECTING
6482 }
6483
6484 // Test if Conn is connected or connecting.
6485 func (nc *Conn) isConnected() bool {
6486 return nc.status == CONNECTED || nc.isDraining()
6487 }
6488
6489 // Test if Conn is in the draining state.
6490 func (nc *Conn) isDraining() bool {
6491 return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
6492 }
6493
6494 // Test if Conn is in the draining state for pubs.
6495 func (nc *Conn) isDrainingPubs() bool {
6496 return nc.status == DRAINING_PUBS
6497 }
6498
6499 // Stats will return a race safe copy of the Statistics section for the connection.
6500 func (nc *Conn) Stats() Statistics {
6501 // Stats are updated either under connection's mu or with atomic operations
6502 // for inbound stats in processMsg().
6503 nc.mu.Lock()
6504 stats := Statistics{
6505 InMsgs: atomic.LoadUint64(&nc.InMsgs),
6506 InBytes: atomic.LoadUint64(&nc.InBytes),
6507 OutMsgs: nc.OutMsgs,
6508 OutBytes: nc.OutBytes,
6509 Reconnects: nc.Reconnects,
6510 }
6511 nc.mu.Unlock()
6512 return stats
6513 }
6514
6515 // MaxPayload returns the size limit that a message payload can have.
6516 // This is set by the server configuration and delivered to the client
6517 // upon connect.
6518 func (nc *Conn) MaxPayload() int64 {
6519 nc.mu.RLock()
6520 defer nc.mu.RUnlock()
6521 return nc.info.MaxPayload
6522 }
6523
6524 // HeadersSupported will return if the server supports headers
6525 func (nc *Conn) HeadersSupported() bool {
6526 nc.mu.RLock()
6527 defer nc.mu.RUnlock()
6528 return nc.info.Headers
6529 }
6530
6531 // AuthRequired will return if the connected server requires authorization.
6532 func (nc *Conn) AuthRequired() bool {
6533 nc.mu.RLock()
6534 defer nc.mu.RUnlock()
6535 return nc.info.AuthRequired
6536 }
6537
6538 // TLSRequired will return if the connected server requires TLS connections.
6539 func (nc *Conn) TLSRequired() bool {
6540 nc.mu.RLock()
6541 defer nc.mu.RUnlock()
6542 return nc.info.TLSRequired
6543 }
6544
6545 // Barrier schedules the given function `f` to all registered asynchronous
6546 // subscriptions.
6547 // Only the last subscription to see this barrier will invoke the function.
6548 // If no subscription is registered at the time of this call, `f()` is invoked
6549 // right away.
6550 // ErrConnectionClosed is returned if the connection is closed prior to
6551 // the call.
6552 func (nc *Conn) Barrier(f func()) error {
6553 nc.mu.Lock()
6554 if nc.isClosed() {
6555 nc.mu.Unlock()
6556 return ErrConnectionClosed
6557 }
6558 nc.subsMu.Lock()
6559 // Need to figure out how many non chan subscriptions there are
6560 numSubs := 0
6561 for _, sub := range nc.subs {
6562 if sub.typ == AsyncSubscription {
6563 numSubs++
6564 }
6565 }
6566 if numSubs == 0 {
6567 nc.subsMu.Unlock()
6568 nc.mu.Unlock()
6569 f()
6570 return nil
6571 }
6572 barrier := &barrierInfo{refs: int64(numSubs), f: f}
6573 for _, sub := range nc.subs {
6574 sub.mu.Lock()
6575 if sub.mch == nil {
6576 msg := &Msg{barrier: barrier}
6577 // Push onto the async pList
6578 if sub.pTail != nil {
6579 sub.pTail.next = msg
6580 } else {
6581 sub.pHead = msg
6582 sub.pCond.Signal()
6583 }
6584 sub.pTail = msg
6585 }
6586 sub.mu.Unlock()
6587 }
6588 nc.subsMu.Unlock()
6589 nc.mu.Unlock()
6590 return nil
6591 }
6592
6593 // ServerPool returns a copy of the current server pool for the connection.
6594 //
6595 // This function should not be called from within connection callbacks to avoid
6596 // potential deadlocks.
6597 func (nc *Conn) ServerPool() []Server {
6598 nc.mu.RLock()
6599 defer nc.mu.RUnlock()
6600 servers := make([]Server, len(nc.srvPool))
6601 for i, srv := range nc.srvPool {
6602 if srv != nil {
6603 // Return a copy to avoid exposing internal state
6604 servers[i] = srv.clone()
6605 }
6606 }
6607 return servers
6608 }
6609
6610 // SetServerPool allows updating the server pool for the connection. This
6611 // replaces the existing pool with the provided list of server URLs. If the
6612 // current server is not in the new pool, the client will switch to a server in
6613 // the new pool on the next reconnect attempt. This function is thread-safe and
6614 // can be called while the connection is active. It will return an error if the
6615 // connection is closed or if any of the provided URLs are invalid.
6616 //
6617 // This function does not trigger an immediate reconnect. The new server
6618 // pool will be used on the next reconnect attempt.
6619 // If you want to trigger an immediate reconnect to apply the new server pool,
6620 // you can call [Conn.ForceReconnect] after this function.
6621 //
6622 // Unless [IgnoreDiscoveredServers] is used true, the client will continue to
6623 // discover and add new servers to the pool as it receives INFO messages from
6624 // the server. If you want to prevent this behavior and only use the servers
6625 // provided in SetServerPool, use [IgnoreDiscoveredServers].
6626 //
6627 // This function should not be called from within connection callbacks to avoid
6628 // potential deadlocks.
6629 func (nc *Conn) SetServerPool(servers []string) error {
6630 nc.mu.Lock()
6631 defer nc.mu.Unlock()
6632 if nc.isClosed() {
6633 return ErrConnectionClosed
6634 }
6635
6636 // Parse and validate all URLs first (without modifying state)
6637 newPool := make([]*Server, 0, len(servers))
6638 newURLs := make(map[string]struct{})
6639
6640 for _, addr := range servers {
6641 s, err := nc.parseServerURL(addr, false, false)
6642 if err != nil {
6643 return err
6644 }
6645 if isWebsocketScheme(s.URL) != nc.ws {
6646 return ErrMixingWebsocketSchemes
6647 }
6648
6649 newPool = append(newPool, s)
6650 newURLs[s.URL.Host] = struct{}{}
6651 }
6652
6653 // Preserve state from existing pool entries
6654 for _, newSrv := range newPool {
6655 if idx := slices.IndexFunc(nc.srvPool, func(oldSrv *Server) bool {
6656 return oldSrv != nil && oldSrv.URL.String() == newSrv.URL.String()
6657 }); idx != -1 {
6658 newSrv.Reconnects = nc.srvPool[idx].Reconnects
6659 newSrv.didConnect = nc.srvPool[idx].didConnect
6660 newSrv.lastErr = nc.srvPool[idx].lastErr
6661 }
6662 }
6663
6664 nc.srvPool = newPool
6665 nc.urls = newURLs
6666
6667 // Update nc.current to point to the corresponding server in the new pool
6668 // This is important because currentServer() uses pointer equality
6669 if nc.current != nil {
6670 currentURL := nc.current.URL.String()
6671 found := false
6672 for _, s := range newPool {
6673 if s.URL.String() == currentURL {
6674 // Update nc.current to point to the server instance in the new pool
6675 nc.current = s
6676 found = true
6677 break
6678 }
6679 }
6680 if !found && len(newPool) > 0 {
6681 // Current server not in new pool - point to first server in new pool
6682 // This ensures selectNextServer() can find it and properly rotate
6683 nc.current = newPool[0]
6684 }
6685 }
6686
6687 return nil
6688 }
6689
6690 // GetClientIP returns the client IP as known by the server.
6691 // Supported as of server version 2.1.6.
6692 func (nc *Conn) GetClientIP() (net.IP, error) {
6693 nc.mu.RLock()
6694 defer nc.mu.RUnlock()
6695 if nc.isClosed() {
6696 return nil, ErrConnectionClosed
6697 }
6698 if nc.info.ClientIP == "" {
6699 return nil, ErrClientIPNotSupported
6700 }
6701 ip := net.ParseIP(nc.info.ClientIP)
6702 return ip, nil
6703 }
6704
6705 // GetClientID returns the client ID assigned by the server to which
6706 // the client is currently connected to. Note that the value may change if
6707 // the client reconnects.
6708 // This function returns ErrClientIDNotSupported if the server is of a
6709 // version prior to 1.2.0.
6710 func (nc *Conn) GetClientID() (uint64, error) {
6711 nc.mu.RLock()
6712 defer nc.mu.RUnlock()
6713 if nc.isClosed() {
6714 return 0, ErrConnectionClosed
6715 }
6716 if nc.info.CID == 0 {
6717 return 0, ErrClientIDNotSupported
6718 }
6719 return nc.info.CID, nil
6720 }
6721
6722 // StatusChanged returns a channel on which given list of connection status changes will be reported.
6723 // If no statuses are provided, defaults will be used: CONNECTED, RECONNECTING, DISCONNECTED, CLOSED.
6724 func (nc *Conn) StatusChanged(statuses ...Status) chan Status {
6725 if len(statuses) == 0 {
6726 statuses = []Status{CONNECTED, RECONNECTING, DISCONNECTED, CLOSED}
6727 }
6728 ch := make(chan Status, 10)
6729 nc.mu.Lock()
6730 defer nc.mu.Unlock()
6731 for _, s := range statuses {
6732 nc.registerStatusChangeListener(s, ch)
6733 }
6734 return ch
6735 }
6736
6737 // RemoveStatusListener removes a status change listener.
6738 // If the channel is not closed, it will be closed.
6739 // Listeners will be removed automatically on status change
6740 // as well, but this is a way to remove them manually.
6741 func (nc *Conn) RemoveStatusListener(ch chan (Status)) {
6742 nc.mu.Lock()
6743 defer nc.mu.Unlock()
6744
6745 select {
6746 case <-ch:
6747 default:
6748 close(ch)
6749 }
6750
6751 for _, listeners := range nc.statListeners {
6752 for range listeners {
6753 delete(listeners, ch)
6754 }
6755 }
6756 }
6757
6758 // registerStatusChangeListener registers a channel waiting for a specific status change event.
6759 // Status change events are non-blocking - if no receiver is waiting for the status change,
6760 // it will not be sent on the channel. Closed channels are ignored.
6761 // The lock should be held entering.
6762 func (nc *Conn) registerStatusChangeListener(status Status, ch chan Status) {
6763 if nc.statListeners == nil {
6764 nc.statListeners = make(map[Status]map[chan Status]struct{})
6765 }
6766 if _, ok := nc.statListeners[status]; !ok {
6767 nc.statListeners[status] = make(map[chan Status]struct{})
6768 }
6769 nc.statListeners[status][ch] = struct{}{}
6770 }
6771
6772 // sendStatusEvent sends connection status event to all channels.
6773 // If channel is closed, or there is no listener, sendStatusEvent
6774 // will not block. Lock should be held entering.
6775 func (nc *Conn) sendStatusEvent(s Status) {
6776 Loop:
6777 for ch := range nc.statListeners[s] {
6778 // make sure channel is not closed
6779 select {
6780 case <-ch:
6781 // if chan is closed, remove it
6782 delete(nc.statListeners[s], ch)
6783 continue Loop
6784 default:
6785 }
6786 // only send event if someone's listening
6787 select {
6788 case ch <- s:
6789 default:
6790 }
6791 }
6792 }
6793
6794 // changeConnStatus changes connections status and sends events
6795 // to all listeners. Lock should be held entering.
6796 func (nc *Conn) changeConnStatus(status Status) {
6797 if nc == nil {
6798 return
6799 }
6800 nc.sendStatusEvent(status)
6801 nc.status = status
6802 }
6803
6804 // NkeyOptionFromSeed will load an nkey pair from a seed file.
6805 // It will return the NKey Option and will handle
6806 // signing of nonce challenges from the server. It will take
6807 // care to not hold keys in memory and to wipe memory.
6808 func NkeyOptionFromSeed(seedFile string) (Option, error) {
6809 kp, err := nkeyPairFromSeedFile(seedFile)
6810 if err != nil {
6811 return nil, err
6812 }
6813 // Wipe our key on exit.
6814 defer kp.Wipe()
6815
6816 pub, err := kp.PublicKey()
6817 if err != nil {
6818 return nil, err
6819 }
6820 if !nkeys.IsValidPublicUserKey(pub) {
6821 return nil, errors.New("nats: Not a valid nkey user seed")
6822 }
6823 sigCB := func(nonce []byte) ([]byte, error) {
6824 return sigHandler(nonce, seedFile)
6825 }
6826 return Nkey(string(pub), sigCB), nil
6827 }
6828
6829 // Just wipe slice with 'x', for clearing contents of creds or nkey seed file.
6830 func wipeSlice(buf []byte) {
6831 for i := range buf {
6832 buf[i] = 'x'
6833 }
6834 }
6835
6836 func userFromFile(userFile string) (string, error) {
6837 path, err := expandPath(userFile)
6838 if err != nil {
6839 return _EMPTY_, fmt.Errorf("nats: %w", err)
6840 }
6841
6842 contents, err := os.ReadFile(path)
6843 if err != nil {
6844 return _EMPTY_, fmt.Errorf("nats: %w", err)
6845 }
6846 defer wipeSlice(contents)
6847 return nkeys.ParseDecoratedJWT(contents)
6848 }
6849
6850 func homeDir() (string, error) {
6851 if runtime.GOOS == "windows" {
6852 homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
6853 userProfile := os.Getenv("USERPROFILE")
6854
6855 var home string
6856 if homeDrive == "" || homePath == "" {
6857 if userProfile == "" {
6858 return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%")
6859 }
6860 home = userProfile
6861 } else {
6862 home = filepath.Join(homeDrive, homePath)
6863 }
6864
6865 return home, nil
6866 }
6867
6868 home := os.Getenv("HOME")
6869 if home == "" {
6870 return _EMPTY_, errors.New("nats: failed to get home dir, require $HOME")
6871 }
6872 return home, nil
6873 }
6874
6875 func expandPath(p string) (string, error) {
6876 p = os.ExpandEnv(p)
6877
6878 if !strings.HasPrefix(p, "~") {
6879 return p, nil
6880 }
6881
6882 home, err := homeDir()
6883 if err != nil {
6884 return _EMPTY_, err
6885 }
6886
6887 return filepath.Join(home, p[1:]), nil
6888 }
6889
6890 func nkeyPairFromSeedFile(seedFile string) (nkeys.KeyPair, error) {
6891 contents, err := os.ReadFile(seedFile)
6892 if err != nil {
6893 return nil, fmt.Errorf("nats: %w", err)
6894 }
6895 defer wipeSlice(contents)
6896 return nkeys.ParseDecoratedNKey(contents)
6897 }
6898
6899 // Sign authentication challenges from the server.
6900 // Do not keep private seed in memory.
6901 func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
6902 kp, err := nkeyPairFromSeedFile(seedFile)
6903 if err != nil {
6904 return nil, fmt.Errorf("unable to extract key pair from file %q: %w", seedFile, err)
6905 }
6906 // Wipe our key on exit.
6907 defer kp.Wipe()
6908
6909 sig, _ := kp.Sign(nonce)
6910 return sig, nil
6911 }
6912
6913 type timeoutWriter struct {
6914 timeout time.Duration
6915 conn net.Conn
6916 }
6917
6918 // Write implements the io.Writer interface.
6919 func (tw *timeoutWriter) Write(p []byte) (int, error) {
6920 tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout))
6921 n, err := tw.conn.Write(p)
6922 tw.conn.SetWriteDeadline(time.Time{})
6923 return n, err
6924 }