scale_helpers_test.go 5.9 KB

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