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
|
package jetstream
import (
"errors"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nuid"
)
type (
pushConsumer struct {
sync.Mutex
js *jetStream
stream string
name string
info *ConsumerInfo
started atomic.Bool
}
pushSubscription struct {
sync.Mutex
id string
errs chan error
subscription *nats.Subscription
connStatusChanged chan nats.Status
closedCh chan struct{}
done chan struct{}
closed atomic.Bool
consumeOpts *pushConsumeOpts
hbMonitor *hbMonitor
idleHeartbeat time.Duration
}
pushConsumeOpts struct {
ErrHandler ConsumeErrHandler
}
PushConsumeOpt interface {
configurePushConsume(*pushConsumeOpts) error
}
)
func (p *pushConsumer) Consume(handler MessageHandler, opts ...PushConsumeOpt) (ConsumeContext, error) {
if handler == nil {
return nil, ErrHandlerRequired
}
consumeOpts := &pushConsumeOpts{}
for _, opt := range opts {
if err := opt.configurePushConsume(consumeOpts); err != nil {
return nil, err
}
}
p.Lock()
defer p.Unlock()
if p.info == nil {
return nil, ErrConsumerNotFound
}
if p.started.Load() {
return nil, ErrConsumerAlreadyConsuming
}
consumeID := nuid.Next()
sub := &pushSubscription{
id: consumeID,
errs: make(chan error, 1),
done: make(chan struct{}, 1),
consumeOpts: consumeOpts,
connStatusChanged: p.js.conn.StatusChanged(nats.CONNECTED, nats.RECONNECTING),
idleHeartbeat: p.info.Config.IdleHeartbeat,
}
sub.hbMonitor = sub.scheduleHeartbeatCheck(sub.idleHeartbeat)
internalHandler := func(msg *nats.Msg) {
if sub.hbMonitor != nil {
sub.hbMonitor.Stop()
}
defer func() {
if sub.hbMonitor != nil {
sub.hbMonitor.Reset(2 * sub.idleHeartbeat)
}
}()
status, descr := msg.Header.Get("Status"), msg.Header.Get("Description")
if status == "" {
jsMsg := p.js.toJSMsg(msg)
handler(jsMsg)
return
}
sub.Lock()
if err, terminate := sub.handleStatusMsg(msg, status, descr); err != nil {
if sub.consumeOpts.ErrHandler != nil {
sub.consumeOpts.ErrHandler(sub, err)
}
if terminate {
sub.Stop()
}
}
sub.Unlock()
}
var err error
sub.subscription, err = p.js.conn.Subscribe(p.info.Config.DeliverSubject, internalHandler)
if err != nil {
return nil, err
}
sub.subscription.SetClosedHandler(func(sid string) func(string) {
return func(subject string) {
p.started.Store(false)
sub.Lock()
defer sub.Unlock()
if sub.closedCh != nil {
close(sub.closedCh)
sub.closedCh = nil
}
}
}(sub.id))
go func() {
isConnected := true
for {
if sub.closed.Load() {
return
}
select {
case status, ok := <-sub.connStatusChanged:
if !ok {
continue
}
if status == nats.RECONNECTING {
if sub.hbMonitor != nil {
sub.hbMonitor.Stop()
}
isConnected = false
}
if status == nats.CONNECTED {
sub.Lock()
if !isConnected {
isConnected = true
if sub.hbMonitor != nil {
sub.hbMonitor.Reset(2 * sub.idleHeartbeat)
}
}
sub.Unlock()
}
case err := <-sub.errs:
sub.Lock()
if sub.consumeOpts.ErrHandler != nil {
sub.consumeOpts.ErrHandler(sub, err)
}
if errors.Is(err, ErrNoHeartbeat) {
if sub.hbMonitor != nil {
sub.hbMonitor.Reset(2 * sub.idleHeartbeat)
}
}
sub.Unlock()
case <-sub.done:
return
}
}
}()
p.started.Store(true)
return sub, nil
}
func (s *pushSubscription) handleStatusMsg(msg *nats.Msg, status, description string) (error, bool) {
switch status {
case statusControlMsg:
switch strings.ToLower(description) {
case idleHeartbeatDescr:
return nil, false
case fcRequestDescr:
if err := msg.Respond(nil); err != nil {
if s.consumeOpts.ErrHandler != nil {
s.consumeOpts.ErrHandler(s, err)
}
}
return nil, false
}
case statusConflict:
if description == consumerDeleted {
return ErrConsumerDeleted, true
}
if description == leadershipChange {
if s.consumeOpts.ErrHandler != nil {
s.consumeOpts.ErrHandler(s, ErrConsumerLeadershipChanged)
return ErrConsumerLeadershipChanged, false
}
}
}
return nil, false
}
// Stop unsubscribes from the stream and cancels subscription.
// No more messages will be received after calling this method.
// All messages that are already in the buffer are discarded.
func (s *pushSubscription) Stop() {
if !s.closed.CompareAndSwap(false, true) {
return
}
s.Lock()
defer s.Unlock()
close(s.done)
s.subscription.Unsubscribe()
if s.hbMonitor != nil {
s.hbMonitor.Stop()
}
}
// Drain unsubscribes from the stream and cancels subscription.
// All messages that are already in the buffer will be processed in callback function.
func (s *pushSubscription) Drain() {
if !s.closed.CompareAndSwap(false, true) {
return
}
s.Lock()
defer s.Unlock()
close(s.done)
s.subscription.Drain()
if s.hbMonitor != nil {
s.hbMonitor.Stop()
}
}
// Closed returns a channel that is closed when consuming is
// fully stopped/drained. When the channel is closed, no more messages
// will be received and processing is complete.
func (s *pushSubscription) Closed() <-chan struct{} {
s.Lock()
defer s.Unlock()
ch := s.closedCh
if ch == nil {
ch = make(chan struct{})
s.closedCh = ch
}
if !s.subscription.IsValid() {
close(s.closedCh)
s.closedCh = nil
}
return ch
}
func (s *pushSubscription) scheduleHeartbeatCheck(dur time.Duration) *hbMonitor {
if dur == 0 {
return nil
}
return &hbMonitor{
timer: time.AfterFunc(2*dur, func() {
s.Lock()
defer s.Unlock()
s.errs <- ErrNoHeartbeat
}),
}
}
|