| 1 |
// Copyright 2022-2024 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 |
"errors" |
| 19 |
"fmt" |
| 20 |
"strconv" |
| 21 |
"strings" |
| 22 |
"sync" |
| 23 |
"sync/atomic" |
| 24 |
"time" |
| 25 |
|
| 26 |
"github.com/nats-io/nats.go" |
| 27 |
) |
| 28 |
|
| 29 |
type ( |
| 30 |
orderedConsumer struct { |
| 31 |
js *jetStream |
| 32 |
cfg *OrderedConsumerConfig |
| 33 |
stream string |
| 34 |
currentConsumer *pullConsumer |
| 35 |
currentSub *pullSubscription |
| 36 |
cursor cursor |
| 37 |
namePrefix string |
| 38 |
serial int |
| 39 |
consumerType consumerType |
| 40 |
doReset chan struct{} |
| 41 |
resetInProgress atomic.Uint32 |
| 42 |
userErrHandler ConsumeErrHandler |
| 43 |
stopAfter int |
| 44 |
stopAfterMsgsLeft chan int |
| 45 |
withStopAfter bool |
| 46 |
runningFetch *fetchResult |
| 47 |
subscription *orderedSubscription |
| 48 |
sync.Mutex |
| 49 |
} |
| 50 |
|
| 51 |
orderedSubscription struct { |
| 52 |
consumer *orderedConsumer |
| 53 |
opts []PullMessagesOpt |
| 54 |
done chan struct{} |
| 55 |
closed atomic.Uint32 |
| 56 |
} |
| 57 |
|
| 58 |
cursor struct { |
| 59 |
streamSeq uint64 |
| 60 |
deliverSeq uint64 |
| 61 |
} |
| 62 |
|
| 63 |
consumerType int |
| 64 |
) |
| 65 |
|
| 66 |
const ( |
| 67 |
consumerTypeNotSet consumerType = iota |
| 68 |
consumerTypeConsume |
| 69 |
consumerTypeFetch |
| 70 |
) |
| 71 |
|
| 72 |
var ( |
| 73 |
errOrderedSequenceMismatch = errors.New("sequence mismatch") |
| 74 |
errOrderedConsumerClosed = errors.New("ordered consumer closed") |
| 75 |
) |
| 76 |
|
| 77 |
// Consume can be used to continuously receive messages and handle them |
| 78 |
// with the provided callback function. Consume cannot be used concurrently |
| 79 |
// when using ordered consumer. |
| 80 |
// |
| 81 |
// See [Consumer.Consume] for more details. |
| 82 |
func (c *orderedConsumer) Consume(handler MessageHandler, opts ...PullConsumeOpt) (ConsumeContext, error) { |
| 83 |
c.Lock() |
| 84 |
defer c.Unlock() |
| 85 |
if (c.consumerType == consumerTypeNotSet || c.consumerType == consumerTypeConsume) && c.currentConsumer == nil { |
| 86 |
err := c.reset() |
| 87 |
if err != nil { |
| 88 |
return nil, err |
| 89 |
} |
| 90 |
} else if c.consumerType == consumerTypeConsume && c.currentConsumer != nil { |
| 91 |
return nil, ErrOrderedConsumerConcurrentRequests |
| 92 |
} |
| 93 |
if c.consumerType == consumerTypeFetch { |
| 94 |
return nil, ErrOrderConsumerUsedAsFetch |
| 95 |
} |
| 96 |
c.consumerType = consumerTypeConsume |
| 97 |
consumeOpts, err := parseConsumeOpts(true, opts...) |
| 98 |
if err != nil { |
| 99 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, err) |
| 100 |
} |
| 101 |
c.userErrHandler = consumeOpts.ErrHandler |
| 102 |
opts = append(opts, consumeReconnectNotify(), |
| 103 |
ConsumeErrHandler(c.errHandler(c.serial))) |
| 104 |
if consumeOpts.StopAfter > 0 { |
| 105 |
c.withStopAfter = true |
| 106 |
c.stopAfter = consumeOpts.StopAfter |
| 107 |
} |
| 108 |
c.stopAfterMsgsLeft = make(chan int, 1) |
| 109 |
if c.stopAfter > 0 { |
| 110 |
opts = append(opts, consumeStopAfterNotify(c.stopAfter, c.stopAfterMsgsLeft)) |
| 111 |
} |
| 112 |
sub := &orderedSubscription{ |
| 113 |
consumer: c, |
| 114 |
done: make(chan struct{}, 1), |
| 115 |
} |
| 116 |
c.subscription = sub |
| 117 |
internalHandler := func(serial int) func(msg Msg) { |
| 118 |
return func(msg Msg) { |
| 119 |
c.Lock() |
| 120 |
// handler is a noop if message was delivered for a consumer with different serial |
| 121 |
if serial != c.serial { |
| 122 |
c.Unlock() |
| 123 |
return |
| 124 |
} |
| 125 |
meta, err := msg.Metadata() |
| 126 |
if err != nil { |
| 127 |
currentSub := c.currentSub |
| 128 |
c.Unlock() |
| 129 |
c.errHandler(serial)(currentSub, err) |
| 130 |
return |
| 131 |
} |
| 132 |
dseq := meta.Sequence.Consumer |
| 133 |
if dseq != c.cursor.deliverSeq+1 { |
| 134 |
c.Unlock() |
| 135 |
c.errHandler(serial)(sub, errOrderedSequenceMismatch) |
| 136 |
return |
| 137 |
} |
| 138 |
c.cursor.deliverSeq = dseq |
| 139 |
c.cursor.streamSeq = meta.Sequence.Stream |
| 140 |
c.Unlock() |
| 141 |
handler(msg) |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
cc, err := c.currentConsumer.Consume(internalHandler(c.serial), opts...) |
| 146 |
if err != nil { |
| 147 |
return nil, err |
| 148 |
} |
| 149 |
c.currentSub = cc.(*pullSubscription) |
| 150 |
|
| 151 |
go func() { |
| 152 |
for { |
| 153 |
select { |
| 154 |
case <-c.doReset: |
| 155 |
if err := c.reset(); err != nil { |
| 156 |
if errors.Is(err, errOrderedConsumerClosed) { |
| 157 |
continue |
| 158 |
} |
| 159 |
c.errHandler(c.serial)(c.currentSub, err) |
| 160 |
} |
| 161 |
if c.withStopAfter { |
| 162 |
select { |
| 163 |
case c.stopAfter = <-c.stopAfterMsgsLeft: |
| 164 |
default: |
| 165 |
} |
| 166 |
if c.stopAfter <= 0 { |
| 167 |
sub.Stop() |
| 168 |
return |
| 169 |
} |
| 170 |
} |
| 171 |
if c.stopAfter > 0 { |
| 172 |
opts = opts[:len(opts)-2] |
| 173 |
} else { |
| 174 |
opts = opts[:len(opts)-1] |
| 175 |
} |
| 176 |
|
| 177 |
// overwrite the previous err handler to use the new serial |
| 178 |
opts = append(opts, ConsumeErrHandler(c.errHandler(c.serial))) |
| 179 |
if c.withStopAfter { |
| 180 |
opts = append(opts, consumeStopAfterNotify(c.stopAfter, c.stopAfterMsgsLeft)) |
| 181 |
} |
| 182 |
if cc, err := c.currentConsumer.Consume(internalHandler(c.serial), opts...); err != nil { |
| 183 |
c.errHandler(c.serial)(cc, err) |
| 184 |
} else { |
| 185 |
c.Lock() |
| 186 |
c.currentSub = cc.(*pullSubscription) |
| 187 |
c.Unlock() |
| 188 |
} |
| 189 |
case <-sub.done: |
| 190 |
s := sub.consumer.currentSub |
| 191 |
if s != nil { |
| 192 |
sub.consumer.Lock() |
| 193 |
s.Stop() |
| 194 |
sub.consumer.Unlock() |
| 195 |
} |
| 196 |
return |
| 197 |
case msgsLeft, ok := <-c.stopAfterMsgsLeft: |
| 198 |
if !ok { |
| 199 |
close(sub.done) |
| 200 |
} |
| 201 |
c.stopAfter = msgsLeft |
| 202 |
return |
| 203 |
} |
| 204 |
} |
| 205 |
}() |
| 206 |
return sub, nil |
| 207 |
} |
| 208 |
|
| 209 |
func (c *orderedConsumer) errHandler(serial int) func(cc ConsumeContext, err error) { |
| 210 |
return func(cc ConsumeContext, err error) { |
| 211 |
c.Lock() |
| 212 |
|
| 213 |
if c.userErrHandler != nil && !errors.Is(err, errOrderedSequenceMismatch) && !errors.Is(err, errConnected) { |
| 214 |
c.userErrHandler(cc, err) |
| 215 |
} |
| 216 |
if errors.Is(err, ErrConnectionClosed) { |
| 217 |
if c.subscription != nil { |
| 218 |
c.Unlock() |
| 219 |
c.subscription.Stop() |
| 220 |
return |
| 221 |
} |
| 222 |
c.Unlock() |
| 223 |
return |
| 224 |
} |
| 225 |
|
| 226 |
if errors.Is(err, ErrNoHeartbeat) || |
| 227 |
errors.Is(err, errOrderedSequenceMismatch) || |
| 228 |
errors.Is(err, ErrConsumerDeleted) || |
| 229 |
errors.Is(err, errConnected) || |
| 230 |
errors.Is(err, nats.ErrNoResponders) { |
| 231 |
// only reset if serial matches the current consumer serial and there is no reset in progress |
| 232 |
if serial == c.serial && c.resetInProgress.Load() == 0 { |
| 233 |
c.resetInProgress.Store(1) |
| 234 |
c.doReset <- struct{}{} |
| 235 |
} |
| 236 |
} |
| 237 |
c.Unlock() |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
// Messages returns MessagesContext, allowing continuously iterating |
| 242 |
// over messages on a stream. Messages cannot be used concurrently |
| 243 |
// when using ordered consumer. |
| 244 |
// |
| 245 |
// See [Consumer.Messages] for more details. |
| 246 |
func (c *orderedConsumer) Messages(opts ...PullMessagesOpt) (MessagesContext, error) { |
| 247 |
if (c.consumerType == consumerTypeNotSet || c.consumerType == consumerTypeConsume) && c.currentConsumer == nil { |
| 248 |
err := c.reset() |
| 249 |
if err != nil { |
| 250 |
return nil, err |
| 251 |
} |
| 252 |
} else if c.consumerType == consumerTypeConsume && c.currentConsumer != nil { |
| 253 |
return nil, ErrOrderedConsumerConcurrentRequests |
| 254 |
} |
| 255 |
if c.consumerType == consumerTypeFetch { |
| 256 |
return nil, ErrOrderConsumerUsedAsFetch |
| 257 |
} |
| 258 |
c.consumerType = consumerTypeConsume |
| 259 |
consumeOpts, err := parseMessagesOpts(true, opts...) |
| 260 |
if err != nil { |
| 261 |
return nil, fmt.Errorf("%w: %s", ErrInvalidOption, err) |
| 262 |
} |
| 263 |
opts = append(opts, |
| 264 |
WithMessagesErrOnMissingHeartbeat(true), |
| 265 |
messagesReconnectNotify()) |
| 266 |
c.stopAfterMsgsLeft = make(chan int, 1) |
| 267 |
if consumeOpts.StopAfter > 0 { |
| 268 |
c.withStopAfter = true |
| 269 |
c.stopAfter = consumeOpts.StopAfter |
| 270 |
} |
| 271 |
c.userErrHandler = consumeOpts.ErrHandler |
| 272 |
if c.stopAfter > 0 { |
| 273 |
opts = append(opts, messagesStopAfterNotify(c.stopAfter, c.stopAfterMsgsLeft)) |
| 274 |
} |
| 275 |
cc, err := c.currentConsumer.Messages(opts...) |
| 276 |
if err != nil { |
| 277 |
return nil, err |
| 278 |
} |
| 279 |
c.currentSub = cc.(*pullSubscription) |
| 280 |
|
| 281 |
sub := &orderedSubscription{ |
| 282 |
consumer: c, |
| 283 |
opts: opts, |
| 284 |
done: make(chan struct{}, 1), |
| 285 |
} |
| 286 |
c.subscription = sub |
| 287 |
|
| 288 |
return sub, nil |
| 289 |
} |
| 290 |
|
| 291 |
func (s *orderedSubscription) Next(opts ...NextOpt) (Msg, error) { |
| 292 |
for { |
| 293 |
msg, err := s.consumer.currentSub.Next(opts...) |
| 294 |
if err != nil { |
| 295 |
// Check for errors which should be returned directly |
| 296 |
// without resetting the consumer |
| 297 |
if errors.Is(err, ErrInvalidOption) { |
| 298 |
return nil, err |
| 299 |
} |
| 300 |
if errors.Is(err, nats.ErrTimeout) { |
| 301 |
return nil, err |
| 302 |
} |
| 303 |
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| 304 |
return nil, err |
| 305 |
} |
| 306 |
if errors.Is(err, ErrMsgIteratorClosed) { |
| 307 |
s.Stop() |
| 308 |
return nil, err |
| 309 |
} |
| 310 |
if s.consumer.withStopAfter { |
| 311 |
select { |
| 312 |
case s.consumer.stopAfter = <-s.consumer.stopAfterMsgsLeft: |
| 313 |
default: |
| 314 |
} |
| 315 |
if s.consumer.stopAfter <= 0 { |
| 316 |
s.Stop() |
| 317 |
return nil, ErrMsgIteratorClosed |
| 318 |
} |
| 319 |
s.opts[len(s.opts)-1] = StopAfter(s.consumer.stopAfter) |
| 320 |
} |
| 321 |
if err := s.consumer.reset(); err != nil { |
| 322 |
if errors.Is(err, errOrderedConsumerClosed) { |
| 323 |
return nil, ErrMsgIteratorClosed |
| 324 |
} |
| 325 |
return nil, err |
| 326 |
} |
| 327 |
cc, err := s.consumer.currentConsumer.Messages(s.opts...) |
| 328 |
if err != nil { |
| 329 |
return nil, err |
| 330 |
} |
| 331 |
s.consumer.currentSub = cc.(*pullSubscription) |
| 332 |
continue |
| 333 |
} |
| 334 |
|
| 335 |
meta, err := msg.Metadata() |
| 336 |
if err != nil { |
| 337 |
return nil, err |
| 338 |
} |
| 339 |
serial := serialNumberFromConsumer(meta.Consumer) |
| 340 |
if serial != s.consumer.serial { |
| 341 |
continue |
| 342 |
} |
| 343 |
dseq := meta.Sequence.Consumer |
| 344 |
if dseq != s.consumer.cursor.deliverSeq+1 { |
| 345 |
if err := s.consumer.reset(); err != nil { |
| 346 |
if errors.Is(err, errOrderedConsumerClosed) { |
| 347 |
return nil, ErrMsgIteratorClosed |
| 348 |
} |
| 349 |
return nil, err |
| 350 |
} |
| 351 |
cc, err := s.consumer.currentConsumer.Messages(s.opts...) |
| 352 |
if err != nil { |
| 353 |
return nil, err |
| 354 |
} |
| 355 |
s.consumer.currentSub = cc.(*pullSubscription) |
| 356 |
continue |
| 357 |
} |
| 358 |
s.consumer.cursor.deliverSeq = dseq |
| 359 |
s.consumer.cursor.streamSeq = meta.Sequence.Stream |
| 360 |
return msg, nil |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
func (s *orderedSubscription) Stop() { |
| 365 |
if !s.closed.CompareAndSwap(0, 1) { |
| 366 |
return |
| 367 |
} |
| 368 |
s.consumer.Lock() |
| 369 |
defer s.consumer.Unlock() |
| 370 |
if s.consumer.currentSub != nil { |
| 371 |
s.consumer.currentSub.Stop() |
| 372 |
} |
| 373 |
close(s.done) |
| 374 |
} |
| 375 |
|
| 376 |
func (s *orderedSubscription) Drain() { |
| 377 |
if !s.closed.CompareAndSwap(0, 1) { |
| 378 |
return |
| 379 |
} |
| 380 |
s.consumer.Lock() |
| 381 |
defer s.consumer.Unlock() |
| 382 |
if s.consumer.currentSub != nil { |
| 383 |
s.consumer.currentSub.Drain() |
| 384 |
} |
| 385 |
close(s.done) |
| 386 |
} |
| 387 |
|
| 388 |
// Closed returns a channel that is closed when the consuming is |
| 389 |
// fully stopped/drained. When the channel is closed, no more messages |
| 390 |
// will be received and processing is complete. |
| 391 |
func (s *orderedSubscription) Closed() <-chan struct{} { |
| 392 |
closedCh := make(chan struct{}) |
| 393 |
|
| 394 |
go func() { |
| 395 |
// First wait for s.done to be closed |
| 396 |
<-s.done |
| 397 |
|
| 398 |
// Then ensure underlying consumer is also closed (it may still be draining) |
| 399 |
s.consumer.Lock() |
| 400 |
if s.consumer.currentSub != nil { |
| 401 |
closed := s.consumer.currentSub.Closed() |
| 402 |
s.consumer.Unlock() |
| 403 |
<-closed |
| 404 |
} else { |
| 405 |
s.consumer.Unlock() |
| 406 |
} |
| 407 |
|
| 408 |
close(closedCh) |
| 409 |
}() |
| 410 |
return closedCh |
| 411 |
} |
| 412 |
|
| 413 |
// Fetch is used to retrieve up to a provided number of messages from a |
| 414 |
// stream. This method will always send a single request and wait until |
| 415 |
// either all messages are retrieved or request times out. |
| 416 |
// |
| 417 |
// It is not efficient to use Fetch with on an ordered consumer, as it will |
| 418 |
// reset the consumer for each subsequent Fetch call. |
| 419 |
// Consider using [Consumer.Consume] or [Consumer.Messages] instead. |
| 420 |
func (c *orderedConsumer) Fetch(batch int, opts ...FetchOpt) (MessageBatch, error) { |
| 421 |
c.Lock() |
| 422 |
if c.consumerType == consumerTypeConsume { |
| 423 |
c.Unlock() |
| 424 |
return nil, ErrOrderConsumerUsedAsConsume |
| 425 |
} |
| 426 |
if c.runningFetch != nil { |
| 427 |
if !c.runningFetch.closed() { |
| 428 |
return nil, ErrOrderedConsumerConcurrentRequests |
| 429 |
} |
| 430 |
if c.runningFetch.sseq != 0 { |
| 431 |
c.cursor.streamSeq = c.runningFetch.sseq |
| 432 |
} |
| 433 |
} |
| 434 |
c.consumerType = consumerTypeFetch |
| 435 |
sub := orderedSubscription{ |
| 436 |
consumer: c, |
| 437 |
done: make(chan struct{}), |
| 438 |
} |
| 439 |
c.subscription = &sub |
| 440 |
c.Unlock() |
| 441 |
err := c.reset() |
| 442 |
if err != nil { |
| 443 |
return nil, err |
| 444 |
} |
| 445 |
msgs, err := c.currentConsumer.Fetch(batch, opts...) |
| 446 |
if err != nil { |
| 447 |
return nil, err |
| 448 |
} |
| 449 |
c.runningFetch = msgs.(*fetchResult) |
| 450 |
return msgs, nil |
| 451 |
} |
| 452 |
|
| 453 |
// FetchBytes is used to retrieve up to a provided bytes from the |
| 454 |
// stream. This method will always send a single request and wait until |
| 455 |
// provided number of bytes is exceeded or request times out. |
| 456 |
// |
| 457 |
// It is not efficient to use FetchBytes with on an ordered consumer, as it will |
| 458 |
// reset the consumer for each subsequent Fetch call. |
| 459 |
// Consider using [Consumer.Consume] or [Consumer.Messages] instead. |
| 460 |
func (c *orderedConsumer) FetchBytes(maxBytes int, opts ...FetchOpt) (MessageBatch, error) { |
| 461 |
c.Lock() |
| 462 |
if c.consumerType == consumerTypeConsume { |
| 463 |
c.Unlock() |
| 464 |
return nil, ErrOrderConsumerUsedAsConsume |
| 465 |
} |
| 466 |
if c.runningFetch != nil { |
| 467 |
if !c.runningFetch.closed() { |
| 468 |
return nil, ErrOrderedConsumerConcurrentRequests |
| 469 |
} |
| 470 |
if c.runningFetch.sseq != 0 { |
| 471 |
c.cursor.streamSeq = c.runningFetch.sseq |
| 472 |
} |
| 473 |
} |
| 474 |
c.consumerType = consumerTypeFetch |
| 475 |
sub := orderedSubscription{ |
| 476 |
consumer: c, |
| 477 |
done: make(chan struct{}), |
| 478 |
} |
| 479 |
c.subscription = &sub |
| 480 |
c.Unlock() |
| 481 |
err := c.reset() |
| 482 |
if err != nil { |
| 483 |
return nil, err |
| 484 |
} |
| 485 |
msgs, err := c.currentConsumer.FetchBytes(maxBytes, opts...) |
| 486 |
if err != nil { |
| 487 |
return nil, err |
| 488 |
} |
| 489 |
c.runningFetch = msgs.(*fetchResult) |
| 490 |
return msgs, nil |
| 491 |
} |
| 492 |
|
| 493 |
// FetchNoWait is used to retrieve up to a provided number of messages |
| 494 |
// from a stream. This method will always send a single request and |
| 495 |
// immediately return up to a provided number of messages or wait until |
| 496 |
// at least one message is available or request times out. |
| 497 |
// |
| 498 |
// It is not efficient to use FetchNoWait with on an ordered consumer, as it will |
| 499 |
// reset the consumer for each subsequent Fetch call. |
| 500 |
// Consider using [Consumer.Consume] or [Consumer.Messages] instead. |
| 501 |
func (c *orderedConsumer) FetchNoWait(batch int) (MessageBatch, error) { |
| 502 |
if c.consumerType == consumerTypeConsume { |
| 503 |
return nil, ErrOrderConsumerUsedAsConsume |
| 504 |
} |
| 505 |
if c.runningFetch != nil && !c.runningFetch.done { |
| 506 |
return nil, ErrOrderedConsumerConcurrentRequests |
| 507 |
} |
| 508 |
c.consumerType = consumerTypeFetch |
| 509 |
sub := orderedSubscription{ |
| 510 |
consumer: c, |
| 511 |
done: make(chan struct{}), |
| 512 |
} |
| 513 |
c.subscription = &sub |
| 514 |
err := c.reset() |
| 515 |
if err != nil { |
| 516 |
return nil, err |
| 517 |
} |
| 518 |
return c.currentConsumer.FetchNoWait(batch) |
| 519 |
} |
| 520 |
|
| 521 |
// Next is used to retrieve the next message from the stream. This |
| 522 |
// method will block until the message is retrieved or timeout is |
| 523 |
// reached. |
| 524 |
// |
| 525 |
// It is not efficient to use Next with on an ordered consumer, as it will |
| 526 |
// reset the consumer for each subsequent Fetch call. |
| 527 |
// Consider using [Consumer.Consume] or [Consumer.Messages] instead. |
| 528 |
func (c *orderedConsumer) Next(opts ...FetchOpt) (Msg, error) { |
| 529 |
res, err := c.Fetch(1, opts...) |
| 530 |
if err != nil { |
| 531 |
return nil, err |
| 532 |
} |
| 533 |
msg := <-res.Messages() |
| 534 |
if msg != nil { |
| 535 |
return msg, nil |
| 536 |
} |
| 537 |
if res.Error() == nil { |
| 538 |
return nil, nats.ErrTimeout |
| 539 |
} |
| 540 |
return nil, res.Error() |
| 541 |
} |
| 542 |
|
| 543 |
func serialNumberFromConsumer(name string) int { |
| 544 |
if len(name) == 0 { |
| 545 |
return 0 |
| 546 |
} |
| 547 |
parts := strings.Split(name, "_") |
| 548 |
if len(parts) < 2 { |
| 549 |
return 0 |
| 550 |
} |
| 551 |
serial, err := strconv.Atoi(parts[len(parts)-1]) |
| 552 |
if err != nil { |
| 553 |
return 0 |
| 554 |
} |
| 555 |
return serial |
| 556 |
} |
| 557 |
|
| 558 |
func (c *orderedConsumer) reset() error { |
| 559 |
c.Lock() |
| 560 |
defer c.Unlock() |
| 561 |
defer c.resetInProgress.Store(0) |
| 562 |
if c.currentConsumer != nil { |
| 563 |
c.currentConsumer.Lock() |
| 564 |
if c.currentSub != nil { |
| 565 |
c.currentSub.Stop() |
| 566 |
} |
| 567 |
consName := c.currentConsumer.CachedInfo().Name |
| 568 |
c.currentConsumer.Unlock() |
| 569 |
go func() { |
| 570 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 571 |
_ = c.js.DeleteConsumer(ctx, c.stream, consName) |
| 572 |
cancel() |
| 573 |
}() |
| 574 |
} |
| 575 |
|
| 576 |
c.cursor.deliverSeq = 0 |
| 577 |
consumerConfig := c.getConsumerConfig() |
| 578 |
|
| 579 |
var err error |
| 580 |
var cons Consumer |
| 581 |
|
| 582 |
backoffOpts := backoffOpts{ |
| 583 |
attempts: c.cfg.MaxResetAttempts, |
| 584 |
initialInterval: time.Second, |
| 585 |
factor: 2, |
| 586 |
maxInterval: 10 * time.Second, |
| 587 |
cancel: c.subscription.done, |
| 588 |
} |
| 589 |
err = retryWithBackoff(func(attempt int) (bool, error) { |
| 590 |
isClosed := c.subscription.closed.Load() == 1 |
| 591 |
if isClosed { |
| 592 |
return false, errOrderedConsumerClosed |
| 593 |
} |
| 594 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 595 |
defer cancel() |
| 596 |
cons, err = c.js.CreateOrUpdateConsumer(ctx, c.stream, *consumerConfig) |
| 597 |
if err != nil { |
| 598 |
return true, err |
| 599 |
} |
| 600 |
return false, nil |
| 601 |
}, backoffOpts) |
| 602 |
if err != nil { |
| 603 |
return err |
| 604 |
} |
| 605 |
c.currentConsumer = cons.(*pullConsumer) |
| 606 |
return nil |
| 607 |
} |
| 608 |
|
| 609 |
func (c *orderedConsumer) getConsumerConfig() *ConsumerConfig { |
| 610 |
c.serial++ |
| 611 |
var nextSeq uint64 |
| 612 |
|
| 613 |
// if stream sequence is not initialized, no message was consumed yet |
| 614 |
// therefore, start from the beginning (either from 1 or from the provided sequence) |
| 615 |
if c.cursor.streamSeq == 0 { |
| 616 |
if c.cfg.OptStartSeq != 0 { |
| 617 |
nextSeq = c.cfg.OptStartSeq |
| 618 |
} else { |
| 619 |
nextSeq = 1 |
| 620 |
} |
| 621 |
} else { |
| 622 |
// otherwise, start from the next sequence |
| 623 |
nextSeq = c.cursor.streamSeq + 1 |
| 624 |
} |
| 625 |
|
| 626 |
if c.cfg.MaxResetAttempts == 0 { |
| 627 |
c.cfg.MaxResetAttempts = -1 |
| 628 |
} |
| 629 |
name := fmt.Sprintf("%s_%d", c.namePrefix, c.serial) |
| 630 |
cfg := &ConsumerConfig{ |
| 631 |
Name: name, |
| 632 |
DeliverPolicy: DeliverByStartSequencePolicy, |
| 633 |
OptStartSeq: nextSeq, |
| 634 |
AckPolicy: AckNonePolicy, |
| 635 |
InactiveThreshold: 5 * time.Minute, |
| 636 |
Replicas: 1, |
| 637 |
HeadersOnly: c.cfg.HeadersOnly, |
| 638 |
MemoryStorage: true, |
| 639 |
Metadata: c.cfg.Metadata, |
| 640 |
} |
| 641 |
if len(c.cfg.FilterSubjects) == 1 { |
| 642 |
cfg.FilterSubject = c.cfg.FilterSubjects[0] |
| 643 |
} else { |
| 644 |
cfg.FilterSubjects = c.cfg.FilterSubjects |
| 645 |
} |
| 646 |
if c.cfg.InactiveThreshold != 0 { |
| 647 |
cfg.InactiveThreshold = c.cfg.InactiveThreshold |
| 648 |
} |
| 649 |
|
| 650 |
// if the cursor is not yet set, use the provided deliver policy |
| 651 |
if c.cursor.streamSeq != 0 { |
| 652 |
return cfg |
| 653 |
} |
| 654 |
|
| 655 |
// initial request, some options may be modified at that point |
| 656 |
cfg.DeliverPolicy = c.cfg.DeliverPolicy |
| 657 |
if c.cfg.DeliverPolicy == DeliverLastPerSubjectPolicy || |
| 658 |
c.cfg.DeliverPolicy == DeliverLastPolicy || |
| 659 |
c.cfg.DeliverPolicy == DeliverNewPolicy || |
| 660 |
c.cfg.DeliverPolicy == DeliverAllPolicy { |
| 661 |
|
| 662 |
cfg.OptStartSeq = 0 |
| 663 |
} else if c.cfg.DeliverPolicy == DeliverByStartTimePolicy { |
| 664 |
cfg.OptStartSeq = 0 |
| 665 |
cfg.OptStartTime = c.cfg.OptStartTime |
| 666 |
} else { |
| 667 |
cfg.OptStartSeq = c.cfg.OptStartSeq |
| 668 |
} |
| 669 |
|
| 670 |
if cfg.DeliverPolicy == DeliverLastPerSubjectPolicy && len(c.cfg.FilterSubjects) == 0 { |
| 671 |
cfg.FilterSubjects = []string{">"} |
| 672 |
} |
| 673 |
|
| 674 |
return cfg |
| 675 |
} |
| 676 |
|
| 677 |
func consumeStopAfterNotify(numMsgs int, msgsLeftAfterStop chan int) PullConsumeOpt { |
| 678 |
return pullOptFunc(func(opts *consumeOpts) error { |
| 679 |
opts.StopAfter = numMsgs |
| 680 |
opts.stopAfterMsgsLeft = msgsLeftAfterStop |
| 681 |
return nil |
| 682 |
}) |
| 683 |
} |
| 684 |
|
| 685 |
func messagesStopAfterNotify(numMsgs int, msgsLeftAfterStop chan int) PullMessagesOpt { |
| 686 |
return pullOptFunc(func(opts *consumeOpts) error { |
| 687 |
opts.StopAfter = numMsgs |
| 688 |
opts.stopAfterMsgsLeft = msgsLeftAfterStop |
| 689 |
return nil |
| 690 |
}) |
| 691 |
} |
| 692 |
|
| 693 |
func consumeReconnectNotify() PullConsumeOpt { |
| 694 |
return pullOptFunc(func(opts *consumeOpts) error { |
| 695 |
opts.notifyOnReconnect = true |
| 696 |
return nil |
| 697 |
}) |
| 698 |
} |
| 699 |
|
| 700 |
func messagesReconnectNotify() PullMessagesOpt { |
| 701 |
return pullOptFunc(func(opts *consumeOpts) error { |
| 702 |
opts.notifyOnReconnect = true |
| 703 |
return nil |
| 704 |
}) |
| 705 |
} |
| 706 |
|
| 707 |
// Info returns information about the ordered consumer. |
| 708 |
// Note that this method will fetch the latest instance of the |
| 709 |
// consumer from the server, which can be deleted by the library at any time. |
| 710 |
func (c *orderedConsumer) Info(ctx context.Context) (*ConsumerInfo, error) { |
| 711 |
c.Lock() |
| 712 |
defer c.Unlock() |
| 713 |
if c.currentConsumer == nil { |
| 714 |
return nil, ErrOrderedConsumerNotCreated |
| 715 |
} |
| 716 |
infoSubject := fmt.Sprintf(apiConsumerInfoT, c.stream, c.currentConsumer.name) |
| 717 |
var resp consumerInfoResponse |
| 718 |
|
| 719 |
if _, err := c.js.apiRequestJSON(ctx, infoSubject, &resp); err != nil { |
| 720 |
return nil, err |
| 721 |
} |
| 722 |
if resp.Error != nil { |
| 723 |
if resp.Error.ErrorCode == JSErrCodeConsumerNotFound { |
| 724 |
return nil, ErrConsumerNotFound |
| 725 |
} |
| 726 |
return nil, resp.Error |
| 727 |
} |
| 728 |
if resp.Error == nil && resp.ConsumerInfo == nil { |
| 729 |
return nil, ErrConsumerNotFound |
| 730 |
} |
| 731 |
|
| 732 |
c.currentConsumer.info = resp.ConsumerInfo |
| 733 |
return resp.ConsumerInfo, nil |
| 734 |
} |
| 735 |
|
| 736 |
// CachedInfo returns cached information about the consumer currently |
| 737 |
// used by the ordered consumer. Cached info will be updated on every call |
| 738 |
// to [Consumer.Info] or on consumer reset. |
| 739 |
func (c *orderedConsumer) CachedInfo() *ConsumerInfo { |
| 740 |
c.Lock() |
| 741 |
defer c.Unlock() |
| 742 |
if c.currentConsumer == nil { |
| 743 |
return nil |
| 744 |
} |
| 745 |
return c.currentConsumer.info |
| 746 |
} |
| 747 |
|
| 748 |
type backoffOpts struct { |
| 749 |
// total retry attempts |
| 750 |
// -1 for unlimited |
| 751 |
attempts int |
| 752 |
// initial interval after which first retry will be performed |
| 753 |
// defaults to 1s |
| 754 |
initialInterval time.Duration |
| 755 |
// determines whether first function execution should be performed immediately |
| 756 |
disableInitialExecution bool |
| 757 |
// multiplier on each attempt |
| 758 |
// defaults to 2 |
| 759 |
factor float64 |
| 760 |
// max interval between retries |
| 761 |
// after reaching this value, all subsequent |
| 762 |
// retries will be performed with this interval |
| 763 |
// defaults to 1 minute |
| 764 |
maxInterval time.Duration |
| 765 |
// custom backoff intervals |
| 766 |
// if set, overrides all other options except attempts |
| 767 |
// if attempts are set, then the last interval will be used |
| 768 |
// for all subsequent retries after reaching the limit |
| 769 |
customBackoff []time.Duration |
| 770 |
// cancel channel |
| 771 |
// if set, retry will be canceled when this channel is closed |
| 772 |
cancel <-chan struct{} |
| 773 |
} |
| 774 |
|
| 775 |
func retryWithBackoff(f func(int) (bool, error), opts backoffOpts) error { |
| 776 |
var err error |
| 777 |
var shouldContinue bool |
| 778 |
// if custom backoff is set, use it instead of other options |
| 779 |
if len(opts.customBackoff) > 0 { |
| 780 |
if opts.attempts != 0 { |
| 781 |
return errors.New("cannot use custom backoff intervals when attempts are set") |
| 782 |
} |
| 783 |
for i, interval := range opts.customBackoff { |
| 784 |
select { |
| 785 |
case <-opts.cancel: |
| 786 |
return nil |
| 787 |
case <-time.After(interval): |
| 788 |
} |
| 789 |
shouldContinue, err = f(i) |
| 790 |
if !shouldContinue { |
| 791 |
return err |
| 792 |
} |
| 793 |
} |
| 794 |
return err |
| 795 |
} |
| 796 |
|
| 797 |
// set default options |
| 798 |
if opts.initialInterval == 0 { |
| 799 |
opts.initialInterval = 1 * time.Second |
| 800 |
} |
| 801 |
if opts.factor == 0 { |
| 802 |
opts.factor = 2 |
| 803 |
} |
| 804 |
if opts.maxInterval == 0 { |
| 805 |
opts.maxInterval = 1 * time.Minute |
| 806 |
} |
| 807 |
if opts.attempts == 0 { |
| 808 |
return errors.New("retry attempts have to be set when not using custom backoff intervals") |
| 809 |
} |
| 810 |
interval := opts.initialInterval |
| 811 |
for i := 0; ; i++ { |
| 812 |
if i == 0 && opts.disableInitialExecution { |
| 813 |
time.Sleep(interval) |
| 814 |
continue |
| 815 |
} |
| 816 |
shouldContinue, err = f(i) |
| 817 |
if !shouldContinue { |
| 818 |
return err |
| 819 |
} |
| 820 |
if opts.attempts > 0 && i >= opts.attempts-1 { |
| 821 |
break |
| 822 |
} |
| 823 |
select { |
| 824 |
case <-opts.cancel: |
| 825 |
return nil |
| 826 |
case <-time.After(interval): |
| 827 |
} |
| 828 |
interval = time.Duration(float64(interval) * opts.factor) |
| 829 |
if interval >= opts.maxInterval { |
| 830 |
interval = opts.maxInterval |
| 831 |
} |
| 832 |
} |
| 833 |
return err |
| 834 |
} |