Debian Codegraph @

buffer_test.go

raw
1 package sturdyc_test
2
3 import (
4 "context"
5 "strconv"
6 "sync"
7 "testing"
8 "time"
9
10 "github.com/viccon/sturdyc"
11 )
12
13 func TestBatchIsRefreshedWhenTheTimeoutExpires(t *testing.T) {
14 t.Parallel()
15
16 ctx := context.Background()
17 capacity := 1000
18 ttl := time.Hour
19 numShards := 100
20 evictionPercentage := 10
21 minRefreshDelay := time.Minute * 5
22 maxRefreshDelay := time.Minute * 10
23 synchronousRefreshDelay := time.Minute * 30
24 refreshRetryInterval := time.Millisecond * 10
25 batchSize := 10
26 batchBufferTimeout := time.Minute
27 clock := sturdyc.NewTestClock(time.Now())
28
29 // The client will be configured as follows:
30 // - Records will be assigned a TTL of one hour.
31 // - If a record is re-requested within a random interval of 5 to
32 // 10 minutes, the client will queue a refresh for that record.
33 // - The queued refresh will be executed under two conditions:
34 // 1. The number of scheduled refreshes exceeds the specified 'batchSize'.
35 // 2. The 'batchBufferTimeout' threshold is exceeded.
36 client := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
37 sturdyc.WithNoContinuousEvictions(),
38 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
39 sturdyc.WithMissingRecordStorage(),
40 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
41 sturdyc.WithClock(clock),
42 )
43
44 // Populate the cache with 100 records.
45 ids := make([]string, 0, 100)
46 for i := 1; i <= 100; i++ {
47 ids = append(ids, strconv.Itoa(i))
48 }
49
50 fetchObserver := NewFetchObserver(1)
51 fetchObserver.BatchResponse(ids)
52 sturdyc.GetOrFetchBatch(ctx, client, ids, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
53
54 <-fetchObserver.FetchCompleted
55 fetchObserver.AssertFetchCount(t, 1)
56 fetchObserver.AssertRequestedRecords(t, ids)
57 fetchObserver.Clear()
58
59 // Next, we'll move the clock past the maxRefreshDelay. This should guarantee
60 // that the next records we request gets scheduled for a refresh.
61 clock.Add(maxRefreshDelay + time.Second)
62
63 // We'll create a batch function that stores the ids it was called with, and
64 // then invoke "GetOrFetchBatch". We are going to request 3 ids, which is less
65 // than our wanted batch size. This should lead to a batch being scheduled.
66 recordsToRequest := []string{"1", "2", "3"}
67 fetchObserver.BatchResponse(recordsToRequest)
68 sturdyc.GetOrFetchBatch(ctx, client, recordsToRequest, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
69 time.Sleep(10 * time.Millisecond)
70 fetchObserver.AssertFetchCount(t, 1)
71
72 // Now, we'll move the clock forward passed the "batchBufferTimeout". This should
73 // trigger a refresh even though we have less records than our wanted buffer size.
74 clock.Add(batchBufferTimeout + 1)
75 <-fetchObserver.FetchCompleted
76 fetchObserver.AssertFetchCount(t, 2)
77 fetchObserver.AssertRequestedRecords(t, recordsToRequest)
78 }
79
80 func TestBatchIsRefreshedWhenTheBufferSizeIsReached(t *testing.T) {
81 t.Parallel()
82
83 ctx := context.Background()
84 capacity := 1000
85 numShards := 50
86 evictionPercentage := 10
87 ttl := time.Hour
88 minRefreshDelay := time.Minute * 5
89 maxRefreshDelay := time.Minute * 10
90 synchronousRefreshDelay := time.Minute * 30
91 refreshRetryInterval := time.Millisecond * 10
92 batchSize := 10
93 batchBufferTimeout := time.Minute
94 clock := sturdyc.NewTestClock(time.Now())
95
96 // The client will be configured as follows:
97 // - Records will be assigned a TTL of one hour.
98 // - If a record is re-requested within a random interval of 5 to
99 // 10 minutes, the client will queue a refresh for that record.
100 // - The queued refresh will be executed under two conditions:
101 // 1. The number of scheduled refreshes exceeds the specified 'batchSize'.
102 // 2. The 'batchBufferTimeout' threshold is exceeded.
103 client := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
104 sturdyc.WithNoContinuousEvictions(),
105 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
106 sturdyc.WithMissingRecordStorage(),
107 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
108 sturdyc.WithClock(clock),
109 )
110
111 ids := make([]string, 0, 100)
112 for i := 1; i <= 100; i++ {
113 ids = append(ids, strconv.Itoa(i))
114 }
115
116 fetchObserver := NewFetchObserver(1)
117 fetchObserver.BatchResponse(ids)
118 sturdyc.GetOrFetchBatch(ctx, client, ids, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
119
120 <-fetchObserver.FetchCompleted
121 fetchObserver.AssertFetchCount(t, 1)
122 fetchObserver.AssertRequestedRecords(t, ids)
123 fetchObserver.Clear()
124
125 // Next, we'll move the clock past the maxRefreshDelay. This should guarantee
126 // that the next records we request gets scheduled for a refresh.
127 clock.Add(maxRefreshDelay + time.Second)
128
129 // We'll create a batch function that stores the ids it was called with, and
130 // then invoke "GetOrFetchBatch". We are going to request 3 ids, which is less
131 // than our ideal batch size. This should lead to a batch being scheduled.
132 firstBatchOfRequestedRecords := []string{"1", "2", "3"}
133 fetchObserver.BatchResponse([]string{"1", "2", "3"})
134 sturdyc.GetOrFetchBatch(ctx, client, firstBatchOfRequestedRecords, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
135
136 // Now, we'll move the clock forward 5 seconds before requesting another 3 records.
137 // Our wanted batch size is 10, hence this should NOT be enough to trigger a refresh.
138 clock.Add(5 * time.Second)
139 secondBatchOfRecords := []string{"4", "5", "6"}
140 sturdyc.GetOrFetchBatch(ctx, client, secondBatchOfRecords, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
141
142 // Move the clock another 10 seconds. Again, this should not trigger a refresh. We'll
143 // perform a sleep here too just to ensure that the buffer is not refreshed prematurely.
144 clock.Add(10 * time.Second)
145 time.Sleep(5 * time.Millisecond)
146 fetchObserver.AssertFetchCount(t, 1)
147
148 // In the the third batch I'm going to request 6 records. With that, we've
149 // requested 12 record in total, which is greater than our buffer size of 10.
150 thirdBatchOfRecords := []string{"7", "8", "9", "10", "11", "12"}
151 sturdyc.GetOrFetchBatch(ctx, client, thirdBatchOfRecords, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
152
153 // An actual refresh should happen for the first 10 ids, while the 2 that
154 // overflows should get scheduled for a refresh. Block until the request has
155 // happened, and then assert that it received the expected batch.
156 wantedRequestedRecords := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}
157 <-fetchObserver.FetchCompleted
158 fetchObserver.AssertFetchCount(t, 2)
159 fetchObserver.AssertRequestedRecords(t, wantedRequestedRecords)
160 fetchObserver.Clear()
161
162 // Lastly, we'll move the clock passed the "batchBufferTimeout" to assert
163 // that the overflowing records were requested when the timer expired. We
164 // have to sleep here because we only know that the goroutine that is going
165 // to listen on the timer has been launched, but it might not have reached
166 // the line where it creates a ticker yet. Hence, we'll sleep just to make
167 // sure it's attached before moving the clock.
168 time.Sleep(30 * time.Millisecond)
169 clock.Add(batchBufferTimeout + time.Second)
170 <-fetchObserver.FetchCompleted
171 fetchObserver.AssertFetchCount(t, 3)
172 fetchObserver.AssertRequestedRecords(t, []string{"11", "12"})
173 }
174
175 func TestBatchIsNotRefreshedByDuplicates(t *testing.T) {
176 t.Parallel()
177
178 ctx := context.Background()
179 capacity := 1000
180 numShards := 100
181 ttl := time.Hour
182 evictionPercentage := 10
183 minRefreshDelay := time.Minute * 5
184 maxRefreshDelay := time.Minute * 10
185 synchronousRefreshDelay := time.Minute * 30
186 refreshRetryInterval := time.Millisecond * 10
187 batchSize := 10
188 batchBufferTimeout := time.Minute
189 clock := sturdyc.NewTestClock(time.Now())
190
191 // The client will be configured as follows:
192 // - Records will be assigned a TTL of one hour.
193 // - If a record is re-requested within a random interval of 5 to
194 // 10 minutes, the client will queue a refresh for that record.
195 // - The queued refresh will be executed under two conditions:
196 // 1. The number of scheduled refreshes exceeds the specified 'batchSize'.
197 // 2. The 'batchBufferTimeout' threshold is exceeded.
198 client := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
199 sturdyc.WithNoContinuousEvictions(),
200 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
201 sturdyc.WithMissingRecordStorage(),
202 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
203 sturdyc.WithClock(clock),
204 )
205
206 // Populate the cache with 100 records.
207 ids := make([]string, 0, 100)
208 for i := 1; i <= 100; i++ {
209 ids = append(ids, strconv.Itoa(i))
210 }
211
212 fetchObserver := NewFetchObserver(1)
213 fetchObserver.BatchResponse(ids)
214 sturdyc.GetOrFetchBatch(ctx, client, ids, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
215 <-fetchObserver.FetchCompleted
216 fetchObserver.AssertFetchCount(t, 1)
217 fetchObserver.AssertRequestedRecords(t, ids)
218 fetchObserver.Clear()
219
220 // Next, we're going to go past the maxRefreshDelay and request id 1, 2, and
221 // 3 100 times. Because we're only requesting the same records over and over
222 // again, we don't expect any outgoing requests.
223 clock.Add(maxRefreshDelay + time.Second)
224 numRequests := 100
225 wg := sync.WaitGroup{}
226 wg.Add(numRequests)
227 for i := 0; i < numRequests; i++ {
228 go func(i int) {
229 id := []string{strconv.Itoa((i % 3) + 1)}
230 sturdyc.GetOrFetchBatch(ctx, client, id, client.BatchKeyFn("item"), fetchObserver.FetchBatch)
231 wg.Done()
232 }(i)
233 }
234 wg.Wait()
235 time.Sleep(5 * time.Millisecond)
236 fetchObserver.AssertFetchCount(t, 1)
237
238 // Now, we'll move the clock forward passed the "batchBufferTimeout".
239 fetchObserver.BatchResponse([]string{"1", "2", "3"})
240 clock.Add(batchBufferTimeout + time.Second)
241 <-fetchObserver.FetchCompleted
242 fetchObserver.AssertFetchCount(t, 2)
243 fetchObserver.AssertRequestedRecords(t, []string{"1", "2", "3"})
244 }
245
246 func TestBatchesAreGroupedByPermutations(t *testing.T) {
247 t.Parallel()
248
249 ctx := context.Background()
250 capacity := 1000
251 numShards := 100
252 ttl := time.Hour
253 evictionPercentage := 15
254 minRefreshDelay := time.Minute * 5
255 maxRefreshDelay := time.Minute * 10
256 synchronousRefreshDelay := time.Minute * 30
257 refreshRetryInterval := time.Millisecond * 10
258 batchSize := 5
259 batchBufferTimeout := time.Minute
260 clock := sturdyc.NewTestClock(time.Now())
261
262 // The c will be configured as follows:
263 // - Records will be assigned a TTL of one hour.
264 // - If a record is re-requested within a random interval of 5 to
265 // 10 minutes, the c will queue a refresh for that record.
266 // - The queued refresh will be executed under two conditions:
267 // 1. The number of scheduled refreshes exceeds the specified 'batchSize'.
268 // 2. The 'batchBufferTimeout' threshold is exceeded.
269 c := sturdyc.New[any](capacity, numShards, ttl, evictionPercentage,
270 sturdyc.WithNoContinuousEvictions(),
271 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
272 sturdyc.WithMissingRecordStorage(),
273 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
274 sturdyc.WithClock(clock),
275 )
276
277 // We are going to seed the cache by adding ids 1-10 but with varying options.
278 prefix := "item"
279 type QueryParams struct {
280 IncludeUpcoming bool
281 ProductGroupIDs []string
282 SortOrder string
283 }
284 optsOne := QueryParams{IncludeUpcoming: true, ProductGroupIDs: []string{"1", "2", "3"}, SortOrder: "asc"}
285 optsTwo := QueryParams{IncludeUpcoming: false, ProductGroupIDs: []string{"4", "5", "6"}, SortOrder: "desc"}
286
287 seedIDs := make([]string, 0, 10)
288 for i := 1; i <= 10; i++ {
289 seedIDs = append(seedIDs, strconv.Itoa(i))
290 }
291
292 fetchObserver := NewFetchObserver(1)
293 fetchObserver.BatchResponse(seedIDs)
294 sturdyc.GetOrFetchBatch(ctx, c, seedIDs, c.PermutatedBatchKeyFn(prefix, optsOne), fetchObserver.FetchBatch)
295 <-fetchObserver.FetchCompleted
296 sturdyc.GetOrFetchBatch(ctx, c, seedIDs, c.PermutatedBatchKeyFn(prefix, optsTwo), fetchObserver.FetchBatch)
297 <-fetchObserver.FetchCompleted
298 fetchObserver.AssertFetchCount(t, 2)
299 fetchObserver.Clear()
300
301 // Next, we'll move the clock past the maxRefreshDelay. This should guarantee
302 // that the next records we request gets scheduled for a refresh.
303 clock.Add(maxRefreshDelay + time.Second)
304
305 // For the records that were stored using optsOne, we'll only request 3
306 // records. We'll have to move the clock later on to make them expire.
307 optsOneIDs := []string{"1", "2", "3"}
308 // For the records that were stored using optsTwo we'll request 5 records in 2 batches,
309 // which should fill the buffer size. We'll want to assert that the batches were grouped
310 // correctly based on the options used, not the sequence in which they were requested.
311 optsTwoBatch1 := []string{"4", "5"}
312 optsTwoBatch2 := []string{"6", "7", "8"}
313
314 // Request the first batch of records. This should wait for additional IDs.
315 sturdyc.GetOrFetchBatch(ctx, c, optsOneIDs, c.PermutatedBatchKeyFn(prefix, optsOne), fetchObserver.FetchBatch)
316
317 // Next, we're requesting ids 4-8 with the second options which should exceed the buffer size for that permutation.
318 fetchObserver.BatchResponse([]string{"4", "5", "6", "7", "8"})
319 sturdyc.GetOrFetchBatch(ctx, c, optsTwoBatch1, c.PermutatedBatchKeyFn(prefix, optsTwo), fetchObserver.FetchBatch)
320 sturdyc.GetOrFetchBatch(ctx, c, optsTwoBatch2, c.PermutatedBatchKeyFn(prefix, optsTwo), fetchObserver.FetchBatch)
321
322 <-fetchObserver.FetchCompleted
323 fetchObserver.AssertFetchCount(t, 3)
324 fetchObserver.AssertRequestedRecords(t, []string{"4", "5", "6", "7", "8"})
325 fetchObserver.Clear()
326
327 // IDs 1-3 should still be waiting because they were requested using
328 // different options. We'll move the clock forward to make them expire.
329 fetchObserver.BatchResponse(optsOneIDs)
330 clock.Add(batchBufferTimeout + time.Second)
331 <-fetchObserver.FetchCompleted
332 fetchObserver.AssertFetchCount(t, 4)
333 fetchObserver.AssertRequestedRecords(t, optsOneIDs)
334 }
335
336 func TestLargeBatchesAreChunkedCorrectly(t *testing.T) {
337 t.Parallel()
338
339 ctx := context.Background()
340 capacity := 1000
341 numShards := 100
342 ttl := time.Hour
343 evictionPercentage := 23
344 minRefreshDelay := time.Minute * 5
345 maxRefreshDelay := time.Minute * 10
346 synchronousRefreshDelay := time.Minute * 30
347 refreshRetryInterval := time.Millisecond * 10
348 batchSize := 5
349 batchBufferTimeout := time.Minute
350 clock := sturdyc.NewTestClock(time.Now())
351
352 // The client will be configured as follows:
353 // - Records will be assigned a TTL of one hour.
354 // - If a record is re-requested within a random interval of 5 to
355 // 10 minutes, the client will queue a refresh for that record.
356 // - The queued refresh will be executed under two conditions:
357 // 1. The number of scheduled refreshes exceeds the specified 'batchSize'.
358 // 2. The 'batchBufferTimeout' threshold is exceeded.
359 client := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
360 sturdyc.WithNoContinuousEvictions(),
361 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
362 sturdyc.WithMissingRecordStorage(),
363 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
364 sturdyc.WithClock(clock),
365 )
366
367 // We are going to seed the cache by adding ids 1-100.
368 cacheKeyPrefix := "item"
369 seedIDs := make([]string, 0, 100)
370 for i := 1; i <= 100; i++ {
371 seedIDs = append(seedIDs, strconv.Itoa(i))
372 }
373
374 fetchObserver := NewFetchObserver(5)
375 fetchObserver.BatchResponse(seedIDs)
376 sturdyc.GetOrFetchBatch(ctx, client, seedIDs, client.BatchKeyFn(cacheKeyPrefix), fetchObserver.FetchBatch)
377 <-fetchObserver.FetchCompleted
378 fetchObserver.AssertFetchCount(t, 1)
379 fetchObserver.AssertRequestedRecords(t, seedIDs)
380 fetchObserver.Clear()
381
382 // Next, we'll move the clock past the maxRefreshDelay. This should guarantee
383 // that the next records we request gets scheduled for a refresh.
384 clock.Add(maxRefreshDelay + time.Second*5)
385
386 // Now we are going to request 50 items at once. The batch size is set to
387 // 5, so this should be chunked internally into 10 separate batches.
388 largeBatch := make([]string, 0, 50)
389 for i := 1; i <= 50; i++ {
390 largeBatch = append(largeBatch, strconv.Itoa(i))
391 }
392 sturdyc.GetOrFetchBatch(ctx, client, largeBatch, client.BatchKeyFn(cacheKeyPrefix), fetchObserver.FetchBatch)
393 for i := 0; i < 10; i++ {
394 <-fetchObserver.FetchCompleted
395 }
396 fetchObserver.AssertFetchCount(t, 11)
397 }
398
399 func TestValuesAreUpdatedCorrectly(t *testing.T) {
400 t.Parallel()
401
402 ctx := context.Background()
403 capacity := 1000
404 ttl := time.Hour
405 numShards := 100
406 evictionPercentage := 10
407 minRefreshDelay := time.Minute * 5
408 maxRefreshDelay := time.Minute * 10
409 synchronousRefreshDelay := time.Minute * 50
410 refreshRetryInterval := time.Millisecond * 10
411 batchSize := 10
412 batchBufferTimeout := time.Minute
413 clock := sturdyc.NewTestClock(time.Now())
414
415 // The client will be configured as follows:
416 // - Records will be assigned a TTL of one hour.
417 // - If a record is re-requested within a random interval of 5 to
418 // 10 minutes, the client will queue a refresh for that record.
419 // - The queued refresh will be executed under two conditions:
420 // 1. The number of scheduled refreshes exceeds the specified 'batchSize'.
421 // 2. The 'batchBufferTimeout' threshold is exceeded.
422 client := sturdyc.New[any](capacity, numShards, ttl, evictionPercentage,
423 sturdyc.WithNoContinuousEvictions(),
424 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
425 sturdyc.WithMissingRecordStorage(),
426 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
427 sturdyc.WithClock(clock),
428 )
429
430 type Foo struct {
431 Value string
432 }
433
434 records := []string{"1", "2", "3"}
435 res, _ := sturdyc.GetOrFetchBatch[Foo](ctx, client, records, client.BatchKeyFn("item"), func(_ context.Context, ids []string) (map[string]Foo, error) {
436 values := make(map[string]Foo, len(ids))
437 for _, id := range ids {
438 values[id] = Foo{Value: "foo-" + id}
439 }
440 return values, nil
441 })
442
443 if res["1"].Value != "foo-1" {
444 t.Errorf("expected 'foo-1', got '%s'", res["1"].Value)
445 }
446
447 clock.Add(time.Minute * 45)
448 sturdyc.GetOrFetchBatch[Foo](ctx, client, records, client.BatchKeyFn("item"), func(_ context.Context, ids []string) (map[string]Foo, error) {
449 values := make(map[string]Foo, len(ids))
450 for _, id := range ids {
451 values[id] = Foo{Value: "foo2-" + id}
452 }
453 return values, nil
454 })
455
456 // Flush out timers and then allow some time for the goroutines to run.
457 time.Sleep(50 * time.Millisecond)
458 clock.Add(batchBufferTimeout + time.Second*10)
459 time.Sleep(50 * time.Millisecond)
460 clock.Add(time.Minute * 45)
461 time.Sleep(50 * time.Millisecond)
462 clock.Add(time.Minute * 5)
463 time.Sleep(50 * time.Millisecond)
464
465 resTwo, _ := sturdyc.GetOrFetchBatch[Foo](ctx, client, records, client.BatchKeyFn("item"), func(_ context.Context, ids []string) (map[string]Foo, error) {
466 values := make(map[string]Foo, len(ids))
467 for _, id := range ids {
468 values[id] = Foo{Value: "foo3-" + id}
469 }
470 return values, nil
471 })
472
473 if resTwo["1"].Value != "foo2-1" {
474 t.Errorf("expected 'foo2-1', got '%s'", resTwo["1"].Value)
475 }
476 }