-
Notifications
You must be signed in to change notification settings - Fork 0
/
track.go
123 lines (101 loc) · 1.69 KB
/
track.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
package ws
import (
"github.com/sasha-s/go-deadlock"
)
var trackMap *TrackMap
type TrackMap struct {
m map[string]map[*Client]bool
deadlock.RWMutex
}
func (tm *TrackMap) trackClient(key string, c *Client) {
if key == "" {
return
}
tm.Lock()
defer tm.Unlock()
// set client key
c.trackKey = key
// add client to the track map
m, ok := tm.m[key]
if !ok {
m = make(map[*Client]bool)
tm.m[key] = m
}
if _, ok := m[c]; !ok {
m[c] = true
}
}
func (tm *TrackMap) dropClient(c *Client) {
tm.Lock()
defer tm.Unlock()
key := c.trackKey
if key == "" {
return
}
m, ok := tm.m[key]
if ok {
_, ok = m[c]
if ok {
delete(m, c)
}
if len(m) == 0 {
delete(tm.m, key)
}
}
}
func IsConnected(key string) bool {
trackMap.RLock()
defer trackMap.RUnlock()
m, ok := trackMap.m[key]
if !ok || len(m) == 0 {
return false
}
return true
}
func ShutConnections(key string) {
trackMap.Lock()
defer trackMap.Unlock()
if m, ok := trackMap.m[key]; ok {
for c := range m {
delete(m, c)
go func(c *Client) {
if c != nil {
select {
case c.close <- struct{}{}:
default:
}
}
}(c)
}
delete(trackMap.m, key)
}
}
func ShutClientPool(key string, uri ...string) {
if len(uri) == 0 {
return
}
trackMap.Lock()
defer trackMap.Unlock()
if m, ok := trackMap.m[key]; ok {
wg := deadlock.WaitGroup{}
for c := range m {
wg.Add(1)
go func(c *Client) {
if c != nil {
c.onCloseMap.fireAndRemove(uri...)
}
wg.Done()
}(c)
}
wg.Wait()
}
}
func TrackedIdents() []string {
var idents []string
trackMap.RLock()
defer trackMap.RUnlock()
for ident := range trackMap.m {
idents = append(idents, ident)
}
return idents
}