client_effective_flow_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package service
  2. import (
  3. "path/filepath"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. )
  9. // EffectiveFlowsByEmails resolves intended flow for many clients in one batched
  10. // query, taking the flow_override of the lowest inbound_id and skipping emails
  11. // with no non-empty flow anywhere.
  12. func TestEffectiveFlowsByEmails(t *testing.T) {
  13. dbDir := t.TempDir()
  14. t.Setenv("XUI_DB_FOLDER", dbDir)
  15. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  16. db := database.GetDB()
  17. const vision = "xtls-rprx-vision"
  18. // vis@x: attached to inbound 20 (empty flow) and 10 (Vision) — lowest
  19. // inbound_id (10) wins, so the empty override on 20 must not mask it.
  20. // plain@x: only an empty flow_override anywhere — absent from the result.
  21. mkClient := func(id int, email string) {
  22. if err := db.Create(&model.ClientRecord{Id: id, Email: email, Enable: true}).Error; err != nil {
  23. t.Fatalf("create client %s: %v", email, err)
  24. }
  25. }
  26. mkLink := func(clientID, inboundID int, flow string) {
  27. if err := db.Create(&model.ClientInbound{ClientId: clientID, InboundId: inboundID, FlowOverride: flow}).Error; err != nil {
  28. t.Fatalf("link %d/%d: %v", clientID, inboundID, err)
  29. }
  30. }
  31. mkClient(1, "vis@x")
  32. mkClient(2, "plain@x")
  33. mkLink(1, 20, "") // higher inbound_id, empty
  34. mkLink(1, 10, vision) // lower inbound_id, Vision
  35. mkLink(2, 30, "") // only empty override
  36. cs := &ClientService{}
  37. got, err := cs.EffectiveFlowsByEmails(nil, []string{"vis@x", "plain@x", "missing@x"})
  38. if err != nil {
  39. t.Fatalf("EffectiveFlowsByEmails: %v", err)
  40. }
  41. if got["vis@x"] != vision {
  42. t.Errorf("vis@x = %q, want %q (lowest inbound_id flow_override)", got["vis@x"], vision)
  43. }
  44. if v, ok := got["plain@x"]; ok {
  45. t.Errorf("plain@x present (%q); want absent (no non-empty flow anywhere)", v)
  46. }
  47. if v, ok := got["missing@x"]; ok {
  48. t.Errorf("missing@x present (%q); want absent (unknown client)", v)
  49. }
  50. // Empty input is a no-op (no query).
  51. if m, err := cs.EffectiveFlowsByEmails(nil, nil); err != nil || len(m) != 0 {
  52. t.Errorf("empty input: got %v err %v, want empty map", m, err)
  53. }
  54. }