File: ordered.go

package info (click to toggle)
golang-github-nats-io-go-nats 1.46.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,240 kB
  • sloc: sh: 13; makefile: 4
file content (828 lines) | stat: -rw-r--r-- 22,299 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// Copyright 2022-2024 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package jetstream

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/nats-io/nats.go"
)

type (
	orderedConsumer struct {
		js                *jetStream
		cfg               *OrderedConsumerConfig
		stream            string
		currentConsumer   *pullConsumer
		currentSub        *pullSubscription
		cursor            cursor
		namePrefix        string
		serial            int
		consumerType      consumerType
		doReset           chan struct{}
		resetInProgress   atomic.Uint32
		userErrHandler    ConsumeErrHandler
		stopAfter         int
		stopAfterMsgsLeft chan int
		withStopAfter     bool
		runningFetch      *fetchResult
		subscription      *orderedSubscription
		sync.Mutex
	}

	orderedSubscription struct {
		consumer *orderedConsumer
		opts     []PullMessagesOpt
		done     chan struct{}
		closed   atomic.Uint32
	}

	cursor struct {
		streamSeq  uint64
		deliverSeq uint64
	}

	consumerType int
)

const (
	consumerTypeNotSet consumerType = iota
	consumerTypeConsume
	consumerTypeFetch
)

var (
	errOrderedSequenceMismatch = errors.New("sequence mismatch")
	errOrderedConsumerClosed   = errors.New("ordered consumer closed")
)

// Consume can be used to continuously receive messages and handle them
// with the provided callback function. Consume cannot be used concurrently
// when using ordered consumer.
//
// See [Consumer.Consume] for more details.
func (c *orderedConsumer) Consume(handler MessageHandler, opts ...PullConsumeOpt) (ConsumeContext, error) {
	c.Lock()
	defer c.Unlock()
	if (c.consumerType == consumerTypeNotSet || c.consumerType == consumerTypeConsume) && c.currentConsumer == nil {
		err := c.reset()
		if err != nil {
			return nil, err
		}
	} else if c.consumerType == consumerTypeConsume && c.currentConsumer != nil {
		return nil, ErrOrderedConsumerConcurrentRequests
	}
	if c.consumerType == consumerTypeFetch {
		return nil, ErrOrderConsumerUsedAsFetch
	}
	c.consumerType = consumerTypeConsume
	consumeOpts, err := parseConsumeOpts(true, opts...)
	if err != nil {
		return nil, fmt.Errorf("%w: %s", ErrInvalidOption, err)
	}
	c.userErrHandler = consumeOpts.ErrHandler
	opts = append(opts, consumeReconnectNotify(),
		ConsumeErrHandler(c.errHandler(c.serial)))
	if consumeOpts.StopAfter > 0 {
		c.withStopAfter = true
		c.stopAfter = consumeOpts.StopAfter
	}
	c.stopAfterMsgsLeft = make(chan int, 1)
	if c.stopAfter > 0 {
		opts = append(opts, consumeStopAfterNotify(c.stopAfter, c.stopAfterMsgsLeft))
	}
	sub := &orderedSubscription{
		consumer: c,
		done:     make(chan struct{}, 1),
	}
	c.subscription = sub
	internalHandler := func(serial int) func(msg Msg) {
		return func(msg Msg) {
			// handler is a noop if message was delivered for a consumer with different serial
			if serial != c.serial {
				return
			}
			meta, err := msg.Metadata()
			if err != nil {
				c.errHandler(serial)(c.currentSub, err)
				return
			}
			dseq := meta.Sequence.Consumer
			if dseq != c.cursor.deliverSeq+1 {
				c.errHandler(serial)(sub, errOrderedSequenceMismatch)
				return
			}
			c.cursor.deliverSeq = dseq
			c.cursor.streamSeq = meta.Sequence.Stream
			handler(msg)
		}
	}

	cc, err := c.currentConsumer.Consume(internalHandler(c.serial), opts...)
	if err != nil {
		return nil, err
	}
	c.currentSub = cc.(*pullSubscription)

	go func() {
		for {
			select {
			case <-c.doReset:
				if err := c.reset(); err != nil {
					if errors.Is(err, errOrderedConsumerClosed) {
						continue
					}
					c.errHandler(c.serial)(c.currentSub, err)
				}
				if c.withStopAfter {
					select {
					case c.stopAfter = <-c.stopAfterMsgsLeft:
					default:
					}
					if c.stopAfter <= 0 {
						sub.Stop()
						return
					}
				}
				if c.stopAfter > 0 {
					opts = opts[:len(opts)-2]
				} else {
					opts = opts[:len(opts)-1]
				}

				// overwrite the previous err handler to use the new serial
				opts = append(opts, ConsumeErrHandler(c.errHandler(c.serial)))
				if c.withStopAfter {
					opts = append(opts, consumeStopAfterNotify(c.stopAfter, c.stopAfterMsgsLeft))
				}
				if cc, err := c.currentConsumer.Consume(internalHandler(c.serial), opts...); err != nil {
					c.errHandler(c.serial)(cc, err)
				} else {
					c.Lock()
					c.currentSub = cc.(*pullSubscription)
					c.Unlock()
				}
			case <-sub.done:
				s := sub.consumer.currentSub
				if s != nil {
					sub.consumer.Lock()
					s.Stop()
					sub.consumer.Unlock()
				}
				return
			case msgsLeft, ok := <-c.stopAfterMsgsLeft:
				if !ok {
					close(sub.done)
				}
				c.stopAfter = msgsLeft
				return
			}
		}
	}()
	return sub, nil
}

