1
0

xray_traffic_job.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package job
  2. import (
  3. "encoding/json"
  4. "github.com/mhsanaei/3x-ui/v3/logger"
  5. "github.com/mhsanaei/3x-ui/v3/web/service"
  6. "github.com/mhsanaei/3x-ui/v3/web/websocket"
  7. "github.com/mhsanaei/3x-ui/v3/xray"
  8. "github.com/valyala/fasthttp"
  9. )
  10. // XrayTrafficJob collects and processes traffic statistics from Xray, updating the database and optionally informing external APIs.
  11. type XrayTrafficJob struct {
  12. settingService service.SettingService
  13. xrayService service.XrayService
  14. inboundService service.InboundService
  15. outboundService service.OutboundService
  16. }
  17. // NewXrayTrafficJob creates a new traffic collection job instance.
  18. func NewXrayTrafficJob() *XrayTrafficJob {
  19. return new(XrayTrafficJob)
  20. }
  21. // Run collects traffic statistics from Xray, updates the database, and pushes
  22. // real-time updates over WebSocket using compact delta payloads — no REST
  23. // fallback, scales to 10k–20k+ clients per inbound.
  24. func (j *XrayTrafficJob) Run() {
  25. if !j.xrayService.IsXrayRunning() {
  26. return
  27. }
  28. traffics, clientTraffics, err := j.xrayService.GetXrayTraffic()
  29. if err != nil {
  30. return
  31. }
  32. needRestart0, clientsDisabled, err := j.inboundService.AddTraffic(traffics, clientTraffics)
  33. if err != nil {
  34. logger.Warning("add inbound traffic failed:", err)
  35. }
  36. err, needRestart1 := j.outboundService.AddTraffic(traffics, clientTraffics)
  37. if err != nil {
  38. logger.Warning("add outbound traffic failed:", err)
  39. }
  40. if clientsDisabled {
  41. restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable()
  42. if settingErr != nil {
  43. logger.Warning("get RestartXrayOnClientDisable failed:", settingErr)
  44. }
  45. if restartOnDisable {
  46. if err := j.xrayService.RestartXray(true); err != nil {
  47. logger.Warning("restart xray after disabling clients failed:", err)
  48. j.xrayService.SetToNeedRestart()
  49. }
  50. }
  51. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  52. }
  53. if ExternalTrafficInformEnable, err := j.settingService.GetExternalTrafficInformEnable(); ExternalTrafficInformEnable {
  54. j.informTrafficToExternalAPI(traffics, clientTraffics)
  55. } else if err != nil {
  56. logger.Warning("get ExternalTrafficInformEnable failed:", err)
  57. }
  58. if needRestart0 || needRestart1 {
  59. j.xrayService.SetToNeedRestart()
  60. }
  61. // If no frontend client is connected, skip all WebSocket broadcasting
  62. // routines — including the active-client DB query and JSON marshaling.
  63. if !websocket.HasClients() {
  64. return
  65. }
  66. // Online presence + traffic deltas — small payload, always fits in WS.
  67. // Force non-nil slice/map so JSON marshalling produces [] / {} instead of
  68. // `null` when everyone is offline. The frontend's traffic handler treats
  69. // a missing/null onlineClients field as "no update", so without this the
  70. // "everyone went offline" transition was silently dropped — stale online
  71. // users lingered in the list and the online filter kept showing them.
  72. onlineClients := j.inboundService.GetOnlineClients()
  73. if onlineClients == nil {
  74. onlineClients = []string{}
  75. }
  76. lastOnlineMap, err := j.inboundService.GetClientsLastOnline()
  77. if err != nil {
  78. logger.Warning("get clients last online failed:", err)
  79. }
  80. if lastOnlineMap == nil {
  81. lastOnlineMap = make(map[string]int64)
  82. }
  83. websocket.BroadcastTraffic(map[string]any{
  84. "traffics": traffics,
  85. "clientTraffics": clientTraffics,
  86. "onlineClients": onlineClients,
  87. "lastOnlineMap": lastOnlineMap,
  88. })
  89. // Compact delta payload: per-client absolute counters for clients active
  90. // this cycle, plus inbound-level absolute totals. Frontend applies both
  91. // in-place — typical payload ~10–50KB even for 10k+ client deployments.
  92. // Replaces the old full-inbound-list broadcast that hit WS size limits
  93. // (5–10MB) and forced the frontend into a REST refetch.
  94. clientStatsPayload := map[string]any{}
  95. if activeEmails := activeEmails(clientTraffics); len(activeEmails) > 0 {
  96. if stats, err := j.inboundService.GetActiveClientTraffics(activeEmails); err != nil {
  97. logger.Warning("get active client traffics for websocket failed:", err)
  98. } else if len(stats) > 0 {
  99. clientStatsPayload["clients"] = stats
  100. }
  101. }
  102. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  103. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  104. } else if len(inboundSummary) > 0 {
  105. clientStatsPayload["inbounds"] = inboundSummary
  106. }
  107. if len(clientStatsPayload) > 0 {
  108. websocket.BroadcastClientStats(clientStatsPayload)
  109. }
  110. // Outbounds list is small (one row per outbound, no per-client expansion)
  111. // so the full snapshot still fits comfortably in WS.
  112. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  113. websocket.BroadcastOutbounds(updatedOutbounds)
  114. } else if err != nil {
  115. logger.Warning("get all outbounds for websocket failed:", err)
  116. }
  117. }
  118. // activeEmails returns the set of client emails that had non-zero traffic in
  119. // the current collection window. Idle clients are skipped — no need to push
  120. // their (unchanged) counters to the frontend.
  121. func activeEmails(clientTraffics []*xray.ClientTraffic) []string {
  122. if len(clientTraffics) == 0 {
  123. return nil
  124. }
  125. emails := make([]string, 0, len(clientTraffics))
  126. for _, ct := range clientTraffics {
  127. if ct == nil || ct.Email == "" {
  128. continue
  129. }
  130. if ct.Up == 0 && ct.Down == 0 {
  131. continue
  132. }
  133. emails = append(emails, ct.Email)
  134. }
  135. return emails
  136. }
  137. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  138. informURL, err := j.settingService.GetExternalTrafficInformURI()
  139. if err != nil {
  140. logger.Warning("get ExternalTrafficInformURI failed:", err)
  141. return
  142. }
  143. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  144. if err != nil {
  145. logger.Warning("parse client/inbound traffic failed:", err)
  146. return
  147. }
  148. request := fasthttp.AcquireRequest()
  149. defer fasthttp.ReleaseRequest(request)
  150. request.Header.SetMethod("POST")
  151. request.Header.SetContentType("application/json; charset=UTF-8")
  152. request.SetBody([]byte(requestBody))
  153. request.SetRequestURI(informURL)
  154. response := fasthttp.AcquireResponse()
  155. defer fasthttp.ReleaseResponse(response)
  156. if err := fasthttp.Do(request, response); err != nil {
  157. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  158. }
  159. }