Debian Codegraph @

jetstream/publish.go

raw
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 "crypto/sha256"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "math/rand"
23 "strconv"
24 "strings"
25 "sync"
26 "time"
27
28 "github.com/nats-io/nats.go"
29 "github.com/nats-io/nuid"
30 )
31
32 type (
33 asyncPublisherOpts struct {
34 // For async publish error handling.
35 aecb MsgErrHandler
36 // For async publish ack handling.
37 ackcb MsgAckHandler
38 // Max async pub ack in flight
39 maxpa int
40 // ackTimeout is the max time to wait for an ack.
41 ackTimeout time.Duration
42 }
43
44 // PublishOpt are the options that can be passed to Publish methods.
45 PublishOpt func(*pubOpts) error
46
47 pubOpts struct {
48 id string
49 lastMsgID string // Expected last msgId
50 stream string // Expected stream name
51 lastSeq *uint64 // Expected last sequence
52 lastSubjectSeq *uint64 // Expected last sequence for subject
53 lastSubject string // Expected subject for last sequence
54 ttl time.Duration // Message TTL
55 schedule string // Schedule expression
56 scheduleTarget string // Target subject for scheduled messages
57 scheduleSource string // Source subject for sampling
58 scheduleTTL string // TTL for generated messages
59 scheduleTZ string // Time zone for cron schedules
60 scheduleRollup string // Rollup for generated messages
61
62 // Publish retries for NoResponders err.
63 retryWait time.Duration // Retry wait between attempts
64 retryAttempts int // Retry attempts
65
66 // stallWait is the max wait of a async pub ack.
67 stallWait time.Duration
68
69 // internal option to re-use existing paf in case of retry.
70 pafRetry *pubAckFuture
71 }
72
73 // PubAckFuture is a future for a PubAck.
74 // It can be used to wait for a PubAck or an error after an async publish.
75 PubAckFuture interface {
76 // Ok returns a receive only channel that can be used to get a PubAck.
77 Ok() <-chan *PubAck
78
79 // Err returns a receive only channel that can be used to get the error from an async publish.
80 Err() <-chan error
81
82 // Msg returns the message that was sent to the server.
83 Msg() *nats.Msg
84 }
85
86 pubAckFuture struct {
87 jsClient *jetStreamClient
88 msg *nats.Msg
89 retries int
90 maxRetries int
91 retryWait time.Duration
92 ack *PubAck
93 err error
94 errCh chan error
95 doneCh chan *PubAck
96 reply string
97 timeout *time.Timer
98 }
99
100 jetStreamClient struct {
101 asyncPublishContext
102 asyncPublisherOpts
103 }
104
105 // MsgErrHandler is used to process asynchronous errors from JetStream
106 // PublishAsync. It will return the original message sent to the server for
107 // possible retransmitting and the error encountered.
108 MsgErrHandler func(JetStream, *nats.Msg, error)
109
110 // MsgAckHandler is used to process asynchronous acks from JetStream
111 // PublishAsync. It will return the original message sent to the server
112 // and the resulting PubAck.
113 //
114 // The handler is invoked synchronously on the ack-processing goroutine,
115 // so it must not block or call methods on the PubAckFuture returned by
116 // the corresponding PublishAsync/PublishMsgAsync call, as doing so may
117 // deadlock.
118 MsgAckHandler func(JetStream, *nats.Msg, *PubAck)
119
120 asyncPublishContext struct {
121 sync.RWMutex
122 replyPrefix string
123 replySub *nats.Subscription
124 acks map[string]*pubAckFuture
125 stallCh chan struct{}
126 doneCh chan struct{}
127 rr *rand.Rand
128 // channel to signal when server is disconnected or conn is closed
129 connStatusCh chan (nats.Status)
130 }
131
132 pubAckResponse struct {
133 apiResponse
134 *PubAck
135 }
136
137 // PubAck is an ack received after successfully publishing a message.
138 PubAck struct {
139 // Stream is the stream name the message was published to.
140 Stream string `json:"stream"`
141
142 // Sequence is the stream sequence number of the message.
143 Sequence uint64 `json:"seq"`
144
145 // Duplicate indicates whether the message was a duplicate.
146 // Duplicate can be detected using the [MsgIDHeader] and [StreamConfig.Duplicates].
147 Duplicate bool `json:"duplicate,omitempty"`
148
149 // Domain is the domain the message was published to.
150 Domain string `json:"domain,omitempty"`
151
152 Value string `json:"val,omitempty"`
153 }
154 )
155
156 const (
157 // Default time wait between retries on Publish if err is ErrNoResponders.
158 DefaultPubRetryWait = 250 * time.Millisecond
159
160 // Default number of retries
161 DefaultPubRetryAttempts = 2
162 )
163
164 const (
165 statusHdr = "Status"
166
167 rdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
168 base = 62
169 )
170
171 // Publish performs a synchronous publish to a stream and waits for ack
172 // from server. It accepts subject name (which must be bound to a stream)
173 // and message payload.
174 func (js *jetStream) Publish(ctx context.Context, subj string, data []byte, opts ...PublishOpt) (*PubAck, error) {
175 return js.PublishMsg(ctx, &nats.Msg{Subject: subj, Data: data}, opts...)
176 }
177
178 // PublishMsg performs a synchronous publish to a stream and waits for
179 // ack from server. It accepts subject name (which must be bound to a
180 // stream) and nats.Message.
181 func (js *jetStream) PublishMsg(ctx context.Context, m *nats.Msg, opts ...PublishOpt) (*PubAck, error) {
182 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
183 if cancel != nil {
184 defer cancel()
185 }
186 o := pubOpts{
187 retryWait: DefaultPubRetryWait,
188 retryAttempts: DefaultPubRetryAttempts,
189 }
190 if len(opts) > 0 {
191 if m.Header == nil {
192 m.Header = nats.Header{}
193 }
194 for _, opt := range opts {
195 if err := opt(&o); err != nil {
196 return nil, err
197 }
198 }
199 }
200 if o.stallWait > 0 {
201 return nil, fmt.Errorf("%w: stall wait cannot be set to sync publish", ErrInvalidOption)
202 }
203
204 if o.id != "" {
205 m.Header.Set(MsgIDHeader, o.id)
206 }
207 if o.lastMsgID != "" {
208 m.Header.Set(ExpectedLastMsgIDHeader, o.lastMsgID)
209 }
210 if o.stream != "" {
211 m.Header.Set(ExpectedStreamHeader, o.stream)
212 }
213 if o.lastSeq != nil {
214 m.Header.Set(ExpectedLastSeqHeader, strconv.FormatUint(*o.lastSeq, 10))
215 }
216 if o.lastSubjectSeq != nil {
217 m.Header.Set(ExpectedLastSubjSeqHeader, strconv.FormatUint(*o.lastSubjectSeq, 10))
218 }
219 if o.lastSubject != "" {
220 m.Header.Set(ExpectedLastSubjSeqSubjHeader, o.lastSubject)
221 m.Header.Set(ExpectedLastSubjSeqHeader, strconv.FormatUint(*o.lastSubjectSeq, 10))
222 }
223 if o.ttl > 0 {
224 m.Header.Set(MsgTTLHeader, o.ttl.String())
225 }
226 if o.schedule != "" {
227 m.Header.Set(ScheduleHeader, o.schedule)
228 }
229 if o.scheduleTarget != "" {
230 m.Header.Set(ScheduleTargetHeader, o.scheduleTarget)
231 }
232 if o.scheduleSource != "" {
233 m.Header.Set(ScheduleSourceHeader, o.scheduleSource)
234 }
235 if o.scheduleTTL != "" {
236 m.Header.Set(ScheduleTTLHeader, o.scheduleTTL)
237 }
238 if o.scheduleTZ != "" {
239 m.Header.Set(ScheduleTimeZoneHeader, o.scheduleTZ)
240 }
241 if o.scheduleRollup != "" {
242 m.Header.Set(ScheduleRollupHeader, o.scheduleRollup)
243 }
244
245 var resp *nats.Msg
246 var err error
247
248 resp, err = js.conn.RequestMsgWithContext(ctx, m)
249
250 if err != nil {
251 for r := 0; errors.Is(err, nats.ErrNoResponders) && (r < o.retryAttempts || o.retryAttempts < 0); r++ {
252 // To protect against small blips in leadership changes etc, if we get a no responders here retry.
253 select {
254 case <-ctx.Done():
255 case <-time.After(o.retryWait):
256 }
257 resp, err = js.conn.RequestMsgWithContext(ctx, m)
258 }
259 if err != nil {
260 if errors.Is(err, nats.ErrNoResponders) {
261 return nil, ErrNoStreamResponse
262 }
263 return nil, err
264 }
265 }
266
267 var ackResp pubAckResponse
268 if err := json.Unmarshal(resp.Data, &ackResp); err != nil {
269 return nil, ErrInvalidJSAck
270 }
271 if ackResp.Error != nil {
272 return nil, fmt.Errorf("nats: %w", ackResp.Error)
273 }
274 if ackResp.PubAck == nil || ackResp.PubAck.Stream == "" {
275 return nil, ErrInvalidJSAck
276 }
277 return ackResp.PubAck, nil
278 }
279
280 // PublishAsync performs an asynchronous publish to a stream and returns
281 // [PubAckFuture] interface. It accepts subject name (which must be bound
282 // to a stream) and message payload.
283 func (js *jetStream) PublishAsync(subj string, data []byte, opts ...PublishOpt) (PubAckFuture, error) {
284 return js.PublishMsgAsync(&nats.Msg{Subject: subj, Data: data}, opts...)
285 }
286
287 // PublishMsgAsync performs an asynchronous publish to a stream and
288 // returns [PubAckFuture] interface. It accepts subject name (which must
289 // be bound to a stream) and nats.Message.
290 func (js *jetStream) PublishMsgAsync(m *nats.Msg, opts ...PublishOpt) (PubAckFuture, error) {
291 o := pubOpts{
292 retryWait: DefaultPubRetryWait,
293 retryAttempts: DefaultPubRetryAttempts,
294 }
295 if len(opts) > 0 {
296 if m.Header == nil {
297 m.Header = nats.Header{}
298 }
299 for _, opt := range opts {
300 if err := opt(&o); err != nil {
301 return nil, err
302 }
303 }
304 }
305 defaultStallWait := 200 * time.Millisecond
306
307 stallWait := defaultStallWait
308 if o.stallWait > 0 {
309 stallWait = o.stallWait
310 }
311
312 if o.id != "" {
313 m.Header.Set(MsgIDHeader, o.id)
314 }
315 if o.lastMsgID != "" {
316 m.Header.Set(ExpectedLastMsgIDHeader, o.lastMsgID)
317 }
318 if o.stream != "" {
319 m.Header.Set(ExpectedStreamHeader, o.stream)
320 }
321 if o.lastSeq != nil {
322 m.Header.Set(ExpectedLastSeqHeader, strconv.FormatUint(*o.lastSeq, 10))
323 }
324 if o.lastSubjectSeq != nil {
325 m.Header.Set(ExpectedLastSubjSeqHeader, strconv.FormatUint(*o.lastSubjectSeq, 10))
326 }
327 if o.lastSubject != "" {
328 m.Header.Set(ExpectedLastSubjSeqSubjHeader, o.lastSubject)
329 m.Header.Set(ExpectedLastSubjSeqHeader, strconv.FormatUint(*o.lastSubjectSeq, 10))
330 }
331 if o.ttl > 0 {
332 m.Header.Set(MsgTTLHeader, o.ttl.String())
333 }
334 if o.schedule != "" {
335 m.Header.Set(ScheduleHeader, o.schedule)
336 }
337 if o.scheduleTarget != "" {
338 m.Header.Set(ScheduleTargetHeader, o.scheduleTarget)
339 }
340 if o.scheduleSource != "" {
341 m.Header.Set(ScheduleSourceHeader, o.scheduleSource)
342 }
343 if o.scheduleTTL != "" {
344 m.Header.Set(ScheduleTTLHeader, o.scheduleTTL)
345 }
346 if o.scheduleTZ != "" {
347 m.Header.Set(ScheduleTimeZoneHeader, o.scheduleTZ)
348 }
349 if o.scheduleRollup != "" {
350 m.Header.Set(ScheduleRollupHeader, o.scheduleRollup)
351 }
352
353 paf := o.pafRetry
354 if paf == nil && m.Reply != "" {
355 return nil, ErrAsyncPublishReplySubjectSet
356 }
357
358 var id string
359 var reply string
360
361 // register new paf if not retrying
362 if paf == nil {
363 var err error
364 reply, err = js.newAsyncReply()
365 if err != nil {
366 return nil, fmt.Errorf("nats: error creating async reply handler: %s", err)
367 }
368 id = reply[js.opts.replyPrefixLen:]
369 paf = &pubAckFuture{msg: m, jsClient: js.publisher, maxRetries: o.retryAttempts, retryWait: o.retryWait, reply: reply}
370 numPending, maxPending := js.registerPAF(id, paf)
371
372 if maxPending > 0 && numPending > maxPending {
373 select {
374 case <-js.asyncStall():
375 case <-time.After(stallWait):
376 js.clearPAF(id)
377 return nil, ErrTooManyStalledMsgs
378 }
379 }
380 if js.publisher.ackTimeout > 0 {
381 paf.timeout = time.AfterFunc(js.publisher.ackTimeout, func() {
382 js.publisher.Lock()
383 defer js.publisher.Unlock()
384
385 if _, ok := js.publisher.acks[id]; !ok {
386 // paf has already been resolved
387 // while waiting for the lock
388 return
389 }
390
391 // ack timed out, remove from pending acks
392 delete(js.publisher.acks, id)
393
394 // check on anyone stalled and waiting.
395 if js.publisher.stallCh != nil && len(js.publisher.acks) < js.publisher.maxpa {
396 close(js.publisher.stallCh)
397 js.publisher.stallCh = nil
398 }
399
400 // send error to user
401 paf.err = ErrAsyncPublishTimeout
402 if paf.errCh != nil {
403 paf.errCh <- paf.err
404 }
405
406 // call error callback if set
407 if js.publisher.asyncPublisherOpts.aecb != nil {
408 js.publisher.asyncPublisherOpts.aecb(js, paf.msg, ErrAsyncPublishTimeout)
409 }
410
411 // check on anyone one waiting on done status.
412 if js.publisher.doneCh != nil && len(js.publisher.acks) == 0 {
413 close(js.publisher.doneCh)
414 js.publisher.doneCh = nil
415 }
416 })
417 }
418 } else {
419 // when retrying, get the ID from existing reply subject
420 reply = paf.reply
421 if paf.timeout != nil {
422 paf.timeout.Reset(js.publisher.ackTimeout)
423 }
424 id = reply[js.opts.replyPrefixLen:]
425 }
426
427 pubMsg := &nats.Msg{
428 Subject: m.Subject,
429 Reply: reply,
430 Data: m.Data,
431 Header: m.Header,
432 }
433 if err := js.conn.PublishMsg(pubMsg); err != nil {
434 js.clearPAF(id)
435 return nil, err
436 }
437
438 return paf, nil
439 }
440
441 // For quick token lookup etc.
442 const (
443 aReplyTokensize = 6
444 )
445
446 func (js *jetStream) newAsyncReply() (string, error) {
447 js.publisher.Lock()
448 if js.publisher.replySub == nil {
449 // Create our wildcard reply subject.
450 sha := sha256.New()
451 sha.Write([]byte(nuid.Next()))
452 b := sha.Sum(nil)
453 for i := 0; i < aReplyTokensize; i++ {
454 b[i] = rdigits[int(b[i]%base)]
455 }
456 js.publisher.replyPrefix = fmt.Sprintf("%s%s.", js.opts.replyPrefix, b[:aReplyTokensize])
457 sub, err := js.conn.Subscribe(fmt.Sprintf("%s*", js.publisher.replyPrefix), js.handleAsyncReply)
458 if err != nil {
459 js.publisher.Unlock()
460 return "", err
461 }
462 js.publisher.replySub = sub
463 js.publisher.rr = rand.New(rand.NewSource(time.Now().UnixNano()))
464 }
465 if js.publisher.connStatusCh == nil {
466 js.publisher.connStatusCh = js.conn.StatusChanged(nats.RECONNECTING, nats.CLOSED)
467 go js.resetPendingAcksOnReconnect()
468 }
469 var sb strings.Builder
470 sb.Grow(len(js.publisher.replyPrefix) + aReplyTokensize)
471 sb.WriteString(js.publisher.replyPrefix)
472 for {
473 rn := js.publisher.rr.Int63()
474 var b [aReplyTokensize]byte
475 for i, l := 0, rn; i < len(b); i++ {
476 b[i] = rdigits[l%base]
477 l /= base
478 }
479 if _, ok := js.publisher.acks[string(b[:])]; ok {
480 continue
481 }
482 sb.Write(b[:])
483 break
484 }
485
486 js.publisher.Unlock()
487 return sb.String(), nil
488 }
489
490 // Handle an async reply from PublishAsync.
491 func (js *jetStream) handleAsyncReply(m *nats.Msg) {
492 if len(m.Subject) <= js.opts.replyPrefixLen {
493 return
494 }
495 id := m.Subject[js.opts.replyPrefixLen:]
496
497 js.publisher.Lock()
498
499 paf := js.getPAF(id)
500 if paf == nil {
501 js.publisher.Unlock()
502 return
503 }
504
505 closeStc := func() {
506 // Check on anyone stalled and waiting.
507 if js.publisher.stallCh != nil && len(js.publisher.acks) < js.publisher.maxpa {
508 close(js.publisher.stallCh)
509 js.publisher.stallCh = nil
510 }
511 }
512
513 closeDchFn := func() func() {
514 var dch chan struct{}
515 // Check on anyone one waiting on done status.
516 if js.publisher.doneCh != nil && len(js.publisher.acks) == 0 {
517 dch = js.publisher.doneCh
518 js.publisher.doneCh = nil
519 }
520 // Return function to close done channel which
521 // should be deferred so that error is processed and
522 // can be checked.
523 return func() {
524 if dch != nil {
525 close(dch)
526 }
527 }
528 }
529
530 if paf.timeout != nil {
531 paf.timeout.Stop()
532 }
533
534 // Process no responders etc.
535 if len(m.Data) == 0 && m.Header.Get(statusHdr) == statusNoResponders {
536 if paf.retries < paf.maxRetries {
537 paf.retries++
538 time.AfterFunc(paf.retryWait, func() {
539 js.publisher.Lock()
540 paf := js.getPAF(id)
541 js.publisher.Unlock()
542 if paf == nil {
543 return
544 }
545 _, err := js.PublishMsgAsync(paf.msg, func(po *pubOpts) error {
546 po.pafRetry = paf
547 return nil
548 })
549 if err != nil {
550 js.publisher.Lock()
551 js.handleAsyncErrAndUnlock(paf, err)
552 }
553 })
554 js.publisher.Unlock()
555 return
556 }
557 delete(js.publisher.acks, id)
558 closeStc()
559 defer closeDchFn()()
560 js.handleAsyncErrAndUnlock(paf, ErrNoStreamResponse)
561 return
562 }
563
564 // Remove
565 delete(js.publisher.acks, id)
566 closeStc()
567 defer closeDchFn()()
568
569 var pa pubAckResponse
570 if err := json.Unmarshal(m.Data, &pa); err != nil {
571 js.handleAsyncErrAndUnlock(paf, ErrInvalidJSAck)
572 return
573 }
574 if pa.Error != nil {
575 js.handleAsyncErrAndUnlock(paf, pa.Error)
576 return
577 }
578 if pa.PubAck == nil || pa.PubAck.Stream == "" {
579 js.handleAsyncErrAndUnlock(paf, ErrInvalidJSAck)
580 return
581 }
582
583 // So here we have received a proper puback.
584 paf.ack = pa.PubAck
585 if paf.doneCh != nil {
586 paf.doneCh <- paf.ack
587 }
588 cb := js.publisher.asyncPublisherOpts.ackcb
589 js.publisher.Unlock()
590 if cb != nil {
591 cb(js, paf.msg, paf.ack)
592 }
593 }
594
595 func (js *jetStream) handleAsyncErrAndUnlock(paf *pubAckFuture, err error) {
596 paf.err = err
597 if paf.errCh != nil {
598 paf.errCh <- paf.err
599 }
600 cb := js.publisher.asyncPublisherOpts.aecb
601 js.publisher.Unlock()
602 if cb != nil {
603 cb(js, paf.msg, err)
604 }
605 }
606
607 func (js *jetStream) resetPendingAcksOnReconnect() {
608 js.publisher.Lock()
609 connStatusCh := js.publisher.connStatusCh
610 js.publisher.Unlock()
611 for {
612 newStatus, ok := <-connStatusCh
613 if !ok || newStatus == nats.CLOSED {
614 return
615 }
616 js.publisher.Lock()
617 errCb := js.publisher.asyncPublisherOpts.aecb
618 for id, paf := range js.publisher.acks {
619 paf.err = nats.ErrDisconnected
620 if paf.errCh != nil {
621 paf.errCh <- paf.err
622 }
623 if errCb != nil {
624 defer errCb(js, paf.msg, nats.ErrDisconnected)
625 }
626 delete(js.publisher.acks, id)
627 }
628 if js.publisher.doneCh != nil {
629 close(js.publisher.doneCh)
630 js.publisher.doneCh = nil
631 }
632 js.publisher.Unlock()
633 }
634 }
635
636 // registerPAF will register for a PubAckFuture.
637 func (js *jetStream) registerPAF(id string, paf *pubAckFuture) (int, int) {
638 js.publisher.Lock()
639 if js.publisher.acks == nil {
640 js.publisher.acks = make(map[string]*pubAckFuture)
641 }
642 js.publisher.acks[id] = paf
643 np := len(js.publisher.acks)
644 maxpa := js.publisher.asyncPublisherOpts.maxpa
645 js.publisher.Unlock()
646 return np, maxpa
647 }
648
649 // Lock should be held.
650 func (js *jetStream) getPAF(id string) *pubAckFuture {
651 if js.publisher.acks == nil {
652 return nil
653 }
654 return js.publisher.acks[id]
655 }
656
657 // clearPAF will remove a PubAckFuture that was registered.
658 func (js *jetStream) clearPAF(id string) {
659 js.publisher.Lock()
660 delete(js.publisher.acks, id)
661 js.publisher.Unlock()
662 }
663
664 func (js *jetStream) asyncStall() <-chan struct{} {
665 js.publisher.Lock()
666 if js.publisher.stallCh == nil {
667 js.publisher.stallCh = make(chan struct{})
668 }
669 stc := js.publisher.stallCh
670 js.publisher.Unlock()
671 return stc
672 }
673
674 func (paf *pubAckFuture) Ok() <-chan *PubAck {
675 paf.jsClient.Lock()
676 defer paf.jsClient.Unlock()
677
678 if paf.doneCh == nil {
679 paf.doneCh = make(chan *PubAck, 1)
680 if paf.ack != nil {
681 paf.doneCh <- paf.ack
682 }
683 }
684
685 return paf.doneCh
686 }
687
688 func (paf *pubAckFuture) Err() <-chan error {
689 paf.jsClient.Lock()
690 defer paf.jsClient.Unlock()
691
692 if paf.errCh == nil {
693 paf.errCh = make(chan error, 1)
694 if paf.err != nil {
695 paf.errCh <- paf.err
696 }
697 }
698
699 return paf.errCh
700 }
701
702 func (paf *pubAckFuture) Msg() *nats.Msg {
703 paf.jsClient.RLock()
704 defer paf.jsClient.RUnlock()
705 return paf.msg
706 }
707
708 // PublishAsyncPending returns the number of async publishes outstanding
709 // for this context.
710 func (js *jetStream) PublishAsyncPending() int {
711 js.publisher.RLock()
712 defer js.publisher.RUnlock()
713 return len(js.publisher.acks)
714 }
715
716 // PublishAsyncComplete returns a channel that will be closed when all
717 // outstanding asynchronously published messages are acknowledged by the
718 // server.
719 func (js *jetStream) PublishAsyncComplete() <-chan struct{} {
720 js.publisher.Lock()
721 defer js.publisher.Unlock()
722 if js.publisher.doneCh == nil {
723 js.publisher.doneCh = make(chan struct{})
724 }
725 dch := js.publisher.doneCh
726 if len(js.publisher.acks) == 0 {
727 close(js.publisher.doneCh)
728 js.publisher.doneCh = nil
729 }
730 return dch
731 }