-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreply_router.go
242 lines (197 loc) · 4.38 KB
/
reply_router.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
package rcgo
import (
"context"
"fmt"
"sync"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/rs/zerolog/log"
)
type Reply struct {
Query string
Data []byte
Err error
}
type replyStr struct {
query string
ch chan *Reply
// Timer to delete the reply when timeout.
timer *time.Timer
}
type replyRouter struct {
id string
ch *amqp.Channel
repliesMap sync.Map
timeout time.Duration
prefetchCount int
}
func newReplyRouter(
appName string,
timeout time.Duration,
prefetchCount int,
) *replyRouter {
if timeout < time.Millisecond*50 {
log.Panic().Msg("Your timeout is too short, please consider give enough timeout to your replies.")
}
return &replyRouter{
repliesMap: sync.Map{},
timeout: timeout,
prefetchCount: prefetchCount,
}
}
// stop will cancel all replies, sending a reply
// with the [rcgo.ErrCanceledReply] error, and
// subsequently closing the channels for each of
// them using the provided context.
func (r *replyRouter) stop(ctx context.Context) error {
// Wait for a moment to ensure that all replies
// that can be added while the publisher is stopped are received.
time.Sleep(time.Millisecond * 100)
r.repliesMap.Range(func(_ interface{}, v interface{}) bool {
replyStr := v.(replyStr)
select {
case <-ctx.Done():
ctx.Err()
return false
default:
}
if !replyStr.timer.Stop() {
<-replyStr.timer.C
return true
}
replyStr.ch <- &Reply{
Query: replyStr.query,
Err: ErrCanceledReply,
}
close(replyStr.ch)
return true
})
return nil
}
func (r *replyRouter) listen(ctx context.Context, conn *amqp.Connection) error {
// We need to ensure that the id is unique to avoid
// conflicts with other reply routers.
r.id = fmt.Sprintf("%s.%s", uuid.New().String(), "reply")
ch, err := conn.Channel()
failOnError(err, "Failed to open a reply channel")
r.ch = ch
err = ch.ExchangeDeclare(
globalReplyExchange,
"topic",
true,
false,
false,
false,
nil,
)
if err != nil {
return err
}
queriesQueue, err := r.ch.QueueDeclare(
r.id, // name
true, // durable
false, // delete when unused
true, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
err = r.ch.QueueBind(
queriesQueue.Name, // queue name
r.id, // routing key
globalReplyExchange, // exchange
false,
nil,
)
if err != nil {
return err
}
err = r.ch.Qos(r.prefetchCount, 0, false)
if err != nil {
return err
}
msgs, err := r.ch.Consume(
queriesQueue.Name, // queue
r.id, // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return err
}
go r.msgsWorker(ctx, msgs)
return nil
}
func (r *replyRouter) msgsWorker(ctx context.Context, msgs <-chan amqp.Delivery) {
for msg := range msgs {
// Create a copy
m := msg
corrId := m.CorrelationId
if corrId == "" {
corrId, ok := m.Headers[correlationIDHeader]
if !ok || corrId == "" {
err := m.Reject(false)
if err != nil {
log.Error().Msgf("can not ack/reject msg: %s", err.Error())
continue
}
continue
}
}
if v, ok := r.repliesMap.LoadAndDelete(corrId); ok {
replyStr := v.(replyStr)
// Verify if the timeout has already elapsed.
if !replyStr.timer.Stop() {
err := m.Reject(false)
if err != nil {
log.Error().Msgf("can not ack/reject msg: %s", err.Error())
continue
}
continue
}
replyStr.ch <- &Reply{
Query: replyStr.query,
Data: m.Body,
Err: nil,
}
close(replyStr.ch)
err := m.Ack(false)
if err != nil {
log.Error().Msgf("can not ack/reject msg: %s", err.Error())
continue
}
continue
}
// Reject if no in repliesMap
m.Reject(false)
}
}
func (r *replyRouter) addReplyToListen(query string, correlationId string) chan *Reply {
ch := make(chan *Reply, 1)
timer := time.AfterFunc(r.timeout, func() {
r.cleanReply(correlationId)
})
r.repliesMap.Store(correlationId, replyStr{
query: query,
ch: ch,
timer: timer,
})
return ch
}
func (r *replyRouter) cleanReply(correlationId string) {
v, ok := r.repliesMap.LoadAndDelete(correlationId)
if !ok {
return
}
replyStr := v.(replyStr)
replyStr.ch <- &Reply{
Err: ErrTimeoutReply,
}
close(replyStr.ch)
}