/
rmq.go
795 lines (688 loc) · 22.6 KB
/
rmq.go
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
package lowlevel
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
genericlist "github.com/bahlo/generic-list-go"
"github.com/companyzero/bisonrelay/client/clientintf"
"github.com/companyzero/bisonrelay/client/internal/multipriq"
"github.com/companyzero/bisonrelay/client/timestats"
"github.com/companyzero/bisonrelay/rpc"
"github.com/companyzero/bisonrelay/zkidentity"
"github.com/decred/slog"
"golang.org/x/sync/errgroup"
)
// rmmsg is the internal structure used to keep track of an outbound RM.
type rmmsg struct {
orm OutboundRM
replyChan chan error
rv RVID
encrypted []byte
mtx sync.Mutex
paidHash []byte
}
func (r *rmmsg) sendReply(err error) {
if r.replyChan == nil {
return
}
r.replyChan <- err
}
// rmmsgReply is the server reply to sending an individual RM. This is sent
// from individual sending goroutines back to sendLoop.
type rmmsgReply struct {
rmm *rmmsg
err error
nextInvoice string
}
type RMQDB interface {
// StoreRVPaymentAttempt should store that an attempt to pay to push
// to the given RV is being made with the given invoice.
StoreRVPaymentAttempt(RVID, string, time.Time) error
// RVHasPaymentAttempt should return the invoice and time that an
// attempt to pay to push to the RV was made (i.e. it returns the
// invoice and time saved on a prior call to StoreRVPaymentAttempt).
RVHasPaymentAttempt(RVID) (string, time.Time, error)
// DeleteRVPaymentAttempt removes the prior attempt to pay for the given
// RV.
DeleteRVPaymentAttempt(RVID) error
}
// RMQ is a queue for sending RoutedMessages (RMs) to the server. The rmq
// supports a flickering server connection: any unsent RMs are queued (FIFO
// style) until a new server session is bound via `bindToSession`.
//
// Sending an RM only fails when the rmq is shutting down or the rm failed to
// encrypt itself.
type RMQ struct {
maxMsgSize atomic.Uint32
// The following fields should only be set during setup this struct and
// are not safe for concurrent modification.
sessionChan chan clientintf.ServerSessionIntf
localID *zkidentity.FullIdentity
log slog.Logger
rmChan chan *rmmsg
enqueueDone chan struct{}
enqueueLenChan chan chan int
sendLenChan chan chan int
timingStat timestats.Tracker
db RMQDB
nextSendChan chan *rmmsg
sendDoneChan chan struct{}
}
func NewRMQ(log slog.Logger, localID *zkidentity.FullIdentity, db RMQDB) *RMQ {
if log == nil {
log = slog.Disabled
}
q := &RMQ{
sessionChan: make(chan clientintf.ServerSessionIntf),
localID: localID,
log: log,
db: db,
rmChan: make(chan *rmmsg),
enqueueDone: make(chan struct{}),
enqueueLenChan: make(chan chan int),
sendLenChan: make(chan chan int),
nextSendChan: make(chan *rmmsg),
sendDoneChan: make(chan struct{}),
timingStat: *timestats.NewTracker(250),
}
q.maxMsgSize.Store(uint32(rpc.MaxMsgSizeForVersion(rpc.MaxMsgSizeV0)))
return q
}
// MaxMsgSize returns the current max message size of the RMQ.
func (q *RMQ) MaxMsgSize() uint32 {
return q.maxMsgSize.Load()
}
// BindToSession binds the rmq to the specified server session. Queued and new
// messages will be sent via this server until it is removed or the rmq stops.
func (q *RMQ) BindToSession(sess clientintf.ServerSessionIntf) {
select {
case q.sessionChan <- sess:
case <-q.enqueueDone:
}
}
// QueueRM enqueues the given RM to be sent to the server as soon as possible.
// Returns when the rm has been queued to be sent.
//
// replyChan is written to when the RM has been received by server (which is
// determined when the RMQ receives the corresponding server ack) or if the rmq
// is stopping.
func (q *RMQ) QueueRM(orm OutboundRM, replyChan chan error) error {
encLen := orm.EncryptedLen()
maxMsgSize := q.maxMsgSize.Load()
if encLen > maxMsgSize {
return fmt.Errorf("%d > %d: %w", encLen, maxMsgSize, errORMTooLarge)
}
rmm := &rmmsg{
orm: orm,
replyChan: replyChan,
}
select { // Enqueue.
case q.rmChan <- rmm:
case <-q.enqueueDone:
return errRMQExiting
}
return nil
}
// SendRM sends the given routed message to the server whenever possible. It
// returns when the RM has been successfully written and acknowledged as received
// by the server.
func (q *RMQ) SendRM(orm OutboundRM) error {
replyChan := make(chan error)
if err := q.QueueRM(orm, replyChan); err != nil {
return err
}
return <-replyChan
}
// TimingStats returns the latest timing stats for the RMQ.
func (q *RMQ) TimingStats() []timestats.Quantile {
return q.timingStat.Quantiles()
}
// processRMAck processes the given ack'd reply from a previously sent rm rpc
// message. It returns a new server invoice, if the reply indicates success
// and there is a new invoice in it.
func (q *RMQ) processRMAck(reply interface{}) (string, error) {
q.log.Tracef("Processing RMAck reply %T", reply)
var err error
var nextInvoice string
switch reply := reply.(type) {
case rpc.RouteMessageReply:
if reply.Error != "" {
if reply.Error == rpc.ErrRMInvoicePayment.Error() {
err = rpc.ErrRMInvoicePayment
} else {
err = routeMessageReplyError{errorStr: reply.Error}
}
}
if reply.NextInvoice != "" {
nextInvoice = reply.NextInvoice
}
case *rpc.RouteMessageReply:
if reply.Error != "" {
if reply.Error == rpc.ErrRMInvoicePayment.Error() {
err = rpc.ErrRMInvoicePayment
} else {
err = routeMessageReplyError{errorStr: reply.Error}
}
}
if reply.NextInvoice != "" {
nextInvoice = reply.NextInvoice
}
case error:
err = reply
default:
err = fmt.Errorf("unknown reply of RMAck: %v", reply)
}
return nextInvoice, err
}
// fetchInvoice requests and returns an invoice for the server to pay for
// pushing an RM.
func (q *RMQ) fetchInvoice(ctx context.Context, sess clientintf.ServerSessionIntf) (string, error) {
msg := rpc.Message{Command: rpc.TaggedCmdGetInvoice}
pc := sess.PayClient()
payload := &rpc.GetInvoice{
PaymentScheme: pc.PayScheme(),
Action: rpc.InvoiceActionPush,
}
q.log.Debugf("Requesting %s invoice for next RM", payload.PaymentScheme)
replyChan := make(chan interface{})
err := sess.SendPRPC(msg, payload, replyChan)
if err != nil {
return "", err
}
// Wait to get the invoice back.
var reply interface{}
select {
case reply = <-replyChan:
case <-ctx.Done():
return "", ctx.Err()
}
switch reply := reply.(type) {
case *rpc.GetInvoiceReply:
q.log.Tracef("Received invoice reply: %q", reply.Invoice)
// Decode invoice and sanity check it.
decoded, err := pc.DecodeInvoice(ctx, reply.Invoice)
if err != nil {
return "", fmt.Errorf("unable to decode received invoice: %v", err)
}
if decoded.IsExpired(rpc.InvoiceExpiryAffordance) {
return "", fmt.Errorf("server sent expired invoice")
}
if decoded.MAtoms != 0 {
return "", fmt.Errorf("server sent invoice with amount instead of zero")
}
return reply.Invoice, nil
case error:
return "", reply
default:
return "", fmt.Errorf("unknown reply from server: %v", err)
}
}
// isRVInvoicePaid checks whether a previous payment attempt for the given RV
// and amount exists, and if it does, if the payment is still valid to be used
// as a payment token to the server.
//
// Returns the payment token, or nil if a new payment attempt is needed.
func (q *RMQ) isRVInvoicePaid(ctx context.Context, rv RVID, amt int64, pc clientintf.PaymentClient,
sess clientintf.ServerSessionIntf) (int64, []byte) {
// Check if there was a previous payment attempt for this rv.
payInvoice, payDate, err := q.db.RVHasPaymentAttempt(rv)
if err != nil || payInvoice == "" {
q.log.Debugf("Push to RV %s has no stored payment attempt", rv)
return 0, nil
}
// Check that the payment attempt isn't so old that the payment token
// is no longer usable.
ppLifetimeDuration := sess.Policy().PushPaymentLifetime
payLifetimeLimit := time.Now().Add(-ppLifetimeDuration)
if payDate.Before(payLifetimeLimit) {
q.log.Warnf("Push payment attempt stored timed out: invoice %q "+
"attempt time %s limit time %s amount %d milliatoms",
payInvoice, payDate, payLifetimeLimit, amt)
return 0, nil
}
// Create a special context to limit how long we wait for inflight
// payments to complete. This handles the case where a payment takes
// too long to complete and we might want to unblock the queue.
//
// NOTE: The payment might still be inflight, but it won't be reused in
// that case, potentially causing a double payment for the same RV.
//
// The tradeoff is having to hang on to the payment attempt for
// potentially a _long_ time (in the worse case scenario, an on-chain
// settlement, hundreds of blocks in the future) and never being able
// to send this message in a timely manner, causing broken ratchets.
//
// We assume this risk of double payment here, for the moment. In the
// future, this should be exposed to the user somehow.
const paymentTimeout = time.Minute
ctx, cancel := context.WithTimeout(ctx, paymentTimeout)
defer cancel()
// Check invoice payment actually completed.
fees, err := pc.IsPaymentCompleted(ctx, payInvoice)
if err != nil {
q.log.Warnf("Push payment attempt stored failed IsPaymentCompleted"+
"check: %v", err)
return 0, nil
}
// Paid for this RV and payment still valid. Extract payment id to
// reuse it.
decoded, err := pc.DecodeInvoice(ctx, payInvoice)
if err != nil {
q.log.Warnf("Push payment attempt stored invoice %s failed "+
"to decode: %v", payInvoice, err)
return 0, nil
}
q.log.Debugf("Reusing payment id for push to RV %s: %x", rv, decoded.ID)
return fees, decoded.ID
}
// payForRM pays for the given rm on the server.
func (q *RMQ) payForRM(ctx context.Context, rmm *rmmsg, invoice string,
sess clientintf.ServerSessionIntf) error {
// Determine payment amount.
pc := sess.PayClient()
payloadSize := rmm.orm.EncryptedLen()
pushPayRate := sess.Policy().PushPayRate
amt := int64(payloadSize) * int64(pushPayRate)
// Enforce the minimum payment policy.
if amt < int64(rpc.MinRMPushPayment) {
amt = int64(rpc.MinRMPushPayment)
}
// Check for a successful previous payment attempt.
// TODO: track fees? What about duplicate checks?
_, paidHash := q.isRVInvoicePaid(ctx, rmm.rv, amt, pc, sess)
if paidHash != nil {
rmm.mtx.Lock()
rmm.paidHash = paidHash
rmm.mtx.Unlock()
return nil
}
// Fetch invoice if needed.
var err error
var decoded clientintf.DecodedInvoice
needsInvoice := false
if invoice == "" {
needsInvoice = true
} else {
// Decode invoice, check if it's expired.
decoded, err = pc.DecodeInvoice(ctx, invoice)
if err != nil {
needsInvoice = true
} else if decoded.IsExpired(rpc.InvoiceExpiryAffordance) {
needsInvoice = true
}
}
if needsInvoice {
invoice, err = q.fetchInvoice(ctx, sess)
if err != nil {
return err
}
if decoded, err = pc.DecodeInvoice(ctx, invoice); err != nil {
return err
}
}
// Save that there's a payment attempt outbound so that on restart
// we double check if the payment completed.
if err := q.db.StoreRVPaymentAttempt(rmm.rv, invoice, time.Now()); err != nil {
return err
}
// Pay for it.
q.log.Tracef("Attempting to pay %d MAtoms to push RM %s", amt, rmm.orm)
ctx, cancel := multiCtx(ctx, sess.Context())
fees, err := pc.PayInvoiceAmount(ctx, invoice, amt)
cancel()
if err == nil {
q.log.Tracef("Payment to push RM %s to RV %s completed "+
"successfully with ID %x", rmm.orm, rmm.rv, decoded.ID)
rmm.mtx.Lock()
rmm.paidHash = decoded.ID
rmm.mtx.Unlock()
rmm.orm.PaidForRM(amt, fees)
}
return err
}
// sendToSession sends the given rm to the given session. It sends the result
// of the send attempt in replyChan.
//
// Errors which are implied to cause a reconnection and resend attempt or are
// terminating (context.Canceled, ErrSubsysExiting, etc) don't cause a reply
// to be sent, as the sendLoop will attempt to send again.
func (q *RMQ) sendToSession(ctx context.Context, rmm *rmmsg, sess clientintf.ServerSessionIntf,
invoice string, replyChan chan rmmsgReply) {
// Pay for the RM.
if err := q.payForRM(ctx, rmm, invoice, sess); err != nil {
q.log.Debugf("Unable to pay for RM %s: %v", rmm.orm, err)
// Request connection close so that we reconnect and try to
// pay again.
sess.RequestClose(err)
return
}
msg := rpc.Message{Command: rpc.TaggedCmdRouteMessage}
payload := &rpc.RouteMessage{
PaidInvoiceID: rmm.paidHash,
Rendezvous: rmm.rv,
Message: rmm.encrypted,
}
// Send it!
ackChan := make(chan interface{})
err := sess.SendPRPC(msg, payload, ackChan)
sendTime := time.Now()
if err != nil {
// Connection will be dropped, try again with next connection.
q.log.Debugf("Error sending rm %s at RV %s: %v", rmm.orm, rmm.rv, err)
return
}
q.log.Debugf("Success sending rm %s at RV %s", rmm.orm, rmm.rv)
// Wait for server ack.
var ackReply interface{}
select {
case ackReply = <-ackChan:
case <-ctx.Done():
// RMQ is quitting.
return
}
// Ack received from server. Process it.
nextInvoice, err := q.processRMAck(ackReply)
// Ignore ErrSubsysExiting. This error happens when (a) the session was
// closed or (b) the user is quitting the client. Either way, the
// sendloop will attempt to send again once the next connection is
// available (or after the client restarts).
if errors.Is(err, clientintf.ErrSubsysExiting) {
return
}
// When we receive back an invoice payment error, clear the invoice
// used for payment and try again with a fresh invoice.
if errors.Is(err, rpc.ErrRMInvoicePayment) {
rmm.mtx.Lock()
oldHash := rmm.paidHash
rmm.paidHash = nil
rmm.mtx.Unlock()
q.log.Warnf("Received ErrRMInvoicePayment when attempting to "+
"push to RV %s with old payment hash %x. Attempting again "+
"with new invoice.", rmm.rv, oldHash)
if err := q.db.DeleteRVPaymentAttempt(rmm.rv); err != nil {
q.log.Warnf("Unable to delete payment to push RV %s: %v",
rmm.rv, err)
}
q.sendToSession(ctx, rmm, sess, "", replyChan)
return
}
// Track how long it took to get the ack.
q.timingStat.Add(time.Since(sendTime))
// Today, an ack error is some processing error on the server side. So
// disconnect and hope sending through the next connection works.
//
// FIXME: This is known to fail in some circumstances, such as a
// message larger than the server accepts causing a reconnection loop.
// The server needs to return a proper error in that situation.
if err != nil {
sess.RequestClose(fmt.Errorf("RM push ack error: %v", err))
return
}
// At this point, err == nil (RM was sent and acknowledged by server).
// Send reply to original caller.
go rmm.sendReply(err)
// Mark payment as used.
if err := q.db.DeleteRVPaymentAttempt(rmm.rv); err != nil {
q.log.Warnf("Unable to delete payment to push RV %s: %v",
rmm.rv, err)
}
// Reply sendLoop that the ack for this was received.
select {
case replyChan <- rmmsgReply{rmm: rmm, err: err, nextInvoice: nextInvoice}:
case <-ctx.Done():
}
}
// Len returns the current number of outstanding messages in the RMQs enqueue
// loop and send loop.
func (q *RMQ) Len() (int, int) {
// Send the request for len.
cq, cs := make(chan int, 1), make(chan int, 1)
select {
case q.enqueueLenChan <- cq:
case <-q.enqueueDone:
return 0, 0
}
select {
case q.sendLenChan <- cs:
case <-q.enqueueDone:
return 0, 0
}
// Read the replies.
var lq, ls int
select {
case lq = <-cq:
case <-q.enqueueDone:
return 0, 0
}
select {
case ls = <-cs:
case <-q.enqueueDone:
return 0, 0
}
return lq, ls
}
// enqueueLoop is responsible for maintaining the prioritized outbound queue of
// routed messages. It attempts to build the queue as fast as possible for
// proper priorization of messages.
//
// It sends individual RMs to sendLoop whenever it needs an additional work item.
func (q *RMQ) enqueueLoop(ctx context.Context) error {
// outq tracks messages that need to be sent out.
outq := new(multipriq.MultiPriorityQueue)
emptyQueue := func() bool {
return outq.Len() == 0
}
// nextRMM to send (last dequeued value).
var nextRMM *rmmsg
// sendChan is set to either q.nextSendChan (when we have items to send)
// or nil (when we have no items to send).
var sendChan chan *rmmsg
// enqueue pushes an rmm into the outq priority queue.
enqueue := func(rmm *rmmsg) {
pri := rmm.orm.Priority()
q.log.Tracef("Queueing rm %s with priority %d", rmm.orm, pri)
outq.Push(rmm, pri)
}
// dequeue pops from outq.
dequeue := func() *rmmsg {
e := outq.Pop()
return e.(*rmmsg)
}
// The strategy for the enqueueLoop is to read as fast as possible from
// rmChan and add items to outq for proper priorization. Whenever there
// are items in outq, we fill sendChan and nextRMM with the next item
// that needs to go to the send loop. We pop from outq as soon as the
// send loop receives nextRMM.
loop:
for {
select {
case rmm := <-q.rmChan:
enqueue(rmm)
if nextRMM == nil {
sendChan = q.nextSendChan
nextRMM = dequeue()
}
case c := <-q.enqueueLenChan:
l := outq.Len()
if nextRMM != nil {
l += 1
}
c <- l
case sendChan <- nextRMM:
if emptyQueue() {
sendChan = nil
nextRMM = nil
} else {
nextRMM = dequeue()
}
case <-ctx.Done():
break loop
}
}
// Alert all outstanding elements in queue that we're exiting.
close(q.enqueueDone)
if nextRMM != nil {
go nextRMM.sendReply(errRMQExiting)
}
for !emptyQueue() {
rmm := dequeue()
go rmm.sendReply(errRMQExiting)
}
return ctx.Err()
}
// sendLoop attempts to send individual RMs to the server and waits until
// they are acked before attempting to send the next one. It receives items
// from enqueueLoop whenever needed.
//
// The sendLoop keeps track of as many messages as the server will accept
// concurrently.
func (q *RMQ) sendLoop(ctx context.Context) error {
// clientMaxPendingRMMs is the max number of pending RMMs the client
// will enforce independently of the server provided setting.
const clientMaxPendingRMMs = 256
// maxPendingRMMs is the max number of pending RMMs/invoices on the
// server.
var maxPendingRMMs int
// sess is the current server session to send RMs to.
var sess clientintf.ServerSessionIntf
// replyChan is the channel where ack replies are written.
replyChan := make(chan rmmsgReply)
// rmm tracks the current RM we're attempting to send.
rmms := make(map[*rmmsg]struct{}, 0)
// sendChan is set to q.nextSendChan when we have less pending RMs
// than maxPendingRMMs and set to nil when we need to wait until an
// RM is ack'd before we can send another.
var sendChan chan *rmmsg
// invoices is the list of available invoices returned by a push message
// and that can be used to pay for the next one.
invoices := &genericlist.List[string]{}
loop:
for {
select {
case sess = <-q.sessionChan:
q.log.Debugf("Using new server session %v", sess)
if sess == nil {
// Lost the server connection, so stop fetching
// new items to send.
invoices = &genericlist.List[string]{}
sendChan = nil
continue loop
}
maxMsgSize := uint32(sess.Policy().MaxMsgSize)
if q.maxMsgSize.Swap(maxMsgSize) != maxMsgSize {
q.log.Infof("Max message size changed to %d bytes",
maxMsgSize)
}
// We received a new session, resend outstanding items.
// The list of available invoices is empty because we
// just reconnected to the server, therefore will
// require new invoices.
q.log.Tracef("Starting to resend %d messages to server in sendloop",
len(rmms))
for rmm := range rmms {
rmm := rmm
go q.sendToSession(ctx, rmm, sess, "", replyChan)
}
// Figure out the max number of outstanding RMs we'll
// use.
newMaxPendingRMMs := sess.Policy().MaxPushInvoices
if newMaxPendingRMMs > clientMaxPendingRMMs {
newMaxPendingRMMs = clientMaxPendingRMMs
}
if newMaxPendingRMMs < maxPendingRMMs {
// We currently don't correctly handle the case
// where the max number of pending RMs is
// reduced across server reconnections, so warn
// and hope the server will accept our already
// inflight messages.
//
// In the future, this case could be handled by
// returning the rmm to the enqueue loop and
// prioritizing it over other items.
q.log.Errorf("Server operator reduced max number "+
"of RMMs from %d to %d", maxPendingRMMs, newMaxPendingRMMs)
}
maxPendingRMMs = newMaxPendingRMMs
if len(rmms) < maxPendingRMMs {
// Start accepting new items to send.
q.log.Tracef("Starting to accept new messages in sendloop")
sendChan = q.nextSendChan
}
case rmm := <-sendChan:
// Prepare the msg. This is done synchronously so that
// RMs sent to the same user are sent in ratchet
// sendcount order.
if rmm.encrypted == nil {
var err error
rmm.rv, rmm.encrypted, err = rmm.orm.EncryptedMsg()
if err != nil {
q.log.Debugf("Error encrypting RM %s: %v",
rmm.orm, err)
// This is a fatal error for this RM.
// We cannot send it anymore, so inform
// original caller of the error.
go rmm.sendReply(err)
continue loop
}
q.log.Tracef("Generated encrypted %T with %d bytes at RV %s", rmm.orm,
len(rmm.encrypted), rmm.rv)
}
// New item to send.
rmms[rmm] = struct{}{}
if len(rmms) >= maxPendingRMMs {
// Stop accepting new items to send while we
// have too many pending for confirmation.
sendChan = nil
q.log.Tracef("Pausing acceptance of new messages "+
"in sendloop due to %d >= %d",
len(rmms), maxPendingRMMs)
}
// Use an available invoice if we have one.
var invoice string
if invoices.Len() > 0 {
e := invoices.Front()
invoice = e.Value
invoices.Remove(e)
}
// Attempt send.
go q.sendToSession(ctx, rmm, sess, invoice, replyChan)
case reply := <-replyChan:
// Whatever we receive as reply, we consider this RM
// as sent.
delete(rmms, reply.rmm)
if len(rmms) < maxPendingRMMs && sess != nil && sendChan == nil {
// We just sent an item and still have a
// session bound, so we can accept more items
// to send.
sendChan = q.nextSendChan
q.log.Tracef("Restarting acceptance of new messages "+
"in sendloop due to %d < %d", len(rmms),
maxPendingRMMs)
}
// Add the invoice in the reply to the list of available
// invoices.
if reply.nextInvoice != "" {
invoices.PushBack(reply.nextInvoice)
}
case c := <-q.sendLenChan:
c <- len(rmms)
case <-ctx.Done():
break loop
}
}
// Send reply to the outstanding queue items that we're quitting.
for rmm := range rmms {
go rmm.sendReply(errRMQExiting)
}
return ctx.Err()
}
// Run the services of this rmq. Must only be called once.
func (q *RMQ) Run(ctx context.Context) error {
g, gctx := errgroup.WithContext(ctx)
g.Go(func() error { return q.enqueueLoop(gctx) })
g.Go(func() error { return q.sendLoop(gctx) })
return g.Wait()
}