1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-18 02:16:10 -05:00
v2fly/common/protocol/server_spec.go

101 lines
1.7 KiB
Go
Raw Normal View History

2016-07-24 17:22:46 -04:00
package protocol
import (
"sync"
"time"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/dice"
v2net "v2ray.com/core/common/net"
2016-07-24 17:22:46 -04:00
)
2016-07-25 10:48:09 -04:00
type ValidationStrategy interface {
IsValid() bool
Invalidate()
}
type AlwaysValidStrategy struct{}
func AlwaysValid() ValidationStrategy {
return AlwaysValidStrategy{}
}
func (this AlwaysValidStrategy) IsValid() bool {
return true
}
func (this AlwaysValidStrategy) Invalidate() {}
type TimeoutValidStrategy struct {
until time.Time
}
func BeforeTime(t time.Time) ValidationStrategy {
2016-07-25 15:31:16 -04:00
return &TimeoutValidStrategy{
2016-07-25 10:48:09 -04:00
until: t,
}
}
2016-07-25 15:55:05 -04:00
func (this *TimeoutValidStrategy) IsValid() bool {
2016-07-25 10:48:09 -04:00
return this.until.After(time.Now())
}
2016-07-25 15:31:16 -04:00
func (this *TimeoutValidStrategy) Invalidate() {
2016-07-25 10:48:09 -04:00
this.until = time.Time{}
}
2016-07-24 17:22:46 -04:00
type ServerSpec struct {
sync.RWMutex
2016-07-25 10:48:09 -04:00
dest v2net.Destination
2016-07-24 17:22:46 -04:00
users []*User
2016-07-25 10:48:09 -04:00
valid ValidationStrategy
2016-07-24 17:22:46 -04:00
}
2016-07-25 10:48:09 -04:00
func NewServerSpec(dest v2net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
2016-07-24 17:22:46 -04:00
return &ServerSpec{
2016-07-25 10:48:09 -04:00
dest: dest,
users: users,
valid: valid,
2016-07-24 17:22:46 -04:00
}
}
2016-07-25 10:48:09 -04:00
func (this *ServerSpec) Destination() v2net.Destination {
return this.dest
}
2016-07-24 17:22:46 -04:00
func (this *ServerSpec) HasUser(user *User) bool {
this.RLock()
defer this.RUnlock()
account := user.Account
for _, u := range this.users {
if u.Account.Equals(account) {
return true
}
}
return false
}
func (this *ServerSpec) AddUser(user *User) {
if this.HasUser(user) {
return
}
this.Lock()
defer this.Unlock()
this.users = append(this.users, user)
}
func (this *ServerSpec) PickUser() *User {
userCount := len(this.users)
return this.users[dice.Roll(userCount)]
}
func (this *ServerSpec) IsValid() bool {
2016-07-25 10:48:09 -04:00
return this.valid.IsValid()
2016-07-24 17:22:46 -04:00
}
2016-07-25 10:48:09 -04:00
func (this *ServerSpec) Invalidate() {
this.valid.Invalidate()
2016-07-24 17:22:46 -04:00
}