func (c *orderedConsumer) errHandler(serial int) func(cc ConsumeContext, err error) {
	return func(cc ConsumeContext, err error) {
		c.Lock()

		if c.userErrHandler != nil && !errors.Is(err, errOrderedSequenceMismatch) && !errors.Is(err, errConnected) {
			c.userErrHandler(cc, err)
		}
		if errors.Is(err, ErrConnectionClosed) {
			if c.subscription != nil {
				c.Unlock()
				c.subscription.Stop()
				return
			}
			c.Unlock()
			return
		}

		if errors.Is(err, ErrNoHeartbeat) ||
			errors.Is(err, errOrderedSequenceMismatch) ||
			errors.Is(err, ErrConsumerDeleted) ||
			errors.Is(err, errConnected) ||
			errors.Is(err, nats.ErrNoResponders) {
			// only reset if serial matches the current consumer serial and there is no reset in progress
			if serial == c.serial && c.resetInProgress.Load() == 0 {
				c.resetInProgress.Store(1)
				c.doReset <- struct{}{}
			}
		}
		c.Unlock()
	}
}

// Messages returns MessagesContext, allowing continuously iterating
// over messages on a stream. Messages cannot be used concurrently
// when using ordered consumer.
//
// See [Consumer.Messages] for more details.
func (c *orderedConsumer) Messages(opts ...PullMessagesOpt) (MessagesContext, error) {
	if (c.consumerType == consumerTypeNotSet || c.consumerType == consumerTypeConsume) && c.currentConsumer == nil {
		err := c.reset()
		if err != nil {
			return nil, err
		}
	} else if c.consumerType == consumerTypeConsume && c.currentConsumer != nil {
		return nil, ErrOrderedConsumerConcurrentRequests
	}
	if c.consumerType == consumerTypeFetch {
		return nil, ErrOrderConsumerUsedAsFetch
	}
	c.consumerType = consumerTypeConsume
	consumeOpts, err := parseMessagesOpts(true, opts...)
	if err != nil {
		return nil, fmt.Errorf("%w: %s", ErrInvalidOption, err)
	}
	opts = append(opts,
		WithMessagesErrOnMissingHeartbeat(true),
		messagesReconnectNotify())
	c.stopAfterMsgsLeft = make(chan int, 1)
	if consumeOpts.StopAfter > 0 {
		c.withStopAfter = true
		c.stopAfter = consumeOpts.StopAfter
	}
	c.userErrHandler = consumeOpts.ErrHandler
	if c.stopAfter > 0 {
		opts = append(opts, messagesStopAfterNotify(c.stopAfter, c.stopAfterMsgsLeft))
	}
	cc, err := c.currentConsumer.Messages(opts...)
	if err != nil {
		return nil, err
	}
	c.currentSub = cc.(*pullSubscription)

	sub := &orderedSubscription{
		consumer: c,
		opts:     opts,
		done:     make(chan struct{}, 1),
	}
	c.subscription = sub

	return sub, nil
}

