/
session.go
292 lines (245 loc) · 6.49 KB
/
session.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
package session
import (
"encoding/json"
"sync"
"github.com/baetyl/baetyl-go/v2/errors"
"github.com/baetyl/baetyl-go/v2/log"
"github.com/baetyl/baetyl-go/v2/mqtt"
"github.com/baetyl/baetyl-broker/v2/common"
"github.com/baetyl/baetyl-broker/v2/queue"
)
// Info session information
type Info struct {
ID string `json:"id,omitempty"`
WillMessage *mqtt.Message `json:"will,omitempty"`
Subscriptions map[string]mqtt.QOS `json:"subs,omitempty"`
CleanSession bool `json:"-"`
}
func (i *Info) String() string {
d, _ := json.Marshal(i)
return string(d)
}
// Session session of a client
type Session struct {
info Info
manager *Manager
subs *mqtt.Trie
cnt *mqtt.Counter
qos0msg queue.Queue // queue for qos0
qos1msg queue.Queue // queue for qos1
qos1pkt *cache
qos1ack chan *eventWrapper
log *log.Logger
mut sync.RWMutex // mutex for session
}
func newSession(i Info, m *Manager) (*Session, error) {
cnt := mqtt.NewCounter()
s := &Session{
info: i,
manager: m,
subs: mqtt.NewTrie(),
cnt: cnt,
qos0msg: queue.NewTemporary(i.ID, m.cfg.MaxInflightQOS0Messages, true),
qos1ack: make(chan *eventWrapper, m.cfg.MaxInflightQOS1Messages),
qos1pkt: &cache{
offset: cnt.GetNextID(),
},
log: m.log.With(log.Any("id", i.ID)),
}
qc := m.cfg.Persistence.Queue
qc.Name = i.ID
qc.BatchSize = m.cfg.MaxInflightQOS1Messages
qbk, err := m.store.NewBatchBucket(qc.Name)
if err != nil {
s.log.Error("failed to create qos1 bucket", log.Error(err))
return nil, err
}
s.qos1msg, err = queue.NewPersistence(qc, qbk)
if err != nil {
s.log.Error("failed to create qos1 persistent", log.Error(err))
return nil, err
}
for topic, qos := range i.Subscriptions {
s.subs.Set(topic, qos)
s.manager.exch.Bind(topic, s)
s.info.Subscriptions[topic] = qos
}
err = s.persistent()
if err != nil {
return nil, errors.Trace(err)
}
return s, nil
}
func (s *Session) close() {
s.log.Info("session is closing")
defer s.log.Info("session has closed")
if s.qos0msg != nil {
err := s.qos0msg.Close(s.info.CleanSession)
if err != nil {
s.log.Error("failed to clase qos0 queue", log.Error(err))
}
}
if s.qos1msg != nil {
err := s.qos1msg.Close(s.info.CleanSession)
if err != nil {
s.log.Error("failed to clase qos1 queue", log.Error(err))
}
}
}
// * the following operations need lock
func (s *Session) update(si Info, auth func(action, topic string) bool) error {
s.mut.Lock()
defer s.mut.Unlock()
s.info.WillMessage = si.WillMessage
s.info.CleanSession = si.CleanSession
for topic := range s.info.Subscriptions {
if auth != nil && !auth(Subscribe, topic) {
s.log.Warn(ErrSessionMessageTopicNotPermitted.Error(), log.Any("topic", topic))
s.subs.Empty(topic)
s.manager.exch.Unbind(topic, s)
delete(s.info.Subscriptions, topic)
}
}
// reset qos1 queue
if s.qos1msg != nil {
err := s.qos1msg.Close(si.CleanSession)
if err != nil {
s.log.Error("failed to close qos1 queue when update", log.Error(err))
return errors.Trace(err)
}
}
qc := s.manager.cfg.Persistence.Queue
qc.Name = si.ID
qc.BatchSize = s.manager.cfg.MaxInflightQOS1Messages
qbk, err := s.manager.store.NewBatchBucket(qc.Name)
if err != nil {
s.log.Error("failed to create qos1 bucket", log.Error(err))
return errors.Trace(err)
}
s.qos1msg, err = queue.NewPersistence(qc, qbk)
if err != nil {
s.log.Error("failed to create qos1 persistent", log.Error(err))
return errors.Trace(err)
}
return errors.Trace(s.persistent())
}
func (s *Session) disableQos1() {
s.mut.Lock()
defer s.mut.Unlock()
if s.qos1msg != nil {
s.qos1msg.Disable()
}
}
// Push pushes source message to session queue
func (s *Session) Push(e *common.Event) error {
s.mut.Lock()
defer s.mut.Unlock()
// always flow message with qos 0 into qos0 queue
if e.Context.QOS == 0 {
return s.qos0msg.Push(e)
}
// TODO: improve
qs := s.subs.Match(e.Context.Topic)
if len(qs) == 0 {
s.log.Warn("a message is ignored since there is no sub matched", log.Any("message", e.String()))
e.Done()
return nil
}
for _, q := range qs {
if q.(mqtt.QOS) > 0 {
// chose maximum QoS of all the matching subscriptions. [MQTT-3.3.5-1]
return s.qos1msg.Push(e)
}
}
return s.qos0msg.Push(e)
}
// ID id
func (s *Session) ID() string {
s.mut.Lock()
defer s.mut.Unlock()
return s.info.ID
}
// * the following operations are only used by mqtt client
func (s *Session) subscribe(subs []mqtt.Subscription, sa *mqtt.Suback, auth func(action, topic string) bool) error {
if len(subs) == 0 {
return nil
}
s.mut.Lock()
defer s.mut.Unlock()
if s.info.Subscriptions == nil {
s.info.Subscriptions = make(map[string]mqtt.QOS)
}
for i, v := range subs {
if auth != nil && !auth(Subscribe, v.Topic) {
s.log.Warn(ErrSessionMessageTopicNotPermitted.Error(), log.Any("topic", v.Topic))
sa.ReturnCodes[i] = mqtt.QOSFailure
continue
}
s.subs.Set(v.Topic, v.QOS)
s.manager.exch.Bind(v.Topic, s)
s.info.Subscriptions[v.Topic] = v.QOS
}
return errors.Trace(s.persistent())
}
func (s *Session) unsubscribe(topics []string) error {
if len(topics) == 0 {
return nil
}
s.mut.Lock()
defer s.mut.Unlock()
for _, topic := range topics {
s.subs.Empty(topic)
s.manager.exch.Unbind(topic, s)
delete(s.info.Subscriptions, topic)
}
return errors.Trace(s.persistent())
}
func (s *Session) will() *mqtt.Message {
s.mut.RLock()
defer s.mut.RUnlock()
return s.info.WillMessage
}
func (s *Session) cleanSession() bool {
s.mut.RLock()
defer s.mut.RUnlock()
return s.info.CleanSession
}
func (s *Session) cleanWill() error {
s.mut.Lock()
defer s.mut.Unlock()
s.info.WillMessage = nil
return errors.Trace(s.persistent())
}
func (s *Session) matchQOS(topic string) (bool, uint32) {
s.mut.RLock()
defer s.mut.RUnlock()
return mqtt.MatchTopicQOS(s.subs, topic)
}
func (s *Session) acknowledge(id uint64) {
s.mut.RLock()
defer s.mut.RUnlock()
err := s.qos1pkt.delete(id)
if err != nil {
s.log.Warn("failed to acknowledge", log.Any("id", id), log.Error(err))
}
}
func (s *Session) persistent() error {
if s.info.CleanSession {
err := s.manager.sessionBucket.DelKV([]byte(s.info.ID))
if err != nil {
s.log.Error("failed to delete session", log.Error(err))
return errors.Trace(err)
}
return nil
}
data, err := json.Marshal(s.info)
if err != nil {
return errors.Trace(err)
}
err = s.manager.sessionBucket.SetKV([]byte(s.info.ID), data)
if err != nil {
s.log.Error("failed to set session", log.Error(err))
return errors.Trace(err)
}
return nil
}