hub_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package websocket
  2. import (
  3. "encoding/json"
  4. "os"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/op/go-logging"
  9. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  10. )
  11. func TestMain(m *testing.M) {
  12. _ = os.Setenv("XUI_LOG_FOLDER", os.TempDir())
  13. xuilogger.InitLogger(logging.ERROR)
  14. os.Exit(m.Run())
  15. }
  16. func TestNewClient_HasBufferedSendChannel(t *testing.T) {
  17. c := NewClient("client-1")
  18. if c.ID != "client-1" {
  19. t.Fatalf("ID = %q, want client-1", c.ID)
  20. }
  21. if cap(c.Send) != clientSendQueue {
  22. t.Fatalf("Send cap = %d, want %d", cap(c.Send), clientSendQueue)
  23. }
  24. }
  25. func TestHub_NilReceiver_DoesNotPanic(t *testing.T) {
  26. var h *Hub
  27. if h.GetClientCount() != 0 {
  28. t.Fatal("nil hub GetClientCount should return 0")
  29. }
  30. h.Broadcast(MessageTypeStatus, "anything")
  31. h.Register(NewClient("x"))
  32. h.Unregister(NewClient("x"))
  33. h.Stop()
  34. }
  35. func TestHub_BroadcastDropsWhenNoClients(t *testing.T) {
  36. h := NewHub()
  37. defer h.Stop()
  38. go h.Run()
  39. h.Broadcast(MessageTypeStatus, "payload")
  40. select {
  41. case <-h.broadcast:
  42. t.Fatal("Broadcast should drop when client count is zero")
  43. case <-time.After(50 * time.Millisecond):
  44. }
  45. }
  46. func TestHub_BroadcastDropsNilPayload(t *testing.T) {
  47. h := NewHub()
  48. defer h.Stop()
  49. go h.Run()
  50. c := NewClient("c1")
  51. h.Register(c)
  52. waitClientCount(t, h, 1)
  53. h.Broadcast(MessageTypeStatus, nil)
  54. select {
  55. case <-c.Send:
  56. t.Fatal("nil payload should be dropped, not delivered")
  57. case <-time.After(50 * time.Millisecond):
  58. }
  59. }
  60. func TestHub_BroadcastDeliversToClient(t *testing.T) {
  61. h := NewHub()
  62. defer h.Stop()
  63. go h.Run()
  64. c := NewClient("c1")
  65. h.Register(c)
  66. waitClientCount(t, h, 1)
  67. h.Broadcast(MessageTypeStatus, map[string]string{"k": "v"})
  68. select {
  69. case raw := <-c.Send:
  70. var message Message
  71. if err := json.Unmarshal(raw, &message); err != nil {
  72. t.Fatalf("payload is not valid JSON: %v", err)
  73. }
  74. if message.Type != MessageTypeStatus {
  75. t.Fatalf("message type = %q, want %q", message.Type, MessageTypeStatus)
  76. }
  77. if message.Time == 0 {
  78. t.Fatal("Time should be set to a non-zero unix-millis value")
  79. }
  80. case <-time.After(500 * time.Millisecond):
  81. t.Fatal("timed out waiting for status broadcast to reach client")
  82. }
  83. for _, source := range []string{"tuic", "xray"} {
  84. h.Broadcast(MessageTypeTraffic, map[string]string{"source": source})
  85. }
  86. for _, wantSource := range []string{"tuic", "xray"} {
  87. select {
  88. case raw := <-c.Send:
  89. var message struct {
  90. Type MessageType `json:"type"`
  91. Payload map[string]string `json:"payload"`
  92. }
  93. if err := json.Unmarshal(raw, &message); err != nil {
  94. t.Fatalf("traffic event is not valid JSON: %v", err)
  95. }
  96. if message.Type != MessageTypeTraffic {
  97. t.Fatalf("message type = %q, want %q", message.Type, MessageTypeTraffic)
  98. }
  99. if got := message.Payload["source"]; got != wantSource {
  100. t.Fatalf("traffic source = %q, want %q", got, wantSource)
  101. }
  102. case <-time.After(500 * time.Millisecond):
  103. t.Fatalf("timed out waiting for %q traffic event", wantSource)
  104. }
  105. }
  106. }
  107. func TestHub_UnregisterClosesSendAndDecrementsCount(t *testing.T) {
  108. h := NewHub()
  109. defer h.Stop()
  110. go h.Run()
  111. c := NewClient("c1")
  112. h.Register(c)
  113. waitClientCount(t, h, 1)
  114. h.Unregister(c)
  115. waitClientCount(t, h, 0)
  116. select {
  117. case _, ok := <-c.Send:
  118. if ok {
  119. t.Fatal("expected Send channel to be closed after Unregister")
  120. }
  121. case <-time.After(500 * time.Millisecond):
  122. t.Fatal("Send channel was not closed after Unregister")
  123. }
  124. }
  125. func TestHub_StopClosesAllClients(t *testing.T) {
  126. h := NewHub()
  127. go h.Run()
  128. c1 := NewClient("c1")
  129. c2 := NewClient("c2")
  130. h.Register(c1)
  131. h.Register(c2)
  132. waitClientCount(t, h, 2)
  133. h.Stop()
  134. for _, c := range []*Client{c1, c2} {
  135. select {
  136. case _, ok := <-c.Send:
  137. if ok {
  138. t.Fatalf("client %s Send should be closed after Stop", c.ID)
  139. }
  140. case <-time.After(500 * time.Millisecond):
  141. t.Fatalf("client %s Send not closed after Stop", c.ID)
  142. }
  143. }
  144. }
  145. func TestHub_ShouldThrottle(t *testing.T) {
  146. h := NewHub()
  147. defer h.Stop()
  148. if h.shouldThrottle(MessageTypeStatus) {
  149. t.Fatal("non-gated message type should never throttle")
  150. }
  151. if h.shouldThrottle(MessageTypeStatus) {
  152. t.Fatal("non-gated message type should never throttle on second call")
  153. }
  154. if h.shouldThrottle(MessageTypeInbounds) {
  155. t.Fatal("first call for gated type should not throttle")
  156. }
  157. if !h.shouldThrottle(MessageTypeInbounds) {
  158. t.Fatal("immediate second call for gated type should throttle")
  159. }
  160. for i := range 2 {
  161. if h.shouldThrottle(MessageTypeTraffic) {
  162. t.Fatalf("traffic event %d must not be throttled", i+1)
  163. }
  164. }
  165. }
  166. func TestHub_ShouldThrottle_DistinctTypesIndependent(t *testing.T) {
  167. h := NewHub()
  168. defer h.Stop()
  169. if h.shouldThrottle(MessageTypeInbounds) {
  170. t.Fatal("first Inbounds call should not throttle")
  171. }
  172. if h.shouldThrottle(MessageTypeOutbounds) {
  173. t.Fatal("first Outbounds call should not throttle even after Inbounds")
  174. }
  175. }
  176. func TestTrySend_SucceedsWithRoom(t *testing.T) {
  177. c := &Client{ID: "c", Send: make(chan []byte, 1)}
  178. if !trySend(c, []byte("hi")) {
  179. t.Fatal("trySend should succeed when buffer has room")
  180. }
  181. }
  182. func TestTrySend_FailsWhenFull(t *testing.T) {
  183. c := &Client{ID: "c", Send: make(chan []byte, 1)}
  184. c.Send <- []byte("first")
  185. if trySend(c, []byte("second")) {
  186. t.Fatal("trySend should fail when buffer is full")
  187. }
  188. }
  189. func TestTrySend_FailsOnClosedChannel(t *testing.T) {
  190. c := &Client{ID: "c", Send: make(chan []byte, 1)}
  191. close(c.Send)
  192. if trySend(c, []byte("after-close")) {
  193. t.Fatal("trySend should fail (not panic) when channel is closed")
  194. }
  195. }
  196. func TestHub_FanoutEvictsSlowClient(t *testing.T) {
  197. h := NewHub()
  198. defer h.Stop()
  199. go h.Run()
  200. slow := &Client{ID: "slow", Send: make(chan []byte, 1)}
  201. slow.Send <- []byte("buffer-already-full")
  202. h.Register(slow)
  203. waitClientCount(t, h, 1)
  204. h.Broadcast(MessageTypeStatus, "payload")
  205. waitClientCount(t, h, 0)
  206. select {
  207. case _, ok := <-slow.Send:
  208. if ok {
  209. _, ok = <-slow.Send
  210. if ok {
  211. t.Fatal("slow client Send should eventually be closed by fanout eviction")
  212. }
  213. }
  214. case <-time.After(500 * time.Millisecond):
  215. t.Fatal("slow client Send channel was not closed")
  216. }
  217. }
  218. func TestHub_ConcurrentRegisterUnregister(t *testing.T) {
  219. h := NewHub()
  220. defer h.Stop()
  221. go h.Run()
  222. const n = 50
  223. var wg sync.WaitGroup
  224. for i := range n {
  225. wg.Add(1)
  226. go func(idx int) {
  227. defer wg.Done()
  228. c := NewClient("c")
  229. h.Register(c)
  230. h.Unregister(c)
  231. }(i)
  232. }
  233. wg.Wait()
  234. waitClientCount(t, h, 0)
  235. }
  236. func waitClientCount(t *testing.T, h *Hub, want int) {
  237. t.Helper()
  238. deadline := time.Now().Add(time.Second)
  239. for time.Now().Before(deadline) {
  240. if h.GetClientCount() == want {
  241. return
  242. }
  243. time.Sleep(5 * time.Millisecond)
  244. }
  245. t.Fatalf("client count never reached %d (last seen %d)", want, h.GetClientCount())
  246. }