-
Notifications
You must be signed in to change notification settings - Fork 13
/
blaze_ack.go
95 lines (79 loc) · 1.55 KB
/
blaze_ack.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
package mixin
import (
"container/list"
"context"
"sync"
"time"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
type AckQueue struct {
list list.List
mux sync.Mutex
}
func (q *AckQueue) pushBack(requests ...*AcknowledgementRequest) {
q.mux.Lock()
for _, req := range requests {
q.list.PushBack(req)
}
q.mux.Unlock()
}
func (q *AckQueue) pushFront(requests ...*AcknowledgementRequest) {
q.mux.Lock()
for _, req := range requests {
q.list.PushFront(req)
}
q.mux.Unlock()
}
func (q *AckQueue) pull(limit int) []*AcknowledgementRequest {
q.mux.Lock()
if limit > q.list.Len() {
limit = q.list.Len()
}
ids := make([]*AcknowledgementRequest, 0, limit)
for i := 0; i < limit; i++ {
e := q.list.Front()
ids = append(ids, e.Value.(*AcknowledgementRequest))
q.list.Remove(e)
}
q.mux.Unlock()
return ids
}
type blazeHandler struct {
*Client
queue AckQueue
}
func (b *blazeHandler) ack(ctx context.Context) error {
var (
g errgroup.Group
sem = semaphore.NewWeighted(5)
dur = time.Second
)
for {
select {
case <-ctx.Done():
return g.Wait()
case <-time.After(dur):
requests := b.queue.pull(ackBatch)
if len(requests) < ackBatch {
dur = time.Second
} else {
dur = 200 * time.Millisecond
}
if len(requests) > 0 {
if !sem.TryAcquire(1) {
b.queue.pushFront(requests...)
break
}
g.Go(func() error {
defer sem.Release(1)
err := b.SendAcknowledgements(ctx, requests)
if err != nil {
b.queue.pushFront(requests...)
}
return err
})
}
}
}
}