Debian Codegraph @

pkg/sievecache/sharded.go

raw symbols SCIP
1 package sievecache
2
3 import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 "hash/maphash"
8 )
9
10 // Default number of shards to use if not specified explicitly.
11 const DefaultShards = 16
12
13 // ShardedSieveCache is a thread-safe implementation of SieveCache that uses multiple shards to reduce contention.
14 type ShardedSieveCache[K comparable, V any] struct {
15 // Array of shard mutexes, each containing a separate SieveCache instance
16 shards []*SyncSieveCache[K, V]
17 // Number of shards in the cache
18 numShards int
19 }
20
21 // NewSharded creates a new sharded cache with the specified capacity, using the default number of shards.
22 func NewSharded[K comparable, V any](capacity int) (*ShardedSieveCache[K, V], error) {
23 return NewShardedWithShards[K, V](capacity, DefaultShards)
24 }
25
26 // NewShardedWithShards creates a new sharded cache with the specified capacity and number of shards.
27 func NewShardedWithShards[K comparable, V any](capacity int, numShards int) (*ShardedSieveCache[K, V], error) {
28 if capacity <= 0 {
29 return nil, errors.New("ShardedSieveCache: capacity must be greater than 0")
30 }
31 if numShards <= 0 {
32 return nil, errors.New("ShardedSieveCache: number of shards must be greater than 0")
33 }
34
35 // Avoid inflating total capacity: never create more shards than the
36 // total capacity can support (each shard needs at least 1 slot).
37 if numShards > capacity {
38 numShards = capacity
39 }
40
41 // Calculate per-shard capacity
42 baseCapacityPerShard := capacity / numShards
43 remaining := capacity % numShards
44
45 shards := make([]*SyncSieveCache[K, V], numShards)
46 for i := 0; i < numShards; i++ {
47 // Distribute the remaining capacity to the first 'remaining' shards
48 shardCapacity := baseCapacityPerShard
49 if i < remaining {
50 shardCapacity++
51 }
52
53 // Ensure at least capacity 1 per shard
54 if shardCapacity < 1 {
55 shardCapacity = 1
56 }
57
58 cache, err := NewSync[K, V](shardCapacity)
59 if err != nil {
60 return nil, err
61 }
62 shards[i] = cache
63 }
64
65 return &ShardedSieveCache[K, V]{
66 shards: shards,
67 numShards: numShards,
68 }, nil
69 }
70
71 // DefaultSharded creates a new sharded cache with a default capacity of 100 and default shard count.
72 func DefaultSharded[K comparable, V any]() *ShardedSieveCache[K, V] {
73 cache, err := NewSharded[K, V](100)
74 if err != nil {
75 // This should never happen with non-zero capacity
76 panic("Failed to create cache with default capacity")
77 }
78 return cache
79 }
80
81 // FromSync creates a new sharded cache from an existing SyncSieveCache.
82 func FromSync[K comparable, V any](syncCache *SyncSieveCache[K, V]) *ShardedSieveCache[K, V] {
83 // Create a new sharded cache with the same capacity
84 capacity := syncCache.Capacity()
85 shardedCache, err := NewSharded[K, V](capacity)
86 if err != nil {
87 // This should never happen with valid capacity
88 panic("Failed to create sharded cache")
89 }
90
91 // Transfer all entries
92 items := syncCache.Items()
93 for _, item := range items {
94 shardedCache.Insert(item.Key, item.Value)
95 }
96
97 return shardedCache
98 }
99
100 var hashSeed = maphash.MakeSeed()
101
102 // getShard returns the shard index for a given key.
103 func (c *ShardedSieveCache[K, V]) getShardIndex(key K) int {
104 var h maphash.Hash
105 h.SetSeed(hashSeed)
106
107 // Use type switch to handle different key types efficiently
108 switch k := any(key).(type) {
109 case string:
110 h.WriteString(k)
111 case []byte:
112 h.Write(k)
113 case int:
114 var buf [8]byte
115 binary.LittleEndian.PutUint64(buf[:], uint64(k))
116 h.Write(buf[:])
117 case int64:
118 var buf [8]byte
119 binary.LittleEndian.PutUint64(buf[:], uint64(k))
120 h.Write(buf[:])
121 default:
122 // For other types, convert to string
123 h.WriteString(ToString(k))
124 }
125
126 hashValue := h.Sum64()
127 return int(hashValue % uint64(c.numShards))
128 }
129
130 // ToString converts a value to string for hashing.
131 // This is a simple implementation that should be customized for better performance
132 // with specific key types.
133 func ToString(v any) string {
134 if s, ok := v.(string); ok {
135 return s
136 }
137 if stringer, ok := v.(interface{ String() string }); ok {
138 return stringer.String()
139 }
140 // For other types, just use %v formatting
141 return fmt.Sprintf("%v", v)
142 }
143
144 // getShard returns the shard for a given key.
145 func (c *ShardedSieveCache[K, V]) getShard(key K) *SyncSieveCache[K, V] {
146 index := c.getShardIndex(key)
147 return c.shards[index]
148 }
149
150 // Capacity returns the total capacity of the cache (sum of all shard capacities).
151 func (c *ShardedSieveCache[K, V]) Capacity() int {
152 total := 0
153 for _, shard := range c.shards {
154 total += shard.Capacity()
155 }
156 return total
157 }
158
159 // Len returns the total number of entries in the cache (sum of all shard lengths).
160 func (c *ShardedSieveCache[K, V]) Len() int {
161 total := 0
162 for _, shard := range c.shards {
163 total += shard.Len()
164 }
165 return total
166 }
167
168 // IsEmpty returns true when no values are currently cached in any shard.
169 func (c *ShardedSieveCache[K, V]) IsEmpty() bool {
170 for _, shard := range c.shards {
171 if !shard.IsEmpty() {
172 return false
173 }
174 }
175 return true
176 }
177
178 // ContainsKey returns true if there is a value in the cache mapped to by key.
179 func (c *ShardedSieveCache[K, V]) ContainsKey(key K) bool {
180 return c.getShard(key).ContainsKey(key)
181 }
182
183 // Get returns the value in the cache mapped to by key.
184 func (c *ShardedSieveCache[K, V]) Get(key K) (V, bool) {
185 return c.getShard(key).Get(key)
186 }
187
188 // GetMut gets a mutable reference to the value in the cache mapped to by key via a callback function.
189 func (c *ShardedSieveCache[K, V]) GetMut(key K, f func(*V)) bool {
190 return c.getShard(key).GetMut(key, f)
191 }
192
193 // Insert maps key to value in the cache, possibly evicting old entries from the appropriate shard.
194 func (c *ShardedSieveCache[K, V]) Insert(key K, value V) bool {
195 return c.getShard(key).Insert(key, value)
196 }
197
198 // Remove removes the cache entry mapped to by key.
199 func (c *ShardedSieveCache[K, V]) Remove(key K) (V, bool) {
200 return c.getShard(key).Remove(key)
201 }
202
203 // Evict removes and returns a value from the cache that was not recently accessed.
204 // It tries each shard in turn until it finds a value to evict.
205 func (c *ShardedSieveCache[K, V]) Evict() (V, bool) {
206 var zero V
207
208 // Try each shard in turn
209 for _, shard := range c.shards {
210 value, found := shard.Evict()
211 if found {
212 return value, true
213 }
214 }
215
216 return zero, false
217 }
218
219 // Clear removes all entries from the cache.
220 func (c *ShardedSieveCache[K, V]) Clear() {
221 for _, shard := range c.shards {
222 shard.Clear()
223 }
224 }
225
226 // Keys returns a slice of all keys in the cache.
227 func (c *ShardedSieveCache[K, V]) Keys() []K {
228 // First count total keys to allocate proper size
229 totalKeys := 0
230 for _, shard := range c.shards {
231 totalKeys += shard.Len()
232 }
233
234 // Pre-allocate slice with exact capacity
235 allKeys := make([]K, 0, totalKeys)
236
237 // Collect keys from all shards
238 for _, shard := range c.shards {
239 allKeys = append(allKeys, shard.Keys()...)
240 }
241
242 return allKeys
243 }
244
245 // Values returns a slice of all values in the cache.
246 func (c *ShardedSieveCache[K, V]) Values() []V {
247 // First count total values to allocate proper size
248 totalValues := 0
249 for _, shard := range c.shards {
250 totalValues += shard.Len()
251 }
252
253 // Pre-allocate slice with exact capacity
254 allValues := make([]V, 0, totalValues)
255
256 // Collect values from all shards
257 for _, shard := range c.shards {
258 allValues = append(allValues, shard.Values()...)
259 }
260
261 return allValues
262 }
263
264 // Items returns a slice of all key-value pairs in the cache.
265 func (c *ShardedSieveCache[K, V]) Items() []struct {
266 Key K
267 Value V
268 } {
269 // First count total items to allocate proper size
270 totalItems := 0
271 for _, shard := range c.shards {
272 totalItems += shard.Len()
273 }
274
275 // Pre-allocate slice with exact capacity
276 allItems := make([]struct {
277 Key K
278 Value V
279 }, 0, totalItems)
280
281 // Collect items from all shards
282 for _, shard := range c.shards {
283 allItems = append(allItems, shard.Items()...)
284 }
285
286 return allItems
287 }
288
289 // ForEachValue applies a function to all values in the cache across all shards.
290 func (c *ShardedSieveCache[K, V]) ForEachValue(f func(*V)) {
291 // Process each shard sequentially
292 for _, shard := range c.shards {
293 shard.ForEachValue(f)
294 }
295 }
296
297 // ForEachEntry applies a function to all key-value pairs in the cache across all shards.
298 func (c *ShardedSieveCache[K, V]) ForEachEntry(f func(K, *V)) {
299 // Process each shard sequentially
300 for _, shard := range c.shards {
301 shard.ForEachEntry(f)
302 }
303 }
304
305 // WithKeyLock gets exclusive access to a specific shard based on the key.
306 // This can be useful for performing multiple operations atomically on entries
307 // that share the same shard.
308 func (c *ShardedSieveCache[K, V]) WithKeyLock(key K, f func(*SieveCache[K, V])) {
309 c.getShard(key).WithLock(f)
310 }
311
312 // NumShards returns the number of shards in this cache.
313 func (c *ShardedSieveCache[K, V]) NumShards() int {
314 return c.numShards
315 }
316
317 // GetShardByIndex gets a specific shard by index.
318 // Returns nil if the index is out of bounds.
319 func (c *ShardedSieveCache[K, V]) GetShardByIndex(index int) *SyncSieveCache[K, V] {
320 if index < 0 || index >= c.numShards {
321 return nil
322 }
323 return c.shards[index]
324 }
325
326 // Retain only keeps elements specified by the predicate.
327 // Removes all entries for which f returns false.
328 func (c *ShardedSieveCache[K, V]) Retain(f func(K, V) bool) {
329 // Process each shard sequentially
330 for _, shard := range c.shards {
331 shard.Retain(f)
332 }
333 }
334
335 // RecommendedCapacity analyzes the current cache utilization and recommends a new capacity.
336 func (c *ShardedSieveCache[K, V]) RecommendedCapacity(minFactor, maxFactor, lowThreshold, highThreshold float64) int {
337 // For each shard, calculate the recommended capacity
338 totalRecommended := 0
339
340 for _, shard := range c.shards {
341 shardRecommended := shard.RecommendedCapacity(minFactor, maxFactor, lowThreshold, highThreshold)
342 totalRecommended += shardRecommended
343 }
344
345 // Ensure we return at least the original capacity for an empty cache
346 // and at least the number of shards otherwise
347 if c.IsEmpty() {
348 return c.Capacity()
349 }
350
351 return max(c.numShards, totalRecommended)
352 }