package store import ( "fmt" "net/netip" "os" "path/filepath" "runtime" "strings" "sync" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) func heapMiB() uint64 { runtime.GC() var m runtime.MemStats runtime.ReadMemStats(&m) return m.HeapAlloc >> 20 } // The reviewer's worst case: 50k IPv6 addresses in distinct /64s, each sending // 8 distinct maximum-size samples, user agents and domains. The table is capped // at the default 20k entries and the per-IP text is bounded, so the heap stays // far below the container limit. func TestWorstCaseMemoryIsBounded(t *testing.T) { st := New(Config{Name: "x", Version: "t"}) h0 := heapMiB() b := netip.MustParseAddr("2001:db8::").As16() now := time.Now() for i := 0; i < 25000; i++ { a := b a[6], a[7] = byte(i>>8), byte(i) // distinct /64 a[15] = 1 ip := netip.AddrFrom16(a).String() for k := 0; k < 8; k++ { st.Ingest(core.Event{Time: now, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Status: 404, Domain: fmt.Sprintf("d%d%d.", i, k) + strings.Repeat("x", 90), Path: fmt.Sprintf("/%d-%d-", i, k) + strings.Repeat("A", 220), UA: fmt.Sprintf("ua%d-%d", i, k) + strings.Repeat("U", 190)}) } } if n := st.IPCount(); n > 20000 { t.Fatalf("table over the default cap: %d", n) } grew := heapMiB() - h0 t.Logf("IPs=%d heap growth=%d MiB", st.IPCount(), grew) if grew > 60 { t.Fatalf("worst case heap growth %d MiB", grew) } runtime.KeepAlive(st) } func TestStoreRaceStress(t *testing.T) { st := New(Config{Name: "x", MaxIPs: 2000}) now := time.Now() var wg sync.WaitGroup stop := make(chan struct{}) for g := 0; g < 4; g++ { wg.Add(1) go func(g int) { defer wg.Done() for i := 0; ; i++ { select { case <-stop: return default: } st.Ingest(core.Event{Time: now, IP: fmt.Sprintf("10.%d.%d.%d", g, i/250%250, i%250), Cat: core.Scanner, Source: "traefik", Path: "/.env", Domain: "d", Method: "GET", UA: "u"}) st.Traffic(core.Event{Time: now, IP: "2.2.2.2", Cat: core.OK, Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200, UA: "u"}) st.Monitoring(now) } }(g) } dir := t.TempDir() for g := 0; g < 3; g++ { wg.Add(1) go func() { defer wg.Done() for { select { case <-stop: return default: } st.Summary("24h") st.AllIPs(ParseRange("7d"), true) st.Export("24h") st.Prune() st.Recent(50) st.IP("10.0.0.1") st.Save(filepath.Join(dir, "s.gob"), nil) st.invalidate() } }() } ch, cancel := st.Subscribe() wg.Add(1) go func() { defer wg.Done() for { select { case <-stop: return case <-ch: } } }() time.Sleep(1500 * time.Millisecond) close(stop) wg.Wait() cancel() _ = os.Stdout }