func (s *orderedSubscription) Next(opts ...NextOpt) (Msg, error) {
	for {
		msg, err := s.consumer.currentSub.Next(opts...)
		if err != nil {
			// Check for errors which should be returned directly
			// without resetting the consumer
			if errors.Is(err, ErrInvalidOption) {
				return nil, err
			}
			if errors.Is(err, nats.ErrTimeout) {
				return nil, err
			}
			if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
				return nil, err
			}
			if errors.Is(err, ErrMsgIteratorClosed) {
				s.Stop()
				return nil, err
			}
			if s.consumer.withStopAfter {
				select {
				case s.consumer.stopAfter = <-s.consumer.stopAfterMsgsLeft:
				default:
				}
				if s.consumer.stopAfter <= 0 {
					s.Stop()
					return nil, ErrMsgIteratorClosed
				}
				s.opts[len(s.opts)-1] = StopAfter(s.consumer.stopAfter)
			}
			if err := s.consumer.reset(); err != nil {
				if errors.Is(err, errOrderedConsumerClosed) {
					return nil, ErrMsgIteratorClosed
				}
				return nil, err
			}
			cc, err := s.consumer.currentConsumer.Messages(s.opts...)
			if err != nil {
				return nil, err
			}
			s.consumer.currentSub = cc.(*pullSubscription)
			continue
		}

		meta, err := msg.Metadata()
		if err != nil {
			return nil, err
		}
		serial := serialNumberFromConsumer(meta.Consumer)
		if serial != s.consumer.serial {
			continue
		}
		dseq := meta.Sequence.Consumer
		if dseq != s.consumer.cursor.deliverSeq+1 {
			if err := s.consumer.reset(); err != nil {
				if errors.Is(err, errOrderedConsumerClosed) {
					return nil, ErrMsgIteratorClosed
				}
				return nil, err
			}
			cc, err := s.consumer.currentConsumer.Messages(s.opts...)
			if err != nil {
				return nil, err
			}
			s.consumer.currentSub = cc.(*pullSubscription)
			continue
		}
		s.consumer.cursor.deliverSeq = dseq
		s.consumer.cursor.streamSeq = meta.Sequence.Stream
		return msg, nil
	}
}

func (s *orderedSubscription) Stop() {
	if !s.closed.CompareAndSwap(0, 1) {
		return
	}
	s.consumer.Lock()
	defer s.consumer.Unlock()
	if s.consumer.currentSub != nil {
		s.consumer.currentSub.Stop()
	}
	close(s.done)
}

func (s *orderedSubscription) Drain() {
	if !s.closed.CompareAndSwap(0, 1) {
		return
	}
	if s.consumer.currentSub != nil {
		s.consumer.currentConsumer.Lock()
		s.consumer.currentSub.Drain()
		s.consumer.currentConsumer.Unlock()
	}
	close(s.done)
}

// Closed returns a channel that is closed when the consuming is
// fully stopped/drained. When the channel is closed, no more messages
// will be received and processing is complete.
func (s *orderedSubscription) Closed() <-chan struct{} {
	closedCh := make(chan struct{})

	go func() {
		// First wait for s.done to be closed
		<-s.done

		// Then ensure underlying consumer is also closed (it may still be draining)
		s.consumer.Lock()
		if s.consumer.currentSub != nil {
			closed := s.consumer.currentSub.Closed()
			s.consumer.Unlock()
			<-closed
		} else {
			s.consumer.Unlock()
		}

		close(closedCh)
	}()
	return closedCh
}

// Fetch is used to retrieve up to a provided number of messages from a
// stream. This method will always send a single request and wait until
// either all messages are retrieved or request times out.
//
// It is not efficient to use Fetch with on an ordered consumer, as it will
// reset the consumer for each subsequent Fetch call.
// Consider using [Consumer.Consume] or [Consumer.Messages] instead.
func (c *orderedConsumer) Fetch(batch int, opts ...FetchOpt) (MessageBatch, error) {
	c.Lock()
	if c.consumerType == consumerTypeConsume {
		c.Unlock()
		return nil, ErrOrderConsumerUsedAsConsume
	}
	if c.runningFetch != nil {
		if !c.runningFetch.closed() {
			return nil, ErrOrderedConsumerConcurrentRequests
		}
		if c.runningFetch.sseq != 0 {
			c.cursor.streamSeq = c.runningFetch.sseq
		}
	}
	c.consumerType = consumerTypeFetch
	sub := orderedSubscription{
		consumer: c,
		done:     make(chan struct{}),
	}
	c.subscription = &sub
	c.Unlock()
	err := c.reset()
	if err != nil {
		return nil, err
	}
	msgs, err := c.currentConsumer.Fetch(batch, opts...)
	if err != nil {
		return nil, err
	}
	c.runningFetch = msgs.(*fetchResult)
	return msgs, nil
}

