/
pubsub_nats.go
229 lines (179 loc) · 4.91 KB
/
pubsub_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
// Copyright 2019 Aporeto Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bahamut
import (
"crypto/tls"
"errors"
"fmt"
"time"
"github.com/gofrs/uuid"
"github.com/nats-io/go-nats"
"go.aporeto.io/elemental"
"go.uber.org/zap"
)
type natsPubSub struct {
natsURL string
client natsClient
retryInterval time.Duration
publishTimeout time.Duration
retryNumber int
clientID string
clusterID string
password string
username string
tlsConfig *tls.Config
}
// NewNATSPubSubClient returns a new PubSubClient backend by Nats.
func NewNATSPubSubClient(natsURL string, options ...NATSOption) PubSubClient {
n := &natsPubSub{
natsURL: natsURL,
retryInterval: 5 * time.Second,
publishTimeout: 8 * time.Second,
retryNumber: 5,
clientID: uuid.Must(uuid.NewV4()).String(),
clusterID: "test-cluster",
}
for _, opt := range options {
opt(n)
}
return n
}
func (p *natsPubSub) Publish(publication *Publication, opts ...PubSubOptPublish) error {
if p.client == nil {
return errors.New("not connected to nats. messages dropped")
}
if publication == nil {
return errors.New("publication cannot be nil")
}
config := natsPublishConfig{}
for _, opt := range opts {
opt(&config)
}
data, err := elemental.Encode(elemental.EncodingTypeMSGPACK, publication)
if err != nil {
return fmt.Errorf("unable to encode publication. message dropped: %s", err)
}
if config.useRequestMode {
msg, err := p.client.RequestWithContext(config.ctx, publication.Topic, data)
if err != nil {
return err
}
if config.replyValidator != nil {
if err := config.replyValidator(msg); err != nil {
return err
}
}
if config.responseCh != nil {
responsePub := NewPublication("")
if err := elemental.Decode(elemental.EncodingTypeMSGPACK, msg.Data, responsePub); err != nil {
return err
}
config.responseCh <- responsePub
}
return nil
}
return p.client.Publish(publication.Topic, data)
}
func (p *natsPubSub) Subscribe(pubs chan *Publication, errors chan error, topic string, opts ...PubSubOptSubscribe) func() {
config := natsSubscribeConfig{}
for _, opt := range opts {
opt(&config)
}
var sub *nats.Subscription
var err error
handler := func(m *nats.Msg) {
publication := NewPublication(topic)
if e := elemental.Decode(elemental.EncodingTypeMSGPACK, m.Data, publication); e != nil {
zap.L().Error("Unable to decode publication envelope. Message dropped.", zap.Error(e))
return
}
if m.Reply != "" {
resp := ackMessage
if config.replier != nil {
resp = config.replier(m)
}
if err := p.client.Publish(m.Reply, resp); err != nil {
zap.L().Error("Unable to send requested reply", zap.Error(err))
return
}
}
pubs <- publication
}
if config.queueGroup == "" {
sub, err = p.client.Subscribe(topic, handler)
} else {
sub, err = p.client.QueueSubscribe(topic, config.queueGroup, handler)
}
if err != nil {
errors <- err
return func() {}
}
return func() { _ = sub.Unsubscribe() }
}
func (p *natsPubSub) Connect() Waiter {
abort := make(chan struct{})
connected := make(chan bool)
go func() {
// First, we create a connection to the nats cluster.
for p.client == nil {
var err error
if p.username != "" || p.password != "" {
p.client, err = nats.Connect(p.natsURL, nats.UserInfo(p.username, p.password), nats.Secure(p.tlsConfig))
} else {
p.client, err = nats.Connect(p.natsURL, nats.Secure(p.tlsConfig))
}
if err == nil {
break
}
zap.L().Warn("Unable to connect to nats cluster. Retrying",
zap.String("url", p.natsURL),
zap.Duration("retry", p.retryInterval),
zap.Error(err),
)
select {
case <-time.After(p.retryInterval):
case <-abort:
connected <- false
return
}
}
connected <- true
}()
return connectionWaiter{
ok: connected,
abort: abort,
}
}
func (p *natsPubSub) Disconnect() error {
if err := p.client.Flush(); err != nil {
return err
}
p.client.Close()
return nil
}
func (p *natsPubSub) Ping(timeout time.Duration) error {
errChannel := make(chan error)
go func() {
if p.client.IsConnected() {
errChannel <- nil
} else if p.client.IsReconnecting() {
errChannel <- fmt.Errorf("reconnecting")
} else {
errChannel <- fmt.Errorf("connection closed")
}
}()
select {
case <-time.After(timeout):
return fmt.Errorf("connection timeout")
case err := <-errChannel:
return err
}
}