1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
|
package sturdyc_test
import (
"strconv"
"strings"
"testing"
"time"
"github.com/viccon/sturdyc"
)
type distributionTestCase struct {
name string
capacity int
numShards int
tolerancePercentage int
keyLength int
}
func TestShardDistribution(t *testing.T) {
t.Parallel()
testCases := []distributionTestCase{
{
name: "1_000_000 capacity, 100 shards, 12% tolerance, 16 key length",
capacity: 1_000_000,
numShards: 100,
tolerancePercentage: 12,
keyLength: 16,
},
{
name: "1000 capacity, 2 shards, 12% tolerance, 14 key length",
capacity: 1000,
numShards: 2,
tolerancePercentage: 12,
keyLength: 14,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
recorder := newTestMetricsRecorder(tc.numShards)
c := sturdyc.New[string](tc.capacity, tc.numShards, time.Hour, 5,
sturdyc.WithNoContinuousEvictions(),
sturdyc.WithMetrics(recorder),
)
for i := 0; i < tc.capacity; i++ {
key := randKey(tc.keyLength)
c.Set(key, "value")
}
recorder.validateShardDistribution(t, tc.tolerancePercentage)
})
}
}
func TestTimeBasedEviction(t *testing.T) {
t.Parallel()
capacity := 10_000
numShards := 100
ttl := time.Hour
evictionPercentage := 5
evictionInterval := time.Second
clock := sturdyc.NewTestClock(time.Now())
metricRecorder := newTestMetricsRecorder(numShards)
c := sturdyc.New[string](
capacity,
numShards,
ttl,
evictionPercentage,
sturdyc.WithMetrics(metricRecorder),
sturdyc.WithClock(clock),
sturdyc.WithEvictionInterval(evictionInterval),
)
for i := 0; i < capacity; i++ {
c.Set(randKey(12), "value")
}
// Expire all entries.
clock.Add(ttl + 1)
// Next, we'll loop through each shard while moving the clock by the evictionInterval. We'll
// sleep for a brief duration to allow the goroutines that were waiting for the timer to run.
for i := 0; i < numShards; i++ {
clock.Add(time.Second + 1)
time.Sleep(5 * time.Millisecond)
}
metricRecorder.Lock()
defer metricRecorder.Unlock()
if metricRecorder.evictedEntries != capacity {
t.Errorf("expected %d evicted entries, got %d", capacity, metricRecorder.evictedEntries)
}
}
type forcedEvictionTestCase struct {
name string
capacity int
writes int
numShards int
evictionPercentage int
minEvictions int
maxEvictions int
}
func TestForcedEvictions(t *testing.T) {
t.Parallel()
testCases := []forcedEvictionTestCase{
{
name: "1000 capacity, 100_000 writes, 100 shards, 5% forced evictions",
capacity: 10_000,
writes: 100_000,
numShards: 100,
evictionPercentage: 5,
minEvictions: 20_000, // Perfect shard distribution.
maxEvictions: 20_800, // Accounting for a 4% tolerance.
},
{
name: "100 capacity, 10_000 writes, 10 shards, 1% forced evictions",
capacity: 100,
writes: 10_000,
numShards: 10,
evictionPercentage: 1,
minEvictions: 9999,
maxEvictions: 10001,
},
{
name: "100 capacity, 1000 writes, 10 shards, 100% forced evictions",
capacity: 100,
writes: 1000,
numShards: 10,
evictionPercentage: 100,
minEvictions: 100,
maxEvictions: 120,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
recorder := newTestMetricsRecorder(tc.numShards)
c := sturdyc.New[string](tc.capacity,
tc.numShards,
time.Hour,
tc.evictionPercentage,
sturdyc.WithMetrics(recorder),
sturdyc.WithNoContinuousEvictions(),
)
// Start by filling the sturdyc.
for i := 0; i < tc.capacity; i++ {
key := randKey(12)
c.Set(key, "value")
}
// Next, we'll write to the cache to force evictions.
for i := 0; i < tc.writes; i++ {
key := randKey(12)
c.Set(key, "value")
}
if recorder.forcedEvictions < tc.minEvictions || recorder.forcedEvictions > tc.maxEvictions {
t.Errorf(
"expected forced evictions between %d and %d, got %d",
tc.minEvictions, tc.maxEvictions, recorder.forcedEvictions,
)
}
})
}
}
func TestForceEvictAllEntries(t *testing.T) {
t.Parallel()
capacity := 100
numShards := 1
ttl := time.Hour
evictionpercentage := 100
clock := sturdyc.NewTestClock(time.Now())
metricRecorder := newTestMetricsRecorder(numShards)
c := sturdyc.New[string](capacity, numShards, ttl, evictionpercentage,
sturdyc.WithClock(clock),
sturdyc.WithMetrics(metricRecorder),
)
// Fill the cache to capacity
for i := 0; i < capacity; i++ {
c.Set(strconv.Itoa(i), strconv.Itoa(i))
}
// Record metrics before eviction
preEvictionCount := metricRecorder.evictedEntries
// Trigger eviction by adding one more entry
// When the eviction is triggered by the 100th write, we expect the cache to
// be emptied. Therefore, the 101th write should mean that the size is now 1.
c.Set("trigger", "value")
// When the eviction is triggered, we expect the cache to be emptied
// and only contain the trigger value
if c.Size() != 1 {
t.Errorf("expected cache size to be 1, got %d", c.Size())
}
// Verify eviction metrics
metricRecorder.Lock()
defer metricRecorder.Unlock()
evictedEntries := metricRecorder.evictedEntries - preEvictionCount
if evictedEntries != capacity {
t.Errorf("got %d evicted entries, want %d", evictedEntries, capacity)
}
if metricRecorder.forcedEvictions != 1 {
t.Errorf("got %d forced eviction events, want 1", metricRecorder.forcedEvictions)
}
}
func TestForceEvictionSameTime(t *testing.T) {
t.Parallel()
capacity := 100
numShards := 2
ttl := time.Hour
evictionpercentage := 50
clock := sturdyc.NewTestClock(time.Now())
c := sturdyc.New[string](capacity, numShards, ttl, evictionpercentage,
sturdyc.WithClock(clock),
)
// Now we're going to write 1000 records to the cache which should
// exceed its capacity and trigger a couple of forced evictions.
for i := 0; i < 1000; i++ {
c.Set(strconv.Itoa(i), strconv.Itoa(i))
}
// Assert that even though we're writing 1000
// records we never exceed the capacity of 100.
if c.Size() > 100 {
t.Errorf("exceeded the cache size of 100, got %d", c.Size())
}
}
func TestForceEvictionTwoDifferentTimes(t *testing.T) {
t.Parallel()
capacity := 100
numShards := 1
ttl := time.Hour
evictionpercentage := 10
clock := sturdyc.NewTestClock(time.Now())
c := sturdyc.New[string](capacity, numShards, ttl, evictionpercentage,
sturdyc.WithClock(clock),
)
// We're going to write 50 records, then move the clock forward
// and write another 50 to reach the capacity of the cache.
for i := 0; i < 50; i++ {
c.Set(strconv.Itoa(i), strconv.Itoa(i))
}
clock.Add(time.Hour)
for i := 0; i < 50; i++ {
c.Set(strconv.Itoa(i+50), strconv.Itoa(i+50))
}
// At this point, the cache should be at its capacity so
// adding another item should trigger a forced eviction.
// Given our eviction percentage of 10%, we expect the
// cache to first remove 10 items, and then write this
// record afterwards.
c.Set(strconv.Itoa(100), strconv.Itoa(100))
if c.Size() != 91 {
t.Errorf("expected cache size to be 91, got %d", c.Size())
}
}
func TestDisablingForcedEvictionMakesSetANoop(t *testing.T) {
t.Parallel()
capacity := 100
numShards := 10
ttl := time.Hour
// Setting the eviction percentage to 0 should disable forced evictions.
evictionpercentage := 0
metricRecorder := newTestMetricsRecorder(numShards)
c := sturdyc.New[string](
capacity,
numShards,
ttl,
evictionpercentage,
sturdyc.WithMetrics(metricRecorder),
)
for i := 0; i < capacity*10; i++ {
c.Set(randKey(12), "value")
}
metricRecorder.Lock()
defer metricRecorder.Unlock()
if metricRecorder.forcedEvictions > 0 {
t.Errorf("expected no forced evictions, got %d", metricRecorder.forcedEvictions)
}
}
func TestSetMany(t *testing.T) {
t.Parallel()
c := sturdyc.New[int](1000, 10, time.Hour, 5)
if c.Size() != 0 {
t.Errorf("expected cache size to be 0, got %d", c.Size())
}
records := make(map[string]int, 10)
for i := 0; i < 10; i++ {
records[strconv.Itoa(i)] = i
}
c.SetMany(records)
if c.Size() != 10 {
t.Errorf("expected cache size to be 10, got %d", c.Size())
}
keys := c.ScanKeys()
if len(keys) != 10 {
t.Errorf("expected 10 keys, got %d", len(keys))
}
for _, key := range keys {
if _, ok := records[key]; !ok {
t.Errorf("expected key %s to be in the cache", key)
}
}
}
func TestSetManyKeyFn(t *testing.T) {
t.Parallel()
c := sturdyc.New[int](1000, 10, time.Hour, 5)
if c.Size() != 0 {
t.Errorf("expected cache size to be 0, got %d", c.Size())
}
records := make(map[string]int, 10)
for i := 0; i < 10; i++ {
records[strconv.Itoa(i)] = i
}
c.SetManyKeyFn(records, c.BatchKeyFn("foo"))
if c.Size() != 10 {
t.Errorf("expected cache size to be 10, got %d", c.Size())
}
keys := c.ScanKeys()
if len(keys) != 10 {
t.Errorf("expected 10 keys, got %d", len(keys))
}
for _, key := range keys {
if !strings.HasPrefix(key, "foo") {
t.Errorf("expected key %s to start with foo", key)
}
}
}
func TestGetMany(t *testing.T) {
t.Parallel()
c := sturdyc.New[int](1000, 10, time.Hour, 5)
if c.Size() != 0 {
t.Errorf("expected cache size to be 0, got %d", c.Size())
}
records := make(map[string]int, 10)
for i := 0; i < 10; i++ {
records[strconv.Itoa(i)] = i
}
c.SetMany(records)
keys := make([]string, 0, 10)
for key := range records {
keys = append(keys, key)
}
cacheHits := c.GetMany(keys)
if len(cacheHits) != 10 {
for key := range records {
if _, ok := cacheHits[key]; !ok {
t.Errorf("expected key %s to be in the cache", key)
}
}
}
}
func TestEvictsAndReturnsTheCorrectSize(t *testing.T) {
t.Parallel()
// Let's create a cache with a capacity of 100 and a
// single shard. We'll set the eviction percentage to 10%.
client := sturdyc.New[int](100, 1, time.Hour, 10)
// Now, if we were to write 101 items, which is 1 more
// than our capacity, we expect 10% to have been evicted.
for i := 0; i < 101; i++ {
client.Set(strconv.Itoa(i), i)
}
if client.Size() != 91 {
t.Errorf("expected cache size to be 91, got %d", client.Size())
}
}
func TestDeletesAllItemsAcrossMultipleShards(t *testing.T) {
t.Parallel()
client := sturdyc.New[string](1_000_000, 1000, time.Hour, 10)
ids := make([]string, 0, 10_000)
for i := 0; i < 10_000; i++ {
id := randKey(12)
ids = append(ids, id)
client.Set(id, "value")
}
if client.Size() != 10_000 {
t.Errorf("expected cache size to be 10_000, got %d", client.Size())
}
for _, id := range ids {
client.Delete(id)
}
if client.Size() != 0 {
t.Errorf("expected cache size to be 0, got %d", client.Size())
}
}
func TestReportsMetricsForHitsAndMisses(t *testing.T) {
t.Parallel()
metricsRecorder := newTestMetricsRecorder(10)
client := sturdyc.New[string](100, 10, time.Hour, 5,
sturdyc.WithMetrics(metricsRecorder),
)
client.Set("existing-key", "value")
client.Get("existing-key")
client.Get("non-existent-key")
if metricsRecorder.cacheHits != 1 {
t.Errorf("expected 1 cache hit, got %d", metricsRecorder.cacheHits)
}
if metricsRecorder.cacheMisses != 1 {
t.Errorf("expected 1 cache miss, got %d", metricsRecorder.cacheMisses)
}
}
|