1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-30 07:46:41 -04:00
v2fly/userset.go

82 lines
1.7 KiB
Go
Raw Normal View History

2015-09-07 17:48:19 -04:00
package core
import (
2015-09-14 12:19:17 -04:00
"time"
2015-09-14 16:00:03 -04:00
_ "github.com/v2ray/v2ray-core/log"
2015-09-14 12:19:17 -04:00
)
const (
updateIntervalSec = 10
cacheDurationSec = 120
)
2015-09-14 13:03:31 -04:00
type UserSet interface {
AddUser(user User) error
GetUser(timeHash []byte) (*ID, bool)
}
type TimedUserSet struct {
2015-09-14 12:19:17 -04:00
validUserIds []ID
userHashes map[string]int
}
type hashEntry struct {
hash string
timeSec int64
}
2015-09-14 13:03:31 -04:00
func NewTimedUserSet() UserSet {
vuSet := new(TimedUserSet)
2015-09-12 16:11:54 -04:00
vuSet.validUserIds = make([]ID, 0, 16)
2015-09-14 12:19:17 -04:00
vuSet.userHashes = make(map[string]int)
go vuSet.updateUserHash(time.Tick(updateIntervalSec * time.Second))
return vuSet
}
2015-09-14 13:03:31 -04:00
func (us *TimedUserSet) updateUserHash(tick <-chan time.Time) {
2015-09-14 12:19:17 -04:00
now := time.Now().UTC()
lastSec := now.Unix() - cacheDurationSec
2015-09-14 16:00:03 -04:00
hash2Remove := make(chan hashEntry, cacheDurationSec*2)
2015-09-14 12:19:17 -04:00
lastSec2Remove := now.Unix() + cacheDurationSec
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)
}
}
2015-09-14 16:00:03 -04:00
for lastSec < nowSec + updateIntervalSec {
for idx, id := range us.validUserIds {
idHash := id.TimeHash(lastSec)
hash2Remove <- hashEntry{string(idHash), lastSec}
//log.Debug("Hash: %v", idHash)
2015-09-14 12:19:17 -04:00
us.userHashes[string(idHash)] = idx
}
2015-09-14 16:00:03 -04:00
lastSec ++
}
2015-09-14 12:19:17 -04:00
}
}
2015-09-14 13:03:31 -04:00
func (us *TimedUserSet) AddUser(user User) error {
id := user.Id
us.validUserIds = append(us.validUserIds, id)
return nil
}
2015-09-14 13:03:31 -04:00
func (us TimedUserSet) GetUser(userHash []byte) (*ID, bool) {
2015-09-14 12:19:17 -04:00
idIndex, found := us.userHashes[string(userHash)]
if found {
return &us.validUserIds[idIndex], true
}
return nil, false
2015-09-07 17:48:19 -04:00
}