-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreliable_send.go
168 lines (131 loc) · 2.45 KB
/
reliable_send.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
package cypress
import (
"sort"
"sync"
"time"
"gopkg.in/tomb.v2"
)
type Connector interface {
Connect() (*Send, error)
}
type ReliableSend struct {
connector Connector
s *Send
lock sync.Mutex
outstanding int
newMessages chan *Message
closed chan bool
flush chan struct{}
shutdown bool
nacked Messages
t tomb.Tomb
}
func NewReliableSend(c Connector, buffer int) *ReliableSend {
return &ReliableSend{
connector: c,
newMessages: make(chan *Message, buffer),
closed: make(chan bool, 1),
flush: make(chan struct{}),
}
}
func (r *ReliableSend) Start() error {
r.reconnect()
r.t.Go(r.drain)
return nil
}
func (r *ReliableSend) Close() error {
r.shutdown = true
r.t.Kill(nil)
return r.t.Wait()
}
func (r *ReliableSend) Flush() error {
r.flush <- struct{}{}
return nil
}
func (r *ReliableSend) Outstanding() int {
return r.outstanding
}
func (r *ReliableSend) Ack(m *Message) {
r.lock.Lock()
defer r.lock.Unlock()
r.outstanding--
}
func (r *ReliableSend) Nack(m *Message) {
r.lock.Lock()
defer r.lock.Unlock()
r.outstanding--
r.nacked = append(r.nacked, m)
}
func (r *ReliableSend) onClosed() {
r.closed <- true
}
func (r *ReliableSend) reconnect() {
r.lock.Lock()
var err error
if r.s != nil {
r.s.Close()
}
for {
s, err := r.connector.Connect()
if err != nil {
if r.shutdown {
r.lock.Unlock()
return
}
time.Sleep(1 * time.Second)
continue
}
s.OnClosed = r.onClosed
r.s = s
break
}
nacked := r.nacked
r.nacked = nil
r.lock.Unlock()
for idx, msg := range nacked {
r.outstanding++
err = r.s.Send(msg, r)
if err != nil {
r.lock.Lock()
r.nacked = append(nacked[idx+1:], r.nacked...)
sort.Sort(r.nacked)
// don't retry here because the OnClose handler will
// prime the closed channel, so we return from here, pick
// up the value from the channel, then this is called again.
r.lock.Unlock()
return
}
}
}
func (r *ReliableSend) Receive(m *Message) error {
r.newMessages <- m
return nil
}
func (r *ReliableSend) drain() error {
for {
select {
case <-r.closed:
r.reconnect()
case <-r.flush:
r.s.Flush()
case m := <-r.newMessages:
r.lock.Lock()
r.outstanding++
r.lock.Unlock()
r.s.Send(m, r)
case <-r.t.Dying():
for {
select {
case m := <-r.newMessages:
r.lock.Lock()
r.outstanding++
r.lock.Unlock()
r.s.Send(m, r)
default:
r.s.Close()
return nil
}
}
}
}
}