forked from ProtonMail/tobubus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessionmanager.go
71 lines (63 loc) · 1.4 KB
/
sessionmanager.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
package tobubus
import (
"math"
"sync"
)
type sessionStrategy int
const (
incrementStrategy sessionStrategy = iota // for test
recycleStrategy // for production
)
type sessionManager struct {
lock sync.RWMutex
sessions map[uint32]chan *message
strategy sessionStrategy
nextSessionID uint32
}
func newSessionManager(strategy sessionStrategy) *sessionManager {
return &sessionManager{
sessions: make(map[uint32]chan *message),
strategy: strategy,
}
}
func (g *sessionManager) getUniqueSessionID() uint32 {
g.lock.Lock()
defer g.lock.Unlock()
switch g.strategy {
case recycleStrategy:
var id uint32
for id = 0; id < math.MaxUint32; id++ {
if _, ok := g.sessions[id]; !ok {
g.sessions[id] = make(chan *message)
return id
}
}
case incrementStrategy:
result := g.nextSessionID
g.nextSessionID++
return result
}
panic("id error")
}
func (g *sessionManager) receiveAndClose(id uint32) *message {
g.lock.Lock()
channel, ok := g.sessions[id]
if !ok {
channel = make(chan *message)
g.sessions[id] = channel
}
g.lock.Unlock()
result := <-channel
delete(g.sessions, id)
return result
}
func (g *sessionManager) getChannelOfSessionID(id uint32) chan *message {
g.lock.Lock()
defer g.lock.Unlock()
if channel, ok := g.sessions[id]; ok {
return channel
}
channel := make(chan *message)
g.sessions[id] = channel
return channel
}