package qaopsmirror import ( "context" "sync" "sync/atomic" "testing" "time" ) func TestDepartmentStatisticsCacheIsBackgroundSingleFlightAndExpires(t *testing.T) { cache := &departmentStatisticsCache{} started := make(chan struct{}) release := make(chan struct{}) var calls atomic.Int64 now := time.Now() load := func(ctx context.Context) (DepartmentStatisticsSnapshot, error) { if calls.Add(1) == 1 { close(started) } select { case <-release: case <-ctx.Done(): return DepartmentStatisticsSnapshot{}, ctx.Err() } return DepartmentStatisticsSnapshot{Period: "all"}, nil } begin := time.Now() r, e := cache.get("tenant/directory-v1/revision-v1/all", now, load) if e != nil || r.State != "pending" || time.Since(begin) > 100*time.Millisecond { t.Fatal("first view performed/blocked aggregation instead of scheduling it", e, r.State) } select { case <-started: case <-time.After(time.Second): t.Fatal("background aggregator did not run") } var wg sync.WaitGroup for i := 0; i < 32; i++ { wg.Add(1) go func() { defer wg.Done() r, e := cache.get("tenant/directory-v1/revision-v1/all", now, load) if e != nil || r.State != "pending" { t.Error("concurrent read did not join background work") } }() } wg.Wait() if calls.Load() != 1 { t.Fatal("identical requests spawned duplicate aggregation") } close(release) for deadline := time.Now().Add(time.Second); ; { r, e = cache.get("tenant/directory-v1/revision-v1/all", now, load) if r.State == "ready" { break } if time.Now().After(deadline) { t.Fatal("background result never published") } time.Sleep(time.Millisecond) } if e != nil || !r.CacheHit || r.Snapshot == nil || calls.Load() != 1 { t.Fatal("result cache was not reused") } r, e = cache.get("tenant/directory-v1/revision-v1/all", now.Add(61*time.Second), load) if e != nil || r.State != "pending" { t.Fatal("expired result was served as fresh") } }