| 1 |
// Copyright 2022-2025 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 |
package jetstream |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"encoding/json" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"math" |
| 22 |
"slices" |
| 23 |
"sync" |
| 24 |
"sync/atomic" |
| 25 |
"time" |
| 26 |
|
| 27 |
"github.com/nats-io/nats.go" |
| 28 |
"github.com/nats-io/nats.go/internal/syncx" |
| 29 |
"github.com/nats-io/nuid" |
| 30 |
) |
| 31 |
|
| 32 |
type ( |
| 33 |
// MessagesContext supports iterating over a messages on a stream. |
| 34 |
// It is returned by [Consumer.Messages] method. |
| 35 |
MessagesContext interface { |
| 36 |
// Next retrieves next message on a stream. If MessagesContext is closed |
| 37 |
// (either stopped or drained), Next will return ErrMsgIteratorClosed |
| 38 |
// error. An optional timeout or context can be provided using NextOpt |
| 39 |
// options. If none are provided, Next will block indefinitely until a |
| 40 |
// message is available, iterator is closed or a heartbeat error occurs. |
| 41 |
Next(opts ...NextOpt) (Msg, error) |
| 42 |
|
| 43 |
// Stop unsubscribes from the stream and cancels subscription. Calling |
| 44 |
// Next after calling Stop will return ErrMsgIteratorClosed error. |
| 45 |
// All messages that are already in the buffer are discarded. |
| 46 |
Stop() |
| 47 |
|
| 48 |
// Drain unsubscribes from the stream and cancels subscription. All |
| 49 |
// messages that are already in the buffer will be available on |
| 50 |
// subsequent calls to Next. After the buffer is drained, Next will |
| 51 |
// return ErrMsgIteratorClosed error. |
| 52 |
Drain() |
| 53 |
} |
| 54 |
|
| 55 |
// ConsumeContext supports processing incoming messages from a stream. |
| 56 |
// It is returned by [Consumer.Consume] method. |
| 57 |
ConsumeContext interface { |
| 58 |
// Stop unsubscribes from the stream and cancels subscription. |
| 59 |
// No more messages will be received after calling this method. |
| 60 |
// All messages that are already in the buffer are discarded. |
| 61 |
Stop() |
| 62 |
|
| 63 |
// Drain unsubscribes from the stream and cancels subscription. |
| 64 |
// All messages that are already in the buffer will be processed in callback function. |
| 65 |
Drain() |
| 66 |
|
| 67 |
// Closed returns a channel that is closed when the consuming is |
| 68 |
// fully stopped/drained. When the channel is closed, no more messages |
| 69 |
// will be received and processing is complete. |
| 70 |
Closed() <-chan struct{} |
| 71 |
} |
| 72 |
|
| 73 |
// MessageHandler is a handler function used as callback in [Consume]. |
| 74 |
MessageHandler func(msg Msg) |
| 75 |
|
| 76 |
// PullConsumeOpt represent additional options used in [Consume] for pull consumers. |
| 77 |
PullConsumeOpt interface { |
| 78 |
configureConsume(*consumeOpts) error |
| 79 |
} |
| 80 |
|
| 81 |
// PullMessagesOpt represent additional options used in [Messages] for pull consumers. |
| 82 |
PullMessagesOpt interface { |
| 83 |
configureMessages(*consumeOpts) error |
| 84 |
} |
| 85 |
|
| 86 |
pullConsumer struct { |
| 87 |
sync.Mutex |
| 88 |
js *jetStream |
| 89 |
stream string |
| 90 |
durable bool |
| 91 |
name string |
| 92 |
info *ConsumerInfo |
| 93 |
subs syncx.Map[string, *pullSubscription] |
| 94 |
pinID string |
| 95 |
} |
| 96 |
|
| 97 |
pullRequest struct { |
| 98 |
Expires time.Duration `json:"expires,omitempty"` |
| 99 |
Batch int `json:"batch,omitempty"` |
| 100 |
MaxBytes int `json:"max_bytes,omitempty"` |
| 101 |
NoWait bool `json:"no_wait,omitempty"` |
| 102 |
Heartbeat time.Duration `json:"idle_heartbeat,omitempty"` |
| 103 |
MinPending int64 `json:"min_pending,omitempty"` |
| 104 |
MinAckPending int64 `json:"min_ack_pending,omitempty"` |
| 105 |
PinID string `json:"id,omitempty"` |
| 106 |
Group string `json:"group,omitempty"` |
| 107 |
Priority uint8 `json:"priority,omitempty"` |
| 108 |
ctx context.Context `json:"-"` |
| 109 |
maxWaitSet bool `json:"-"` |
| 110 |
} |
| 111 |
|
| 112 |
consumeOpts struct { |
| 113 |
Expires time.Duration |
| 114 |
MaxMessages int |
| 115 |
MaxBytes int |
| 116 |
LimitSize bool |
| 117 |
MinPending int64 |
| 118 |
MinAckPending int64 |
| 119 |
Priority uint8 |
| 120 |
Group string |
| 121 |
Heartbeat time.Duration |
| 122 |
ErrHandler ConsumeErrHandler |
| 123 |
ReportMissingHeartbeats bool |
| 124 |
ThresholdMessages int |
| 125 |
ThresholdBytes int |
| 126 |
StopAfter int |
| 127 |
stopAfterMsgsLeft chan int |
| 128 |
notifyOnReconnect bool |
| 129 |
} |
| 130 |
|
| 131 |
ConsumeErrHandlerFunc func(consumeCtx ConsumeContext, err error) |
| 132 |
|
| 133 |
pullSubscription struct { |
| 134 |
sync.Mutex |
| 135 |
id string |
| 136 |
consumer *pullConsumer |
| 137 |
subscription *nats.Subscription |
| 138 |
msgs chan *nats.Msg |
| 139 |
msgsClosed atomic.Uint32 |
| 140 |
errs chan error |
| 141 |
pending pendingMsgs |
| 142 |
hbMonitor *hbMonitor |
| 143 |
fetchInProgress atomic.Uint32 |
| 144 |
closed atomic.Uint32 |
| 145 |
draining atomic.Uint32 |
| 146 |
done chan struct{} |
| 147 |
connStatusChanged chan nats.Status |
| 148 |
fetchNext chan *pullRequest |
| 149 |
consumeOpts *consumeOpts |
| 150 |
delivered int |
| 151 |
closedCh chan struct{} |
| 152 |
} |
| 153 |
|
| 154 |
pendingMsgs struct { |
| 155 |
msgCount int |
| 156 |
byteCount int |
| 157 |
} |
| 158 |
|
| 159 |
MessageBatch interface { |
| 160 |
Messages() <-chan Msg |
| 161 |
Error() error |
| 162 |
} |
| 163 |
|
| 164 |
fetchResult struct { |
| 165 |
sync.Mutex |
| 166 |
msgs chan Msg |
| 167 |
err error |
| 168 |
done bool |
| 169 |
sseq uint64 |
| 170 |
} |
| 171 |
|
| 172 |
FetchOpt func(*pullRequest) error |
| 173 |
|
| 174 |
hbMonitor struct { |
| 175 |
timer *time.Timer |
| 176 |
sync.Mutex |
| 177 |
} |
| 178 |
|
| 179 |
// NextOpt is an option for configuring the behavior of MessagesContext.Next. |
| 180 |
NextOpt interface { |
| 181 |
configureNext(*nextOpts) |
| 182 |
} |
| 183 |
|
| 184 |
nextOpts struct { |
| 185 |
timeout time.Duration |
| 186 |
ctx context.Context |
| 187 |
} |
| 188 |
) |
| 189 |
|
| 190 |
const ( |
| 191 |
DefaultMaxMessages = 500 |
| 192 |
DefaultExpires = 30 * time.Second |
| 193 |
defaultBatchMaxBytesOnly = 1_000_000 |
| 194 |
unset = -1 |
| 195 |
) |
| 196 |
|
| 197 |
// Consume can be used to continuously receive messages and handle them |
| 198 |
// with the provided callback function. Consume cannot be used concurrently |
| 199 |
// when using ordered consumer. |
| 200 |
// |
| 201 |
// See [Consumer.Consume] for more details. |
| 202 |
func (p *pullConsumer) Consume(handler MessageHandler, opts ...PullConsumeOpt) (ConsumeContext, error) { |
| 203 |
if handler == nil { |
| 204 |
return nil, ErrHandlerRequired |
| 205 |
} |
| 206 |
consumeOpts, err := parseConsumeOpts(false, opts...) |
| 207 |
if err != nil { |
| 208 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, err) |
| 209 |
} |
| 210 |
|
| 211 |
if len(p.info.Config.PriorityGroups) != 0 { |
| 212 |
if consumeOpts.Group == "" { |
| 213 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, "priority group is required for priority consumer") |
| 214 |
} |
| 215 |
|
| 216 |
if !slices.Contains(p.info.Config.PriorityGroups, consumeOpts.Group) { |
| 217 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, "invalid priority group") |
| 218 |
} |
| 219 |
} else if consumeOpts.Group != "" { |
| 220 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, "priority group is not supported for this consumer") |
| 221 |
} |
| 222 |
|
| 223 |
p.Lock() |
| 224 |
|
| 225 |
subject := p.js.apiSubject(fmt.Sprintf(apiRequestNextT, p.stream, p.name)) |
| 226 |
|
| 227 |
consumeID := nuid.Next() |
| 228 |
sub := &pullSubscription{ |
| 229 |
id: consumeID, |
| 230 |
consumer: p, |
| 231 |
errs: make(chan error, 10), |
| 232 |
done: make(chan struct{}, 1), |
| 233 |
fetchNext: make(chan *pullRequest, 1), |
| 234 |
consumeOpts: consumeOpts, |
| 235 |
} |
| 236 |
sub.connStatusChanged = p.js.conn.StatusChanged(nats.CONNECTED, nats.RECONNECTING, nats.CLOSED) |
| 237 |
|
| 238 |
sub.hbMonitor = sub.scheduleHeartbeatCheck(consumeOpts.Heartbeat) |
| 239 |
|
| 240 |
p.subs.Store(sub.id, sub) |
| 241 |
p.Unlock() |
| 242 |
|
| 243 |
internalHandler := func(msg *nats.Msg) { |
| 244 |
if sub.hbMonitor != nil { |
| 245 |
sub.hbMonitor.Stop() |
| 246 |
} |
| 247 |
userMsg, msgErr := checkMsg(msg) |
| 248 |
if !userMsg && msgErr == nil { |
| 249 |
if sub.hbMonitor != nil { |
| 250 |
sub.hbMonitor.Reset(2 * consumeOpts.Heartbeat) |
| 251 |
} |
| 252 |
return |
| 253 |
} |
| 254 |
if !userMsg { |
| 255 |
// heartbeat message |
| 256 |
if msgErr == nil { |
| 257 |
return |
| 258 |
} |
| 259 |
|
| 260 |
sub.Lock() |
| 261 |
termErr, notifyErr := sub.handleStatusMsg(msg, msgErr) |
| 262 |
if termErr == nil { |
| 263 |
sub.checkPending() |
| 264 |
if sub.hbMonitor != nil { |
| 265 |
sub.hbMonitor.Reset(2 * consumeOpts.Heartbeat) |
| 266 |
} |
| 267 |
} |
| 268 |
sub.Unlock() |
| 269 |
|
| 270 |
if sub.consumeOpts.ErrHandler != nil && notifyErr != nil { |
| 271 |
sub.consumeOpts.ErrHandler(sub, notifyErr) |
| 272 |
} |
| 273 |
if termErr != nil { |
| 274 |
if sub.closed.Load() == 1 { |
| 275 |
return |
| 276 |
} |
| 277 |
if sub.consumeOpts.ErrHandler != nil { |
| 278 |
sub.consumeOpts.ErrHandler(sub, termErr) |
| 279 |
} |
| 280 |
sub.Stop() |
| 281 |
} |
| 282 |
return |
| 283 |
} |
| 284 |
if pinId := msg.Header.Get("Nats-Pin-Id"); pinId != "" { |
| 285 |
p.setPinID(pinId) |
| 286 |
} |
| 287 |
handler(p.js.toJSMsg(msg)) |
| 288 |
sub.Lock() |
| 289 |
sub.decrementPendingMsgs(msg) |
| 290 |
sub.incrementDeliveredMsgs() |
| 291 |
sub.checkPending() |
| 292 |
if sub.hbMonitor != nil { |
| 293 |
sub.hbMonitor.Reset(2 * consumeOpts.Heartbeat) |
| 294 |
} |
| 295 |
sub.Unlock() |
| 296 |
|
| 297 |
if sub.consumeOpts.StopAfter > 0 && sub.consumeOpts.StopAfter == sub.delivered { |
| 298 |
sub.Stop() |
| 299 |
} |
| 300 |
} |
| 301 |
inbox := p.js.conn.NewInbox() |
| 302 |
sub.subscription, err = p.js.conn.Subscribe(inbox, internalHandler) |
| 303 |
if err != nil { |
| 304 |
return nil, err |
| 305 |
} |
| 306 |
sub.subscription.SetClosedHandler(func(sid string) func(string) { |
| 307 |
return func(subject string) { |
| 308 |
p.subs.Delete(sid) |
| 309 |
sub.draining.CompareAndSwap(1, 0) |
| 310 |
sub.Lock() |
| 311 |
if sub.closedCh != nil { |
| 312 |
close(sub.closedCh) |
| 313 |
sub.closedCh = nil |
| 314 |
} |
| 315 |
sub.Unlock() |
| 316 |
} |
| 317 |
}(sub.id)) |
| 318 |
|
| 319 |
sub.Lock() |
| 320 |
// initial pull |
| 321 |
sub.resetPendingMsgs() |
| 322 |
batchSize := sub.consumeOpts.MaxMessages |
| 323 |
if sub.consumeOpts.StopAfter > 0 { |
| 324 |
batchSize = min(batchSize, sub.consumeOpts.StopAfter-sub.delivered) |
| 325 |
} |
| 326 |
if err := sub.pull(&pullRequest{ |
| 327 |
Expires: consumeOpts.Expires, |
| 328 |
Batch: batchSize, |
| 329 |
MaxBytes: consumeOpts.MaxBytes, |
| 330 |
Heartbeat: consumeOpts.Heartbeat, |
| 331 |
MinPending: consumeOpts.MinPending, |
| 332 |
MinAckPending: consumeOpts.MinAckPending, |
| 333 |
Priority: consumeOpts.Priority, |
| 334 |
Group: consumeOpts.Group, |
| 335 |
PinID: p.getPinID(), |
| 336 |
}, subject); err != nil { |
| 337 |
sub.errs <- err |
| 338 |
} |
| 339 |
sub.Unlock() |
| 340 |
|
| 341 |
go func() { |
| 342 |
isConnected := true |
| 343 |
for { |
| 344 |
if sub.closed.Load() == 1 { |
| 345 |
return |
| 346 |
} |
| 347 |
select { |
| 348 |
case status, ok := <-sub.connStatusChanged: |
| 349 |
if !ok { |
| 350 |
continue |
| 351 |
} |
| 352 |
switch status { |
| 353 |
case nats.RECONNECTING: |
| 354 |
if sub.hbMonitor != nil { |
| 355 |
sub.hbMonitor.Stop() |
| 356 |
} |
| 357 |
isConnected = false |
| 358 |
case nats.CONNECTED: |
| 359 |
sub.Lock() |
| 360 |
if !isConnected { |
| 361 |
isConnected = true |
| 362 |
if sub.consumeOpts.notifyOnReconnect { |
| 363 |
sub.errs <- errConnected |
| 364 |
} |
| 365 |
|
| 366 |
sub.fetchNext <- &pullRequest{ |
| 367 |
Expires: sub.consumeOpts.Expires, |
| 368 |
Batch: sub.consumeOpts.MaxMessages, |
| 369 |
MaxBytes: sub.consumeOpts.MaxBytes, |
| 370 |
Heartbeat: sub.consumeOpts.Heartbeat, |
| 371 |
MinPending: sub.consumeOpts.MinPending, |
| 372 |
MinAckPending: sub.consumeOpts.MinAckPending, |
| 373 |
Priority: sub.consumeOpts.Priority, |
| 374 |
Group: sub.consumeOpts.Group, |
| 375 |
PinID: p.getPinID(), |
| 376 |
} |
| 377 |
if sub.hbMonitor != nil { |
| 378 |
sub.hbMonitor.Reset(2 * sub.consumeOpts.Heartbeat) |
| 379 |
} |
| 380 |
sub.resetPendingMsgs() |
| 381 |
} |
| 382 |
sub.Unlock() |
| 383 |
|
| 384 |
case nats.CLOSED: |
| 385 |
sub.errs <- ErrConnectionClosed |
| 386 |
} |
| 387 |
case err := <-sub.errs: |
| 388 |
sub.Lock() |
| 389 |
if errors.Is(err, ErrNoHeartbeat) { |
| 390 |
batchSize := sub.consumeOpts.MaxMessages |
| 391 |
if sub.consumeOpts.StopAfter > 0 { |
| 392 |
batchSize = min(batchSize, sub.consumeOpts.StopAfter-sub.delivered) |
| 393 |
} |
| 394 |
sub.fetchNext <- &pullRequest{ |
| 395 |
Expires: sub.consumeOpts.Expires, |
| 396 |
Batch: batchSize, |
| 397 |
MaxBytes: sub.consumeOpts.MaxBytes, |
| 398 |
Heartbeat: sub.consumeOpts.Heartbeat, |
| 399 |
MinPending: sub.consumeOpts.MinPending, |
| 400 |
MinAckPending: sub.consumeOpts.MinAckPending, |
| 401 |
Priority: sub.consumeOpts.Priority, |
| 402 |
Group: sub.consumeOpts.Group, |
| 403 |
PinID: p.getPinID(), |
| 404 |
} |
| 405 |
if sub.hbMonitor != nil { |
| 406 |
sub.hbMonitor.Reset(2 * sub.consumeOpts.Heartbeat) |
| 407 |
} |
| 408 |
sub.resetPendingMsgs() |
| 409 |
} |
| 410 |
sub.Unlock() |
| 411 |
if sub.consumeOpts.ErrHandler != nil { |
| 412 |
sub.consumeOpts.ErrHandler(sub, err) |
| 413 |
} |
| 414 |
if errors.Is(err, ErrConnectionClosed) { |
| 415 |
sub.Stop() |
| 416 |
} |
| 417 |
case <-sub.done: |
| 418 |
return |
| 419 |
} |
| 420 |
} |
| 421 |
}() |
| 422 |
|
| 423 |
go sub.pullMessages(subject) |
| 424 |
|
| 425 |
return sub, nil |
| 426 |
} |
| 427 |
|
| 428 |
// resetPendingMsgs resets pending message count and byte count |
| 429 |
// to the values set in consumeOpts |
| 430 |
// lock should be held before calling this method |
| 431 |
func (s *pullSubscription) resetPendingMsgs() { |
| 432 |
s.pending.msgCount = s.consumeOpts.MaxMessages |
| 433 |
s.pending.byteCount = s.consumeOpts.MaxBytes |
| 434 |
} |
| 435 |
|
| 436 |
// decrementPendingMsgs decrements pending message count and byte count |
| 437 |
// lock should be held before calling this method |
| 438 |
func (s *pullSubscription) decrementPendingMsgs(msg *nats.Msg) { |
| 439 |
s.pending.msgCount-- |
| 440 |
if s.consumeOpts.MaxBytes != 0 && !s.consumeOpts.LimitSize { |
| 441 |
s.pending.byteCount -= msg.Size() |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
// incrementDeliveredMsgs increments delivered message count |
| 446 |
// lock should be held before calling this method |
| 447 |
func (s *pullSubscription) incrementDeliveredMsgs() { |
| 448 |
s.delivered++ |
| 449 |
} |
| 450 |
|
| 451 |
// checkPending verifies whether there are enough messages in |
| 452 |
// the buffer to trigger a new pull request. |
| 453 |
// lock should be held before calling this method |
| 454 |
func (s *pullSubscription) checkPending() { |
| 455 |
// check if we went below any threshold |
| 456 |
// we don't want to track bytes threshold if either it's not set or we used |
| 457 |
// PullMaxMessagesWithBytesLimit |
| 458 |
if (s.pending.msgCount < s.consumeOpts.ThresholdMessages || |
| 459 |
(s.pending.byteCount < s.consumeOpts.ThresholdBytes && s.consumeOpts.MaxBytes != 0 && !s.consumeOpts.LimitSize)) && |
| 460 |
s.fetchInProgress.Load() == 0 { |
| 461 |
|
| 462 |
var batchSize, maxBytes int |
| 463 |
batchSize = s.consumeOpts.MaxMessages - s.pending.msgCount |
| 464 |
if s.consumeOpts.MaxBytes != 0 { |
| 465 |
if s.consumeOpts.LimitSize { |
| 466 |
maxBytes = s.consumeOpts.MaxBytes |
| 467 |
} else { |
| 468 |
maxBytes = s.consumeOpts.MaxBytes - s.pending.byteCount |
| 469 |
// when working with max bytes only, always ask for full batch |
| 470 |
batchSize = s.consumeOpts.MaxMessages |
| 471 |
} |
| 472 |
} |
| 473 |
if s.consumeOpts.StopAfter > 0 { |
| 474 |
batchSize = min(batchSize, s.consumeOpts.StopAfter-s.delivered-s.pending.msgCount) |
| 475 |
} |
| 476 |
if batchSize > 0 { |
| 477 |
pinID := "" |
| 478 |
if s.consumer != nil { |
| 479 |
pinID = s.consumer.getPinID() |
| 480 |
} |
| 481 |
s.fetchNext <- &pullRequest{ |
| 482 |
Expires: s.consumeOpts.Expires, |
| 483 |
Batch: batchSize, |
| 484 |
MaxBytes: maxBytes, |
| 485 |
Heartbeat: s.consumeOpts.Heartbeat, |
| 486 |
PinID: pinID, |
| 487 |
Group: s.consumeOpts.Group, |
| 488 |
MinPending: s.consumeOpts.MinPending, |
| 489 |
MinAckPending: s.consumeOpts.MinAckPending, |
| 490 |
Priority: s.consumeOpts.Priority, |
| 491 |
} |
| 492 |
|
| 493 |
s.pending.msgCount = s.consumeOpts.MaxMessages |
| 494 |
s.pending.byteCount = s.consumeOpts.MaxBytes |
| 495 |
} |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
// Messages returns MessagesContext, allowing continuously iterating |
| 500 |
// over messages on a stream. Messages cannot be used concurrently |
| 501 |
// when using ordered consumer. |
| 502 |
// |
| 503 |
// See [Consumer.Messages] for more details. |
| 504 |
func (p *pullConsumer) Messages(opts ...PullMessagesOpt) (MessagesContext, error) { |
| 505 |
consumeOpts, err := parseMessagesOpts(false, opts...) |
| 506 |
if err != nil { |
| 507 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, err) |
| 508 |
} |
| 509 |
|
| 510 |
if len(p.info.Config.PriorityGroups) != 0 { |
| 511 |
if consumeOpts.Group == "" { |
| 512 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, "priority group is required for priority consumer") |
| 513 |
} |
| 514 |
|
| 515 |
if !slices.Contains(p.info.Config.PriorityGroups, consumeOpts.Group) { |
| 516 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, "invalid priority group") |
| 517 |
} |
| 518 |
} else if consumeOpts.Group != "" { |
| 519 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, "priority group is not supported for this consumer") |
| 520 |
} |
| 521 |
|
| 522 |
p.Lock() |
| 523 |
subject := p.js.apiSubject(fmt.Sprintf(apiRequestNextT, p.stream, p.name)) |
| 524 |
|
| 525 |
msgs := make(chan *nats.Msg, consumeOpts.MaxMessages) |
| 526 |
|
| 527 |
consumeID := nuid.Next() |
| 528 |
sub := &pullSubscription{ |
| 529 |
id: consumeID, |
| 530 |
consumer: p, |
| 531 |
done: make(chan struct{}, 1), |
| 532 |
msgs: msgs, |
| 533 |
errs: make(chan error, 10), |
| 534 |
fetchNext: make(chan *pullRequest, 1), |
| 535 |
consumeOpts: consumeOpts, |
| 536 |
} |
| 537 |
sub.connStatusChanged = p.js.conn.StatusChanged(nats.CONNECTED, nats.RECONNECTING) |
| 538 |
inbox := p.js.conn.NewInbox() |
| 539 |
sub.subscription, err = p.js.conn.ChanSubscribe(inbox, sub.msgs) |
| 540 |
if err != nil { |
| 541 |
p.Unlock() |
| 542 |
return nil, err |
| 543 |
} |
| 544 |
sub.subscription.SetClosedHandler(func(sid string) func(string) { |
| 545 |
return func(subject string) { |
| 546 |
if sub.draining.Load() != 1 { |
| 547 |
// if we're not draining, subscription can be closed as soon |
| 548 |
// as closed handler is called |
| 549 |
// otherwise, we need to wait until all messages are drained |
| 550 |
// in Next |
| 551 |
p.subs.Delete(sid) |
| 552 |
} |
| 553 |
sub.closeMsgs() |
| 554 |
} |
| 555 |
}(sub.id)) |
| 556 |
|
| 557 |
p.subs.Store(sub.id, sub) |
| 558 |
p.Unlock() |
| 559 |
|
| 560 |
go sub.pullMessages(subject) |
| 561 |
|
| 562 |
go func() { |
| 563 |
// Connection state is tracked here, for the lifetime of the |
| 564 |
// iterator, rather than inside Next: a reconnect that completes |
| 565 |
// between two Next calls (for example when Next is driven with a |
| 566 |
// short NextMaxWait) must still reset the pull request accounting, |
| 567 |
// otherwise no new pull request is ever sent and the iterator goes |
| 568 |
// silent on a healthy connection. |
| 569 |
isConnected := true |
| 570 |
for { |
| 571 |
select { |
| 572 |
case status, ok := <-sub.connStatusChanged: |
| 573 |
if !ok { |
| 574 |
return |
| 575 |
} |
| 576 |
switch status { |
| 577 |
case nats.RECONNECTING: |
| 578 |
isConnected = false |
| 579 |
select { |
| 580 |
case sub.errs <- errDisconnected: |
| 581 |
case <-sub.done: |
| 582 |
return |
| 583 |
} |
| 584 |
case nats.CONNECTED: |
| 585 |
if isConnected { |
| 586 |
continue |
| 587 |
} |
| 588 |
isConnected = true |
| 589 |
select { |
| 590 |
case sub.errs <- errConnected: |
| 591 |
case <-sub.done: |
| 592 |
return |
| 593 |
} |
| 594 |
} |
| 595 |
case <-sub.done: |
| 596 |
return |
| 597 |
} |
| 598 |
} |
| 599 |
}() |
| 600 |
|
| 601 |
return sub, nil |
| 602 |
} |
| 603 |
|
| 604 |
var ( |
| 605 |
errConnected = errors.New("connected") |
| 606 |
errDisconnected = errors.New("disconnected") |
| 607 |
) |
| 608 |
|
| 609 |
// Next retrieves next message on a stream. If MessagesContext is closed |
| 610 |
// (either stopped or drained), Next will return ErrMsgIteratorClosed |
| 611 |
// error. An optional timeout or context can be provided using NextOpt |
| 612 |
// options. If none are provided, Next will block indefinitely until a |
| 613 |
// message is available, iterator is closed or a heartbeat error occurs. |
| 614 |
func (s *pullSubscription) Next(opts ...NextOpt) (Msg, error) { |
| 615 |
var nextOpts nextOpts |
| 616 |
for _, opt := range opts { |
| 617 |
opt.configureNext(&nextOpts) |
| 618 |
} |
| 619 |
|
| 620 |
if nextOpts.timeout > 0 && nextOpts.ctx != nil { |
| 621 |
return nil, fmt.Errorf("%w: cannot specify both NextMaxWait and NextContext", ErrInvalidOption) |
| 622 |
} |
| 623 |
|
| 624 |
// Create timeout channel if needed |
| 625 |
var timeoutCh <-chan time.Time |
| 626 |
if nextOpts.timeout > 0 { |
| 627 |
timer := time.NewTimer(nextOpts.timeout) |
| 628 |
defer timer.Stop() |
| 629 |
timeoutCh = timer.C |
| 630 |
} |
| 631 |
|
| 632 |
// Use context if provided |
| 633 |
var ctxDone <-chan struct{} |
| 634 |
if nextOpts.ctx != nil { |
| 635 |
ctxDone = nextOpts.ctx.Done() |
| 636 |
} |
| 637 |
|
| 638 |
s.Lock() |
| 639 |
defer s.Unlock() |
| 640 |
drainMode := s.draining.Load() == 1 |
| 641 |
closed := s.closed.Load() == 1 |
| 642 |
if closed && !drainMode { |
| 643 |
// Check if iterator was closed due to connection closure |
| 644 |
if s.consumer.js.conn.IsClosed() { |
| 645 |
return nil, fmt.Errorf("%w: %w", ErrMsgIteratorClosed, ErrConnectionClosed) |
| 646 |
} |
| 647 |
return nil, ErrMsgIteratorClosed |
| 648 |
} |
| 649 |
hbMonitor := s.scheduleHeartbeatCheck(s.consumeOpts.Heartbeat) |
| 650 |
defer func() { |
| 651 |
if hbMonitor != nil { |
| 652 |
hbMonitor.Stop() |
| 653 |
} |
| 654 |
}() |
| 655 |
|
| 656 |
if s.consumeOpts.StopAfter > 0 && s.delivered >= s.consumeOpts.StopAfter { |
| 657 |
s.Stop() |
| 658 |
return nil, ErrMsgIteratorClosed |
| 659 |
} |
| 660 |
|
| 661 |
for { |
| 662 |
s.checkPending() |
| 663 |
select { |
| 664 |
case msg, ok := <-s.msgs: |
| 665 |
if !ok { |
| 666 |
// if msgs channel is closed, it means that subscription was either drained or stopped |
| 667 |
s.consumer.subs.Delete(s.id) |
| 668 |
s.draining.CompareAndSwap(1, 0) |
| 669 |
// Check if iterator was closed due to connection closure |
| 670 |
if s.consumer.js.conn.IsClosed() { |
| 671 |
return nil, fmt.Errorf("%w: %w", ErrMsgIteratorClosed, ErrConnectionClosed) |
| 672 |
} |
| 673 |
return nil, ErrMsgIteratorClosed |
| 674 |
} |
| 675 |
if hbMonitor != nil { |
| 676 |
hbMonitor.Reset(2 * s.consumeOpts.Heartbeat) |
| 677 |
} |
| 678 |
userMsg, msgErr := checkMsg(msg) |
| 679 |
if !userMsg { |
| 680 |
// heartbeat message |
| 681 |
if msgErr == nil { |
| 682 |
continue |
| 683 |
} |
| 684 |
if termErr, _ := s.handleStatusMsg(msg, msgErr); termErr != nil { |
| 685 |
s.Stop() |
| 686 |
return nil, termErr |
| 687 |
} |
| 688 |
continue |
| 689 |
} |
| 690 |
if pinId := msg.Header.Get("Nats-Pin-Id"); pinId != "" { |
| 691 |
s.consumer.setPinID(pinId) |
| 692 |
} |
| 693 |
s.decrementPendingMsgs(msg) |
| 694 |
s.incrementDeliveredMsgs() |
| 695 |
return s.consumer.js.toJSMsg(msg), nil |
| 696 |
case err := <-s.errs: |
| 697 |
if errors.Is(err, ErrNoHeartbeat) { |
| 698 |
s.pending.msgCount = 0 |
| 699 |
s.pending.byteCount = 0 |
| 700 |
if s.consumeOpts.ReportMissingHeartbeats { |
| 701 |
return nil, err |
| 702 |
} |
| 703 |
if hbMonitor != nil { |
| 704 |
hbMonitor.Reset(2 * s.consumeOpts.Heartbeat) |
| 705 |
} |
| 706 |
} |
| 707 |
if errors.Is(err, errConnected) { |
| 708 |
// errConnected is only sent for a CONNECTED that follows a |
| 709 |
// RECONNECTING, so this is always a real reconnect: the pull |
| 710 |
// request parked on the previous server is gone and a new one |
| 711 |
// has to be issued. |
| 712 |
if s.consumeOpts.notifyOnReconnect { |
| 713 |
return nil, errConnected |
| 714 |
} |
| 715 |
s.pending.msgCount = 0 |
| 716 |
s.pending.byteCount = 0 |
| 717 |
if hbMonitor != nil { |
| 718 |
hbMonitor.Reset(2 * s.consumeOpts.Heartbeat) |
| 719 |
} |
| 720 |
} |
| 721 |
if errors.Is(err, errDisconnected) { |
| 722 |
if hbMonitor != nil { |
| 723 |
hbMonitor.Stop() |
| 724 |
} |
| 725 |
} |
| 726 |
case <-timeoutCh: |
| 727 |
return nil, nats.ErrTimeout |
| 728 |
case <-ctxDone: |
| 729 |
return nil, nextOpts.ctx.Err() |
| 730 |
} |
| 731 |
} |
| 732 |
} |
| 733 |
|
| 734 |
// handleStatusMsg processes a status message from the server. |
| 735 |
// It returns a terminal error (caller should stop) and a non-terminal |
| 736 |
// error to notify the user about via ErrHandler. The caller should invoke |
| 737 |
// ErrHandler outside the lock to avoid deadlocks. |
| 738 |
func (s *pullSubscription) handleStatusMsg(msg *nats.Msg, msgErr error) (error, error) { |
| 739 |
if !errors.Is(msgErr, nats.ErrTimeout) && !errors.Is(msgErr, ErrMaxBytesExceeded) && !errors.Is(msgErr, ErrBatchCompleted) { |
| 740 |
if errors.Is(msgErr, ErrConsumerDeleted) || errors.Is(msgErr, ErrBadRequest) { |
| 741 |
return msgErr, nil |
| 742 |
} |
| 743 |
if errors.Is(msgErr, ErrPinIDMismatch) { |
| 744 |
s.consumer.setPinID("") |
| 745 |
s.pending.msgCount = 0 |
| 746 |
s.pending.byteCount = 0 |
| 747 |
} |
| 748 |
if errors.Is(msgErr, ErrConsumerLeadershipChanged) { |
| 749 |
s.pending.msgCount = 0 |
| 750 |
s.pending.byteCount = 0 |
| 751 |
} |
| 752 |
return nil, msgErr |
| 753 |
} |
| 754 |
msgsLeft, bytesLeft, err := parsePending(msg) |
| 755 |
if err != nil { |
| 756 |
return err, nil |
| 757 |
} |
| 758 |
s.pending.msgCount -= msgsLeft |
| 759 |
if s.pending.msgCount < 0 { |
| 760 |
s.pending.msgCount = 0 |
| 761 |
} |
| 762 |
if s.consumeOpts.MaxBytes > 0 && !s.consumeOpts.LimitSize { |
| 763 |
s.pending.byteCount -= bytesLeft |
| 764 |
if s.pending.byteCount < 0 { |
| 765 |
s.pending.byteCount = 0 |
| 766 |
} |
| 767 |
} |
| 768 |
return nil, nil |
| 769 |
} |
| 770 |
|
| 771 |
func (hb *hbMonitor) Stop() { |
| 772 |
hb.Lock() |
| 773 |
hb.timer.Stop() |
| 774 |
hb.Unlock() |
| 775 |
} |
| 776 |
|
| 777 |
func (hb *hbMonitor) Reset(dur time.Duration) { |
| 778 |
hb.Lock() |
| 779 |
hb.timer.Reset(dur) |
| 780 |
hb.Unlock() |
| 781 |
} |
| 782 |
|
| 783 |
// Stop unsubscribes from the stream and cancels subscription. Calling |
| 784 |
// Next after calling Stop will return ErrMsgIteratorClosed error. |
| 785 |
// All messages that are already in the buffer are discarded. |
| 786 |
func (s *pullSubscription) Stop() { |
| 787 |
if !s.closed.CompareAndSwap(0, 1) { |
| 788 |
return |
| 789 |
} |
| 790 |
close(s.done) |
| 791 |
if s.consumeOpts.stopAfterMsgsLeft != nil { |
| 792 |
if s.delivered >= s.consumeOpts.StopAfter { |
| 793 |
close(s.consumeOpts.stopAfterMsgsLeft) |
| 794 |
} else { |
| 795 |
s.consumeOpts.stopAfterMsgsLeft <- s.consumeOpts.StopAfter - s.delivered |
| 796 |
} |
| 797 |
} |
| 798 |
} |
| 799 |
|
| 800 |
// Drain unsubscribes from the stream and cancels subscription. All |
| 801 |
// messages that are already in the buffer will be available on |
| 802 |
// subsequent calls to Next. After the buffer is drained, Next will |
| 803 |
// return ErrMsgIteratorClosed error. |
| 804 |
func (s *pullSubscription) Drain() { |
| 805 |
if !s.closed.CompareAndSwap(0, 1) { |
| 806 |
return |
| 807 |
} |
| 808 |
s.draining.Store(1) |
| 809 |
close(s.done) |
| 810 |
if s.consumeOpts.stopAfterMsgsLeft != nil { |
| 811 |
if s.delivered >= s.consumeOpts.StopAfter { |
| 812 |
close(s.consumeOpts.stopAfterMsgsLeft) |
| 813 |
} else { |
| 814 |
s.consumeOpts.stopAfterMsgsLeft <- s.consumeOpts.StopAfter - s.delivered |
| 815 |
} |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
// Closed returns a channel that is closed when consuming is |
| 820 |
// fully stopped/drained. When the channel is closed, no more messages |
| 821 |
// will be received and processing is complete. |
| 822 |
func (s *pullSubscription) Closed() <-chan struct{} { |
| 823 |
s.Lock() |
| 824 |
defer s.Unlock() |
| 825 |
closedCh := s.closedCh |
| 826 |
if closedCh == nil { |
| 827 |
closedCh = make(chan struct{}) |
| 828 |
s.closedCh = closedCh |
| 829 |
} |
| 830 |
if !s.subscription.IsValid() { |
| 831 |
close(s.closedCh) |
| 832 |
s.closedCh = nil |
| 833 |
} |
| 834 |
return closedCh |
| 835 |
} |
| 836 |
|
| 837 |
// Fetch sends a single request to retrieve given number of messages. |
| 838 |
// It will wait up to provided expiry time if not all messages are available. |
| 839 |
func (p *pullConsumer) Fetch(batch int, opts ...FetchOpt) (MessageBatch, error) { |
| 840 |
req := &pullRequest{ |
| 841 |
Batch: batch, |
| 842 |
Expires: DefaultExpires, |
| 843 |
Heartbeat: unset, |
| 844 |
} |
| 845 |
for _, opt := range opts { |
| 846 |
if err := opt(req); err != nil { |
| 847 |
return nil, err |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
if req.ctx != nil && req.maxWaitSet { |
| 852 |
return nil, fmt.Errorf("%w: cannot specify both FetchContext and FetchMaxWait", ErrInvalidOption) |
| 853 |
} |
| 854 |
|
| 855 |
// if heartbeat was not explicitly set, set it to 5 seconds for longer pulls |
| 856 |
// and disable it for shorter pulls |
| 857 |
if req.Heartbeat == unset { |
| 858 |
if req.Expires >= 10*time.Second { |
| 859 |
req.Heartbeat = 5 * time.Second |
| 860 |
} else { |
| 861 |
req.Heartbeat = 0 |
| 862 |
} |
| 863 |
} |
| 864 |
if req.Expires < 2*req.Heartbeat { |
| 865 |
return nil, fmt.Errorf("%w: expiry time should be at least 2 times the heartbeat", ErrInvalidOption) |
| 866 |
} |
| 867 |
|
| 868 |
return p.fetch(req) |
| 869 |
} |
| 870 |
|
| 871 |
// FetchBytes is used to retrieve up to a provided bytes from the stream. |
| 872 |
func (p *pullConsumer) FetchBytes(maxBytes int, opts ...FetchOpt) (MessageBatch, error) { |
| 873 |
req := &pullRequest{ |
| 874 |
Batch: defaultBatchMaxBytesOnly, |
| 875 |
MaxBytes: maxBytes, |
| 876 |
Expires: DefaultExpires, |
| 877 |
Heartbeat: unset, |
| 878 |
} |
| 879 |
for _, opt := range opts { |
| 880 |
if err := opt(req); err != nil { |
| 881 |
return nil, err |
| 882 |
} |
| 883 |
} |
| 884 |
|
| 885 |
if req.ctx != nil && req.maxWaitSet { |
| 886 |
return nil, fmt.Errorf("%w: cannot specify both FetchContext and FetchMaxWait", ErrInvalidOption) |
| 887 |
} |
| 888 |
|
| 889 |
// if heartbeat was not explicitly set, set it to 5 seconds for longer pulls |
| 890 |
// and disable it for shorter pulls |
| 891 |
if req.Heartbeat == unset { |
| 892 |
if req.Expires >= 10*time.Second { |
| 893 |
req.Heartbeat = 5 * time.Second |
| 894 |
} else { |
| 895 |
req.Heartbeat = 0 |
| 896 |
} |
| 897 |
} |
| 898 |
if req.Expires < 2*req.Heartbeat { |
| 899 |
return nil, fmt.Errorf("%w: expiry time should be at least 2 times the heartbeat", ErrInvalidOption) |
| 900 |
} |
| 901 |
|
| 902 |
return p.fetch(req) |
| 903 |
} |
| 904 |
|
| 905 |
// FetchNoWait sends a single request to retrieve given number of messages. |
| 906 |
// FetchNoWait will only return messages that are available at the time of the |
| 907 |
// request. It will not wait for more messages to arrive. |
| 908 |
func (p *pullConsumer) FetchNoWait(batch int) (MessageBatch, error) { |
| 909 |
req := &pullRequest{ |
| 910 |
Batch: batch, |
| 911 |
NoWait: true, |
| 912 |
} |
| 913 |
|
| 914 |
return p.fetch(req) |
| 915 |
} |
| 916 |
|
| 917 |
func (p *pullConsumer) fetch(req *pullRequest) (MessageBatch, error) { |
| 918 |
res := &fetchResult{ |
| 919 |
msgs: make(chan Msg, req.Batch), |
| 920 |
} |
| 921 |
msgs := make(chan *nats.Msg, 2*req.Batch) |
| 922 |
subject := p.js.apiSubject(fmt.Sprintf(apiRequestNextT, p.stream, p.name)) |
| 923 |
|
| 924 |
sub := &pullSubscription{ |
| 925 |
consumer: p, |
| 926 |
done: make(chan struct{}, 1), |
| 927 |
msgs: msgs, |
| 928 |
errs: make(chan error, 10), |
| 929 |
} |
| 930 |
inbox := p.js.conn.NewInbox() |
| 931 |
var err error |
| 932 |
sub.subscription, err = p.js.conn.ChanSubscribe(inbox, sub.msgs) |
| 933 |
if err != nil { |
| 934 |
return nil, err |
| 935 |
} |
| 936 |
req.PinID = p.getPinID() |
| 937 |
if err := sub.pull(req, subject); err != nil { |
| 938 |
return nil, err |
| 939 |
} |
| 940 |
|
| 941 |
var receivedMsgs, receivedBytes int |
| 942 |
hbTimer := sub.scheduleHeartbeatCheck(req.Heartbeat) |
| 943 |
|
| 944 |
// Use context if provided |
| 945 |
var ctxDone <-chan struct{} |
| 946 |
if req.ctx != nil { |
| 947 |
ctxDone = req.ctx.Done() |
| 948 |
} |
| 949 |
|
| 950 |
go func(res *fetchResult) { |
| 951 |
defer sub.subscription.Unsubscribe() |
| 952 |
defer close(res.msgs) |
| 953 |
for { |
| 954 |
select { |
| 955 |
case msg := <-msgs: |
| 956 |
res.Lock() |
| 957 |
if hbTimer != nil { |
| 958 |
hbTimer.Reset(2 * req.Heartbeat) |
| 959 |
} |
| 960 |
userMsg, err := checkMsg(msg) |
| 961 |
if err != nil { |
| 962 |
errNotTimeoutOrNoMsgs := !errors.Is(err, nats.ErrTimeout) && !errors.Is(err, ErrNoMessages) |
| 963 |
if errNotTimeoutOrNoMsgs && !errors.Is(err, ErrMaxBytesExceeded) { |
| 964 |
res.err = err |
| 965 |
} |
| 966 |
if errors.Is(err, ErrPinIDMismatch) { |
| 967 |
p.setPinID("") |
| 968 |
} |
| 969 |
res.done = true |
| 970 |
res.Unlock() |
| 971 |
return |
| 972 |
} |
| 973 |
if !userMsg { |
| 974 |
res.Unlock() |
| 975 |
continue |
| 976 |
} |
| 977 |
if pinId := msg.Header.Get("Nats-Pin-Id"); pinId != "" { |
| 978 |
p.setPinID(pinId) |
| 979 |
} |
| 980 |
res.msgs <- p.js.toJSMsg(msg) |
| 981 |
meta, err := msg.Metadata() |
| 982 |
if err != nil { |
| 983 |
res.err = fmt.Errorf("parsing message metadata: %s", err) |
| 984 |
res.done = true |
| 985 |
res.Unlock() |
| 986 |
return |
| 987 |
} |
| 988 |
res.sseq = meta.Sequence.Stream |
| 989 |
receivedMsgs++ |
| 990 |
if req.MaxBytes != 0 { |
| 991 |
receivedBytes += msg.Size() |
| 992 |
} |
| 993 |
if receivedMsgs == req.Batch || (req.MaxBytes != 0 && receivedBytes >= req.MaxBytes) { |
| 994 |
res.done = true |
| 995 |
res.Unlock() |
| 996 |
return |
| 997 |
} |
| 998 |
res.Unlock() |
| 999 |
case err := <-sub.errs: |
| 1000 |
res.Lock() |
| 1001 |
res.err = err |
| 1002 |
res.done = true |
| 1003 |
res.Unlock() |
| 1004 |
return |
| 1005 |
case <-time.After(req.Expires + 1*time.Second): |
| 1006 |
res.Lock() |
| 1007 |
res.done = true |
| 1008 |
res.Unlock() |
| 1009 |
return |
| 1010 |
case <-ctxDone: |
| 1011 |
res.Lock() |
| 1012 |
res.err = req.ctx.Err() |
| 1013 |
res.done = true |
| 1014 |
res.Unlock() |
| 1015 |
return |
| 1016 |
} |
| 1017 |
} |
| 1018 |
}(res) |
| 1019 |
return res, nil |
| 1020 |
} |
| 1021 |
|
| 1022 |
func (fr *fetchResult) Messages() <-chan Msg { |
| 1023 |
fr.Lock() |
| 1024 |
defer fr.Unlock() |
| 1025 |
return fr.msgs |
| 1026 |
} |
| 1027 |
|
| 1028 |
func (fr *fetchResult) Error() error { |
| 1029 |
fr.Lock() |
| 1030 |
defer fr.Unlock() |
| 1031 |
return fr.err |
| 1032 |
} |
| 1033 |
|
| 1034 |
func (fr *fetchResult) closed() bool { |
| 1035 |
fr.Lock() |
| 1036 |
defer fr.Unlock() |
| 1037 |
return fr.done |
| 1038 |
} |
| 1039 |
|
| 1040 |
// Next is used to retrieve the next message from the stream. This |
| 1041 |
// method will block until the message is retrieved or timeout is |
| 1042 |
// reached. |
| 1043 |
func (p *pullConsumer) Next(opts ...FetchOpt) (Msg, error) { |
| 1044 |
res, err := p.Fetch(1, opts...) |
| 1045 |
if err != nil { |
| 1046 |
return nil, err |
| 1047 |
} |
| 1048 |
msg := <-res.Messages() |
| 1049 |
if msg != nil { |
| 1050 |
return msg, nil |
| 1051 |
} |
| 1052 |
if res.Error() == nil { |
| 1053 |
return nil, nats.ErrTimeout |
| 1054 |
} |
| 1055 |
return nil, res.Error() |
| 1056 |
} |
| 1057 |
|
| 1058 |
func (s *pullSubscription) pullMessages(subject string) { |
| 1059 |
for { |
| 1060 |
select { |
| 1061 |
case req := <-s.fetchNext: |
| 1062 |
s.fetchInProgress.Store(1) |
| 1063 |
|
| 1064 |
if err := s.pull(req, subject); err != nil { |
| 1065 |
if errors.Is(err, ErrMsgIteratorClosed) { |
| 1066 |
s.cleanup() |
| 1067 |
return |
| 1068 |
} |
| 1069 |
s.errs <- err |
| 1070 |
} |
| 1071 |
s.fetchInProgress.Store(0) |
| 1072 |
case <-s.done: |
| 1073 |
s.cleanup() |
| 1074 |
return |
| 1075 |
} |
| 1076 |
} |
| 1077 |
} |
| 1078 |
|
| 1079 |
func (s *pullSubscription) closeMsgs() { |
| 1080 |
if s.msgsClosed.CompareAndSwap(0, 1) { |
| 1081 |
close(s.msgs) |
| 1082 |
} |
| 1083 |
} |
| 1084 |
|
| 1085 |
func (s *pullSubscription) scheduleHeartbeatCheck(dur time.Duration) *hbMonitor { |
| 1086 |
if dur == 0 { |
| 1087 |
return nil |
| 1088 |
} |
| 1089 |
return &hbMonitor{ |
| 1090 |
timer: time.AfterFunc(2*dur, func() { |
| 1091 |
s.errs <- ErrNoHeartbeat |
| 1092 |
}), |
| 1093 |
} |
| 1094 |
} |
| 1095 |
|
| 1096 |
func (s *pullSubscription) cleanup() { |
| 1097 |
// For now this function does not need to hold the lock. |
| 1098 |
// Holding the lock here might cause a deadlock if Next() |
| 1099 |
// is already holding the lock and waiting. |
| 1100 |
// The fields that are read (subscription, hbMonitor) |
| 1101 |
// are read only (Only written on creation of pullSubscription). |
| 1102 |
if s.subscription == nil || !s.subscription.IsValid() { |
| 1103 |
return |
| 1104 |
} |
| 1105 |
if s.consumer != nil { |
| 1106 |
nc := s.consumer.js.conn |
| 1107 |
nc.RemoveStatusListener(s.connStatusChanged) |
| 1108 |
} |
| 1109 |
if s.hbMonitor != nil { |
| 1110 |
s.hbMonitor.Stop() |
| 1111 |
} |
| 1112 |
drainMode := s.draining.Load() == 1 |
| 1113 |
if drainMode { |
| 1114 |
s.subscription.Drain() |
| 1115 |
} else { |
| 1116 |
s.subscription.Unsubscribe() |
| 1117 |
} |
| 1118 |
s.closed.Store(1) |
| 1119 |
} |
| 1120 |
|
| 1121 |
// pull sends a pull request to the server and waits for messages using a subscription from [pullSubscription]. |
| 1122 |
// Messages will be fetched up to given batch_size or until there are no more messages or timeout is returned |
| 1123 |
func (s *pullSubscription) pull(req *pullRequest, subject string) error { |
| 1124 |
s.consumer.Lock() |
| 1125 |
defer s.consumer.Unlock() |
| 1126 |
if s.closed.Load() == 1 { |
| 1127 |
return ErrMsgIteratorClosed |
| 1128 |
} |
| 1129 |
if req.Batch < 1 { |
| 1130 |
return fmt.Errorf("%w: batch size must be at least 1", nats.ErrInvalidArg) |
| 1131 |
} |
| 1132 |
reqJSON, err := json.Marshal(req) |
| 1133 |
if err != nil { |
| 1134 |
return err |
| 1135 |
} |
| 1136 |
reply := s.subscription.Subject |
| 1137 |
|
| 1138 |
if err := s.consumer.js.conn.PublishRequest(subject, reply, reqJSON); err != nil { |
| 1139 |
return err |
| 1140 |
} |
| 1141 |
return nil |
| 1142 |
} |
| 1143 |
|
| 1144 |
func parseConsumeOpts(ordered bool, opts ...PullConsumeOpt) (*consumeOpts, error) { |
| 1145 |
consumeOpts := &consumeOpts{ |
| 1146 |
MaxMessages: unset, |
| 1147 |
MaxBytes: unset, |
| 1148 |
Expires: DefaultExpires, |
| 1149 |
Heartbeat: unset, |
| 1150 |
ReportMissingHeartbeats: true, |
| 1151 |
StopAfter: unset, |
| 1152 |
} |
| 1153 |
for _, opt := range opts { |
| 1154 |
if err := opt.configureConsume(consumeOpts); err != nil { |
| 1155 |
return nil, err |
| 1156 |
} |
| 1157 |
} |
| 1158 |
if err := consumeOpts.setDefaults(ordered); err != nil { |
| 1159 |
return nil, err |
| 1160 |
} |
| 1161 |
return consumeOpts, nil |
| 1162 |
} |
| 1163 |
|
| 1164 |
func parseMessagesOpts(ordered bool, opts ...PullMessagesOpt) (*consumeOpts, error) { |
| 1165 |
consumeOpts := &consumeOpts{ |
| 1166 |
MaxMessages: unset, |
| 1167 |
MaxBytes: unset, |
| 1168 |
Expires: DefaultExpires, |
| 1169 |
Heartbeat: unset, |
| 1170 |
ReportMissingHeartbeats: true, |
| 1171 |
StopAfter: unset, |
| 1172 |
} |
| 1173 |
for _, opt := range opts { |
| 1174 |
if err := opt.configureMessages(consumeOpts); err != nil { |
| 1175 |
return nil, err |
| 1176 |
} |
| 1177 |
} |
| 1178 |
if err := consumeOpts.setDefaults(ordered); err != nil { |
| 1179 |
return nil, err |
| 1180 |
} |
| 1181 |
return consumeOpts, nil |
| 1182 |
} |
| 1183 |
|
| 1184 |
func (consumeOpts *consumeOpts) setDefaults(ordered bool) error { |
| 1185 |
// we cannot use both max messages and max bytes unless we're using max bytes as fetch size limiter |
| 1186 |
if consumeOpts.MaxBytes != unset && consumeOpts.MaxMessages != unset && !consumeOpts.LimitSize { |
| 1187 |
return errors.New("only one of MaxMessages and MaxBytes can be specified") |
| 1188 |
} |
| 1189 |
if consumeOpts.MaxBytes != unset && !consumeOpts.LimitSize { |
| 1190 |
// we used PullMaxBytes setting, set MaxMessages to a high value |
| 1191 |
consumeOpts.MaxMessages = defaultBatchMaxBytesOnly |
| 1192 |
} else if consumeOpts.MaxMessages == unset { |
| 1193 |
// otherwise, if max messages is not set, set it to default value |
| 1194 |
consumeOpts.MaxMessages = DefaultMaxMessages |
| 1195 |
} |
| 1196 |
// if user did not set max bytes, set it to 0 |
| 1197 |
if consumeOpts.MaxBytes == unset { |
| 1198 |
consumeOpts.MaxBytes = 0 |
| 1199 |
} |
| 1200 |
|
| 1201 |
if consumeOpts.ThresholdMessages == 0 { |
| 1202 |
// half of the max messages, rounded up |
| 1203 |
consumeOpts.ThresholdMessages = int(math.Ceil(float64(consumeOpts.MaxMessages) / 2)) |
| 1204 |
} |
| 1205 |
if consumeOpts.ThresholdBytes == 0 { |
| 1206 |
// half of the max bytes, rounded up |
| 1207 |
consumeOpts.ThresholdBytes = int(math.Ceil(float64(consumeOpts.MaxBytes) / 2)) |
| 1208 |
} |
| 1209 |
|
| 1210 |
// set default heartbeats |
| 1211 |
if consumeOpts.Heartbeat == unset { |
| 1212 |
// by default, use 50% of expiry time |
| 1213 |
consumeOpts.Heartbeat = consumeOpts.Expires / 2 |
| 1214 |
if ordered { |
| 1215 |
// for ordered consumers, the default heartbeat is 5 seconds |
| 1216 |
if consumeOpts.Expires < 10*time.Second { |
| 1217 |
consumeOpts.Heartbeat = consumeOpts.Expires / 2 |
| 1218 |
} else { |
| 1219 |
consumeOpts.Heartbeat = 5 * time.Second |
| 1220 |
} |
| 1221 |
} else if consumeOpts.Heartbeat > 30*time.Second { |
| 1222 |
// cap the heartbeat to 30 seconds |
| 1223 |
consumeOpts.Heartbeat = 30 * time.Second |
| 1224 |
} |
| 1225 |
} |
| 1226 |
if consumeOpts.Heartbeat > consumeOpts.Expires/2 { |
| 1227 |
return fmt.Errorf("%w: the value of Heartbeat must be less than 50%% of expiry", ErrInvalidOption) |
| 1228 |
} |
| 1229 |
return nil |
| 1230 |
} |
| 1231 |
|
| 1232 |
func (c *pullConsumer) getPinID() string { |
| 1233 |
c.Lock() |
| 1234 |
defer c.Unlock() |
| 1235 |
return c.pinID |
| 1236 |
} |
| 1237 |
|
| 1238 |
func (c *pullConsumer) setPinID(pinID string) { |
| 1239 |
c.Lock() |
| 1240 |
defer c.Unlock() |
| 1241 |
c.pinID = pinID |
| 1242 |
} |