// FetchBytes is used to retrieve up to a provided bytes from the
// stream. This method will always send a single request and wait until
// provided number of bytes is exceeded or request times out.
//
// It is not efficient to use FetchBytes with on an ordered consumer, as it will
// reset the consumer for each subsequent Fetch call.
// Consider using [Consumer.Consume] or [Consumer.Messages] instead.
func (c *orderedConsumer) FetchBytes(maxBytes int, opts ...FetchOpt) (MessageBatch, error) {
	c.Lock()
	if c.consumerType == consumerTypeConsume {
		c.Unlock()
		return nil, ErrOrderConsumerUsedAsConsume
	}
	if c.runningFetch != nil {
		if !c.runningFetch.closed() {
			return nil, ErrOrderedConsumerConcurrentRequests
		}
		if c.runningFetch.sseq != 0 {
			c.cursor.streamSeq = c.runningFetch.sseq
		}
	}
	c.consumerType = consumerTypeFetch
	sub := orderedSubscription{
		consumer: c,
		done:     make(chan struct{}),
	}
	c.subscription = &sub
	c.Unlock()
	err := c.reset()
	if err != nil {
		return nil, err
	}
	msgs, err := c.currentConsumer.FetchBytes(maxBytes, opts...)
	if err != nil {
		return nil, err
	}
	c.runningFetch = msgs.(*fetchResult)
	return msgs, nil
}

// FetchNoWait is used to retrieve up to a provided number of messages
// from a stream. This method will always send a single request and
// immediately return up to a provided number of messages or wait until
// at least one message is available or request times out.
//
// It is not efficient to use FetchNoWait with on an ordered consumer, as it will
// reset the consumer for each subsequent Fetch call.
// Consider using [Consumer.Consume] or [Consumer.Messages] instead.
func (c *orderedConsumer) FetchNoWait(batch int) (MessageBatch, error) {
	if c.consumerType == consumerTypeConsume {
		return nil, ErrOrderConsumerUsedAsConsume
	}
	if c.runningFetch != nil && !c.runningFetch.done {
		return nil, ErrOrderedConsumerConcurrentRequests
	}
	c.consumerType = consumerTypeFetch
	sub := orderedSubscription{
		consumer: c,
		done:     make(chan struct{}),
	}
	c.subscription = &sub
	err := c.reset()
	if err != nil {
		return nil, err
	}
	return c.currentConsumer.FetchNoWait(batch)
}

// Next is used to retrieve the next message from the stream. This
// method will block until the message is retrieved or timeout is
// reached.
//
// It is not efficient to use Next with on an ordered consumer, as it will
// reset the consumer for each subsequent Fetch call.
// Consider using [Consumer.Consume] or [Consumer.Messages] instead.
func (c *orderedConsumer) Next(opts ...FetchOpt) (Msg, error) {
	res, err := c.Fetch(1, opts...)
	if err != nil {
		return nil, err
	}
	msg := <-res.Messages()
	if msg != nil {
		return msg, nil
	}
	if res.Error() == nil {
		return nil, nats.ErrTimeout
	}
	return nil, res.Error()
}

func serialNumberFromConsumer(name string) int {
	if len(name) == 0 {
		return 0
	}
	parts := strings.Split(name, "_")
	if len(parts) < 2 {
		return 0
	}
	serial, err := strconv.Atoi(parts[len(parts)-1])
	if err != nil {
		return 0
	}
	return serial
}

