-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.go
375 lines (292 loc) · 8.73 KB
/
client.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
package courier
import (
"context"
"errors"
"fmt"
"math/rand"
"os"
"sync"
"sync/atomic"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
// ErrClientNotInitialized is returned when the client is not initialized
var ErrClientNotInitialized = errors.New("courier: client not initialized")
var newClientFunc = defaultNewClientFunc()
// Client allows to communicate with an MQTT broker
type Client struct {
options *clientOptions
subscriptions map[string]*subscriptionMeta
mqttClient mqtt.Client
mqttClients map[string]*internalState
publisher Publisher
subscriber Subscriber
unsubscriber Unsubscriber
pMiddlewares []publishMiddleware
sMiddlewares []subscribeMiddleware
usMiddlewares []unsubscribeMiddleware
rrCounter *atomicCounter
multiConnRevision atomic.Uint64
rndPool *sync.Pool
clientMu sync.RWMutex
subMu sync.RWMutex
stopInfoEmitter context.CancelFunc
}
// NewClient creates the Client struct with the clientOptions provided,
// it can return error when prometheus.DefaultRegisterer has already
// been used to register the collected metrics
func NewClient(opts ...ClientOption) (*Client, error) {
co := defaultClientOptions()
for _, opt := range opts {
opt.apply(co)
}
if len(co.brokerAddress) == 0 && co.resolver == nil {
return nil, fmt.Errorf("at least WithAddress or WithResolver ClientOption should be used")
}
if co.infoEmitterCfg != nil && co.infoEmitterCfg.Emitter != nil && co.infoEmitterCfg.Interval.Seconds() < 1 {
return nil, fmt.Errorf("client info emitter interval must be greater than or equal to 1s")
}
c := &Client{
options: co,
subscriptions: map[string]*subscriptionMeta{},
rrCounter: &atomicCounter{value: 0},
rndPool: &sync.Pool{New: func() any {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}},
}
if len(co.brokerAddress) != 0 {
c.mqttClient = newClientFunc.Load().(func(*mqtt.ClientOptions) mqtt.Client)(toClientOptions(c, c.options, ""))
}
c.publisher = publishHandler(c)
c.subscriber = subscriberFuncs(c)
c.unsubscriber = unsubscriberHandler(c)
return c, nil
}
// IsConnected checks whether the client is connected to the broker
func (c *Client) IsConnected() bool {
val := &atomic.Bool{}
return c.execute(func(cc mqtt.Client) error {
if cc.IsConnectionOpen() {
val.CompareAndSwap(false, true)
}
return nil
}, execAll) == nil && val.Load()
}
// Start will attempt to connect to the broker.
func (c *Client) Start() error {
if c.options.resolver != nil {
return c.runResolver()
}
return c.runConnect()
}
// Stop will disconnect from the broker and finish up any pending work on internal
// communication workers. This can only block until the period configured with
// the ClientOption WithGracefulShutdownPeriod.
func (c *Client) Stop() { _ = c.stop() }
// Run will start running the Client. This makes Client compatible with github.com/gojekfarm/xrun package.
// https://pkg.go.dev/github.com/gojekfarm/xrun
func (c *Client) Run(ctx context.Context) error {
if c.options.startOptions != nil {
exponentialStartStrategy(ctx, c, c.options.startOptions)
} else {
if err := c.Start(); err != nil {
return err
}
}
<-ctx.Done()
return c.stop()
}
func (c *Client) stop() error {
err := c.execute(func(cc mqtt.Client) error {
cc.Disconnect(uint(c.options.gracefulShutdownPeriod / time.Millisecond))
return nil
}, execAll)
if c.stopInfoEmitter != nil {
c.stopInfoEmitter()
}
if err == nil {
c.clientMu.Lock()
defer c.clientMu.Unlock()
c.mqttClient = nil
c.mqttClients = nil
}
return err
}
func (c *Client) handleInfoEmitter() {
if c.options.infoEmitterCfg != nil && c.options.infoEmitterCfg.Emitter != nil {
ctx, cancel := context.WithCancel(context.Background())
c.stopInfoEmitter = cancel
go c.runBrokerInfoEmitter(ctx)
}
}
func (c *Client) handleToken(ctx context.Context, t mqtt.Token, timeoutErr error) error {
if err := c.waitForToken(ctx, t, timeoutErr); err != nil {
return err
}
if err := t.Error(); err != nil {
return err
}
return nil
}
func (c *Client) waitForToken(ctx context.Context, t mqtt.Token, timeoutErr error) error {
if _, ok := ctx.Deadline(); ok {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.Done():
return t.Error()
}
}
if !t.WaitTimeout(c.options.writeTimeout) {
return timeoutErr
}
return nil
}
func (c *Client) runResolver() error {
// try first connect attempt on start, then start a watcher on channel
select {
case <-time.After(c.options.connectTimeout):
return ErrConnectTimeout
case addrs := <-c.options.resolver.UpdateChan():
if err := c.attemptConnections(addrs); err != nil {
return err
}
}
c.handleInfoEmitter()
go c.watchAddressUpdates(c.options.resolver)
return nil
}
func (c *Client) runConnect() error {
err := c.execute(func(cc mqtt.Client) error {
t := cc.Connect()
if !t.WaitTimeout(c.options.connectTimeout) {
return ErrConnectTimeout
}
return t.Error()
}, execAll)
if err != nil {
return err
}
c.handleInfoEmitter()
return nil
}
func (c *Client) attemptSingleConnection(addrs []TCPAddress) error {
if len(addrs) == 0 {
c.reloadClient(nil)
return nil
}
cc := c.newClient(addrs, 0)
c.reloadClient(cc)
return c.resumeSubscriptions()
}
func (c *Client) removeStoredSubsCalled(cc mqtt.Client) {
c.clientMu.RLock()
defer c.clientMu.RUnlock()
for _, v := range c.mqttClients {
if v.client == cc {
v.mu.Lock()
v.subsCalled.Delete(v.subsCalled.Values()...)
v.mu.Unlock()
}
}
}
func toClientOptions(c *Client, o *clientOptions, idSuffix string) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()
if hostname, err := os.Hostname(); o.clientID == "" && err == nil {
opts.SetClientID(fmt.Sprintf("%s%s", hostname, idSuffix))
} else {
opts.SetClientID(fmt.Sprintf("%s%s", o.clientID, idSuffix))
}
setCredentials(o, opts)
if o.connectRetryPolicy.enabled {
opts.SetConnectRetry(true)
opts.SetConnectRetryInterval(o.connectRetryPolicy.interval)
}
opts.AddBroker(formatAddressWithProtocol(o)).
SetResumeSubs(o.resumeSubscriptions).
SetTLSConfig(o.tlsConfig).
SetAutoReconnect(o.autoReconnect).
SetCleanSession(o.cleanSession).
SetOrderMatters(o.maintainOrder).
SetKeepAlive(o.keepAlive).
SetConnectTimeout(o.connectTimeout).
SetMaxReconnectInterval(o.maxReconnectInterval).
SetReconnectingHandler(reconnectHandler(c, o)).
SetConnectionLostHandler(connectionLostHandler(c, o)).
SetOnConnectHandler(onConnectHandler(c, o))
return opts
}
func setCredentials(o *clientOptions, opts *mqtt.ClientOptions) {
if o.credentialFetcher != nil {
refreshCredentialsWithFetcher(o, opts)
opts.SetCredentialsProvider(credentialsRefresher(o))
return
}
opts.SetUsername(o.username)
opts.SetPassword(o.password)
}
func credentialsRefresher(o *clientOptions) func() (string, string) {
return func() (string, string) {
ctx, cancel := context.WithTimeout(context.Background(), o.credentialFetchTimeout)
defer cancel()
c, err := o.credentialFetcher.Credentials(ctx)
if err != nil {
o.logger.Error(ctx, err, map[string]any{"message": "failed to fetch credentials"})
return "<unknown>", ""
}
return c.Username, c.Password
}
}
func refreshCredentialsWithFetcher(o *clientOptions, opts *mqtt.ClientOptions) {
ctx, cancel := context.WithTimeout(context.Background(), o.credentialFetchTimeout)
defer cancel()
c, err := o.credentialFetcher.Credentials(ctx)
if err != nil {
o.logger.Error(ctx, err, map[string]any{"message": "failed to fetch credentials"})
return
}
opts.SetUsername(c.Username)
opts.SetPassword(c.Password)
}
func formatAddressWithProtocol(opts *clientOptions) string {
if opts.tlsConfig != nil {
return fmt.Sprintf("tls://%s", opts.brokerAddress)
}
return fmt.Sprintf("tcp://%s", opts.brokerAddress)
}
func reconnectHandler(client PubSub, o *clientOptions) mqtt.ReconnectHandler {
return func(_ mqtt.Client, opts *mqtt.ClientOptions) {
if o.logger != nil {
o.logger.Info(context.Background(), "reconnecting", map[string]any{"client_id": opts.ClientID})
}
if o.onReconnectHandler != nil {
o.onReconnectHandler(client)
}
}
}
func connectionLostHandler(c *Client, o *clientOptions) mqtt.ConnectionLostHandler {
return func(cc mqtt.Client, err error) {
if o.logger != nil {
o.logger.Error(context.Background(), err, map[string]any{
"message": "connection lost",
"client_id": clientIDMapper(cc),
})
}
c.removeStoredSubsCalled(cc)
if o.onConnectionLostHandler != nil {
o.onConnectionLostHandler(err)
}
}
}
func onConnectHandler(client PubSub, o *clientOptions) mqtt.OnConnectHandler {
return func(_ mqtt.Client) {
if o.onConnectHandler != nil {
o.onConnectHandler(client)
}
}
}
func defaultNewClientFunc() *atomic.Value {
v := &atomic.Value{}
v.Store(mqtt.NewClient)
return v
}