external_subscription_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package sub
  2. import (
  3. "errors"
  4. "net/http"
  5. "net/http/httptest"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "testing"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. )
  15. func resetSubscriptionCache(t *testing.T) {
  16. t.Helper()
  17. subscriptionCache.Lock()
  18. previousEntries := subscriptionCache.m
  19. previousInflight := subscriptionCache.inflight
  20. subscriptionCache.m = make(map[string]subscriptionCacheEntry)
  21. subscriptionCache.inflight = make(map[string]*subscriptionFetch)
  22. subscriptionCache.Unlock()
  23. t.Cleanup(func() {
  24. subscriptionCache.Lock()
  25. subscriptionCache.m = previousEntries
  26. subscriptionCache.inflight = previousInflight
  27. subscriptionCache.Unlock()
  28. })
  29. }
  30. func TestFetchSubscriptionLinksSharesConcurrentRefresh(t *testing.T) {
  31. resetSubscriptionCache(t)
  32. var requests atomic.Int32
  33. release := make(chan struct{})
  34. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  35. requests.Add(1)
  36. <-release
  37. _, _ = w.Write([]byte("vless://[email protected]:443"))
  38. }))
  39. defer srv.Close()
  40. const callers = 16
  41. results := make(chan []string, callers)
  42. var wg sync.WaitGroup
  43. for range callers {
  44. wg.Go(func() {
  45. results <- fetchSubscriptionLinks(srv.URL).links
  46. })
  47. }
  48. time.Sleep(100 * time.Millisecond)
  49. close(release)
  50. wg.Wait()
  51. close(results)
  52. for links := range results {
  53. if len(links) != 1 || links[0] != "vless://[email protected]:443" {
  54. t.Fatalf("links = %#v", links)
  55. }
  56. }
  57. if got := requests.Load(); got != 1 {
  58. t.Fatalf("requests = %d, want 1", got)
  59. }
  60. }
  61. func TestFetchSubscriptionLinksBoundsCacheSize(t *testing.T) {
  62. resetSubscriptionCache(t)
  63. var requests atomic.Int32
  64. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  65. requests.Add(1)
  66. _, _ = w.Write([]byte("vless://[email protected]:443"))
  67. }))
  68. defer srv.Close()
  69. for i := range subscriptionCacheCapacity + 1 {
  70. links := fetchSubscriptionLinks(srv.URL + "?id=" + strconv.Itoa(i)).links
  71. if len(links) != 1 {
  72. t.Fatalf("links at %d = %#v", i, links)
  73. }
  74. }
  75. subscriptionCache.Lock()
  76. entries := len(subscriptionCache.m)
  77. subscriptionCache.Unlock()
  78. if entries != subscriptionCacheCapacity {
  79. t.Fatalf("cache entries = %d, want %d", entries, subscriptionCacheCapacity)
  80. }
  81. if got := requests.Load(); got != subscriptionCacheCapacity+1 {
  82. t.Fatalf("requests = %d, want %d", got, subscriptionCacheCapacity+1)
  83. }
  84. }
  85. func TestFetchSubscriptionLinksSharesStaleResultAfterRefreshFailure(t *testing.T) {
  86. resetSubscriptionCache(t)
  87. stale := []string{"vless://[email protected]:443"}
  88. release := make(chan struct{})
  89. var staleRequests atomic.Int32
  90. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  91. if r.URL.Path == "/stale" {
  92. staleRequests.Add(1)
  93. <-release
  94. w.WriteHeader(http.StatusBadGateway)
  95. return
  96. }
  97. _, _ = w.Write([]byte("vless://[email protected]:443"))
  98. }))
  99. defer srv.Close()
  100. staleURL := srv.URL + "/stale"
  101. subscriptionCache.Lock()
  102. subscriptionCache.m[staleURL] = subscriptionCacheEntry{
  103. links: stale,
  104. fetchedAt: time.Now().Add(-subscriptionCacheTTL),
  105. }
  106. for i := range subscriptionCacheCapacity - 1 {
  107. subscriptionCache.m["cached-"+strconv.Itoa(i)] = subscriptionCacheEntry{fetchedAt: time.Now()}
  108. }
  109. subscriptionCache.Unlock()
  110. const callers = 16
  111. results := make(chan []string, callers)
  112. var wg sync.WaitGroup
  113. for range callers {
  114. wg.Go(func() {
  115. results <- fetchSubscriptionLinks(staleURL).links
  116. })
  117. }
  118. time.Sleep(100 * time.Millisecond)
  119. if links := fetchSubscriptionLinks(srv.URL + "/fresh").links; len(links) != 1 || links[0] != "vless://[email protected]:443" {
  120. t.Fatalf("fresh links = %#v", links)
  121. }
  122. close(release)
  123. wg.Wait()
  124. close(results)
  125. for links := range results {
  126. if len(links) != 1 || links[0] != stale[0] {
  127. t.Fatalf("links = %#v, want %#v", links, stale)
  128. }
  129. }
  130. if got := staleRequests.Load(); got != 1 {
  131. t.Fatalf("requests = %d, want 1", got)
  132. }
  133. }
  134. func TestDoFetchSubscriptionLinks_RejectsOversizedBody(t *testing.T) {
  135. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  136. _, _ = w.Write([]byte(strings.Repeat("a", subscriptionMaxBytes+1)))
  137. }))
  138. defer srv.Close()
  139. links, err := doFetchSubscriptionLinks(srv.URL)
  140. if !errors.Is(err, errSubscriptionBodyTooLarge) {
  141. t.Fatalf("err = %v, want errSubscriptionBodyTooLarge", err)
  142. }
  143. if links != nil {
  144. t.Fatalf("links = %v, want nil", links)
  145. }
  146. }
  147. func TestDoFetchSubscriptionLinks_AcceptsBodyAtLimit(t *testing.T) {
  148. link := "vless://example"
  149. body := link + "\n" + strings.Repeat("#", subscriptionMaxBytes-len(link)-1)
  150. if len(body) != subscriptionMaxBytes {
  151. t.Fatalf("fixture size = %d, want %d", len(body), subscriptionMaxBytes)
  152. }
  153. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  154. _, _ = w.Write([]byte(body))
  155. }))
  156. defer srv.Close()
  157. links, err := doFetchSubscriptionLinks(srv.URL)
  158. if err != nil {
  159. t.Fatalf("unexpected err: %v", err)
  160. }
  161. if len(links) != 1 || links[0] != link {
  162. t.Fatalf("links = %v, want [%q]", links, link)
  163. }
  164. }
  165. func TestRecordExternalSubscriptionFetchStampsEveryRowForTheURL(t *testing.T) {
  166. initMutDB(t)
  167. resetSubscriptionCache(t)
  168. db := database.GetDB()
  169. var failing atomic.Bool
  170. failing.Store(true)
  171. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  172. if failing.Load() {
  173. w.WriteHeader(http.StatusBadGateway)
  174. return
  175. }
  176. _, _ = w.Write([]byte("vless://[email protected]:443#Node"))
  177. }))
  178. defer srv.Close()
  179. owners := []model.ClientRecord{
  180. {Email: "[email protected]", SubID: "sub-fetch", UUID: "uuid-1", Enable: true},
  181. {Email: "[email protected]", SubID: "sub-fetch", UUID: "uuid-2", Enable: true},
  182. }
  183. for i := range owners {
  184. if err := db.Create(&owners[i]).Error; err != nil {
  185. t.Fatalf("seed client %d: %v", i, err)
  186. }
  187. row := model.ClientExternalLink{
  188. ClientId: owners[i].Id,
  189. Kind: model.ExternalLinkKindSubscription,
  190. Value: srv.URL,
  191. }
  192. if err := db.Create(&row).Error; err != nil {
  193. t.Fatalf("seed external link %d: %v", i, err)
  194. }
  195. }
  196. svc := NewSubService("")
  197. entries, err := svc.getClientExternalLinksBySubId("sub-fetch")
  198. if err != nil {
  199. t.Fatalf("getClientExternalLinksBySubId: %v", err)
  200. }
  201. if len(entries) != 2 {
  202. t.Fatalf("entries = %d, want 2", len(entries))
  203. }
  204. for _, e := range entries {
  205. expandEntry(e)
  206. }
  207. var rows []model.ClientExternalLink
  208. if err := db.Where("value = ?", srv.URL).Find(&rows).Error; err != nil {
  209. t.Fatalf("read rows: %v", err)
  210. }
  211. if len(rows) != 2 {
  212. t.Fatalf("rows = %d, want 2", len(rows))
  213. }
  214. for _, row := range rows {
  215. if row.LastFetchAt <= 0 {
  216. t.Fatalf("row %d lastFetchAt = %d, want a stamped timestamp", row.Id, row.LastFetchAt)
  217. }
  218. if row.LastFetchError != errBadStatus.Error() {
  219. t.Fatalf("row %d lastFetchError = %q, want %q", row.Id, row.LastFetchError, errBadStatus)
  220. }
  221. }
  222. failing.Store(false)
  223. resetSubscriptionCache(t)
  224. for _, e := range entries {
  225. expandEntry(e)
  226. }
  227. if err := db.Where("value = ?", srv.URL).Find(&rows).Error; err != nil {
  228. t.Fatalf("re-read rows: %v", err)
  229. }
  230. for _, row := range rows {
  231. if row.LastFetchError != "" {
  232. t.Fatalf("row %d lastFetchError = %q, want cleared after a good fetch", row.Id, row.LastFetchError)
  233. }
  234. if row.LastFetchAt <= 0 {
  235. t.Fatalf("row %d lastFetchAt = %d, want a stamped timestamp", row.Id, row.LastFetchAt)
  236. }
  237. }
  238. }
  239. func TestExpandEntryCacheHitWritesNothing(t *testing.T) {
  240. initMutDB(t)
  241. resetSubscriptionCache(t)
  242. db := database.GetDB()
  243. const subURL = "https://provider.example/cached"
  244. rec := model.ClientRecord{Email: "[email protected]", SubID: "sub-cached", UUID: "uuid", Enable: true}
  245. if err := db.Create(&rec).Error; err != nil {
  246. t.Fatalf("seed client: %v", err)
  247. }
  248. row := model.ClientExternalLink{ClientId: rec.Id, Kind: model.ExternalLinkKindSubscription, Value: subURL}
  249. if err := db.Create(&row).Error; err != nil {
  250. t.Fatalf("seed external link: %v", err)
  251. }
  252. subscriptionCache.Lock()
  253. subscriptionCache.m[subURL] = subscriptionCacheEntry{
  254. links: []string{"vless://[email protected]:443#Node"},
  255. fetchedAt: time.Now(),
  256. }
  257. subscriptionCache.Unlock()
  258. if got := expandEntry(externalLinkEntry{Kind: model.ExternalLinkKindSubscription, Value: subURL}); len(got) != 1 {
  259. t.Fatalf("expandEntry = %#v, want the cached link", got)
  260. }
  261. var after model.ClientExternalLink
  262. if err := db.First(&after, row.Id).Error; err != nil {
  263. t.Fatalf("read row: %v", err)
  264. }
  265. if after.LastFetchAt != 0 || after.LastFetchError != "" {
  266. t.Fatalf("cache hit wrote fetch status: %#v", after)
  267. }
  268. }