scale_helpers_test.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package service
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/config"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "github.com/op/go-logging"
  17. "gorm.io/gorm"
  18. )
  19. // setupScaleDB initializes the DB for a scale benchmark on either Postgres
  20. // (XUI_DB_TYPE=postgres + XUI_DB_DSN) or SQLite (XUI_SCALE_TEST=1, temp file;
  21. // XUI_SCALE_DB_PATH persists the DB for manual smoke runs), and registers
  22. // cleanup. Skips the test when neither backend is configured.
  23. func setupScaleDB(t *testing.T) {
  24. t.Helper()
  25. xuilogger.InitLogger(logging.ERROR)
  26. if os.Getenv("XUI_DB_TYPE") == "postgres" && strings.TrimSpace(os.Getenv("XUI_DB_DSN")) != "" {
  27. if err := database.InitDB(""); err != nil {
  28. t.Fatalf("InitDB(postgres): %v", err)
  29. }
  30. t.Cleanup(func() { _ = database.CloseDB() })
  31. return
  32. }
  33. switch strings.ToLower(strings.TrimSpace(os.Getenv("XUI_SCALE_TEST"))) {
  34. case "1", "true", "yes":
  35. dbPath := strings.TrimSpace(os.Getenv("XUI_SCALE_DB_PATH"))
  36. if dbPath == "" {
  37. dbPath = filepath.Join(t.TempDir(), "scale.db")
  38. }
  39. dbtest.InitDB(t, dbPath)
  40. return
  41. }
  42. t.Skip("set XUI_SCALE_TEST=1 (sqlite) or XUI_DB_TYPE=postgres + XUI_DB_DSN (postgres) to run the scale benchmark")
  43. }
  44. // scaleSizes returns the default size ladder unless XUI_SCALE_SIZES overrides
  45. // it with a comma-separated list (e.g. "500000" or "10000,100000,500000").
  46. func scaleSizes(t *testing.T, def ...int) []int {
  47. t.Helper()
  48. raw := strings.TrimSpace(os.Getenv("XUI_SCALE_SIZES"))
  49. if raw == "" {
  50. return def
  51. }
  52. var out []int
  53. for part := range strings.SplitSeq(raw, ",") {
  54. part = strings.TrimSpace(part)
  55. if part == "" {
  56. continue
  57. }
  58. n, err := strconv.Atoi(part)
  59. if err != nil || n <= 0 {
  60. t.Fatalf("XUI_SCALE_SIZES: invalid size %q", part)
  61. }
  62. out = append(out, n)
  63. }
  64. if len(out) == 0 {
  65. return def
  66. }
  67. return out
  68. }
  69. type scaleDataset struct {
  70. inboundIds []int
  71. tags []string
  72. emails []string
  73. perInbound [][]model.Client
  74. }
  75. // seedScaleDataset seeds n healthy clients (future expiry, unfilled quota)
  76. // spread across numInbounds inbounds, writing inbounds, clients,
  77. // client_inbounds and client_traffics directly in one transaction — orders of
  78. // magnitude faster than SyncInbound and one fsync instead of thousands.
  79. func seedScaleDataset(t *testing.T, n, numInbounds int) scaleDataset {
  80. t.Helper()
  81. db := database.GetDB()
  82. resetScaleTables(t, db, "inbounds", "clients", "client_inbounds", "client_traffics")
  83. clients := makeScaleClients(n)
  84. exp := time.Now().AddDate(1, 0, 0).UnixMilli()
  85. for i := range clients {
  86. clients[i].ExpiryTime = exp
  87. clients[i].TotalGB = 100 << 30
  88. }
  89. ds := scaleDataset{emails: emailsOf(clients)}
  90. start := time.Now()
  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. per := n / numInbounds
  102. for i := range numInbounds {
  103. lo, hi := i*per, (i+1)*per
  104. if i == numInbounds-1 {
  105. hi = n
  106. }
  107. chunk := clients[lo:hi]
  108. ib := &model.Inbound{
  109. UserId: 1,
  110. Tag: fmt.Sprintf("scale-%d-%d", n, i),
  111. Enable: true,
  112. Port: 41000 + i,
  113. Protocol: model.VLESS,
  114. Settings: clientsSettings(t, chunk),
  115. }
  116. if err := tx.Create(ib).Error; err != nil {
  117. t.Fatalf("seed inbound %d: %v", i, err)
  118. }
  119. records := make([]*model.ClientRecord, len(chunk))
  120. for j := range chunk {
  121. records[j] = chunk[j].ToRecord()
  122. }
  123. if err := tx.CreateInBatches(records, 500).Error; err != nil {
  124. t.Fatalf("seed clients %d: %v", i, err)
  125. }
  126. links := make([]model.ClientInbound, len(records))
  127. for j := range records {
  128. links[j] = model.ClientInbound{ClientId: records[j].Id, InboundId: ib.Id}
  129. }
  130. if err := tx.CreateInBatches(links, 1000).Error; err != nil {
  131. t.Fatalf("seed client_inbounds %d: %v", i, err)
  132. }
  133. traffics := make([]xray.ClientTraffic, len(chunk))
  134. for j := range chunk {
  135. traffics[j] = xray.ClientTraffic{
  136. InboundId: ib.Id,
  137. Email: chunk[j].Email,
  138. Enable: true,
  139. Total: chunk[j].TotalGB,
  140. ExpiryTime: chunk[j].ExpiryTime,
  141. }
  142. }
  143. if err := tx.CreateInBatches(traffics, 1000).Error; err != nil {
  144. t.Fatalf("seed client_traffics %d: %v", i, err)
  145. }
  146. ds.inboundIds = append(ds.inboundIds, ib.Id)
  147. ds.tags = append(ds.tags, ib.Tag)
  148. ds.perInbound = append(ds.perInbound, chunk)
  149. }
  150. if err := tx.Commit().Error; err != nil {
  151. t.Fatalf("commit seed tx: %v", err)
  152. }
  153. committed = true
  154. db.Exec("ANALYZE")
  155. t.Logf("seeded N=%d across %d inbound(s) in %v", n, numInbounds, time.Since(start).Round(time.Millisecond))
  156. return ds
  157. }
  158. // sampleEmails picks k evenly spaced emails so active clients span the id range.
  159. func sampleEmails(emails []string, k int) []string {
  160. if k >= len(emails) {
  161. return emails
  162. }
  163. out := make([]string, 0, k)
  164. step := len(emails) / k
  165. for i := 0; i < len(emails) && len(out) < k; i += step {
  166. out = append(out, emails[i])
  167. }
  168. return out
  169. }
  170. // resetScaleTables empties the given tables between sub-sizes. Postgres uses a
  171. // single TRUNCATE ... CASCADE; SQLite deletes per table and clears the
  172. // autoincrement counters so ids restart like RESTART IDENTITY.
  173. func resetScaleTables(t *testing.T, db *gorm.DB, tables ...string) {
  174. t.Helper()
  175. if config.GetDBKind() == "postgres" {
  176. stmt := "TRUNCATE TABLE " + strings.Join(tables, ", ") + " RESTART IDENTITY CASCADE"
  177. if err := db.Exec(stmt).Error; err != nil {
  178. t.Fatalf("truncate: %v", err)
  179. }
  180. return
  181. }
  182. for _, tbl := range tables {
  183. if err := db.Exec("DELETE FROM " + tbl).Error; err != nil {
  184. t.Fatalf("delete %s: %v", tbl, err)
  185. }
  186. }
  187. // Best-effort id reset; sqlite_sequence is absent until the first insert.
  188. db.Exec("DELETE FROM sqlite_sequence")
  189. }