This repository has been archived by the owner on Nov 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathroom.go
91 lines (75 loc) · 2.04 KB
/
room.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
package room
import (
"errors"
"fmt"
"sync"
"sync/atomic"
)
type CountedSyncMap struct {
sync.Map
len uint64
}
func (m *CountedSyncMap) CountedDelete(key interface{}) {
m.Delete(key)
atomic.AddUint64(&m.len, ^uint64(0))
}
func (m *CountedSyncMap) CountedStore(key, value interface{}) {
m.Store(key, value)
atomic.AddUint64(&m.len, uint64(1))
}
func (m *CountedSyncMap) CountedLen() uint64 {
return atomic.LoadUint64(&m.len)
}
var apiKeysMap CountedSyncMap
func GetRoom(apiKey, room string) (*CountedSyncMap, bool) {
rooms, ok := apiKeysMap.Load(apiKey)
if ok == false {
return nil, ok
}
sessionKeys, ok := rooms.(*CountedSyncMap).Load(room)
if ok {
return sessionKeys.(*CountedSyncMap), ok
} else {
return nil, ok
}
}
func GetSession(apiKey, room, sessionKey string) (interface{}, bool) {
sessions, ok := GetRoom(apiKey, room)
if ok == false {
return nil, false
}
return sessions.Load(sessionKey)
}
func StoreSession(apiKey, room, sessionKey string, c interface{}) {
rooms, ok := apiKeysMap.Load(apiKey)
if ok == false {
apiKeysMap.CountedStore(apiKey, &CountedSyncMap{})
rooms, _ = apiKeysMap.Load(apiKey)
}
sessionKeys, ok := rooms.(*CountedSyncMap).Load(room)
if ok == false {
rooms.(*CountedSyncMap).CountedStore(room, &CountedSyncMap{})
sessionKeys, _ = rooms.(*CountedSyncMap).Load(room)
}
sessionKeys.(*CountedSyncMap).CountedStore(sessionKey, c)
}
func DestroySession(apiKey, room, sessionKey string) error {
rooms, ok := apiKeysMap.Load(apiKey)
if ok == false {
return errors.New(fmt.Sprintf("No rooms for apiKey %s", apiKey))
}
sessionKeys, ok := rooms.(*CountedSyncMap).Load(room)
if ok == false {
return errors.New(fmt.Sprintf("Room %s not found for %s", room, apiKey))
}
sessionKeys.(*CountedSyncMap).CountedDelete(sessionKey)
// No more sessions, destroy room
if sessionKeys.(*CountedSyncMap).CountedLen() == 0 {
rooms.(*CountedSyncMap).CountedDelete(room)
}
// No more rooms, destroy apiKey
if rooms.(*CountedSyncMap).CountedLen() == 0 {
apiKeysMap.CountedDelete(apiKey)
}
return nil
}