-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
87 lines (74 loc) · 1.76 KB
/
channel.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
package link
import (
"sync"
)
type KEY interface{}
type Channel struct {
mutex sync.RWMutex
sessions map[KEY]*Session
// channel state
State interface{}
}
func NewChannel() *Channel {
return &Channel{
sessions: make(map[KEY]*Session),
}
}
func (channel *Channel) Len() int {
channel.mutex.RLock()
defer channel.mutex.RUnlock()
return len(channel.sessions)
}
func (channel *Channel) Fetch(callback func(*Session)) {
channel.mutex.RLock()
defer channel.mutex.RUnlock()
for _, session := range channel.sessions {
callback(session)
}
}
func (channel *Channel) Get(key KEY) *Session {
channel.mutex.RLock()
defer channel.mutex.RUnlock()
session, _ := channel.sessions[key]
return session
}
func (channel *Channel) Put(key KEY, session *Session) {
channel.mutex.Lock()
defer channel.mutex.Unlock()
if session, exists := channel.sessions[key]; exists {
channel.remove(key, session)
}
session.AddCloseCallback(channel, key, func() {
channel.Remove(key)
})
channel.sessions[key] = session
}
func (channel *Channel) remove(key KEY, session *Session) {
session.RemoveCloseCallback(channel, key)
delete(channel.sessions, key)
}
func (channel *Channel) Remove(key KEY) bool {
channel.mutex.Lock()
defer channel.mutex.Unlock()
session, exists := channel.sessions[key]
if exists {
channel.remove(key, session)
}
return exists
}
func (channel *Channel) FetchAndRemove(callback func(*Session)) {
channel.mutex.Lock()
defer channel.mutex.Unlock()
for key, session := range channel.sessions {
session.RemoveCloseCallback(channel, key)
delete(channel.sessions, key)
callback(session)
}
}
func (channel *Channel) Close() {
channel.mutex.Lock()
defer channel.mutex.Unlock()
for key, session := range channel.sessions {
channel.remove(key, session)
}
}