-
Notifications
You must be signed in to change notification settings - Fork 11
/
client_subscribe.go
185 lines (148 loc) · 4.53 KB
/
client_subscribe.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
package courier
import (
"bytes"
"context"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gojekfarm/xtools/generic/slice"
)
// Subscribe allows to subscribe to messages from an MQTT broker
func (c *Client) Subscribe(ctx context.Context, topic string, callback MessageHandler, opts ...Option) error {
if err := c.subscriber.Subscribe(ctx, topic, callback, opts...); err != nil {
return err
}
c.subMu.Lock()
c.subscriptions[topic] = &subscriptionMeta{
topic: topic,
options: opts,
callback: callback,
}
c.subMu.Unlock()
return nil
}
// SubscribeMultiple allows to subscribe to messages on multiple topics from an MQTT broker
func (c *Client) SubscribeMultiple(
ctx context.Context,
topicsWithQos map[string]QOSLevel,
callback MessageHandler,
) error {
if err := c.subscriber.SubscribeMultiple(ctx, topicsWithQos, callback); err != nil {
return err
}
c.subMu.Lock()
for topic := range topicsWithQos {
c.subscriptions[topic] = &subscriptionMeta{
topic: topic,
options: []Option{topicsWithQos[topic]},
callback: callback,
}
}
c.subMu.Unlock()
return nil
}
// UseSubscriberMiddleware appends a SubscriberMiddlewareFunc to the chain.
// Middleware can be used to intercept or otherwise modify, process or skip subscriptions.
// They are executed in the order that they are applied to the Client.
func (c *Client) UseSubscriberMiddleware(mwf ...SubscriberMiddlewareFunc) {
for _, fn := range mwf {
c.sMiddlewares = append(c.sMiddlewares, fn)
}
c.subscriber = subscriberFuncs(c)
for i := len(c.sMiddlewares) - 1; i >= 0; i-- {
c.subscriber = c.sMiddlewares[i].Middleware(c.subscriber)
}
}
type subscriptionMeta struct {
topic string
options []Option
callback MessageHandler
}
func subscriberFuncs(c *Client) Subscriber {
return NewSubscriberFuncs(
func(ctx context.Context, topic string, callback MessageHandler, opts ...Option) error {
o := composeOptions(opts)
var eo execOpt = execOneRandom
if c.options.sharedSubscriptionPredicate(topic) {
eo = subscribeOnlyOnce(topic)
}
return c.execute(func(cc mqtt.Client) error {
return c.handleToken(ctx, cc.Subscribe(topic, o.qos, callbackWrapper(c, callback)), ErrSubscribeTimeout)
}, eo)
},
func(ctx context.Context, topicsWithQos map[string]QOSLevel, callback MessageHandler) error {
sharedSubs, normalSubs := filterSubs(topicsWithQos, c.options.sharedSubscriptionPredicate)
execs := make([]func(context.Context) error, 0, 2)
if len(sharedSubs) > 0 {
execs = append(execs, func(ctx context.Context) error {
return c.execute(func(cc mqtt.Client) error {
return c.handleToken(ctx, cc.SubscribeMultiple(
sharedSubs,
callbackWrapper(c, callback),
), ErrSubscribeMultipleTimeout)
}, execAll)
})
}
if len(normalSubs) > 0 {
execs = append(execs, func(ctx context.Context) error {
return c.execute(func(cc mqtt.Client) error {
return c.handleToken(ctx, cc.SubscribeMultiple(
normalSubs,
callbackWrapper(c, callback),
), ErrSubscribeMultipleTimeout)
}, execOneRandom)
})
}
return slice.Reduce(slice.MapConcurrentWithContext(ctx, execs,
func(ctx context.Context, f func(context.Context) error) error { return f(ctx) },
), accumulateErrors)
},
)
}
func callbackWrapper(c *Client, callback MessageHandler) mqtt.MessageHandler {
return func(_ mqtt.Client, m mqtt.Message) {
ctx := context.Background()
msg := NewMessageWithDecoder(
c.options.newDecoder(ctx, bytes.NewReader(m.Payload())),
)
msg.ID = int(m.MessageID())
msg.Topic = m.Topic()
msg.Duplicate = m.Duplicate()
msg.Retained = m.Retained()
msg.QoS = QOSLevel(m.Qos())
callback(ctx, c, msg)
}
}
func subscribeOnlyOnce(topic string) execOptWithState {
return func(f func(mqtt.Client) error, s *internalState) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.subsCalled.Has(topic) {
return nil
}
err := f(s.client)
if err == nil {
s.subsCalled.Add(topic)
}
return err
}
}
func filterSubs(
topicsWithQos map[string]QOSLevel,
predicate SharedSubscriptionPredicate,
) (map[string]byte, map[string]byte) {
sharedSubs, normalSubs := make(map[string]byte), make(map[string]byte)
for topic, qosLevel := range topicsWithQos {
if predicate(topic) {
sharedSubs[topic] = byte(qosLevel)
continue
}
normalSubs[topic] = byte(qosLevel)
}
return sharedSubs, normalSubs
}
func routeFilters(topicsWithQos map[string]QOSLevel) map[string]byte {
m := make(map[string]byte)
for topic, q := range topicsWithQos {
m[topic] = byte(q)
}
return m
}