-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
server_spec.go
122 lines (98 loc) · 2.09 KB
/
server_spec.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package protocol
import (
"sync"
"time"
"v2ray.com/core/common/dice"
"v2ray.com/core/common/net"
)
type ValidationStrategy interface {
IsValid() bool
Invalidate()
}
type alwaysValidStrategy struct{}
func AlwaysValid() ValidationStrategy {
return alwaysValidStrategy{}
}
func (alwaysValidStrategy) IsValid() bool {
return true
}
func (alwaysValidStrategy) Invalidate() {}
type timeoutValidStrategy struct {
until time.Time
}
func BeforeTime(t time.Time) ValidationStrategy {
return &timeoutValidStrategy{
until: t,
}
}
func (s *timeoutValidStrategy) IsValid() bool {
return s.until.After(time.Now())
}
func (s *timeoutValidStrategy) Invalidate() {
s.until = time.Time{}
}
type ServerSpec struct {
sync.RWMutex
dest net.Destination
users []*MemoryUser
valid ValidationStrategy
}
func NewServerSpec(dest net.Destination, valid ValidationStrategy, users ...*MemoryUser) *ServerSpec {
return &ServerSpec{
dest: dest,
users: users,
valid: valid,
}
}
func NewServerSpecFromPB(spec ServerEndpoint) (*ServerSpec, error) {
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
mUsers := make([]*MemoryUser, len(spec.User))
for idx, u := range spec.User {
mUser, err := u.ToMemoryUser()
if err != nil {
return nil, err
}
mUsers[idx] = mUser
}
return NewServerSpec(dest, AlwaysValid(), mUsers...), nil
}
func (s *ServerSpec) Destination() net.Destination {
return s.dest
}
func (s *ServerSpec) HasUser(user *MemoryUser) bool {
s.RLock()
defer s.RUnlock()
for _, u := range s.users {
if u.Account.Equals(user.Account) {
return true
}
}
return false
}
func (s *ServerSpec) AddUser(user *MemoryUser) {
if s.HasUser(user) {
return
}
s.Lock()
defer s.Unlock()
s.users = append(s.users, user)
}
func (s *ServerSpec) PickUser() *MemoryUser {
s.RLock()
defer s.RUnlock()
userCount := len(s.users)
switch userCount {
case 0:
return nil
case 1:
return s.users[0]
default:
return s.users[dice.Roll(userCount)]
}
}
func (s *ServerSpec) IsValid() bool {
return s.valid.IsValid()
}
func (s *ServerSpec) Invalidate() {
s.valid.Invalidate()
}