forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nsq.go
361 lines (294 loc) · 6.24 KB
/
nsq.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
// Package nsq provides an NSQ broker
package nsq
import (
"context"
"math/rand"
"sync"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/codec/json"
"github.com/nsqio/go-nsq"
)
type nsqBroker struct {
lookupdAddrs []string
addrs []string
opts broker.Options
config *nsq.Config
sync.Mutex
running bool
p []*nsq.Producer
c []*subscriber
}
type publication struct {
topic string
m *broker.Message
nm *nsq.Message
opts broker.PublishOptions
}
type subscriber struct {
topic string
opts broker.SubscribeOptions
c *nsq.Consumer
// handler so we can resubcribe
h nsq.HandlerFunc
// concurrency
n int
}
var (
DefaultConcurrentHandlers = 1
)
func init() {
rand.Seed(time.Now().UnixNano())
cmd.DefaultBrokers["nsq"] = NewBroker
}
func (n *nsqBroker) Init(opts ...broker.Option) error {
for _, o := range opts {
o(&n.opts)
}
var addrs []string
for _, addr := range n.opts.Addrs {
if len(addr) > 0 {
addrs = append(addrs, addr)
}
}
if len(addrs) == 0 {
addrs = []string{"127.0.0.1:4150"}
}
n.addrs = addrs
n.configure(n.opts.Context)
return nil
}
func (n *nsqBroker) configure(ctx context.Context) {
if v, ok := ctx.Value(lookupdAddrsKey{}).([]string); ok {
n.lookupdAddrs = v
}
if v, ok := ctx.Value(consumerOptsKey{}).([]string); ok {
cfgFlag := &nsq.ConfigFlag{Config: n.config}
for _, opt := range v {
cfgFlag.Set(opt)
}
}
}
func (n *nsqBroker) Options() broker.Options {
return n.opts
}
func (n *nsqBroker) Address() string {
return n.addrs[rand.Intn(len(n.addrs))]
}
func (n *nsqBroker) Connect() error {
n.Lock()
defer n.Unlock()
if n.running {
return nil
}
var producers []*nsq.Producer
// create producers
for _, addr := range n.addrs {
p, err := nsq.NewProducer(addr, n.config)
if err != nil {
return err
}
if err = p.Ping(); err != nil {
return err
}
producers = append(producers, p)
}
// create consumers
for _, c := range n.c {
channel := c.opts.Queue
if len(channel) == 0 {
channel = uuid.New().String() + "#ephemeral"
}
cm, err := nsq.NewConsumer(c.topic, channel, n.config)
if err != nil {
return err
}
cm.AddConcurrentHandlers(c.h, c.n)
c.c = cm
if len(n.lookupdAddrs) > 0 {
c.c.ConnectToNSQLookupds(n.lookupdAddrs)
} else {
err = c.c.ConnectToNSQDs(n.addrs)
if err != nil {
return err
}
}
}
n.p = producers
n.running = true
return nil
}
func (n *nsqBroker) Disconnect() error {
n.Lock()
defer n.Unlock()
if !n.running {
return nil
}
// stop the producers
for _, p := range n.p {
p.Stop()
}
// stop the consumers
for _, c := range n.c {
c.c.Stop()
if len(n.lookupdAddrs) > 0 {
// disconnect from all lookupd
for _, addr := range n.lookupdAddrs {
c.c.DisconnectFromNSQLookupd(addr)
}
} else {
// disconnect from all nsq brokers
for _, addr := range n.addrs {
c.c.DisconnectFromNSQD(addr)
}
}
}
n.p = nil
n.running = false
return nil
}
func (n *nsqBroker) Publish(topic string, message *broker.Message, opts ...broker.PublishOption) error {
p := n.p[rand.Intn(len(n.p))]
options := broker.PublishOptions{}
for _, o := range opts {
o(&options)
}
var (
doneChan chan *nsq.ProducerTransaction
delay time.Duration
)
if options.Context != nil {
if v, ok := options.Context.Value(asyncPublishKey{}).(chan *nsq.ProducerTransaction); ok {
doneChan = v
}
if v, ok := options.Context.Value(deferredPublishKey{}).(time.Duration); ok {
delay = v
}
}
b, err := n.opts.Codec.Marshal(message)
if err != nil {
return err
}
if doneChan != nil {
if delay > 0 {
return p.DeferredPublishAsync(topic, delay, b, doneChan)
}
return p.PublishAsync(topic, b, doneChan)
} else {
if delay > 0 {
return p.DeferredPublish(topic, delay, b)
}
return p.Publish(topic, b)
}
}
func (n *nsqBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
options := broker.SubscribeOptions{
AutoAck: true,
}
for _, o := range opts {
o(&options)
}
concurrency, maxInFlight := DefaultConcurrentHandlers, DefaultConcurrentHandlers
if options.Context != nil {
if v, ok := options.Context.Value(concurrentHandlerKey{}).(int); ok {
maxInFlight, concurrency = v, v
}
if v, ok := options.Context.Value(maxInFlightKey{}).(int); ok {
maxInFlight = v
}
}
channel := options.Queue
if len(channel) == 0 {
channel = uuid.New().String() + "#ephemeral"
}
config := *n.config
config.MaxInFlight = maxInFlight
c, err := nsq.NewConsumer(topic, channel, &config)
if err != nil {
return nil, err
}
h := nsq.HandlerFunc(func(nm *nsq.Message) error {
if !options.AutoAck {
nm.DisableAutoResponse()
}
var m broker.Message
if err := n.opts.Codec.Unmarshal(nm.Body, &m); err != nil {
return err
}
return handler(&publication{
topic: topic,
m: &m,
nm: nm,
})
})
c.AddConcurrentHandlers(h, concurrency)
if len(n.lookupdAddrs) > 0 {
err = c.ConnectToNSQLookupds(n.lookupdAddrs)
} else {
err = c.ConnectToNSQDs(n.addrs)
}
if err != nil {
return nil, err
}
sub := &subscriber{
c: c,
opts: options,
topic: topic,
h: h,
n: concurrency,
}
n.c = append(n.c, sub)
return sub, nil
}
func (n *nsqBroker) String() string {
return "nsq"
}
func (p *publication) Topic() string {
return p.topic
}
func (p *publication) Message() *broker.Message {
return p.m
}
func (p *publication) Ack() error {
p.nm.Finish()
return nil
}
func (s *subscriber) Options() broker.SubscribeOptions {
return s.opts
}
func (s *subscriber) Topic() string {
return s.topic
}
func (s *subscriber) Unsubscribe() error {
s.c.Stop()
return nil
}
func NewBroker(opts ...broker.Option) broker.Broker {
options := broker.Options{
// Default codec
Codec: json.Marshaler{},
// Default context
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
var addrs []string
for _, addr := range options.Addrs {
if len(addr) > 0 {
addrs = append(addrs, addr)
}
}
if len(addrs) == 0 {
addrs = []string{"127.0.0.1:4150"}
}
n := &nsqBroker{
addrs: addrs,
opts: options,
config: nsq.NewConfig(),
}
n.configure(n.opts.Context)
return n
}