1
1
package tsdb
2
2
3
3
import (
4
- "context"
5
4
"fmt"
6
5
"strings"
6
+ "sync"
7
7
"testing"
8
8
"time"
9
9
10
10
"github.com/prometheus/client_golang/prometheus"
11
11
"github.com/stretchr/testify/require"
12
+ "go.uber.org/atomic"
12
13
)
13
14
15
+ func Test_ShouldFetchPromiseOnlyOnce (t * testing.T ) {
16
+ cfg := PostingsCacheConfig {
17
+ Enabled : true ,
18
+ Ttl : time .Hour ,
19
+ MaxBytes : 10 << 20 ,
20
+ }
21
+ m := NewPostingCacheMetrics (prometheus .NewPedanticRegistry ())
22
+ cache := newFifoCache [int ](cfg , "test" , m , time .Now )
23
+ calls := atomic.Int64 {}
24
+ concurrency := 100
25
+ wg := sync.WaitGroup {}
26
+ wg .Add (concurrency )
27
+
28
+ fetchFunc := func () (int , int64 , error ) {
29
+ calls .Inc ()
30
+ time .Sleep (100 * time .Millisecond )
31
+ return 0 , 0 , nil
32
+ }
33
+
34
+ for i := 0 ; i < 100 ; i ++ {
35
+ go func () {
36
+ defer wg .Done ()
37
+ cache .getPromiseForKey ("key1" , fetchFunc )
38
+ }()
39
+ }
40
+
41
+ wg .Wait ()
42
+ require .Equal (t , int64 (1 ), calls .Load ())
43
+
44
+ }
45
+
14
46
func TestFifoCacheDisabled (t * testing.T ) {
15
47
cfg := PostingsCacheConfig {}
16
48
cfg .Enabled = false
17
- m := NewPostingCacheMetrics (prometheus .DefaultRegisterer )
49
+ m := NewPostingCacheMetrics (prometheus .NewPedanticRegistry () )
18
50
timeNow := time .Now
19
51
cache := newFifoCache [int ](cfg , "test" , m , timeNow )
20
52
old , loaded := cache .getPromiseForKey ("key1" , func () (int , int64 , error ) {
21
53
return 1 , 0 , nil
22
54
})
23
55
require .False (t , loaded )
24
- v , err := old .result (context .Background ())
25
- require .NoError (t , err )
26
- require .Equal (t , 1 , v )
56
+ require .Equal (t , 1 , old .v )
27
57
require .False (t , cache .contains ("key1" ))
28
58
}
29
59
@@ -68,17 +98,13 @@ func TestFifoCacheExpire(t *testing.T) {
68
98
return 1 , 8 , nil
69
99
})
70
100
require .False (t , loaded )
71
- v , err := p .result (context .Background ())
72
- require .NoError (t , err )
73
- require .Equal (t , 1 , v )
101
+ require .Equal (t , 1 , p .v )
74
102
require .True (t , cache .contains (key ))
75
103
p , loaded = cache .getPromiseForKey (key , func () (int , int64 , error ) {
76
104
return 1 , 0 , nil
77
105
})
78
106
require .True (t , loaded )
79
- v , err = p .result (context .Background ())
80
- require .NoError (t , err )
81
- require .Equal (t , 1 , v )
107
+ require .Equal (t , 1 , p .v )
82
108
}
83
109
84
110
totalCacheSize := 0
@@ -104,10 +130,8 @@ func TestFifoCacheExpire(t *testing.T) {
104
130
return 2 , 18 , nil
105
131
})
106
132
require .False (t , loaded )
107
- v , err := p .result (context .Background ())
108
- require .NoError (t , err )
109
133
// New value
110
- require .Equal (t , 2 , v )
134
+ require .Equal (t , 2 , p . v )
111
135
// Total Size Updated
112
136
require .Equal (t , originalSize + 10 , cache .cachedBytes )
113
137
}
0 commit comments