server_spec.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package protocol
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/v2ray/v2ray-core/common/dice"
  6. v2net "github.com/v2ray/v2ray-core/common/net"
  7. )
  8. type ValidationStrategy interface {
  9. IsValid() bool
  10. Invalidate()
  11. }
  12. type AlwaysValidStrategy struct{}
  13. func AlwaysValid() ValidationStrategy {
  14. return AlwaysValidStrategy{}
  15. }
  16. func (this AlwaysValidStrategy) IsValid() bool {
  17. return true
  18. }
  19. func (this AlwaysValidStrategy) Invalidate() {}
  20. type TimeoutValidStrategy struct {
  21. until time.Time
  22. }
  23. func BeforeTime(t time.Time) ValidationStrategy {
  24. return &TimeoutValidStrategy{
  25. until: t,
  26. }
  27. }
  28. func (this *TimeoutValidStrategy) IsValid() bool {
  29. return this.until.After(time.Now())
  30. }
  31. func (this *TimeoutValidStrategy) Invalidate() {
  32. this.until = time.Time{}
  33. }
  34. type ServerSpec struct {
  35. sync.RWMutex
  36. dest v2net.Destination
  37. users []*User
  38. valid ValidationStrategy
  39. }
  40. func NewServerSpec(dest v2net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
  41. return &ServerSpec{
  42. dest: dest,
  43. users: users,
  44. valid: valid,
  45. }
  46. }
  47. func (this *ServerSpec) Destination() v2net.Destination {
  48. return this.dest
  49. }
  50. func (this *ServerSpec) HasUser(user *User) bool {
  51. this.RLock()
  52. defer this.RUnlock()
  53. account := user.Account
  54. for _, u := range this.users {
  55. if u.Account.Equals(account) {
  56. return true
  57. }
  58. }
  59. return false
  60. }
  61. func (this *ServerSpec) AddUser(user *User) {
  62. if this.HasUser(user) {
  63. return
  64. }
  65. this.Lock()
  66. defer this.Unlock()
  67. this.users = append(this.users, user)
  68. }
  69. func (this *ServerSpec) PickUser() *User {
  70. userCount := len(this.users)
  71. return this.users[dice.Roll(userCount)]
  72. }
  73. func (this *ServerSpec) IsValid() bool {
  74. return this.valid.IsValid()
  75. }
  76. func (this *ServerSpec) Invalidate() {
  77. this.valid.Invalidate()
  78. }