catalog_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // catalog_test.go - #1697: descubrimiento del catálogo de vendors. Todos los
  2. // tests corren sin red: el fetch se inyecta con FetchOverride y el reloj con
  3. // Catalog.Now.
  4. package rintegration
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "sync/atomic"
  10. "testing"
  11. "time"
  12. "github.com/gnacho/netpulse/server-go/internal/db"
  13. )
  14. // seedVendor devuelve un vendor de la semilla embebida (helper de tests).
  15. func seedVendor(t *testing.T, id string) Vendor {
  16. t.Helper()
  17. v, ok := (&Catalog{}).Lookup(id)
  18. if !ok {
  19. t.Fatalf("vendor %q missing from the embedded seed", id)
  20. }
  21. return v
  22. }
  23. // fakeClock es un reloj inyectable para probar el TTL sin esperar.
  24. type fakeClock struct {
  25. t time.Time
  26. }
  27. func (c *fakeClock) Now() time.Time { return c.t }
  28. func (c *fakeClock) Add(d time.Duration) {
  29. c.t = c.t.Add(d)
  30. }
  31. // overrideOf devuelve un FetchOverride que sirve los cuerpos en orden y
  32. // cuenta las llamadas; al agotarse repite el último.
  33. func overrideOf(t *testing.T, calls *atomic.Int32, bodies ...string) func(string) ([]byte, error) {
  34. t.Helper()
  35. return func(string) ([]byte, error) {
  36. n := int(calls.Add(1)) - 1
  37. if n >= len(bodies) {
  38. n = len(bodies) - 1
  39. }
  40. return []byte(bodies[n]), nil
  41. }
  42. }
  43. func failingOverride(calls *atomic.Int32) func(string) ([]byte, error) {
  44. return func(string) ([]byte, error) {
  45. calls.Add(1)
  46. return nil, errors.New("dial tcp: connection refused")
  47. }
  48. }
  49. const labVendorA = `{"vendors":[{"id":"labvendor","mode":"local","arches":["amd64"],"tagPrefix":"lab/v","binary":"lab-pusher","target":"lab/cmd/lab-pusher","description":"Lab vendor"}]}`
  50. const labVendorB = `{"vendors":[{"id":"labvendor","mode":"local","arches":["amd64","arm64"],"tagPrefix":"lab/v","binary":"lab-pusher","target":"lab/cmd/lab-pusher","description":"Lab vendor with two arches"}]}`
  51. func newTestCatalogDB(t *testing.T) *db.DB {
  52. t.Helper()
  53. d, err := db.Open(t.TempDir())
  54. if err != nil {
  55. t.Fatalf("db.Open: %v", err)
  56. }
  57. t.Cleanup(func() { _ = d.Close() })
  58. return d
  59. }
  60. // TestSeedCatalogServesCurrentVendors: la semilla embebida (generada del
  61. // vendors.json real, con el campo target) cubre los cuatro vendors
  62. // publicados, y la resolución deriva Repo/AssetTmpl/Init que el schema no
  63. // lleva: bbox usa el prefijo del binario compartido y asuswrt es merlin.
  64. func TestSeedCatalogServesCurrentVendors(t *testing.T) {
  65. want := []struct {
  66. id string
  67. mode string
  68. arches string
  69. prefix string
  70. binary string
  71. init string
  72. version string
  73. arch string
  74. asset string
  75. }{
  76. {"routeros", "local", "[amd64]", "routeros/v", "routeros-pusher", "procd", "1.2.3", "amd64", "routeros_1.2.3_linux_amd64.tar.gz"},
  77. {"asuswrt", "ssh", "[arm64]", "asuswrt/v", "asuswrt-pusher", "merlin", "1.0.0", "arm64", "asuswrt_1.0.0_linux_arm64.tar.gz"},
  78. {"bbox", "local", "[amd64 arm64]", "bbox/v", "netpulse-integrations", "procd", "0.1.0", "amd64", "integrations-supervisor_0.1.0_linux_amd64.tar.gz"},
  79. {"unifi", "local", "[amd64]", "unifi/v", "unifi-pusher", "procd", "1.0.0", "amd64", "unifi_1.0.0_linux_amd64.tar.gz"},
  80. }
  81. c := NewCatalog(nil)
  82. if got := len(c.Current()); got != len(want) {
  83. t.Fatalf("seed serves %d vendors, want %d", got, len(want))
  84. }
  85. for _, w := range want {
  86. v, ok := c.Lookup(w.id)
  87. if !ok {
  88. t.Fatalf("seed vendor %q missing", w.id)
  89. }
  90. if v.Mode != w.mode || v.TagPrefix != w.prefix || v.Binary != w.binary {
  91. t.Fatalf("%s: %+v", w.id, v)
  92. }
  93. if fmt.Sprint(v.Arches) != w.arches {
  94. t.Fatalf("%s arches = %v, want %s", w.id, v.Arches, w.arches)
  95. }
  96. if got := v.InitSystem(); got != w.init {
  97. t.Fatalf("%s init = %q, want %q", w.id, got, w.init)
  98. }
  99. if v.Repo != CatalogRepo {
  100. t.Fatalf("%s repo = %q, want %q", w.id, v.Repo, CatalogRepo)
  101. }
  102. if got := v.AssetName(w.version, w.arch); got != w.asset {
  103. t.Fatalf("%s asset = %q, want %q", w.id, got, w.asset)
  104. }
  105. }
  106. if _, ok := c.Lookup("nope"); ok {
  107. t.Fatal("unknown vendor must not resolve")
  108. }
  109. }
  110. // TestCatalogServesSeedWithoutNetwork: un catálogo sin base de datos (demo,
  111. // fallback de tests) no intenta fetch nunca y sirve la semilla.
  112. func TestCatalogServesSeedWithoutNetwork(t *testing.T) {
  113. c := NewCatalog(nil)
  114. c.FetchOverride = func(url string) ([]byte, error) {
  115. t.Fatalf("fetch must not be attempted without a db (url %s)", url)
  116. return nil, nil
  117. }
  118. vs := c.Vendors(context.Background())
  119. if len(vs) != 4 {
  120. t.Fatalf("seed vendors = %d, want 4", len(vs))
  121. }
  122. if !c.LastRefreshedAt().IsZero() {
  123. t.Fatal("seed-only catalog must have zero lastRefreshedAt")
  124. }
  125. }
  126. // TestCatalogFetchPersistsAndReloads: el catálogo descargado se sirve, se
  127. // persiste en kv y una segunda apertura sobre la misma base lo recupera sin
  128. // tocar la red.
  129. func TestCatalogFetchPersistsAndReloads(t *testing.T) {
  130. d := newTestCatalogDB(t)
  131. clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
  132. var calls atomic.Int32
  133. c := NewCatalog(d.DB)
  134. c.Now = clock.Now
  135. c.FetchOverride = overrideOf(t, &calls, labVendorA)
  136. vs := c.Vendors(context.Background())
  137. if len(vs) != 1 || vs[0].ID != "labvendor" {
  138. t.Fatalf("fetched catalog = %+v", vs)
  139. }
  140. if calls.Load() != 1 {
  141. t.Fatalf("fetch calls = %d, want 1", calls.Load())
  142. }
  143. if !c.LastRefreshedAt().Equal(clock.t) {
  144. t.Fatalf("lastRefreshedAt = %v, want %v", c.LastRefreshedAt(), clock.t)
  145. }
  146. if _, ok := kvGet(d.DB, kvCatalogKey); !ok {
  147. t.Fatal("catalog not persisted in kv")
  148. }
  149. // Reapertura sobre la misma base: sin red, desde kv.
  150. c2 := NewCatalog(d.DB)
  151. c2.Now = clock.Now
  152. c2.FetchOverride = func(url string) ([]byte, error) {
  153. t.Fatalf("reopened catalog must serve from kv without fetching (url %s)", url)
  154. return nil, nil
  155. }
  156. got, ok := c2.Lookup("labvendor")
  157. if !ok || got.Binary != "lab-pusher" {
  158. t.Fatalf("reloaded vendor = %+v ok=%v", got, ok)
  159. }
  160. if !c2.LastRefreshedAt().Equal(clock.t) {
  161. t.Fatalf("reloaded lastRefreshedAt = %v, want %v", c2.LastRefreshedAt(), clock.t)
  162. }
  163. }
  164. // TestCatalogTTLExpiredRefetches: dentro del TTL no hay segunda descarga;
  165. // pasado el TTL la siguiente lectura refresca.
  166. func TestCatalogTTLExpiredRefetches(t *testing.T) {
  167. d := newTestCatalogDB(t)
  168. clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
  169. var calls atomic.Int32
  170. c := NewCatalog(d.DB)
  171. c.Now = clock.Now
  172. c.FetchOverride = overrideOf(t, &calls, labVendorA, labVendorB)
  173. if vs := c.Vendors(context.Background()); len(vs[0].Arches) != 1 {
  174. t.Fatalf("first serve should be body A: %+v", vs)
  175. }
  176. clock.Add(catalogTTL - time.Minute)
  177. if vs := c.Vendors(context.Background()); len(vs[0].Arches) != 1 {
  178. t.Fatalf("within TTL the cache must still be served: %+v", vs)
  179. }
  180. if calls.Load() != 1 {
  181. t.Fatalf("fetch calls within TTL = %d, want 1", calls.Load())
  182. }
  183. clock.Add(2 * time.Minute)
  184. vs := c.Vendors(context.Background())
  185. if calls.Load() != 2 {
  186. t.Fatalf("fetch calls after TTL = %d, want 2", calls.Load())
  187. }
  188. if len(vs[0].Arches) != 2 {
  189. t.Fatalf("after TTL the refreshed catalog must be served: %+v", vs)
  190. }
  191. }
  192. // TestCatalogFetchFailsKeepsCache: con caché previa, un fetch fallido sirve
  193. // la caché vieja, no cambia lastRefreshedAt y no reintenta dentro del
  194. // cooldown.
  195. func TestCatalogFetchFailsKeepsCache(t *testing.T) {
  196. d := newTestCatalogDB(t)
  197. clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
  198. var calls atomic.Int32
  199. c := NewCatalog(d.DB)
  200. c.Now = clock.Now
  201. c.FetchOverride = overrideOf(t, &calls, labVendorA)
  202. if vs := c.Vendors(context.Background()); len(vs) != 1 {
  203. t.Fatalf("setup fetch failed: %+v", vs)
  204. }
  205. firstRefresh := c.LastRefreshedAt()
  206. clock.Add(catalogTTL + time.Hour)
  207. c.FetchOverride = failingOverride(&calls)
  208. vs := c.Vendors(context.Background())
  209. if len(vs) != 1 || vs[0].ID != "labvendor" {
  210. t.Fatalf("stale cache must be served after a failed fetch: %+v", vs)
  211. }
  212. if calls.Load() != 2 {
  213. t.Fatalf("fetch calls = %d, want 2 (setup + failed attempt)", calls.Load())
  214. }
  215. if !c.LastRefreshedAt().Equal(firstRefresh) {
  216. t.Fatalf("lastRefreshedAt changed on failure: %v", c.LastRefreshedAt())
  217. }
  218. // Cooldown: la siguiente lectura no reintenta.
  219. if vs := c.Vendors(context.Background()); len(vs) != 1 {
  220. t.Fatalf("cache must survive: %+v", vs)
  221. }
  222. if calls.Load() != 2 {
  223. t.Fatalf("retry happened within the cooldown (%d calls)", calls.Load())
  224. }
  225. if c.LastError() == "" {
  226. t.Fatal("last error must be recorded for diagnostics")
  227. }
  228. }
  229. // TestCatalogFetchFailsNoCacheServesSeed: sin caché y sin red, la semilla se
  230. // sirve sin error y la lista nunca queda vacía.
  231. func TestCatalogFetchFailsNoCacheServesSeed(t *testing.T) {
  232. d := newTestCatalogDB(t)
  233. var calls atomic.Int32
  234. c := NewCatalog(d.DB)
  235. c.FetchOverride = failingOverride(&calls)
  236. vs := c.Vendors(context.Background())
  237. if len(vs) != 4 {
  238. t.Fatalf("seed must be served when the fetch fails without cache: %d vendors", len(vs))
  239. }
  240. if _, ok := c.Lookup("routeros"); !ok {
  241. t.Fatal("seed lookup broken after failed fetch")
  242. }
  243. if !c.LastRefreshedAt().IsZero() {
  244. t.Fatal("lastRefreshedAt must stay zero without a successful fetch")
  245. }
  246. }
  247. // TestCatalogInvalidEntriesDropped: las entradas inválidas se descartan una a
  248. // una sin romper el resto; un catálogo sin ninguna entrada válida no se
  249. // aplica y devuelve error conservando el anterior.
  250. func TestCatalogInvalidEntriesDropped(t *testing.T) {
  251. d := newTestCatalogDB(t)
  252. clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
  253. var calls atomic.Int32
  254. mixed := `{"vendors":[
  255. {"id":"badmode","mode":"telnet","arches":["amd64"],"tagPrefix":"bad/v","binary":"b","target":"x","description":"bad mode"},
  256. {"id":"noduplicates","mode":"local","arches":["amd64"],"tagPrefix":"dup/v","binary":"b","target":"x","description":"first"},
  257. {"id":"noduplicates","mode":"local","arches":["amd64"],"tagPrefix":"dup/v","binary":"b","target":"x","description":"duplicate id"},
  258. {"id":"noarches","mode":"local","arches":[],"tagPrefix":"na/v","binary":"b","target":"x","description":"empty arches"},
  259. {"id":"goodone","mode":"ssh","arches":["arm64"],"tagPrefix":"good/v","binary":"good-pusher","target":"good/cmd/good-pusher","description":"Good one"}
  260. ]}`
  261. c := NewCatalog(d.DB)
  262. c.Now = clock.Now
  263. c.FetchOverride = overrideOf(t, &calls, mixed)
  264. if err := c.Refresh(context.Background()); err != nil {
  265. t.Fatalf("Refresh with mixed entries: %v", err)
  266. }
  267. vs := c.Current()
  268. if len(vs) != 2 {
  269. t.Fatalf("valid vendors = %d, want 2 (goodone + noduplicates): %+v", len(vs), vs)
  270. }
  271. if _, ok := c.Lookup("goodone"); !ok {
  272. t.Fatal("good entry must survive invalid siblings")
  273. }
  274. if _, ok := c.Lookup("badmode"); ok {
  275. t.Fatal("entry with unknown mode must be dropped")
  276. }
  277. if _, ok := c.Lookup("noarches"); ok {
  278. t.Fatal("entry with empty arches must be dropped")
  279. }
  280. // Todo inválido: error y catálogo anterior intacto.
  281. empty := `{"vendors":[{"id":"Bad ID","mode":"local","arches":["amd64"],"tagPrefix":"x/v","binary":"b","target":"x","description":"bad id"}]}`
  282. c.FetchOverride = overrideOf(t, &calls, empty)
  283. if err := c.Refresh(context.Background()); err == nil {
  284. t.Fatal("Refresh must fail when no entry is valid")
  285. }
  286. if len(c.Current()) != 2 {
  287. t.Fatalf("previous catalog must survive a fully invalid refresh: %+v", c.Current())
  288. }
  289. if !c.LastRefreshedAt().Equal(clock.t) {
  290. t.Fatal("lastRefreshedAt must not advance on a failed refresh")
  291. }
  292. // JSON malformado: mismo trato.
  293. c.FetchOverride = overrideOf(t, &calls, `{"vendors": [[["bad`)
  294. if err := c.Refresh(context.Background()); err == nil {
  295. t.Fatal("Refresh must fail on malformed JSON")
  296. }
  297. if len(c.Current()) != 2 {
  298. t.Fatalf("previous catalog must survive malformed JSON: %+v", c.Current())
  299. }
  300. }
  301. // TestCatalogRefreshForcesFetch: el refresco admin salta el TTL, actualiza el
  302. // catálogo y lastRefreshedAt, y devuelve el error si el fetch falla sin tocar
  303. // lo servido.
  304. func TestCatalogRefreshForcesFetch(t *testing.T) {
  305. d := newTestCatalogDB(t)
  306. clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
  307. var calls atomic.Int32
  308. c := NewCatalog(d.DB)
  309. c.Now = clock.Now
  310. c.FetchOverride = overrideOf(t, &calls, labVendorA, labVendorB)
  311. _ = c.Vendors(context.Background())
  312. clock.Add(time.Minute) // fresco: Vendors no refrescaría
  313. if err := c.Refresh(context.Background()); err != nil {
  314. t.Fatalf("forced Refresh: %v", err)
  315. }
  316. if calls.Load() != 2 {
  317. t.Fatalf("forced refresh must fetch even within the TTL (calls %d)", calls.Load())
  318. }
  319. if vs := c.Current(); len(vs[0].Arches) != 2 {
  320. t.Fatalf("refreshed catalog not served: %+v", vs)
  321. }
  322. if !c.LastRefreshedAt().Equal(clock.t) {
  323. t.Fatalf("lastRefreshedAt = %v, want %v", c.LastRefreshedAt(), clock.t)
  324. }
  325. c.FetchOverride = failingOverride(&calls)
  326. if err := c.Refresh(context.Background()); err == nil {
  327. t.Fatal("failed forced refresh must return the error")
  328. }
  329. if vs := c.Current(); len(vs[0].Arches) != 2 {
  330. t.Fatalf("failed refresh must keep the previous catalog: %+v", vs)
  331. }
  332. }