1
0

xray_traffic_job.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package job
  2. import (
  3. "encoding/json"
  4. "github.com/mhsanaei/3x-ui/v2/logger"
  5. "github.com/mhsanaei/3x-ui/v2/web/service"
  6. "github.com/mhsanaei/3x-ui/v2/web/websocket"
  7. "github.com/mhsanaei/3x-ui/v2/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. }
  52. if ExternalTrafficInformEnable, err := j.settingService.GetExternalTrafficInformEnable(); ExternalTrafficInformEnable {
  53. j.informTrafficToExternalAPI(traffics, clientTraffics)
  54. } else if err != nil {
  55. logger.Warning("get ExternalTrafficInformEnable failed:", err)
  56. }
  57. if needRestart0 || needRestart1 {
  58. j.xrayService.SetToNeedRestart()
  59. }
  60. // If no frontend client is connected, skip all WebSocket broadcasting
  61. // routines — including the active-client DB query and JSON marshaling.
  62. if !websocket.HasClients() {
  63. return
  64. }
  65. // Online presence + traffic deltas — small payload, always fits in WS.
  66. // Force non-nil slice/map so JSON marshalling produces [] / {} instead of
  67. // `null` when everyone is offline. The frontend's traffic handler treats
  68. // a missing/null onlineClients field as "no update", so without this the
  69. // "everyone went offline" transition was silently dropped — stale online
  70. // users lingered in the list and the online filter kept showing them.
  71. onlineClients := j.inboundService.GetOnlineClients()
  72. if onlineClients == nil {
  73. onlineClients = []string{}
  74. }
  75. lastOnlineMap, err := j.inboundService.GetClientsLastOnline()
  76. if err != nil {
  77. logger.Warning("get clients last online failed:", err)
  78. }
  79. if lastOnlineMap == nil {
  80. lastOnlineMap = make(map[string]int64)
  81. }
  82. websocket.BroadcastTraffic(map[string]any{
  83. "traffics": traffics,
  84. "clientTraffics": clientTraffics,
  85. "onlineClients": onlineClients,
  86. "lastOnlineMap": lastOnlineMap,
  87. })
  88. // Compact delta payload: per-client absolute counters for clients active
  89. // this cycle, plus inbound-level absolute totals. Frontend applies both
  90. // in-place — typical payload ~10–50KB even for 10k+ client deployments.
  91. // Replaces the old full-inbound-list broadcast that hit WS size limits
  92. // (5–10MB) and forced the frontend into a REST refetch.
  93. clientStatsPayload := map[string]any{}
  94. if activeEmails := activeEmails(clientTraffics); len(activeEmails) > 0 {
  95. if stats, err := j.inboundService.GetActiveClientTraffics(activeEmails); err != nil {
  96. logger.Warning("get active client traffics for websocket failed:", err)
  97. } else if len(stats) > 0 {
  98. clientStatsPayload["clients"] = stats
  99. }
  100. }
  101. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  102. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  103. } else if len(inboundSummary) > 0 {
  104. clientStatsPayload["inbounds"] = inboundSummary
  105. }
  106. if len(clientStatsPayload) > 0 {
  107. websocket.BroadcastClientStats(clientStatsPayload)
  108. }
  109. // Outbounds list is small (one row per outbound, no per-client expansion)
  110. // so the full snapshot still fits comfortably in WS.
  111. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  112. websocket.BroadcastOutbounds(updatedOutbounds)
  113. } else if err != nil {
  114. logger.Warning("get all outbounds for websocket failed:", err)
  115. }
  116. }
  117. // activeEmails returns the set of client emails that had non-zero traffic in
  118. // the current collection window. Idle clients are skipped — no need to push
  119. // their (unchanged) counters to the frontend.
  120. func activeEmails(clientTraffics []*xray.ClientTraffic) []string {
  121. if len(clientTraffics) == 0 {
  122. return nil
  123. }
  124. emails := make([]string, 0, len(clientTraffics))
  125. for _, ct := range clientTraffics {
  126. if ct == nil || ct.Email == "" {
  127. continue
  128. }
  129. if ct.Up == 0 && ct.Down == 0 {
  130. continue
  131. }
  132. emails = append(emails, ct.Email)
  133. }
  134. return emails
  135. }
  136. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  137. informURL, err := j.settingService.GetExternalTrafficInformURI()
  138. if err != nil {
  139. logger.Warning("get ExternalTrafficInformURI failed:", err)
  140. return
  141. }
  142. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  143. if err != nil {
  144. logger.Warning("parse client/inbound traffic failed:", err)
  145. return
  146. }
  147. request := fasthttp.AcquireRequest()
  148. defer fasthttp.ReleaseRequest(request)
  149. request.Header.SetMethod("POST")
  150. request.Header.SetContentType("application/json; charset=UTF-8")
  151. request.SetBody([]byte(requestBody))
  152. request.SetRequestURI(informURL)
  153. response := fasthttp.AcquireResponse()
  154. defer fasthttp.ReleaseResponse(response)
  155. if err := fasthttp.Do(request, response); err != nil {
  156. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  157. }
  158. }