xray_traffic_job.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package job
  2. import (
  3. "encoding/json"
  4. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  5. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  6. "github.com/mhsanaei/3x-ui/v3/internal/web/service/outbound"
  7. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. "github.com/valyala/fasthttp"
  10. )
  11. // XrayTrafficJob collects and processes traffic statistics from Xray, updating the database and optionally informing external APIs.
  12. type XrayTrafficJob struct {
  13. settingService service.SettingService
  14. xrayService service.XrayService
  15. inboundService service.InboundService
  16. outboundService outbound.OutboundService
  17. }
  18. // clientStatsSnapshotMaxClients caps how many client_traffics rows the job
  19. // ships as a full websocket snapshot per poll (same spirit as the
  20. // controller's broadcastInboundsUpdateClientLimit). Above it, a snapshot
  21. // would blow past the hub's payload cap and be dropped wholesale, so the job
  22. // broadcasts only this poll's active rows and the UI leans on its 5s REST
  23. // refetch for the rest.
  24. const clientStatsSnapshotMaxClients = 5000
  25. // NewXrayTrafficJob creates a new traffic collection job instance.
  26. func NewXrayTrafficJob() *XrayTrafficJob {
  27. return new(XrayTrafficJob)
  28. }
  29. // Run collects traffic statistics from Xray, updates the database, and pushes
  30. // real-time updates over WebSocket using compact delta payloads — no REST
  31. // fallback, scales to 10k–20k+ clients per inbound.
  32. func (j *XrayTrafficJob) Run() {
  33. if !j.xrayService.IsXrayRunning() {
  34. return
  35. }
  36. traffics, clientTraffics, err := j.xrayService.GetXrayTraffic()
  37. if err != nil {
  38. return
  39. }
  40. needRestart0, clientsDisabled, err := j.inboundService.AddTraffic(traffics, clientTraffics)
  41. if err != nil {
  42. logger.Warning("add inbound traffic failed:", err)
  43. }
  44. err, needRestart1 := j.outboundService.AddTraffic(traffics, clientTraffics)
  45. if err != nil {
  46. logger.Warning("add outbound traffic failed:", err)
  47. }
  48. if clientsDisabled {
  49. restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable()
  50. if settingErr != nil {
  51. logger.Warning("get RestartXrayOnClientDisable failed:", settingErr)
  52. }
  53. if restartOnDisable {
  54. if err := j.xrayService.RestartXray(false); err != nil {
  55. logger.Warning("reconcile xray after disabling clients failed:", err)
  56. j.xrayService.SetToNeedRestart()
  57. }
  58. }
  59. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  60. }
  61. if ExternalTrafficInformEnable, err := j.settingService.GetExternalTrafficInformEnable(); ExternalTrafficInformEnable {
  62. j.informTrafficToExternalAPI(traffics, clientTraffics)
  63. } else if err != nil {
  64. logger.Warning("get ExternalTrafficInformEnable failed:", err)
  65. }
  66. if needRestart0 || needRestart1 {
  67. j.xrayService.SetToNeedRestart()
  68. }
  69. // Derive the local online set from this poll's per-email deltas rather
  70. // than the shared last_online column, which remote-node syncs also bump
  71. // and would otherwise make a client active only on a remote node appear
  72. // online on local inbounds.
  73. activeEmails := make([]string, 0, len(clientTraffics))
  74. deltaActive := make(map[string]bool, len(clientTraffics))
  75. for _, ct := range clientTraffics {
  76. if ct != nil && ct.Up+ct.Down > 0 {
  77. activeEmails = append(activeEmails, ct.Email)
  78. deltaActive[ct.Email] = true
  79. }
  80. }
  81. // When the core supports the online-stats API, union in connection-based
  82. // onlines. Neither signal alone covers everything: an idle-but-connected
  83. // client moves no bytes between polls (the delta heuristic's blind spot),
  84. // while a short-lived connection can close before this poll yet still show
  85. // in the delta. Older cores fall back to deltas alone.
  86. if onlineUsers, apiMode, ouErr := j.xrayService.GetOnlineUsers(); ouErr != nil {
  87. logger.Debug("get online users from xray api failed:", ouErr)
  88. } else if apiMode {
  89. idleOnline := make([]string, 0, len(onlineUsers))
  90. for _, u := range onlineUsers {
  91. if !deltaActive[u.Email] {
  92. activeEmails = append(activeEmails, u.Email)
  93. idleOnline = append(idleOnline, u.Email)
  94. }
  95. }
  96. // The traffic path only bumps last_online on a non-zero delta; keep the
  97. // column fresh for clients kept online purely by a live connection.
  98. if err := j.inboundService.BumpClientsLastOnline(idleOnline); err != nil {
  99. logger.Warning("bump last online for connected clients failed:", err)
  100. }
  101. }
  102. // Pair the email signal with the inbound tags that moved bytes this poll.
  103. // Xray's user>>>email counter aggregates across every inbound a client is
  104. // attached to, so an online email alone can't say which inbound it used —
  105. // gating the per-inbound view on these tags keeps a multi-inbound client
  106. // off inbounds that saw no traffic. See issue #4859.
  107. activeInboundTags := make([]string, 0, len(traffics))
  108. for _, tr := range traffics {
  109. if tr != nil && tr.IsInbound && tr.Up+tr.Down > 0 {
  110. activeInboundTags = append(activeInboundTags, tr.Tag)
  111. }
  112. }
  113. j.inboundService.RefreshLocalOnlineClients(activeEmails, activeInboundTags)
  114. if !websocket.HasClients() {
  115. return
  116. }
  117. // Small installs broadcast the full snapshot (see GetAllClientTraffics for
  118. // why deltas alone left UI rows stale). Above the threshold the snapshot
  119. // would be dropped by the hub's payload cap anyway, so ship this poll's
  120. // active rows instead and scope last-online to them; the initial full map
  121. // still arrives over REST.
  122. snapshot := true
  123. if total, countErr := j.inboundService.CountClientTraffics(); countErr != nil {
  124. logger.Warning("count client traffics for websocket failed:", countErr)
  125. } else if total > clientStatsSnapshotMaxClients {
  126. snapshot = false
  127. }
  128. var stats []*xray.ClientTraffic
  129. var statsErr error
  130. if snapshot {
  131. stats, statsErr = j.inboundService.GetAllClientTraffics()
  132. } else {
  133. stats, statsErr = j.inboundService.GetActiveClientTraffics(activeEmails)
  134. }
  135. if statsErr != nil {
  136. logger.Warning("get client traffics for websocket failed:", statsErr)
  137. }
  138. var lastOnlineMap map[string]int64
  139. if snapshot {
  140. if lastOnlineMap, err = j.inboundService.GetClientsLastOnline(); err != nil {
  141. logger.Warning("get clients last online failed:", err)
  142. }
  143. } else {
  144. lastOnlineMap = make(map[string]int64, len(stats))
  145. for _, ct := range stats {
  146. if ct != nil {
  147. lastOnlineMap[ct.Email] = ct.LastOnline
  148. }
  149. }
  150. }
  151. if lastOnlineMap == nil {
  152. lastOnlineMap = make(map[string]int64)
  153. }
  154. onlineClients := j.inboundService.GetOnlineClients()
  155. if onlineClients == nil {
  156. onlineClients = []string{}
  157. }
  158. websocket.BroadcastTraffic(map[string]any{
  159. "traffics": traffics,
  160. "clientTraffics": clientTraffics,
  161. "onlineClients": onlineClients,
  162. "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
  163. "activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
  164. "lastOnlineMap": lastOnlineMap,
  165. })
  166. clientStatsPayload := map[string]any{"snapshot": snapshot}
  167. if len(stats) > 0 {
  168. clientStatsPayload["clients"] = stats
  169. }
  170. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  171. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  172. } else if len(inboundSummary) > 0 {
  173. clientStatsPayload["inbounds"] = inboundSummary
  174. }
  175. if len(clientStatsPayload) > 1 {
  176. websocket.BroadcastClientStats(clientStatsPayload)
  177. }
  178. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  179. websocket.BroadcastOutbounds(updatedOutbounds)
  180. } else if err != nil {
  181. logger.Warning("get all outbounds for websocket failed:", err)
  182. }
  183. }
  184. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  185. informURL, err := j.settingService.GetExternalTrafficInformURI()
  186. if err != nil {
  187. logger.Warning("get ExternalTrafficInformURI failed:", err)
  188. return
  189. }
  190. informURL, err = service.SanitizePublicHTTPURL(informURL, false)
  191. if err != nil {
  192. logger.Warning("ExternalTrafficInformURI blocked:", err)
  193. return
  194. }
  195. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  196. if err != nil {
  197. logger.Warning("parse client/inbound traffic failed:", err)
  198. return
  199. }
  200. request := fasthttp.AcquireRequest()
  201. defer fasthttp.ReleaseRequest(request)
  202. request.Header.SetMethod("POST")
  203. request.Header.SetContentType("application/json; charset=UTF-8")
  204. request.SetBody(requestBody)
  205. request.SetRequestURI(informURL)
  206. response := fasthttp.AcquireResponse()
  207. defer fasthttp.ReleaseResponse(response)
  208. if err := fasthttp.Do(request, response); err != nil {
  209. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  210. }
  211. }