Compare commits

..

2 commits

Author SHA1 Message Date
2a574d6f3b
add test for cache miss
All checks were successful
ci/woodpecker/push/golang-test Pipeline was successful
ci/woodpecker/pr/docker-deploy Pipeline was successful
2024-04-19 11:10:00 +02:00
36e9aa49f7
fix deadlock with waiting mutex 2024-04-19 11:09:06 +02:00
2 changed files with 17 additions and 1 deletions

3
cache/cache.go vendored
View file

@ -69,12 +69,13 @@ func (sc *ScoreCache) Add(score float64, ip netip.Addr, ts time.Time) {
func (lc *ScoreCache) Get(ip netip.Addr) (ServerScore, error) {
now := time.Now()
lc.mu.RLock()
defer lc.mu.RUnlock()
cachedScore, ok := lc.scores[ip]
if !ok {
lc.mu.RUnlock()
return ServerScore{}, newCacheMissError()
}
lc.mu.RUnlock()
if now.After(cachedScore.expiresAt) {
lc.delete(ip)

15
cache/cache_test.go vendored
View file

@ -32,3 +32,18 @@ func TestCacheGet(t *testing.T) {
t.Fatalf("cache.Get(\"1.2.3.4\") = %f, want %f", score.Score, testFloat)
}
}
func TestCacheMiss(t *testing.T) {
now := time.Now()
const testFloat = 1.23456
expiredTime := now.Add(-(time.Minute * 10))
cache := NewLocalCache()
cache.Add(testFloat, netip.MustParseAddr("1.2.3.4"), expiredTime)
_, err := cache.Get(netip.MustParseAddr("1.2.3.4"))
if err == nil {
t.Fatalf("cache.Get(\"1.2.3.4\") = got nil, want error")
}
}