1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-29 18:45:23 +00:00
v2fly/userset.go

87 lines
1.8 KiB
Go
Raw Normal View History

2015-09-07 21:48:19 +00:00
package core
import (
2015-09-14 16:19:17 +00:00
"time"
2015-09-16 19:13:13 +00:00
v2hash "github.com/v2ray/v2ray-core/hash"
2015-09-14 16:19:17 +00:00
)
const (
updateIntervalSec = 10
cacheDurationSec = 120
)
2015-09-14 17:03:31 +00:00
type UserSet interface {
AddUser(user User) error
2015-09-14 23:32:55 +00:00
GetUser(timeHash []byte) (*ID, int64, bool)
2015-09-14 17:03:31 +00:00
}
type TimedUserSet struct {
2015-09-14 16:19:17 +00:00
validUserIds []ID
2015-09-14 23:32:55 +00:00
userHashes map[string]indexTimePair
}
type indexTimePair struct {
2015-09-15 22:06:22 +00:00
index int
timeSec int64
2015-09-14 16:19:17 +00:00
}
type hashEntry struct {
hash string
timeSec int64
}
2015-09-14 17:03:31 +00:00
func NewTimedUserSet() UserSet {
vuSet := new(TimedUserSet)
2015-09-12 20:11:54 +00:00
vuSet.validUserIds = make([]ID, 0, 16)
2015-09-14 23:32:55 +00:00
vuSet.userHashes = make(map[string]indexTimePair)
2015-09-14 16:19:17 +00:00
go vuSet.updateUserHash(time.Tick(updateIntervalSec * time.Second))
return vuSet
}
2015-09-14 17:03:31 +00:00
func (us *TimedUserSet) updateUserHash(tick <-chan time.Time) {
2015-09-14 16:19:17 +00:00
now := time.Now().UTC()
lastSec := now.Unix() - cacheDurationSec
2015-09-15 11:00:42 +00:00
hash2Remove := make(chan hashEntry, cacheDurationSec*3*len(us.validUserIds))
2015-09-14 20:45:55 +00:00
lastSec2Remove := now.Unix()
2015-09-16 19:13:13 +00:00
idHash := v2hash.NewTimeHash(v2hash.HMACHash{})
2015-09-14 16:19:17 +00:00
for {
now := <-tick
nowSec := now.UTC().Unix()
2015-09-15 22:06:22 +00:00
remove2Sec := nowSec - cacheDurationSec
2015-09-14 16:19:17 +00:00
if remove2Sec > lastSec2Remove {
for lastSec2Remove+1 < remove2Sec {
entry := <-hash2Remove
lastSec2Remove = entry.timeSec
delete(us.userHashes, entry.hash)
}
}
2015-09-15 22:06:22 +00:00
for lastSec < nowSec+cacheDurationSec {
for idx, id := range us.validUserIds {
2015-09-16 19:13:13 +00:00
idHash := idHash.Hash(id.Bytes, lastSec)
2015-09-14 20:00:03 +00:00
hash2Remove <- hashEntry{string(idHash), lastSec}
2015-09-14 23:32:55 +00:00
us.userHashes[string(idHash)] = indexTimePair{idx, lastSec}
2015-09-14 16:19:17 +00:00
}
2015-09-15 22:06:22 +00:00
lastSec++
}
2015-09-14 16:19:17 +00:00
}
}
2015-09-14 17:03:31 +00:00
func (us *TimedUserSet) AddUser(user User) error {
id := user.Id
us.validUserIds = append(us.validUserIds, id)
return nil
}
2015-09-14 23:32:55 +00:00
func (us TimedUserSet) GetUser(userHash []byte) (*ID, int64, bool) {
pair, found := us.userHashes[string(userHash)]
if found {
2015-09-14 23:32:55 +00:00
return &us.validUserIds[pair.index], pair.timeSec, true
}
2015-09-14 23:32:55 +00:00
return nil, 0, false
2015-09-07 21:48:19 +00:00
}