-
Notifications
You must be signed in to change notification settings - Fork 1
/
retaintree.go
111 lines (95 loc) · 2.41 KB
/
retaintree.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
package beeq
import (
"git.zgwit.com/iot/beeq/packet"
"strings"
"sync"
)
type RetainNode struct {
//Subscribed retains
//clientId
//retains map[string]*packet.Publish
retains sync.Map
//Sub level
//topic->children
//children map[string]*RetainNode
children sync.Map
}
func (rn *RetainNode) Fetch(topics []string, cb func(clientId string, pub *packet.Publish)) {
if len(topics) == 0 {
// Publish all matched retains
rn.retains.Range(func(key, value interface{}) bool {
cb(key.(string), value.(*packet.Publish))
return true
})
} else {
name := topics[0]
if name == "#" {
//All retains
rn.retains.Range(func(key, value interface{}) bool {
cb(key.(string), value.(*packet.Publish))
return true
})
//And all children
rn.children.Range(func(key, value interface{}) bool {
value.(*RetainNode).Fetch(topics, cb)
return true
})
} else if name == "+" {
//Children
rn.children.Range(func(key, value interface{}) bool {
value.(*RetainNode).Fetch(topics[1:], cb)
return true
})
} else {
// Sub-Level
if value, ok := rn.children.Load(name); ok {
value.(*RetainNode).Fetch(topics[1:], cb)
}
}
}
}
func (rn *RetainNode) Retain(topics []string, clientId string, pub *packet.Publish) *RetainNode {
if len(topics) == 0 {
// Publish to specific client
rn.retains.Store(clientId, pub)
return rn
} else {
name := topics[0]
// Sub-Level
value, _ := rn.children.LoadOrStore(name, &RetainNode{})
return value.(*RetainNode).Retain(topics[1:], clientId, pub)
}
}
type RetainTree struct {
//root
root RetainNode
//tree index
//ClientId -> Node (hold Publish message)
//retains map[string]*RetainNode
retains sync.Map
}
func (rt *RetainTree) Fetch(topic []byte, cb func(clientId string, pub *packet.Publish)) {
topics := strings.Split(string(topic), "/")
if topics[0] == "" {
topics[0] = "/"
}
rt.root.Fetch(topics, cb)
}
func (rt *RetainTree) Retain(topic []byte, clientId string, pub *packet.Publish) {
// Remove last retain publish, firstly
rt.UnRetain(clientId)
topics := strings.Split(string(topic), "/")
if topics[0] == "" {
topics[0] = "/"
}
node := rt.root.Retain(topics, clientId, pub)
//indexed node
rt.retains.Store(clientId, node)
}
func (rt *RetainTree) UnRetain(clientId string) {
if value, ok := rt.retains.Load(clientId); ok {
node := value.(*RetainNode)
node.retains.Delete(clientId)
rt.retains.Delete(clientId)
}
}