xray_traffic_job.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. lastOnlineMap, err := j.inboundService.GetClientsLastOnline()
  73. if err != nil {
  74. logger.Warning("get clients last online failed:", err)
  75. }
  76. if lastOnlineMap == nil {
  77. lastOnlineMap = make(map[string]int64)
  78. }
  79. // Determine online clients from lastOnline timestamps with a 5-second
  80. // grace period instead of just the current 5-second traffic poll. This
  81. // prevents idle-but-connected clients from randomly disappearing from
  82. // the UI between polling windows.
  83. j.inboundService.RefreshOnlineClientsFromMap(lastOnlineMap)
  84. onlineClients := j.inboundService.GetOnlineClients()
  85. if onlineClients == nil {
  86. onlineClients = []string{}
  87. }
  88. websocket.BroadcastTraffic(map[string]any{
  89. "traffics": traffics,
  90. "clientTraffics": clientTraffics,
  91. "onlineClients": onlineClients,
  92. "lastOnlineMap": lastOnlineMap,
  93. })
  94. // Full snapshot every cycle: absolute per-client counters and inbound
  95. // totals. Frontend overwrites both in place. The previous delta path
  96. // (activeEmails -> GetActiveClientTraffics) silently omitted the
  97. // clients array whenever nobody moved bytes in the cycle, leaving the
  98. // client rows in the UI stuck at stale traffic/remained/all-time.
  99. clientStatsPayload := map[string]any{}
  100. if stats, err := j.inboundService.GetAllClientTraffics(); err != nil {
  101. logger.Warning("get all client traffics for websocket failed:", err)
  102. } else if len(stats) > 0 {
  103. clientStatsPayload["clients"] = stats
  104. }
  105. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  106. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  107. } else if len(inboundSummary) > 0 {
  108. clientStatsPayload["inbounds"] = inboundSummary
  109. }
  110. if len(clientStatsPayload) > 0 {
  111. websocket.BroadcastClientStats(clientStatsPayload)
  112. }
  113. // Outbounds list is small (one row per outbound, no per-client expansion)
  114. // so the full snapshot still fits comfortably in WS.
  115. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  116. websocket.BroadcastOutbounds(updatedOutbounds)
  117. } else if err != nil {
  118. logger.Warning("get all outbounds for websocket failed:", err)
  119. }
  120. }
  121. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  122. informURL, err := j.settingService.GetExternalTrafficInformURI()
  123. if err != nil {
  124. logger.Warning("get ExternalTrafficInformURI failed:", err)
  125. return
  126. }
  127. informURL, err = service.SanitizePublicHTTPURL(informURL, false)
  128. if err != nil {
  129. logger.Warning("ExternalTrafficInformURI blocked:", err)
  130. return
  131. }
  132. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  133. if err != nil {
  134. logger.Warning("parse client/inbound traffic failed:", err)
  135. return
  136. }
  137. request := fasthttp.AcquireRequest()
  138. defer fasthttp.ReleaseRequest(request)
  139. request.Header.SetMethod("POST")
  140. request.Header.SetContentType("application/json; charset=UTF-8")
  141. request.SetBody([]byte(requestBody))
  142. request.SetRequestURI(informURL)
  143. response := fasthttp.AcquireResponse()
  144. defer fasthttp.ReleaseResponse(response)
  145. if err := fasthttp.Do(request, response); err != nil {
  146. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  147. }
  148. }