1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-20 14:35:23 +00:00
v2fly/common/protocol/server_spec.go

101 lines
1.7 KiB
Go
Raw Normal View History

2016-07-24 21:22:46 +00:00
package protocol
import (
"sync"
"time"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/dice"
v2net "v2ray.com/core/common/net"
2016-07-24 21:22:46 +00:00
)
2016-07-25 14:48:09 +00: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 19:31:16 +00:00
return &TimeoutValidStrategy{
2016-07-25 14:48:09 +00:00
until: t,
}
}
2016-07-25 19:55:05 +00:00
func (this *TimeoutValidStrategy) IsValid() bool {
2016-07-25 14:48:09 +00:00
return this.until.After(time.Now())
}
2016-07-25 19:31:16 +00:00
func (this *TimeoutValidStrategy) Invalidate() {
2016-07-25 14:48:09 +00:00
this.until = time.Time{}
}
2016-07-24 21:22:46 +00:00
type ServerSpec struct {
sync.RWMutex
2016-07-25 14:48:09 +00:00
dest v2net.Destination
2016-07-24 21:22:46 +00:00
users []*User
2016-07-25 14:48:09 +00:00
valid ValidationStrategy
2016-07-24 21:22:46 +00:00
}
2016-07-25 14:48:09 +00:00
func NewServerSpec(dest v2net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
2016-07-24 21:22:46 +00:00
return &ServerSpec{
2016-07-25 14:48:09 +00:00
dest: dest,
users: users,
valid: valid,
2016-07-24 21:22:46 +00:00
}
}
2016-07-25 14:48:09 +00:00
func (this *ServerSpec) Destination() v2net.Destination {
return this.dest
}
2016-07-24 21:22:46 +00: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 14:48:09 +00:00
return this.valid.IsValid()
2016-07-24 21:22:46 +00:00
}
2016-07-25 14:48:09 +00:00
func (this *ServerSpec) Invalidate() {
this.valid.Invalidate()
2016-07-24 21:22:46 +00:00
}