1
0

check_client_ip_scale_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package job
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/op/go-logging"
  12. "gorm.io/gorm"
  13. "github.com/mhsanaei/3x-ui/v3/internal/config"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  17. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. )
  19. // setupScaleJobDB mirrors the service package's scale gating: Postgres via
  20. // XUI_DB_TYPE/XUI_DB_DSN, SQLite via XUI_SCALE_TEST=1, skip otherwise.
  21. func setupScaleJobDB(t *testing.T) {
  22. t.Helper()
  23. loggerInitOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) })
  24. t.Setenv("XUI_LOG_FOLDER", t.TempDir())
  25. if os.Getenv("XUI_DB_TYPE") == "postgres" && strings.TrimSpace(os.Getenv("XUI_DB_DSN")) != "" {
  26. if err := database.InitDB(""); err != nil {
  27. t.Fatalf("InitDB(postgres): %v", err)
  28. }
  29. t.Cleanup(func() { _ = database.CloseDB() })
  30. return
  31. }
  32. switch strings.ToLower(strings.TrimSpace(os.Getenv("XUI_SCALE_TEST"))) {
  33. case "1", "true", "yes":
  34. dbtest.InitDB(t, filepath.Join(t.TempDir(), "scale.db"))
  35. return
  36. }
  37. t.Skip("set XUI_SCALE_TEST=1 (sqlite) or XUI_DB_TYPE=postgres + XUI_DB_DSN (postgres) to run the scale benchmark")
  38. }
  39. func scaleJobSizes(t *testing.T, def ...int) []int {
  40. t.Helper()
  41. raw := strings.TrimSpace(os.Getenv("XUI_SCALE_SIZES"))
  42. if raw == "" {
  43. return def
  44. }
  45. var out []int
  46. for part := range strings.SplitSeq(raw, ",") {
  47. part = strings.TrimSpace(part)
  48. if part == "" {
  49. continue
  50. }
  51. n, err := strconv.Atoi(part)
  52. if err != nil || n <= 0 {
  53. t.Fatalf("XUI_SCALE_SIZES: invalid size %q", part)
  54. }
  55. out = append(out, n)
  56. }
  57. if len(out) == 0 {
  58. return def
  59. }
  60. return out
  61. }
  62. func resetScaleJobTables(t *testing.T, db *gorm.DB) {
  63. t.Helper()
  64. if config.GetDBKind() == "postgres" {
  65. if err := db.Exec("TRUNCATE TABLE inbounds, clients, client_inbounds RESTART IDENTITY CASCADE").Error; err != nil {
  66. t.Fatalf("truncate: %v", err)
  67. }
  68. } else {
  69. for _, tbl := range []string{"inbounds", "clients", "client_inbounds"} {
  70. if err := db.Exec("DELETE FROM " + tbl).Error; err != nil {
  71. t.Fatalf("delete %s: %v", tbl, err)
  72. }
  73. }
  74. db.Exec("DELETE FROM sqlite_sequence")
  75. }
  76. if err := db.Where("1 = 1").Delete(&model.InboundClientIps{}).Error; err != nil {
  77. t.Fatalf("clear inbound client ips: %v", err)
  78. }
  79. if err := db.Where("1 = 1").Delete(&model.NodeClientIp{}).Error; err != nil {
  80. t.Fatalf("clear node client ips: %v", err)
  81. }
  82. }
  83. // seedScaleIPDataset seeds n clients across numInbounds inbounds. Every client
  84. // in the LAST inbound carries limitIp=3 (and 0 elsewhere), so hasLimitIp pays
  85. // its full scan cost before finding a hit, and the returned emails all resolve
  86. // to that last inbound for the processObserved measurement.
  87. func seedScaleIPDataset(t *testing.T, n, numInbounds int) []string {
  88. t.Helper()
  89. db := database.GetDB()
  90. resetScaleJobTables(t, db)
  91. tx := db.Begin()
  92. if tx.Error != nil {
  93. t.Fatalf("begin seed tx: %v", tx.Error)
  94. }
  95. committed := false
  96. defer func() {
  97. if !committed {
  98. tx.Rollback()
  99. }
  100. }()
  101. var limitedEmails []string
  102. per := n / numInbounds
  103. for i := range numInbounds {
  104. lo, hi := i*per, (i+1)*per
  105. if i == numInbounds-1 {
  106. hi = n
  107. }
  108. limitIp := 0
  109. if i == numInbounds-1 {
  110. limitIp = 3
  111. }
  112. clients := make([]model.Client, 0, hi-lo)
  113. records := make([]*model.ClientRecord, 0, hi-lo)
  114. for j := lo; j < hi; j++ {
  115. email := fmt.Sprintf("user-%07d@ipscale", j)
  116. clients = append(clients, model.Client{Email: email, LimitIP: limitIp, Enable: true})
  117. records = append(records, &model.ClientRecord{Email: email, LimitIP: limitIp, Enable: true})
  118. if limitIp > 0 {
  119. limitedEmails = append(limitedEmails, email)
  120. }
  121. }
  122. settings, err := json.Marshal(map[string][]model.Client{"clients": clients})
  123. if err != nil {
  124. t.Fatalf("marshal settings: %v", err)
  125. }
  126. ib := &model.Inbound{
  127. UserId: 1,
  128. Tag: fmt.Sprintf("ipscale-%d-%d", n, i),
  129. Enable: true,
  130. Port: 42000 + i,
  131. Protocol: model.VLESS,
  132. Settings: string(settings),
  133. }
  134. if err := tx.Create(ib).Error; err != nil {
  135. t.Fatalf("seed inbound %d: %v", i, err)
  136. }
  137. if err := tx.CreateInBatches(records, 500).Error; err != nil {
  138. t.Fatalf("seed clients %d: %v", i, err)
  139. }
  140. links := make([]model.ClientInbound, len(records))
  141. for j := range records {
  142. links[j] = model.ClientInbound{ClientId: records[j].Id, InboundId: ib.Id}
  143. }
  144. if err := tx.CreateInBatches(links, 1000).Error; err != nil {
  145. t.Fatalf("seed client_inbounds %d: %v", i, err)
  146. }
  147. }
  148. if err := tx.Commit().Error; err != nil {
  149. t.Fatalf("commit seed tx: %v", err)
  150. }
  151. committed = true
  152. db.Exec("ANALYZE")
  153. return limitedEmails
  154. }
  155. // TestCheckClientIpScale measures the @every 10s ip-limit job pieces: the
  156. // hasLimitIp gate (settings LIKE scan + full JSON parse of every matching
  157. // inbound) and processObserved with M online users (per-email inbound lookup,
  158. // settings parse and autocommit save). Run twice: first scan half add / half
  159. // update, second scan all update path.
  160. func TestCheckClientIpScale(t *testing.T) {
  161. shapes := []struct {
  162. name string
  163. inbounds int
  164. observed int
  165. }{{"single", 1, 50}, {"spread50", 50, 1000}}
  166. for _, n := range scaleJobSizes(t, 10000, 100000) {
  167. for _, shape := range shapes {
  168. t.Run(fmt.Sprintf("N=%d_%s", n, shape.name), func(t *testing.T) {
  169. setupScaleJobDB(t)
  170. limited := seedScaleIPDataset(t, n, shape.inbounds)
  171. m := min(shape.observed, len(limited))
  172. j := NewCheckClientIpJob()
  173. const reps = 3
  174. start := time.Now()
  175. for range reps {
  176. if !j.hasLimitIp() {
  177. t.Fatal("hasLimitIp = false, want true")
  178. }
  179. }
  180. t.Logf("N=%-7d shape=%-8s hasLimitIp=%v/call", n, shape.name, (time.Since(start) / reps).Round(time.Millisecond))
  181. now := time.Now().Unix()
  182. observed := make(map[string]map[string]int64, m)
  183. for i := range m {
  184. observed[limited[i]] = map[string]int64{
  185. fmt.Sprintf("10.0.%d.%d", i/250, i%250+1): now,
  186. }
  187. }
  188. for i := range m / 2 {
  189. seedClientIps(t, limited[i], []IPWithTimestamp{{IP: "10.99.0.1", Timestamp: now - 60}})
  190. }
  191. start = time.Now()
  192. j.processObserved(observed, true, true)
  193. firstScan := time.Since(start)
  194. start = time.Now()
  195. j.processObserved(observed, true, true)
  196. secondScan := time.Since(start)
  197. t.Logf("N=%-7d shape=%-8s processObserved M=%-5d first=%-10v second=%-10v (%.1fms/email)",
  198. n, shape.name, m, firstScan.Round(time.Millisecond), secondScan.Round(time.Millisecond),
  199. float64(secondScan.Milliseconds())/float64(m))
  200. var rows int64
  201. if err := database.GetDB().Model(&model.InboundClientIps{}).Count(&rows).Error; err != nil {
  202. t.Fatalf("count ip rows: %v", err)
  203. }
  204. if rows != int64(m) {
  205. t.Fatalf("inbound_client_ips rows = %d, want %d", rows, m)
  206. }
  207. })
  208. }
  209. }
  210. }