-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher.go
373 lines (319 loc) · 7.13 KB
/
publisher.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
package rcgo
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/rs/zerolog/log"
)
type Publisher struct {
id string
appName string
isStopped bool
conn *amqp.Connection
ch *amqp.Channel
configs *PublisherConfigs
replyRouter *replyRouter
}
// Stop closes the connection with the RabbitMQ server.
func (p *Publisher) Stop() error {
p.isStopped = true
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return p.StopWithContext(ctx)
}
// StopWithContext closes the connection with the RabbitMQ
// server using the specified context.
func (p *Publisher) StopWithContext(ctx context.Context) error {
p.isStopped = true
log.Info().Msgf("[PUBLISHER] Stopping %s...\n", p.appName)
if p.conn == nil {
return nil
}
cErr := make(chan error)
cDone := make(chan struct{})
doneCount := 2
go func() {
err := p.conn.Close()
if err != nil {
cErr <- err
}
cDone <- struct{}{}
}()
go func() {
err := p.replyRouter.stop(ctx)
if err != nil {
cErr <- err
}
cDone <- struct{}{}
}()
for {
select {
case <-ctx.Done():
return errors.New("ctx expired while stopping publisher")
case err := <-cErr:
return err
case <-cDone:
doneCount--
if doneCount <= 0 {
return nil
}
}
}
}
// Panics if an invalid config is provided.
func NewPublisher(
configs *PublisherConfigs,
appName string,
) *Publisher {
if configs.Url == "" {
panic("Can not connect to RabbitMQ url is blank")
}
replyRouter := newReplyRouter(
appName,
configs.ReplyTimeout.Abs(),
configs.PrefetchCount,
)
return &Publisher{
id: fmt.Sprintf("%s.%s", appName, uuid.NewString()),
appName: appName,
configs: configs,
replyRouter: replyRouter,
}
}
// Start establishes a connection to the RabbitMQ server.
// It should be invoked before publishing any messages.
func (p *Publisher) Start(
ctx context.Context,
) error {
p.isStopped = false
log.Info().Msgf("[PUBLISHER] Starting %s...\n", p.appName)
conn, err := amqp.Dial(p.configs.Url)
if err != nil {
return fmt.Errorf("failed to connect to RabbitMQ: %s", err.Error())
}
p.conn = conn
ch, err := conn.Channel()
if err != nil {
return fmt.Errorf("failed to open a channel: %s", err.Error())
}
p.ch = ch
err = p.replyRouter.listen(ctx, conn)
if err != nil {
return fmt.Errorf("failed to listen for replies: %s", err.Error())
}
return nil
}
// SendCmd publishes a command to a specified app in RabbitMQ
func (p *Publisher) SendCmd(
ctx context.Context,
appTarget string,
cmd string,
data interface{},
options ...Options,
) error {
if p.isStopped {
return ErrPublisherStopped
}
err := p.validateConn(ctx)
if err != nil {
return err
}
opts := p.firstOrDefaultOptions(options)
body, err := mapToAmqp(
uuid.NewString(),
p.appName,
cmd,
MsgTypeCmd,
data,
opts,
)
if err != nil {
return errors.New("command can not be parsed")
}
err = p.ch.PublishWithContext(
ctx,
directMessagesExchange, // exchange
appTarget, // routing key
false, // mandatory
false, // immediate
*body,
)
return err
}
// PublishEvent publishes an event to the message broker.
func (p *Publisher) PublishEvent(
ctx context.Context,
event string,
data interface{},
options ...Options,
) error {
if p.isStopped {
return ErrPublisherStopped
}
err := p.validateConn(ctx)
if err != nil {
return err
}
opts := p.firstOrDefaultOptions(options)
body, err := mapToAmqp(
uuid.NewString(),
p.appName,
event,
MsgTypeEvent,
data,
opts,
)
if err != nil {
return errors.New("event can not be parsed")
}
err = p.ch.PublishWithContext(
ctx,
eventsExchange, // exchange
event, // routing key
false, // mandatory
false, // immediate
*body,
)
return err
}
// RequestReply function serves as a wrapper
// for [rcgo.RequestReplyC] managing response
// handling and returning the reply.
func (p *Publisher) RequestReply(
ctx context.Context,
appTarget string,
query string,
data interface{},
options ...Options,
) ([]byte, error) {
if p.isStopped {
return []byte{}, ErrPublisherStopped
}
resCh, err := p.RequestReplyC(ctx, appTarget, query, data, options...)
if err != nil {
return []byte{}, err
}
var reply *Reply
select {
case reply = <-resCh:
case <-ctx.Done():
return []byte{}, ctx.Err()
}
if reply.Err != nil {
return []byte{}, reply.Err
}
return reply.Data, nil
}
// RequestReplyC sends a request to a specific
// application target, expecting a reply and
// providing a channel to receive the reply
// asynchronously.
//
// When using the returned reply channel, ensure
// to handle closure events.
// The channel will be closed when a reply is
// received or when a timeout occurs.
// Listen for the [rcgo.ErrTimeoutReply] or
// [rcgo.ErrCanceledReply] errors on the reply
// to appropriately handle it.
//
// By default, the expiration is set to the configs
// ReplyTimeout plus one second.
// If an expiration is provided in the Options,
// the smaller value will be set.
//
// Example:
//
// resCh, err := p.RequestReplyC(ctx, "anyListener", "anyListener.employees", qdata)
// if err != nil {
// return err
// }
//
// reply := <-resCh
//
// if reply.Err != nil {
// if reply.Err == ErrTimeoutReply {
// // Solely for demonstrating the handling of a timeout error.
// return err
// }
// return err
// }
//
// res := make(map[string]interface{})
//
// err = json.Unmarshal(reply.data, &res)
// if err != nil {
// return err
// }
func (p *Publisher) RequestReplyC(
ctx context.Context,
appTarget string,
query string,
data interface{},
options ...Options,
) (chan *Reply, error) {
if p.isStopped {
return nil, ErrPublisherStopped
}
err := p.validateConn(ctx)
if err != nil {
return nil, fmt.Errorf("error when request reply %s", err.Error())
}
correlationId := uuid.NewString()
opts := p.firstOrDefaultOptions(options)
rt := fmt.Sprint(p.configs.ReplyTimeout.Milliseconds())
if opts.Expiration == "" {
opts.Expiration = rt
} else {
ex1, err := strconv.ParseInt(opts.Expiration, 10, 64)
if err != nil {
opts.Expiration = rt
}
if p.configs.ReplyTimeout < time.Duration(ex1) {
opts.Expiration = rt
}
}
body, err := mapToAmqp(
correlationId,
p.replyRouter.id,
query,
MsgTypeQuery,
data,
opts,
)
if err != nil {
return nil, errors.New("command can not be parsed")
}
err = p.ch.PublishWithContext(
ctx,
directMessagesExchange, // exchange
buildQueueName(appTarget, queriesQueueSuffix), // routing key
false, // mandatory
false, // immediate
*body,
)
if err != nil {
return nil, err
}
return p.replyRouter.addReplyToListen(query, correlationId), nil
}
// validateConn validates the connection, and if an error,
// restart the publisher.
func (p *Publisher) validateConn(ctx context.Context) error {
if !p.isStopped && (p.ch == nil || p.ch.IsClosed()) {
return p.Start(ctx)
}
return nil
}
func (p *Publisher) firstOrDefaultOptions(options []Options) Options {
opts := Options{}
if len(options) > 0 {
opts = options[0]
}
return opts
}