forked from absmach/magistrala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriber.go
172 lines (156 loc) · 4.08 KB
/
subscriber.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
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mqtt
import (
"fmt"
"sync"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gogo/protobuf/proto"
log "github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mainflux/pkg/messaging"
)
var (
errSubscribeTimeout = errors.New("failed to subscribe due to timeout reached")
errUnsubscribeTimeout = errors.New("failed to unsubscribe due to timeout reached")
errUnsubscribeDeleteTopic = errors.New("failed to unsubscribe due to deletion of topic")
errAlreadySubscribed = errors.New("already subscribed to topic")
errNotSubscribed = errors.New("not subscribed")
errEmptyTopic = errors.New("empty topic")
errEmptyID = errors.New("empty ID")
)
var _ messaging.Subscriber = (*subscriber)(nil)
type subscription struct {
client mqtt.Client
topics []string
}
type subscriber struct {
address string
timeout time.Duration
logger log.Logger
subscriptions map[string]subscription
mu *sync.RWMutex
}
// NewSubscriber returns a new MQTT message subscriber.
func NewSubscriber(address string, timeout time.Duration, logger log.Logger) (messaging.Subscriber, error) {
ret := subscriber{
address: address,
timeout: timeout,
logger: logger,
subscriptions: make(map[string]subscription),
}
return ret, nil
}
func (sub subscriber) Subscribe(id, topic string, handler messaging.MessageHandler) error {
if id == "" {
return errEmptyID
}
if topic == "" {
return errEmptyTopic
}
sub.mu.Lock()
defer sub.mu.Unlock()
// Check client ID
s, ok := sub.subscriptions[id]
switch ok {
case true:
// Check topic
if ok = s.contains(topic); ok {
return errAlreadySubscribed
}
s.topics = append(s.topics, topic)
default:
opts := mqtt.NewClientOptions().SetUsername(username).AddBroker(sub.address).SetClientID(id)
client := mqtt.NewClient(opts)
token := client.Connect()
if token.Error() != nil {
return token.Error()
}
s = subscription{
client: client,
topics: []string{topic},
}
}
token := s.client.Subscribe(topic, qos, sub.mqttHandler(handler))
if token.Error() != nil {
return token.Error()
}
if ok := token.WaitTimeout(sub.timeout); !ok {
return errSubscribeTimeout
}
return token.Error()
}
func (sub subscriber) Unsubscribe(id, topic string) error {
if id == "" {
return errEmptyID
}
if topic == "" {
return errEmptyTopic
}
sub.mu.Lock()
defer sub.mu.Unlock()
// Check client ID
s, ok := sub.subscriptions[id]
switch ok {
case true:
// Check topic
if ok := s.contains(topic); !ok {
return errNotSubscribed
}
default:
return errNotSubscribed
}
token := s.client.Unsubscribe(topic)
if token.Error() != nil {
return token.Error()
}
ok = token.WaitTimeout(sub.timeout)
if !ok {
return errUnsubscribeTimeout
}
if ok := s.delete(topic); !ok {
return errUnsubscribeDeleteTopic
}
if len(s.topics) == 0 {
delete(sub.subscriptions, id)
}
return token.Error()
}
func (sub subscriber) mqttHandler(h messaging.MessageHandler) mqtt.MessageHandler {
return func(c mqtt.Client, m mqtt.Message) {
var msg messaging.Message
if err := proto.Unmarshal(m.Payload(), &msg); err != nil {
sub.logger.Warn(fmt.Sprintf("Failed to unmarshal received message: %s", err))
return
}
if err := h.Handle(msg); err != nil {
sub.logger.Warn(fmt.Sprintf("Failed to handle Mainflux message: %s", err))
}
}
}
// contains checks if a topic is present
func (sub subscription) contains(topic string) bool {
return sub.indexOf(topic) != -1
}
// Finds the index of an item in the topics
func (sub subscription) indexOf(element string) int {
for k, v := range sub.topics {
if element == v {
return k
}
}
return -1
}
// Deletes a topic from the slice
func (sub subscription) delete(topic string) bool {
index := sub.indexOf(topic)
if index == -1 {
return false
}
topics := make([]string, len(sub.topics)-1)
copy(topics[:index], sub.topics[:index])
copy(topics[index:], sub.topics[index+1:])
sub.topics = topics
return true
}