forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuserset.go
83 lines (69 loc) · 1.74 KB
/
userset.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
package core
import (
"time"
)
const (
updateIntervalSec = 10
cacheDurationSec = 120
)
type UserSet interface {
AddUser(user User) error
GetUser(timeHash []byte) (*ID, int64, bool)
}
type TimedUserSet struct {
validUserIds []ID
userHashes map[string]indexTimePair
}
type indexTimePair struct {
index int
timeSec int64
}
type hashEntry struct {
hash string
timeSec int64
}
func NewTimedUserSet() UserSet {
vuSet := new(TimedUserSet)
vuSet.validUserIds = make([]ID, 0, 16)
vuSet.userHashes = make(map[string]indexTimePair)
go vuSet.updateUserHash(time.Tick(updateIntervalSec * time.Second))
return vuSet
}
func (us *TimedUserSet) updateUserHash(tick <-chan time.Time) {
now := time.Now().UTC()
lastSec := now.Unix() - cacheDurationSec
hash2Remove := make(chan hashEntry, cacheDurationSec*2*len(us.validUserIds))
lastSec2Remove := now.Unix()
for {
now := <-tick
nowSec := now.UTC().Unix()
remove2Sec := nowSec - cacheDurationSec
if remove2Sec > lastSec2Remove {
for lastSec2Remove+1 < remove2Sec {
entry := <-hash2Remove
lastSec2Remove = entry.timeSec
delete(us.userHashes, entry.hash)
}
}
for lastSec < nowSec + cacheDurationSec {
for idx, id := range us.validUserIds {
idHash := id.TimeHash(lastSec)
hash2Remove <- hashEntry{string(idHash), lastSec}
us.userHashes[string(idHash)] = indexTimePair{idx, lastSec}
}
lastSec ++
}
}
}
func (us *TimedUserSet) AddUser(user User) error {
id := user.Id
us.validUserIds = append(us.validUserIds, id)
return nil
}
func (us TimedUserSet) GetUser(userHash []byte) (*ID, int64, bool) {
pair, found := us.userHashes[string(userHash)]
if found {
return &us.validUserIds[pair.index], pair.timeSec, true
}
return nil, 0, false
}