forked from raystack/raccoon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.go
More file actions
92 lines (79 loc) · 1.84 KB
/
Copy pathtable.go
File metadata and controls
92 lines (79 loc) · 1.84 KB
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
package connection
import (
"errors"
"sync"
"github.com/goto/raccoon/identification"
)
var (
errMaxConnectionReached = errors.New("max connection reached")
errConnDuplicated = errors.New("duplicated connection")
)
type Table struct {
m *sync.RWMutex
connMap map[identification.Identifier]map[string]struct{}
counter map[string]int
maxUser int
}
func NewTable(maxUser int) *Table {
return &Table{
m: &sync.RWMutex{},
connMap: make(map[identification.Identifier]map[string]struct{}),
maxUser: maxUser,
counter: make(map[string]int),
}
}
func (t *Table) Exists(c identification.Identifier) bool {
t.m.Lock()
defer t.m.Unlock()
_, ok := t.connMap[c]
return ok
}
func (t *Table) Store(c identification.Identifier) error {
t.m.Lock()
defer t.m.Unlock()
if len(t.connMap) >= t.maxUser {
return errMaxConnectionReached
}
if _, ok := t.connMap[c]; ok {
return errConnDuplicated
}
t.connMap[c] = make(map[string]struct{})
t.counter[c.Group] = t.counter[c.Group] + 1
return nil
}
func (t *Table) StoreBatch(c identification.Identifier, id string) {
t.m.Lock()
defer t.m.Unlock()
if _, ok := t.connMap[c]; ok {
t.connMap[c][id] = struct{}{}
}
}
func (t *Table) HasBatch(c identification.Identifier, id string) bool {
t.m.RLock()
defer t.m.RUnlock()
_, ok := t.connMap[c][id]
return ok
}
func (t *Table) RemoveBatch(c identification.Identifier, id string) {
t.m.RLock()
defer t.m.RUnlock()
delete(t.connMap[c], id)
}
func (t *Table) Remove(c identification.Identifier) {
t.m.Lock()
defer t.m.Unlock()
delete(t.connMap, c)
t.counter[c.Group] = t.counter[c.Group] - 1
}
func (t *Table) TotalConnection() int {
t.m.Lock()
defer t.m.Unlock()
return len(t.connMap)
}
func (t *Table) RangeConnectionPerGroup(fn func(string, int)) {
t.m.RLock()
defer t.m.RUnlock()
for k, v := range t.counter {
fn(k, v)
}
}