func (c *orderedConsumer) reset() error {
	c.Lock()
	defer c.Unlock()
	defer c.resetInProgress.Store(0)
	if c.currentConsumer != nil {
		c.currentConsumer.Lock()
		if c.currentSub != nil {
			c.currentSub.Stop()
		}
		consName := c.currentConsumer.CachedInfo().Name
		c.currentConsumer.Unlock()
		go func() {
			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			_ = c.js.DeleteConsumer(ctx, c.stream, consName)
			cancel()
		}()
	}

	c.cursor.deliverSeq = 0
	consumerConfig := c.getConsumerConfig()

	var err error
	var cons Consumer

	backoffOpts := backoffOpts{
		attempts:        c.cfg.MaxResetAttempts,
		initialInterval: time.Second,
		factor:          2,
		maxInterval:     10 * time.Second,
		cancel:          c.subscription.done,
	}
	err = retryWithBackoff(func(attempt int) (bool, error) {
		isClosed := c.subscription.closed.Load() == 1
		if isClosed {
			return false, errOrderedConsumerClosed
		}
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		cons, err = c.js.CreateOrUpdateConsumer(ctx, c.stream, *consumerConfig)
		if err != nil {
			return true, err
		}
		return false, nil
	}, backoffOpts)
	if err != nil {
		return err
	}
	c.currentConsumer = cons.(*pullConsumer)
	return nil
}

func (c *orderedConsumer) getConsumerConfig() *ConsumerConfig {
	c.serial++
	var nextSeq uint64

	// if stream sequence is not initialized, no message was consumed yet
	// therefore, start from the beginning (either from 1 or from the provided sequence)
	if c.cursor.streamSeq == 0 {
		if c.cfg.OptStartSeq != 0 {
			nextSeq = c.cfg.OptStartSeq
		} else {
			nextSeq = 1
		}
	} else {
		// otherwise, start from the next sequence
		nextSeq = c.cursor.streamSeq + 1
	}

	if c.cfg.MaxResetAttempts == 0 {
		c.cfg.MaxResetAttempts = -1
	}
	name := fmt.Sprintf("%s_%d", c.namePrefix, c.serial)
	cfg := &ConsumerConfig{
		Name:              name,
		DeliverPolicy:     DeliverByStartSequencePolicy,
		OptStartSeq:       nextSeq,
		AckPolicy:         AckNonePolicy,
		InactiveThreshold: 5 * time.Minute,
		Replicas:          1,
		HeadersOnly:       c.cfg.HeadersOnly,
		MemoryStorage:     true,
		Metadata:          c.cfg.Metadata,
	}
	if len(c.cfg.FilterSubjects) == 1 {
		cfg.FilterSubject = c.cfg.FilterSubjects[0]
	} else {
		cfg.FilterSubjects = c.cfg.FilterSubjects
	}
	if c.cfg.InactiveThreshold != 0 {
		cfg.InactiveThreshold = c.cfg.InactiveThreshold
	}

	// if the cursor is not yet set, use the provided deliver policy
	if c.cursor.streamSeq != 0 {
		return cfg
	}

	// initial request, some options may be modified at that point
	cfg.DeliverPolicy = c.cfg.DeliverPolicy
	if c.cfg.DeliverPolicy == DeliverLastPerSubjectPolicy ||
		c.cfg.DeliverPolicy == DeliverLastPolicy ||
		c.cfg.DeliverPolicy == DeliverNewPolicy ||
		c.cfg.DeliverPolicy == DeliverAllPolicy {

		cfg.OptStartSeq = 0
	} else if c.cfg.DeliverPolicy == DeliverByStartTimePolicy {
		cfg.OptStartSeq = 0
		cfg.OptStartTime = c.cfg.OptStartTime
	} else {
		cfg.OptStartSeq = c.cfg.OptStartSeq
	}

	if cfg.DeliverPolicy == DeliverLastPerSubjectPolicy && len(c.cfg.FilterSubjects) == 0 {
		cfg.FilterSubjects = []string{">"}
	}

	return cfg
}

func consumeStopAfterNotify(numMsgs int, msgsLeftAfterStop chan int) PullConsumeOpt {
	return pullOptFunc(func(opts *consumeOpts) error {
		opts.StopAfter = numMsgs
		opts.stopAfterMsgsLeft = msgsLeftAfterStop
		return nil
	})
}

