-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats.go
394 lines (323 loc) · 7.68 KB
/
nats.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Package nats provides a NATS registry using broadcast queries
package nats
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/registry"
"github.com/nats-io/nats"
)
type natsRegistry struct {
addrs []string
opts registry.Options
nopts nats.Options
queryTopic string
watchTopic string
sync.RWMutex
conn *nats.Conn
services map[string][]*registry.Service
listeners map[string]chan bool
}
var (
defaultQueryTopic = "micro.registry.nats.query"
defaultWatchTopic = "micro.registry.nats.watch"
)
func init() {
cmd.DefaultRegistries["nats"] = NewRegistry
}
func setAddrs(addrs []string) []string {
var cAddrs []string
for _, addr := range addrs {
if len(addr) == 0 {
continue
}
if !strings.HasPrefix(addr, "nats://") {
addr = "nats://" + addr
}
cAddrs = append(cAddrs, addr)
}
if len(cAddrs) == 0 {
cAddrs = []string{nats.DefaultURL}
}
return cAddrs
}
func (n *natsRegistry) newConn() (*nats.Conn, error) {
opts := n.nopts
opts.Servers = n.addrs
opts.Secure = n.opts.Secure
opts.TLSConfig = n.opts.TLSConfig
// secure might not be set
if opts.TLSConfig != nil {
opts.Secure = true
}
return opts.Connect()
}
func (n *natsRegistry) getConn() (*nats.Conn, error) {
n.Lock()
defer n.Unlock()
if n.conn != nil {
return n.conn, nil
}
c, err := n.newConn()
if err != nil {
return nil, err
}
n.conn = c
return n.conn, nil
}
func (n *natsRegistry) register(s *registry.Service) error {
conn, err := n.getConn()
if err != nil {
return err
}
n.Lock()
defer n.Unlock()
// cache service
n.services[s.Name] = addServices(n.services[s.Name], []*registry.Service{s})
// create query listener
if n.listeners[s.Name] == nil {
listener := make(chan bool)
// create a subscriber that responds to queries
sub, err := conn.Subscribe(n.queryTopic, func(m *nats.Msg) {
var result *registry.Result
if err := json.Unmarshal(m.Data, &result); err != nil {
return
}
var services []*registry.Service
switch result.Action {
// is this a get query and we own the service?
case "get":
if result.Service.Name != s.Name {
return
}
n.RLock()
services = n.services[s.Name]
n.RUnlock()
// it's a list request, but we're still only a
// subscriber for this service... so just get this service
// totally suboptimal
case "list":
n.RLock()
services = n.services[s.Name]
n.RUnlock()
default:
// does not match
return
}
// respond to query
for _, service := range services {
b, err := json.Marshal(service)
if err != nil {
continue
}
conn.Publish(m.Reply, b)
}
})
if err != nil {
return err
}
// Unsubscribe if we're told to do so
go func() {
<-listener
sub.Unsubscribe()
}()
n.listeners[s.Name] = listener
}
return nil
}
func (n *natsRegistry) deregister(s *registry.Service) error {
n.Lock()
defer n.Unlock()
// cache leftover service
services := delServices(n.services[s.Name], []*registry.Service{s})
if len(services) > 0 {
n.services[s.Name] = services
return nil
}
// delete cached service
delete(n.services, s.Name)
// delete query listener
if listener, lexists := n.listeners[s.Name]; lexists {
close(listener)
delete(n.listeners, s.Name)
}
return nil
}
func (n *natsRegistry) query(s string, quorum int) ([]*registry.Service, error) {
conn, err := n.getConn()
if err != nil {
return nil, err
}
var action string
var service *registry.Service
if len(s) > 0 {
action = "get"
service = ®istry.Service{Name: s}
} else {
action = "list"
}
inbox := nats.NewInbox()
response := make(chan *registry.Service, 10)
sub, err := conn.Subscribe(inbox, func(m *nats.Msg) {
var service *registry.Service
if err := json.Unmarshal(m.Data, &service); err != nil {
return
}
select {
case response <- service:
case <-time.After(n.opts.Timeout):
}
})
if err != nil {
return nil, err
}
defer sub.Unsubscribe()
b, err := json.Marshal(®istry.Result{Action: action, Service: service})
if err != nil {
return nil, err
}
if err := conn.PublishMsg(&nats.Msg{
Subject: n.queryTopic,
Reply: inbox,
Data: b,
}); err != nil {
return nil, err
}
timeoutChan := time.After(n.opts.Timeout)
serviceMap := make(map[string]*registry.Service)
loop:
for {
select {
case service := <-response:
key := service.Name + "-" + service.Version
srv, ok := serviceMap[key]
if ok {
srv.Nodes = append(srv.Nodes, service.Nodes...)
serviceMap[key] = srv
} else {
serviceMap[key] = service
}
if quorum > 0 && len(serviceMap[key].Nodes) >= quorum {
break loop
}
case <-timeoutChan:
break loop
}
}
var services []*registry.Service
for _, service := range serviceMap {
services = append(services, service)
}
return services, nil
}
func (n *natsRegistry) Options() registry.Options {
return n.opts
}
func (n *natsRegistry) Register(s *registry.Service, opts ...registry.RegisterOption) error {
if err := n.register(s); err != nil {
return err
}
conn, err := n.getConn()
if err != nil {
return err
}
b, err := json.Marshal(®istry.Result{Action: "create", Service: s})
if err != nil {
return err
}
return conn.Publish(n.watchTopic, b)
}
func (n *natsRegistry) Deregister(s *registry.Service) error {
if err := n.deregister(s); err != nil {
return err
}
conn, err := n.getConn()
if err != nil {
return err
}
b, err := json.Marshal(®istry.Result{Action: "delete", Service: s})
if err != nil {
return err
}
return conn.Publish(n.watchTopic, b)
}
func (n *natsRegistry) GetService(s string) ([]*registry.Service, error) {
services, err := n.query(s, getQuorum(n.opts))
if err != nil {
return nil, err
}
return services, nil
}
func (n *natsRegistry) ListServices() ([]*registry.Service, error) {
services, err := n.query("", 0)
if err != nil {
return nil, err
}
return services, nil
}
func (n *natsRegistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) {
conn, err := n.getConn()
if err != nil {
return nil, err
}
sub, err := conn.SubscribeSync(n.watchTopic)
if err != nil {
return nil, err
}
var wo registry.WatchOptions
for _, o := range opts {
o(&wo)
}
return &natsWatcher{sub, wo}, nil
}
func (n *natsRegistry) String() string {
return "nats"
}
func NewRegistry(opts ...registry.Option) registry.Registry {
options := registry.Options{
Timeout: time.Millisecond * 100,
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
natsOptions := nats.GetDefaultOptions()
if n, ok := options.Context.Value(optionsKey{}).(nats.Options); ok {
natsOptions = n
}
queryTopic := defaultQueryTopic
if qt, ok := options.Context.Value(queryTopicKey{}).(string); ok {
queryTopic = qt
}
watchTopic := defaultWatchTopic
if wt, ok := options.Context.Value(watchTopicKey{}).(string); ok {
watchTopic = wt
}
// registry.Options have higher priority than nats.Options
// only if Addrs, Secure or TLSConfig were not set through a registry.Option
// we read them from nats.Option
if len(options.Addrs) == 0 {
options.Addrs = natsOptions.Servers
}
if !options.Secure {
options.Secure = natsOptions.Secure
}
if options.TLSConfig == nil {
options.TLSConfig = natsOptions.TLSConfig
}
// check & add nats:// prefix (this makes also sure that the addresses
// stored in natsRegistry.addrs and options.Addrs are identical)
options.Addrs = setAddrs(options.Addrs)
return &natsRegistry{
addrs: options.Addrs,
opts: options,
nopts: natsOptions,
queryTopic: queryTopic,
watchTopic: watchTopic,
services: make(map[string][]*registry.Service),
listeners: make(map[string]chan bool),
}
}