droboticflow/internal/outputsnapshot/query_shared_cache_test.go

87 lines
2.7 KiB
Go

package outputsnapshot
import (
"context"
"droboticflow/internal/queryserving"
"droboticflow/internal/workforcestats"
"sync"
"sync/atomic"
"testing"
"time"
)
type queryTestCache struct {
mu sync.Mutex
data map[string][]byte
}
func (c *queryTestCache) Get(_ context.Context, k string) ([]byte, bool) {
c.mu.Lock()
defer c.mu.Unlock()
v, ok := c.data[k]
return append([]byte(nil), v...), ok
}
func (c *queryTestCache) Put(_ context.Context, k string, v []byte, _ time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
if c.data == nil {
c.data = map[string][]byte{}
}
c.data[k] = append([]byte(nil), v...)
}
type queryCachedBackend struct {
MemoryBackend
cache queryTestCache
blobs atomic.Int64
}
func (b *queryCachedBackend) SharedQueryCache() queryserving.Cache { return &b.cache }
func (b *queryCachedBackend) OutputSnapshotBlob(ctx context.Context, g Generation) ([]byte, error) {
b.blobs.Add(1)
return b.MemoryBackend.OutputSnapshotBlob(ctx, g)
}
func TestQueryServingSharedOutputCacheKeepsScopeLocationAndGeneration(t *testing.T) {
now := time.Now().UTC()
backend := &queryCachedBackend{}
source := func(context.Context, string, []string) (workforcestats.OutputSnapshot, error) {
return testData(now), nil
}
one := NewReader(backend, source)
defer one.Close()
if _, err := one.Prewarm(t.Context(), "org", []string{"p"}); err != nil {
t.Fatal(err)
}
_, info := ready(t, one, "")
q := workforcestats.OutputQuery{From: now.Add(-24 * time.Hour), To: now.Add(time.Hour), Location: time.UTC, MatchUser: true, ScopeUserID: "u"}
r, _, err := one.Query(t.Context(), "org", []string{"p"}, info.ID, q)
if err != nil || r.Totals.Submitted.Count != 12 {
t.Fatal("initial report", err)
}
calls := backend.blobs.Load()
two := NewReader(backend, source)
defer two.Close()
q.Location = time.FixedZone("UTC", 0)
r, _, err = two.Query(t.Context(), "org", []string{"p"}, info.ID, q)
if err != nil || r.Totals.Submitted.Count != 12 || backend.blobs.Load() != calls {
t.Fatal("same immutable scope failed cross-reader reuse", err)
}
r.Tasks = nil
r, _, err = two.Query(t.Context(), "org", []string{"p"}, info.ID, q)
if err != nil || len(r.Tasks) == 0 {
t.Fatal("shared response mutated by another caller")
}
q.ScopeUserID = "not-authorized-user"
r, _, err = two.Query(t.Context(), "org", []string{"p"}, info.ID, q)
if err != nil || r.Totals.Submitted.Count != 0 {
t.Fatal("personal cache leaked another user's data", err)
}
if _, _, err = two.Query(t.Context(), "other-org", []string{"p"}, info.ID, q); err != ErrExpired {
t.Fatal("foreign organization borrowed generation", err)
}
if _, _, err = two.Query(t.Context(), "org", []string{"not-visible"}, info.ID, q); err != ErrExpired {
t.Fatal("changed project scope borrowed generation", err)
}
}