func messagesStopAfterNotify(numMsgs int, msgsLeftAfterStop chan int) PullMessagesOpt {
	return pullOptFunc(func(opts *consumeOpts) error {
		opts.StopAfter = numMsgs
		opts.stopAfterMsgsLeft = msgsLeftAfterStop
		return nil
	})
}

func consumeReconnectNotify() PullConsumeOpt {
	return pullOptFunc(func(opts *consumeOpts) error {
		opts.notifyOnReconnect = true
		return nil
	})
}

func messagesReconnectNotify() PullMessagesOpt {
	return pullOptFunc(func(opts *consumeOpts) error {
		opts.notifyOnReconnect = true
		return nil
	})
}

// Info returns information about the ordered consumer.
// Note that this method will fetch the latest instance of the
// consumer from the server, which can be deleted by the library at any time.
func (c *orderedConsumer) Info(ctx context.Context) (*ConsumerInfo, error) {
	c.Lock()
	defer c.Unlock()
	if c.currentConsumer == nil {
		return nil, ErrOrderedConsumerNotCreated
	}
	infoSubject := fmt.Sprintf(apiConsumerInfoT, c.stream, c.currentConsumer.name)
	var resp consumerInfoResponse

	if _, err := c.js.apiRequestJSON(ctx, infoSubject, &resp); err != nil {
		return nil, err
	}
	if resp.Error != nil {
		if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
			return nil, ErrConsumerNotFound
		}
		return nil, resp.Error
	}
	if resp.Error == nil && resp.ConsumerInfo == nil {
		return nil, ErrConsumerNotFound
	}

	c.currentConsumer.info = resp.ConsumerInfo
	return resp.ConsumerInfo, nil
}

// CachedInfo returns cached information about the consumer currently
// used by the ordered consumer. Cached info will be updated on every call
// to [Consumer.Info] or on consumer reset.
func (c *orderedConsumer) CachedInfo() *ConsumerInfo {
	c.Lock()
	defer c.Unlock()
	if c.currentConsumer == nil {
		return nil
	}
	return c.currentConsumer.info
}

type backoffOpts struct {
	// total retry attempts
	// -1 for unlimited
	attempts int
	// initial interval after which first retry will be performed
	// defaults to 1s
	initialInterval time.Duration
	// determines whether first function execution should be performed immediately
	disableInitialExecution bool
	// multiplier on each attempt
	// defaults to 2
	factor float64
	// max interval between retries
	// after reaching this value, all subsequent
	// retries will be performed with this interval
	// defaults to 1 minute
	maxInterval time.Duration
	// custom backoff intervals
	// if set, overrides all other options except attempts
	// if attempts are set, then the last interval will be used
	// for all subsequent retries after reaching the limit
	customBackoff []time.Duration
	// cancel channel
	// if set, retry will be canceled when this channel is closed
	cancel <-chan struct{}
}

func retryWithBackoff(f func(int) (bool, error), opts backoffOpts) error {
	var err error
	var shouldContinue bool
	// if custom backoff is set, use it instead of other options
	if len(opts.customBackoff) > 0 {
		if opts.attempts != 0 {
			return errors.New("cannot use custom backoff intervals when attempts are set")
		}
		for i, interval := range opts.customBackoff {
			select {
			case <-opts.cancel:
				return nil
			case <-time.After(interval):
			}
			shouldContinue, err = f(i)
			if !shouldContinue {
				return err
			}
		}
		return err
	}

	// set default options
	if opts.initialInterval == 0 {
		opts.initialInterval = 1 * time.Second
	}
	if opts.factor == 0 {
		opts.factor = 2
	}
	if opts.maxInterval == 0 {
		opts.maxInterval = 1 * time.Minute
	}
	if opts.attempts == 0 {
		return errors.New("retry attempts have to be set when not using custom backoff intervals")
	}
	interval := opts.initialInterval
	for i := 0; ; i++ {
		if i == 0 && opts.disableInitialExecution {
			time.Sleep(interval)
			continue
		}
		shouldContinue, err = f(i)
		if !shouldContinue {
			return err
		}
		if opts.attempts > 0 && i >= opts.attempts-1 {
			break
		}
		select {
		case <-opts.cancel:
			return nil
		case <-time.After(interval):
		}
		interval = time.Duration(float64(interval) * opts.factor)
		if interval >= opts.maxInterval {
			interval = opts.maxInterval
		}
	}
	return err
}