-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
427 lines (353 loc) · 8.65 KB
/
client.go
File metadata and controls
427 lines (353 loc) · 8.65 KB
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
package amqprpc
import (
"context"
"errors"
"sync"
"github.com/makasim/amqpextra/publisher"
"time"
"fmt"
"github.com/google/uuid"
"github.com/makasim/amqpextra"
"github.com/makasim/amqpextra/consumer"
"github.com/makasim/amqpextra/consumer/middleware"
"github.com/streadway/amqp"
)
var ErrNotDone = errors.New("amqprpc: call is not done")
var ErrReplyQueueGoneAway = errors.New("amqprpc: reply queue has gone away")
var ErrShutdown = errors.New("amqprpc: client is shut down")
type options struct {
replyQueue ReplyQueue
consumer Consumer
preFetchCount int
workerCount int
shutdownPeriod time.Duration
}
type replyQueue struct {
name string
closeCh <-chan struct{}
}
type Client struct {
opts options
context context.Context
cancelFunc context.CancelFunc
pool *pool
consumer *consumer.Consumer
consumerStateCh chan consumer.State
consumerUnreadyCh chan error
publisher *publisher.Publisher
publisherStateCh chan publisher.State
publisherUnreadyCh chan error
replyQueueCh chan replyQueue
closeCallsCh chan struct{}
closingMutex sync.Mutex
closing bool
}
func New(
consumerConnCh,
publisherConnCh <-chan *amqpextra.Connection,
opts ...Option,
) (*Client, error) {
c := &Client{
opts: options{
replyQueue: ReplyQueue{
Name: "",
Declare: true,
AutoDelete: true,
Exclusive: true,
},
consumer: Consumer{
AutoAck: true,
Exclusive: true,
},
preFetchCount: 10,
workerCount: 10,
shutdownPeriod: 20 * time.Second,
},
context: context.Background(),
closeCallsCh: make(chan struct{}),
replyQueueCh: make(chan replyQueue),
consumerUnreadyCh: make(chan error),
consumerStateCh: make(chan consumer.State, 1),
publisherUnreadyCh: make(chan error),
publisherStateCh: make(chan publisher.State, 1),
pool: newPool(),
}
for _, opt := range opts {
opt(c)
}
handler := consumer.Wrap(
consumer.HandlerFunc(c.reply),
middleware.Recover(),
middleware.AckNack(),
)
var err error
c.consumer, err = amqpextra.NewConsumer(
consumerConnCh,
c.opts.resolveConsumerOptions(handler, c.consumerStateCh)...)
if err != nil {
return nil, err
}
c.publisher, err = amqpextra.NewPublisher(
publisherConnCh,
publisher.WithNotify(c.publisherStateCh))
if err != nil {
return nil, err
}
c.context, c.cancelFunc = context.WithCancel(c.context)
go c.serveConsumerReplyQueue()
go c.serveConsumerUnreadyState()
go c.servePublisherUnreadyState()
return c, nil
}
func (c *Client) Go(msg publisher.Message, done chan *Call) *Call {
call := newCall(msg, done, c.pool, c.opts.consumer.AutoAck)
go c.send(call)
return call
}
func (c *Client) Call(msg publisher.Message) (amqp.Delivery, error) {
doneCh := make(chan *Call, 1)
call := newCall(msg, doneCh, c.pool, c.opts.consumer.AutoAck)
c.send(call)
return call.Reply()
}
func (c *Client) Close() error {
c.closingMutex.Lock()
if c.closing {
c.closingMutex.Unlock()
return ErrShutdown
}
c.closing = true
c.closingMutex.Unlock()
defer c.cancelFunc()
defer c.consumer.Close()
defer c.publisher.Close()
shutdownPeriodTimer := time.NewTimer(c.opts.shutdownPeriod)
defer shutdownPeriodTimer.Stop()
c.publisher.Close()
select {
case <-c.publisher.NotifyClosed():
case <-shutdownPeriodTimer.C:
return fmt.Errorf("amqprpc: shutdown grace period time out: publisher not stopped")
}
var result error
if c.pool.count() > 0 {
ticker := time.NewTicker(time.Millisecond * 200)
defer ticker.Stop()
loop:
for {
select {
case <-ticker.C:
if c.pool.count() == 0 {
break loop
}
case <-shutdownPeriodTimer.C:
result = fmt.Errorf("amqprpc: shutdown grace period time out: some calls have not been done")
shutdownPeriodTimer.Reset(2 * time.Second)
break loop
}
}
}
close(c.closeCallsCh)
c.consumer.Close()
select {
case <-c.consumer.NotifyClosed():
case <-shutdownPeriodTimer.C:
return fmt.Errorf("amqprpc: shutdown grace period time out: consumer not stopped")
}
return result
}
func (c *Client) send(call *Call) {
var (
publisherUnreadyCh chan error
consumerUnreadyCh chan error
)
if call.request.ErrOnUnready {
publisherUnreadyCh = c.publisherUnreadyCh
consumerUnreadyCh = c.consumerUnreadyCh
}
if call.request.Context == nil {
call.request.Context = context.Background()
}
select {
case rq := <-c.replyQueueCh:
msg := call.Request()
msg.Publishing.ReplyTo = rq.name
msg.Publishing.CorrelationId = uuid.New().String()
msg.ResultCh = make(chan error, 1)
call.set(msg)
c.pool.set(call)
err := c.publisher.Publish(call.request)
if err != nil {
call.errored(err)
return
}
c.waitReply(call, rq)
return
case <-call.Closed():
return
// noinspection GoNilness
case err := <-consumerUnreadyCh:
call.errored(fmt.Errorf("amqprpc: consumer unready: %s", err))
return
// noinspection GoNilness
case err := <-publisherUnreadyCh:
call.errored(fmt.Errorf("amqprpc: publisher not ready: %s", err))
return
case <-call.request.Context.Done():
call.errored(call.request.Context.Err())
return
case <-c.publisher.NotifyClosed():
call.errored(ErrShutdown)
return
}
}
func (c *Client) waitReply(call *Call, rq replyQueue) {
publishResultCh := call.Request().ResultCh
for {
select {
case err := <-publishResultCh:
if err != nil {
call.errored(err)
return
}
publishResultCh = nil
continue
case <-call.Closed():
return
case <-call.closeCh:
return
case <-c.closeCallsCh:
call.errored(ErrShutdown)
return
case <-rq.closeCh:
call.errored(ErrReplyQueueGoneAway)
return
case <-call.request.Context.Done():
call.errored(call.request.Context.Err())
return
}
}
}
func (c *Client) reply(_ context.Context, msg amqp.Delivery) interface{} {
if msg.CorrelationId == "" {
return middleware.Nack
}
call, ok := c.pool.fetch(msg.CorrelationId)
if !ok {
return middleware.Nack
}
if !call.ok(msg) {
return middleware.Nack
}
return middleware.Ack
}
func (c *Client) serveConsumerReplyQueue() {
closeCh := make(chan struct{})
var localReplyQueueCh chan replyQueue
var rq replyQueue
for {
select {
case state := <-c.consumerStateCh:
if state.Unready != nil {
if rq == (replyQueue{}) {
continue
}
if c.opts.replyQueue.Name == "" || c.opts.replyQueue.AutoDelete{
localReplyQueueCh = nil
rq = replyQueue{}
close(closeCh)
closeCh = make(chan struct{})
}
continue
}
if state.Ready != nil {
localReplyQueueCh = c.replyQueueCh
rq = replyQueue{name: state.Ready.Queue, closeCh: closeCh}
}
continue
case <-c.consumer.NotifyClosed():
return
case localReplyQueueCh <- rq:
}
}
}
func (c *Client) serveConsumerUnreadyState() {
localStateCh := c.consumer.Notify(make(chan consumer.State, 1))
localConsumerUnreadyCh := c.consumerUnreadyCh
var err error = amqp.ErrClosed
for {
select {
case state, ok := <-localStateCh:
if !ok {
panic("that should never happen")
}
if state.Ready != nil {
localConsumerUnreadyCh = nil
}
if state.Unready != nil {
err = state.Unready.Err
localConsumerUnreadyCh = c.consumerUnreadyCh
}
continue
case localConsumerUnreadyCh <- err:
continue
case <-c.context.Done():
return
}
}
}
func (c *Client) servePublisherUnreadyState() {
localPublisherUnreadyCh := c.publisherUnreadyCh
var err error = amqp.ErrClosed
for {
select {
case state, ok := <-c.publisherStateCh:
if !ok {
panic("that should never happen")
}
if state.Ready != nil {
localPublisherUnreadyCh = nil
}
if state.Unready != nil {
err = state.Unready.Err
localPublisherUnreadyCh = c.publisherUnreadyCh
}
continue
case localPublisherUnreadyCh <- err:
continue
case <-c.context.Done():
return
}
}
}
func (o *options) resolveConsumerOptions(h consumer.Handler, sateCh chan consumer.State) []consumer.Option {
var (
ops = []consumer.Option{
consumer.WithWorker(consumer.NewParallelWorker(o.workerCount)),
consumer.WithNotify(sateCh),
consumer.WithQos(o.preFetchCount, false),
consumer.WithHandler(h),
}
declare = o.replyQueue.Declare
name = o.replyQueue.Name
)
if declare && name == "" {
ops = append(ops, consumer.WithTmpQueue())
} else if !declare && name == "" {
panic("declare flag or queue name for ReplyQueue must be provided in WithReplyQueue")
}
if declare && name != "" {
ops = append(ops, consumer.WithDeclareQueue(
o.replyQueue.Name,
o.replyQueue.Durable,
o.replyQueue.AutoDelete,
o.replyQueue.Exclusive,
o.replyQueue.NoWait,
o.replyQueue.Args,
))
}
if !declare && name != "" {
ops = append(ops, consumer.WithQueue(name))
}
return ops
}