1
0

periodic_traffic_reset_client_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package job
  2. import (
  3. "encoding/json"
  4. "path/filepath"
  5. "testing"
  6. "time"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  11. )
  12. func initResetJobDB(t *testing.T) {
  13. t.Helper()
  14. dbDir := t.TempDir()
  15. t.Setenv("XUI_DB_FOLDER", dbDir)
  16. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  17. }
  18. type seededClient struct {
  19. email string
  20. cycle string
  21. day int
  22. recordEnable bool
  23. quotaEnable bool
  24. total int64
  25. }
  26. // seedClientOnCycle creates an inbound that never resets on its own, a client
  27. // carrying its own cycle, and the client_inbounds link the reset path resolves
  28. // through — without it every reset falls into the orphaned-client branch.
  29. func seedClientOnCycle(t *testing.T, port int, c seededClient) {
  30. t.Helper()
  31. db := database.GetDB()
  32. client := model.Client{
  33. Email: c.email, ID: uuidFor(port), Enable: c.recordEnable,
  34. TrafficReset: c.cycle, TrafficResetDay: c.day,
  35. }
  36. settings, err := json.Marshal(map[string]any{"clients": []model.Client{client}})
  37. if err != nil {
  38. t.Fatalf("marshal settings: %v", err)
  39. }
  40. ib := model.Inbound{
  41. UserId: 1, Enable: true, Port: port, Protocol: model.VLESS,
  42. Tag: "inbound-" + c.email, TrafficReset: "never", Settings: string(settings),
  43. }
  44. if err := db.Create(&ib).Error; err != nil {
  45. t.Fatalf("create inbound: %v", err)
  46. }
  47. rec := model.ClientRecord{
  48. Email: c.email, UUID: client.ID, Enable: c.recordEnable,
  49. TrafficReset: c.cycle, TrafficResetDay: c.day,
  50. }
  51. if err := db.Create(&rec).Error; err != nil {
  52. t.Fatalf("create client record: %v", err)
  53. }
  54. // gorm skips a false bool on insert, so the column default:true wins; the
  55. // disabled case has to be written back explicitly.
  56. if err := db.Model(&model.ClientRecord{}).Where("id = ?", rec.Id).
  57. Update("enable", c.recordEnable).Error; err != nil {
  58. t.Fatalf("set record enable: %v", err)
  59. }
  60. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: ib.Id}).Error; err != nil {
  61. t.Fatalf("link client to inbound: %v", err)
  62. }
  63. if err := db.Create(&xray.ClientTraffic{
  64. InboundId: ib.Id, Email: c.email, Enable: c.quotaEnable, Up: 500, Down: 700, Total: c.total,
  65. }).Error; err != nil {
  66. t.Fatalf("create traffic: %v", err)
  67. }
  68. }
  69. func uuidFor(port int) string {
  70. return "00000000-0000-0000-0000-0000000" + string(rune('0'+port/10000%10)) +
  71. string(rune('0'+port/1000%10)) + string(rune('0'+port/100%10)) +
  72. string(rune('0'+port/10%10)) + string(rune('0'+port%10))
  73. }
  74. func trafficFor(t *testing.T, email string) xray.ClientTraffic {
  75. t.Helper()
  76. var row xray.ClientTraffic
  77. if err := database.GetDB().Where("email = ?", email).First(&row).Error; err != nil {
  78. t.Fatalf("read traffic for %s: %v", email, err)
  79. }
  80. return row
  81. }
  82. func recordFor(t *testing.T, email string) model.ClientRecord {
  83. t.Helper()
  84. var rec model.ClientRecord
  85. if err := database.GetDB().Where("email = ?", email).First(&rec).Error; err != nil {
  86. t.Fatalf("read record for %s: %v", email, err)
  87. }
  88. return rec
  89. }
  90. func TestPeriodicTrafficResetClients(t *testing.T) {
  91. t.Run("resets a client on its own cycle inside a never-reset inbound", func(t *testing.T) {
  92. initResetJobDB(t)
  93. seedClientOnCycle(t, 41001, seededClient{email: "[email protected]", cycle: "weekly", day: 1, recordEnable: true, quotaEnable: true})
  94. seedClientOnCycle(t, 41002, seededClient{email: "[email protected]", cycle: "monthly", day: 1, recordEnable: true, quotaEnable: true})
  95. NewPeriodicTrafficResetJob("weekly", time.UTC).Run()
  96. if row := trafficFor(t, "[email protected]"); row.Up != 0 || row.Down != 0 {
  97. t.Fatalf("weekly client not reset by the weekly run: up=%d down=%d", row.Up, row.Down)
  98. }
  99. if row := trafficFor(t, "[email protected]"); row.Up != 500 || row.Down != 700 {
  100. t.Fatalf("monthly client reset by the weekly run: up=%d down=%d", row.Up, row.Down)
  101. }
  102. })
  103. t.Run("leaves a client with no cycle of its own alone", func(t *testing.T) {
  104. initResetJobDB(t)
  105. seedClientOnCycle(t, 41003, seededClient{email: "[email protected]", cycle: "never", day: 1, recordEnable: true, quotaEnable: true})
  106. for _, period := range []Period{"hourly", "daily", "weekly", "monthly"} {
  107. NewPeriodicTrafficResetJob(period, time.UTC).Run()
  108. }
  109. if row := trafficFor(t, "[email protected]"); row.Up != 500 || row.Down != 700 {
  110. t.Fatalf("client with trafficReset=never was reset: up=%d down=%d", row.Up, row.Down)
  111. }
  112. })
  113. t.Run("monthly client waits for its own day", func(t *testing.T) {
  114. initResetJobDB(t)
  115. today := time.Now().In(time.UTC).Day()
  116. otherDay := today%28 + 1
  117. seedClientOnCycle(t, 41004, seededClient{email: "[email protected]", cycle: "monthly", day: today, recordEnable: true, quotaEnable: true})
  118. seedClientOnCycle(t, 41005, seededClient{email: "[email protected]", cycle: "monthly", day: otherDay, recordEnable: true, quotaEnable: true})
  119. NewPeriodicTrafficResetJob("monthly", time.UTC).Run()
  120. if row := trafficFor(t, "[email protected]"); row.Up != 0 || row.Down != 0 {
  121. t.Fatalf("client due today was not reset: up=%d down=%d", row.Up, row.Down)
  122. }
  123. if row := trafficFor(t, "[email protected]"); row.Up != 500 || row.Down != 700 {
  124. t.Fatalf("client due on another day was reset: up=%d down=%d", row.Up, row.Down)
  125. }
  126. })
  127. t.Run("restores a client the quota switched off", func(t *testing.T) {
  128. initResetJobDB(t)
  129. // Depletion disables all three of client_traffics.enable, clients.enable
  130. // and the settings JSON, so a reset that lifts only the first leaves the
  131. // client out of the running core with nothing left to revisit it.
  132. seedClientOnCycle(t, 41006, seededClient{
  133. email: "[email protected]", cycle: "daily", day: 1,
  134. recordEnable: false, quotaEnable: false, total: 1000,
  135. })
  136. NewPeriodicTrafficResetJob("daily", time.UTC).Run()
  137. if row := trafficFor(t, "[email protected]"); !row.Enable {
  138. t.Fatal("quota gate not lifted: the client cannot use its new allowance")
  139. }
  140. if rec := recordFor(t, "[email protected]"); !rec.Enable {
  141. t.Fatal("clients.enable still false: GetXrayConfig skips the client, so it stays locked out for good")
  142. }
  143. if enabled := settingsEnableOf(t, 41006); !enabled {
  144. t.Fatal("the inbound settings JSON still has the client disabled")
  145. }
  146. })
  147. t.Run("leaves a client the operator switched off", func(t *testing.T) {
  148. initResetJobDB(t)
  149. // Disabled with usage below quota: nothing but a human did that.
  150. seedClientOnCycle(t, 41007, seededClient{
  151. email: "[email protected]", cycle: "daily", day: 1,
  152. recordEnable: false, quotaEnable: true, total: 100000,
  153. })
  154. NewPeriodicTrafficResetJob("daily", time.UTC).Run()
  155. if rec := recordFor(t, "[email protected]"); rec.Enable {
  156. t.Fatal("an operator-disabled client was switched back on by a cron job")
  157. }
  158. if row := trafficFor(t, "[email protected]"); row.Up != 500 || row.Down != 700 {
  159. t.Fatalf("an operator-disabled client was reset anyway: up=%d down=%d", row.Up, row.Down)
  160. }
  161. })
  162. }
  163. func settingsEnableOf(t *testing.T, port int) bool {
  164. t.Helper()
  165. var stored model.Inbound
  166. if err := database.GetDB().Where("port = ?", port).First(&stored).Error; err != nil {
  167. t.Fatal(err)
  168. }
  169. var settings struct {
  170. Clients []model.Client `json:"clients"`
  171. }
  172. if err := json.Unmarshal([]byte(stored.Settings), &settings); err != nil {
  173. t.Fatalf("parse inbound settings: %v", err)
  174. }
  175. if len(settings.Clients) != 1 {
  176. t.Fatalf("inbound holds %d clients, want 1", len(settings.Clients))
  177. }
  178. return settings.Clients[0].Enable
  179. }