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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
|
/*
* SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
* SPDX-License-Identifier: Apache-2.0
*/
package ristretto
import (
"fmt"
"math/rand"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/dgraph-io/ristretto/v2/z"
"github.com/stretchr/testify/require"
)
var wait = time.Millisecond * 10
func TestCacheKeyToHash(t *testing.T) {
keyToHashCount := 0
c, err := NewCache(&Config[int, int]{
NumCounters: 10,
MaxCost: 1000,
BufferItems: 64,
IgnoreInternalCost: true,
KeyToHash: func(key int) (uint64, uint64) {
keyToHashCount++
return z.KeyToHash(key)
},
})
require.NoError(t, err)
if c.Set(1, 1, 1) {
time.Sleep(wait)
val, ok := c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
c.Del(1)
}
require.Equal(t, 3, keyToHashCount)
}
func TestCacheMaxCost(t *testing.T) {
charset := "abcdefghijklmnopqrstuvwxyz0123456789"
key := func() []byte {
k := make([]byte, 2)
for i := range k {
k[i] = charset[rand.Intn(len(charset))]
}
return k
}
c, err := NewCache(&Config[[]byte, string]{
NumCounters: 12960, // 36^2 * 10
MaxCost: 1e6, // 1mb
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
stop := make(chan struct{}, 8)
for i := 0; i < 8; i++ {
go func() {
for {
select {
case <-stop:
return
default:
time.Sleep(time.Millisecond)
k := key()
if _, ok := c.Get(k); !ok {
val := ""
if rand.Intn(100) < 10 {
val = "test"
} else {
val = strings.Repeat("a", 1000)
}
c.Set(key(), val, int64(2+len(val)))
}
}
}
}()
}
for i := 0; i < 20; i++ {
time.Sleep(time.Second)
cacheCost := c.Metrics.CostAdded() - c.Metrics.CostEvicted()
t.Logf("total cache cost: %d\n", cacheCost)
require.True(t, float64(cacheCost) <= float64(1e6*1.05))
}
for i := 0; i < 8; i++ {
stop <- struct{}{}
}
}
func TestUpdateMaxCost(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 10,
MaxCost: 10,
BufferItems: 64,
})
require.NoError(t, err)
require.Equal(t, int64(10), c.MaxCost())
require.True(t, c.Set(1, 1, 1))
time.Sleep(wait)
_, ok := c.Get(1)
// Set is rejected because the cost of the entry is too high
// when accounting for the internal cost of storing the entry.
require.False(t, ok)
// Update the max cost of the cache and retry.
c.UpdateMaxCost(1000)
require.Equal(t, int64(1000), c.MaxCost())
require.True(t, c.Set(1, 1, 1))
time.Sleep(wait)
val, ok := c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
c.Del(1)
}
func TestRemainingCost(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 10,
MaxCost: 100,
BufferItems: 64,
})
require.NoError(t, err)
require.Equal(t, int64(100), c.RemainingCost())
// Set allowed into cache
require.True(t, c.Set(1, 1, 1))
c.Wait()
_, ok := c.Get(1)
require.True(t, ok)
expectedUsed := 1 + itemSize
require.Equal(t, c.MaxCost()-expectedUsed, c.RemainingCost())
// Set rejected due to exceeding capacity
require.True(t, c.Set(2, 2, 99))
c.Wait()
_, ok = c.Get(2)
require.False(t, ok)
// No change in RemainingCost
require.Equal(t, c.MaxCost()-expectedUsed, c.RemainingCost())
// RemainingCost is still MaxCost() - Used after UpdateMaxCost()
c.UpdateMaxCost(1000)
require.Equal(t, int64(1000), c.MaxCost())
require.Equal(t, c.MaxCost()-expectedUsed, c.RemainingCost())
c.Del(1)
}
func TestNewCache(t *testing.T) {
_, err := NewCache(&Config[int, int]{
NumCounters: 0,
})
require.Error(t, err)
_, err = NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 0,
})
require.Error(t, err)
_, err = NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 0,
})
require.Error(t, err)
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
require.NotNil(t, c)
}
func TestNilCache(t *testing.T) {
var c *Cache[int, int]
val, ok := c.Get(1)
require.False(t, ok)
require.Zero(t, val)
require.False(t, c.Set(1, 1, 1))
c.Del(1)
c.Clear()
c.Close()
}
func TestMultipleClose(t *testing.T) {
var c *Cache[int, int]
c.Close()
var err error
c, err = NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
c.Close()
c.Close()
}
func TestSetAfterClose(t *testing.T) {
c, err := newTestCache()
require.NoError(t, err)
require.NotNil(t, c)
c.Close()
require.False(t, c.Set(1, 1, 1))
}
func TestClearAfterClose(t *testing.T) {
c, err := newTestCache()
require.NoError(t, err)
require.NotNil(t, c)
c.Close()
c.Clear()
}
func TestGetAfterClose(t *testing.T) {
c, err := newTestCache()
require.NoError(t, err)
require.NotNil(t, c)
require.True(t, c.Set(1, 1, 1))
c.Close()
_, ok := c.Get(1)
require.False(t, ok)
}
func TestDelAfterClose(t *testing.T) {
c, err := newTestCache()
require.NoError(t, err)
require.NotNil(t, c)
require.True(t, c.Set(1, 1, 1))
c.Close()
c.Del(1)
}
func TestCacheProcessItems(t *testing.T) {
m := &sync.Mutex{}
evicted := make(map[uint64]struct{})
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
IgnoreInternalCost: true,
Cost: func(value int) int64 {
return int64(value)
},
OnEvict: func(item *Item[int]) {
m.Lock()
defer m.Unlock()
evicted[item.Key] = struct{}{}
},
})
require.NoError(t, err)
var key uint64
var conflict uint64
key, conflict = z.KeyToHash(1)
c.setBuf <- &Item[int]{
flag: itemNew,
Key: key,
Conflict: conflict,
Value: 1,
Cost: 0,
}
time.Sleep(wait)
require.True(t, c.cachePolicy.Has(1))
require.Equal(t, int64(1), c.cachePolicy.Cost(1))
key, conflict = z.KeyToHash(1)
c.setBuf <- &Item[int]{
flag: itemUpdate,
Key: key,
Conflict: conflict,
Value: 2,
Cost: 0,
}
time.Sleep(wait)
require.Equal(t, int64(2), c.cachePolicy.Cost(1))
key, conflict = z.KeyToHash(1)
c.setBuf <- &Item[int]{
flag: itemDelete,
Key: key,
Conflict: conflict,
}
time.Sleep(wait)
key, conflict = z.KeyToHash(1)
val, ok := c.storedItems.Get(key, conflict)
require.False(t, ok)
require.Zero(t, val)
require.False(t, c.cachePolicy.Has(1))
key, conflict = z.KeyToHash(2)
c.setBuf <- &Item[int]{
flag: itemNew,
Key: key,
Conflict: conflict,
Value: 2,
Cost: 3,
}
key, conflict = z.KeyToHash(3)
c.setBuf <- &Item[int]{
flag: itemNew,
Key: key,
Conflict: conflict,
Value: 3,
Cost: 3,
}
key, conflict = z.KeyToHash(4)
c.setBuf <- &Item[int]{
flag: itemNew,
Key: key,
Conflict: conflict,
Value: 3,
Cost: 3,
}
key, conflict = z.KeyToHash(5)
c.setBuf <- &Item[int]{
flag: itemNew,
Key: key,
Conflict: conflict,
Value: 3,
Cost: 5,
}
time.Sleep(wait)
m.Lock()
require.NotEqual(t, 0, len(evicted))
m.Unlock()
defer func() {
require.NotNil(t, recover())
}()
c.Close()
c.setBuf <- &Item[int]{flag: itemNew}
}
func TestCacheGet(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
IgnoreInternalCost: true,
Metrics: true,
})
require.NoError(t, err)
key, conflict := z.KeyToHash(1)
i := Item[int]{
Key: key,
Conflict: conflict,
Value: 1,
}
c.storedItems.Set(&i)
val, ok := c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
val, ok = c.Get(2)
require.False(t, ok)
require.Zero(t, val)
// 0.5 and not 1.0 because we tried Getting each item twice
require.Equal(t, 0.5, c.Metrics.Ratio())
c = nil
val, ok = c.Get(0)
require.False(t, ok)
require.Zero(t, val)
}
// retrySet calls SetWithTTL until the item is accepted by the cache.
func retrySet(t *testing.T, c *Cache[int, int], key, value int, cost int64, ttl time.Duration) {
for {
if set := c.SetWithTTL(key, value, cost, ttl); !set {
time.Sleep(wait)
continue
}
time.Sleep(wait)
val, ok := c.Get(key)
require.True(t, ok)
require.NotNil(t, val)
require.Equal(t, value, val)
return
}
}
func TestCacheSet(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
retrySet(t, c, 1, 1, 1, 0)
c.Set(1, 2, 2)
val, ok := c.storedItems.Get(z.KeyToHash(1))
require.True(t, ok)
require.Equal(t, 2, val)
c.stop <- struct{}{}
<-c.done
for i := 0; i < setBufSize; i++ {
key, conflict := z.KeyToHash(1)
c.setBuf <- &Item[int]{
flag: itemUpdate,
Key: key,
Conflict: conflict,
Value: 1,
Cost: 1,
}
}
require.False(t, c.Set(2, 2, 1))
require.Equal(t, uint64(1), c.Metrics.SetsDropped())
close(c.setBuf)
close(c.stop)
close(c.done)
c = nil
require.False(t, c.Set(1, 1, 1))
}
func TestCacheInternalCost(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
// Get should return false because the cache's cost is too small to storedItems the item
// when accounting for the internal cost.
c.SetWithTTL(1, 1, 1, 0)
time.Sleep(wait)
_, ok := c.Get(1)
require.False(t, ok)
}
func TestRecacheWithTTL(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
// Set initial value for key = 1
insert := c.SetWithTTL(1, 1, 1, 5*time.Second)
require.True(t, insert)
time.Sleep(2 * time.Second)
// Get value from cache for key = 1
val, ok := c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
require.Equal(t, 1, val)
// Wait for expiration
time.Sleep(5 * time.Second)
// The cached value for key = 1 should be gone
val, ok = c.Get(1)
require.False(t, ok)
require.Zero(t, val)
// Set new value for key = 1
insert = c.SetWithTTL(1, 2, 1, 5*time.Second)
require.True(t, insert)
time.Sleep(2 * time.Second)
// Get value from cache for key = 1
val, ok = c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
require.Equal(t, 2, val)
}
func TestCacheSetWithTTL(t *testing.T) {
m := &sync.Mutex{}
evicted := make(map[uint64]struct{})
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
OnEvict: func(item *Item[int]) {
m.Lock()
defer m.Unlock()
evicted[item.Key] = struct{}{}
},
})
require.NoError(t, err)
retrySet(t, c, 1, 1, 1, time.Second)
// Sleep to make sure the item has expired after execution resumes.
time.Sleep(2 * time.Second)
val, ok := c.Get(1)
require.False(t, ok)
require.Zero(t, val)
// Sleep to ensure that the bucket where the item was stored has been cleared
// from the expiraton map.
time.Sleep(5 * time.Second)
m.Lock()
require.Equal(t, 1, len(evicted))
_, ok = evicted[1]
require.True(t, ok)
m.Unlock()
// Verify that expiration times are overwritten.
retrySet(t, c, 2, 1, 1, time.Second)
retrySet(t, c, 2, 2, 1, 100*time.Second)
time.Sleep(3 * time.Second)
val, ok = c.Get(2)
require.True(t, ok)
require.Equal(t, 2, val)
// Verify that entries with no expiration are overwritten.
retrySet(t, c, 3, 1, 1, 0)
retrySet(t, c, 3, 2, 1, time.Second)
time.Sleep(3 * time.Second)
val, ok = c.Get(3)
require.False(t, ok)
require.Zero(t, val)
}
func TestCacheDel(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
})
require.NoError(t, err)
c.Set(1, 1, 1)
c.Del(1)
// The deletes and sets are pushed through the setbuf. It might be possible
// that the delete is not processed before the following get is called. So
// wait for a millisecond for things to be processed.
time.Sleep(time.Millisecond)
val, ok := c.Get(1)
require.False(t, ok)
require.Zero(t, val)
c = nil
defer func() {
require.Nil(t, recover())
}()
c.Del(1)
}
func TestCacheDelWithTTL(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
})
require.NoError(t, err)
retrySet(t, c, 3, 1, 1, 10*time.Second)
time.Sleep(1 * time.Second)
// Delete the item
c.Del(3)
// Ensure the key is deleted.
val, ok := c.Get(3)
require.False(t, ok)
require.Zero(t, val)
}
func TestCacheGetTTL(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
// try expiration with valid ttl item
{
expiration := time.Second * 5
retrySet(t, c, 1, 1, 1, expiration)
val, ok := c.Get(1)
require.True(t, ok)
require.Equal(t, 1, val)
ttl, ok := c.GetTTL(1)
require.True(t, ok)
require.WithinDuration(t,
time.Now().Add(expiration), time.Now().Add(ttl), 1*time.Second)
c.Del(1)
ttl, ok = c.GetTTL(1)
require.False(t, ok)
require.Equal(t, ttl, time.Duration(0))
}
// try expiration with no ttl
{
retrySet(t, c, 2, 2, 1, time.Duration(0))
val, ok := c.Get(2)
require.True(t, ok)
require.Equal(t, 2, val)
ttl, ok := c.GetTTL(2)
require.True(t, ok)
require.Equal(t, ttl, time.Duration(0))
}
// try expiration with missing item
{
ttl, ok := c.GetTTL(3)
require.False(t, ok)
require.Equal(t, ttl, time.Duration(0))
}
// try expiration with expired item
{
expiration := time.Second
retrySet(t, c, 3, 3, 1, expiration)
val, ok := c.Get(3)
require.True(t, ok)
require.Equal(t, 3, val)
time.Sleep(time.Second)
ttl, ok := c.GetTTL(3)
require.False(t, ok)
require.Equal(t, ttl, time.Duration(0))
}
}
func TestCacheClear(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
for i := 0; i < 10; i++ {
c.Set(i, i, 1)
}
time.Sleep(wait)
require.Equal(t, uint64(10), c.Metrics.KeysAdded())
c.Clear()
require.Equal(t, uint64(0), c.Metrics.KeysAdded())
for i := 0; i < 10; i++ {
val, ok := c.Get(i)
require.False(t, ok)
require.Zero(t, val)
}
}
func TestCacheMetrics(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
for i := 0; i < 10; i++ {
c.Set(i, i, 1)
}
time.Sleep(wait)
m := c.Metrics
require.Equal(t, uint64(10), m.KeysAdded())
}
func TestMetrics(t *testing.T) {
newMetrics()
}
func TestNilMetrics(t *testing.T) {
var m *Metrics
for _, f := range []func() uint64{
m.Hits,
m.Misses,
m.KeysAdded,
m.KeysEvicted,
m.CostEvicted,
m.SetsDropped,
m.SetsRejected,
m.GetsDropped,
m.GetsKept,
} {
require.Equal(t, uint64(0), f())
}
}
func TestMetricsAddGet(t *testing.T) {
m := newMetrics()
m.add(hit, 1, 1)
m.add(hit, 2, 2)
m.add(hit, 3, 3)
require.Equal(t, uint64(6), m.Hits())
m = nil
m.add(hit, 1, 1)
require.Equal(t, uint64(0), m.Hits())
}
func TestMetricsRatio(t *testing.T) {
m := newMetrics()
require.Equal(t, float64(0), m.Ratio())
m.add(hit, 1, 1)
m.add(hit, 2, 2)
m.add(miss, 1, 1)
m.add(miss, 2, 2)
require.Equal(t, 0.5, m.Ratio())
m = nil
require.Equal(t, float64(0), m.Ratio())
}
func TestMetricsString(t *testing.T) {
m := newMetrics()
m.add(hit, 1, 1)
m.add(miss, 1, 1)
m.add(keyAdd, 1, 1)
m.add(keyUpdate, 1, 1)
m.add(keyEvict, 1, 1)
m.add(costAdd, 1, 1)
m.add(costEvict, 1, 1)
m.add(dropSets, 1, 1)
m.add(rejectSets, 1, 1)
m.add(dropGets, 1, 1)
m.add(keepGets, 1, 1)
require.Equal(t, uint64(1), m.Hits())
require.Equal(t, uint64(1), m.Misses())
require.Equal(t, 0.5, m.Ratio())
require.Equal(t, uint64(1), m.KeysAdded())
require.Equal(t, uint64(1), m.KeysUpdated())
require.Equal(t, uint64(1), m.KeysEvicted())
require.Equal(t, uint64(1), m.CostAdded())
require.Equal(t, uint64(1), m.CostEvicted())
require.Equal(t, uint64(1), m.SetsDropped())
require.Equal(t, uint64(1), m.SetsRejected())
require.Equal(t, uint64(1), m.GetsDropped())
require.Equal(t, uint64(1), m.GetsKept())
require.NotEqual(t, 0, len(m.String()))
m = nil
require.Equal(t, 0, len(m.String()))
require.Equal(t, "unidentified", stringFor(doNotUse))
}
func TestCacheMetricsClear(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
c.Set(1, 1, 1)
stop := make(chan struct{})
go func() {
for {
select {
case <-stop:
return
default:
c.Get(1)
}
}
}()
time.Sleep(wait)
c.Clear()
stop <- struct{}{}
c.Metrics = nil
c.Metrics.Clear()
}
func init() {
// Set bucketSizeSecs to 1 to avoid waiting too much during the tests.
bucketDurationSecs = 1
}
func TestBlockOnClear(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: false,
})
require.NoError(t, err)
defer c.Close()
done := make(chan struct{})
go func() {
for i := 0; i < 10; i++ {
c.Wait()
}
close(done)
}()
for i := 0; i < 10; i++ {
c.Clear()
}
select {
case <-done:
// We're OK
case <-time.After(1 * time.Second):
t.Fatalf("timed out while waiting on cache")
}
}
// Regression test for bug https://github.com/hypermodeinc/ristretto/issues/167
func TestDropUpdates(t *testing.T) {
originalSetBufSize := setBufSize
defer func() { setBufSize = originalSetBufSize }()
test := func() {
// droppedMap stores the items dropped from the cache.
droppedMap := make(map[int]struct{})
lastEvictedSet := int64(-1)
var err error
handler := func(_ interface{}, value interface{}) {
v := value.(string)
lastEvictedSet, err = strconv.ParseInt(v, 10, 32)
require.NoError(t, err)
_, ok := droppedMap[int(lastEvictedSet)]
if ok {
panic(fmt.Sprintf("val = %+v was dropped but it got evicted. Dropped items: %+v\n",
lastEvictedSet, droppedMap))
}
}
// This is important. The race condition shows up only when the setBuf
// is full and that's why we reduce the buf size here. The test will
// try to fill up the setbuf to it's capacity and then perform an
// update on a key.
setBufSize = 10
c, err := NewCache(&Config[int, string]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
IgnoreInternalCost: true,
Metrics: true,
OnEvict: func(item *Item[string]) {
handler(nil, item.Value)
},
})
require.NoError(t, err)
for i := 0; i < 5*setBufSize; i++ {
v := fmt.Sprintf("%0100d", i)
// We're updating the same key.
if !c.Set(0, v, 1) {
// The race condition doesn't show up without this sleep.
time.Sleep(time.Microsecond)
droppedMap[i] = struct{}{}
}
}
// Wait for all items to be processed: prevents next c.Set from getting dropped
c.Wait()
// This will cause eviction from the cache.
require.True(t, c.Set(1, "1", 10))
// Close() calls Clear(), which can cause the (key, value) pair of (1, nil) to be passed to
// the OnEvict() callback if it was still in the setBuf. This fixes a panic in OnEvict:
// "interface {} is nil, not string"
c.Wait()
c.Close()
require.NotEqual(t, int64(-1), lastEvictedSet)
}
// Run the test 100 times since it's not reliable.
for i := 0; i < 100; i++ {
test()
}
}
func TestRistrettoCalloc(t *testing.T) {
maxCacheSize := 1 << 20
config := &Config[int, []byte]{
// Use 5% of cache memory for storing counters.
NumCounters: int64(float64(maxCacheSize) * 0.05 * 2),
MaxCost: int64(float64(maxCacheSize) * 0.95),
BufferItems: 64,
Metrics: true,
OnExit: func(val []byte) {
z.Free(val)
},
}
r, err := NewCache(config)
require.NoError(t, err)
defer r.Close()
var wg sync.WaitGroup
for i := 0; i < runtime.NumCPU(); i++ {
wg.Add(1)
go func() {
defer wg.Done()
rd := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 10000; i++ {
k := rd.Intn(10000)
v := z.Calloc(256, "test")
rd.Read(v)
if !r.Set(k, v, 256) {
z.Free(v)
}
if rd.Intn(10) == 0 {
r.Del(k)
}
}
}()
}
wg.Wait()
r.Clear()
require.Zero(t, z.NumAllocBytes())
}
func TestRistrettoCallocTTL(t *testing.T) {
maxCacheSize := 1 << 20
config := &Config[int, []byte]{
// Use 5% of cache memory for storing counters.
NumCounters: int64(float64(maxCacheSize) * 0.05 * 2),
MaxCost: int64(float64(maxCacheSize) * 0.95),
BufferItems: 64,
Metrics: true,
OnExit: func(val []byte) {
z.Free(val)
},
}
r, err := NewCache(config)
require.NoError(t, err)
defer r.Close()
var wg sync.WaitGroup
for i := 0; i < runtime.NumCPU(); i++ {
wg.Add(1)
go func() {
defer wg.Done()
rd := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 10000; i++ {
k := rd.Intn(10000)
v := z.Calloc(256, "test")
rd.Read(v)
if !r.SetWithTTL(k, v, 256, time.Second) {
z.Free(v)
}
if rd.Intn(10) == 0 {
r.Del(k)
}
}
}()
}
wg.Wait()
time.Sleep(5 * time.Second)
require.Zero(t, z.NumAllocBytes())
}
func newTestCache() (*Cache[int, int], error) {
return NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
})
}
func TestCacheWithTTL(t *testing.T) {
// There may be a race condition, so run the test multiple times.
const try = 10
for i := 0; i < try; i++ {
t.Run(strconv.Itoa(i), func(t *testing.T) {
c, err := NewCache(&Config[int, int]{
NumCounters: 100,
MaxCost: 1000,
BufferItems: 64,
Metrics: true,
})
require.NoError(t, err)
// Set initial value for key = 1
insert := c.SetWithTTL(1, 1, 1, 800*time.Millisecond)
require.True(t, insert)
time.Sleep(100 * time.Millisecond)
// Get value from cache for key = 1
val, ok := c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
require.Equal(t, 1, val)
time.Sleep(1200 * time.Millisecond)
val, ok = c.Get(1)
require.False(t, ok)
require.Zero(t, val)
})
}
}
|