|
| 1 | +package dbcache |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/sei-protocol/sei-chain/sei-db/common/threading" |
| 10 | + "github.com/sei-protocol/sei-chain/sei-db/db_engine/types" |
| 11 | +) |
| 12 | + |
| 13 | +var _ Cache = (*cache)(nil) |
| 14 | + |
| 15 | +// A standard implementation of a flatcache. |
| 16 | +type cache struct { |
| 17 | + ctx context.Context |
| 18 | + |
| 19 | + // A utility for assigning keys to shard indices. |
| 20 | + shardManager *shardManager |
| 21 | + |
| 22 | + // The shards in the cache. |
| 23 | + shards []*shard |
| 24 | + |
| 25 | + // A pool for asynchronous reads. |
| 26 | + readPool threading.Pool |
| 27 | + |
| 28 | + // A pool for miscellaneous operations that are neither computationally intensive nor IO bound. |
| 29 | + miscPool threading.Pool |
| 30 | +} |
| 31 | + |
| 32 | +// Creates a new Cache. If cacheName is non-empty, OTel metrics are enabled and the |
| 33 | +// background size scrape runs every metricsScrapeInterval. |
| 34 | +func NewStandardCache( |
| 35 | + ctx context.Context, |
| 36 | + // The number of shards in the cache. Must be a power of two and greater than 0. |
| 37 | + shardCount uint64, |
| 38 | + // The maximum size of the cache, in bytes. |
| 39 | + maxSize uint64, |
| 40 | + // A work pool for reading from the DB. |
| 41 | + readPool threading.Pool, |
| 42 | + // A work pool for miscellaneous operations that are neither computationally intensive nor IO bound. |
| 43 | + miscPool threading.Pool, |
| 44 | + // The estimated overhead per entry, in bytes. This is used to calculate the maximum size of the cache. |
| 45 | + // This value should be derived experimentally, and may differ between different builds and architectures. |
| 46 | + estimatedOverheadPerEntry uint64, |
| 47 | + // Name used as the "cache" attribute on metrics. Empty string disables metrics. |
| 48 | + cacheName string, |
| 49 | + // How often to scrape cache size for metrics. Ignored if cacheName is empty. |
| 50 | + metricsScrapeInterval time.Duration, |
| 51 | +) (Cache, error) { |
| 52 | + if shardCount == 0 || (shardCount&(shardCount-1)) != 0 { |
| 53 | + return nil, ErrNumShardsNotPowerOfTwo |
| 54 | + } |
| 55 | + if maxSize == 0 { |
| 56 | + return nil, fmt.Errorf("maxSize must be greater than 0") |
| 57 | + } |
| 58 | + |
| 59 | + shardManager, err := newShardManager(shardCount) |
| 60 | + if err != nil { |
| 61 | + return nil, fmt.Errorf("failed to create shard manager: %w", err) |
| 62 | + } |
| 63 | + sizePerShard := maxSize / shardCount |
| 64 | + if sizePerShard == 0 { |
| 65 | + return nil, fmt.Errorf("maxSize must be greater than shardCount") |
| 66 | + } |
| 67 | + |
| 68 | + shards := make([]*shard, shardCount) |
| 69 | + for i := uint64(0); i < shardCount; i++ { |
| 70 | + shards[i], err = NewShard(ctx, readPool, sizePerShard, estimatedOverheadPerEntry) |
| 71 | + if err != nil { |
| 72 | + return nil, fmt.Errorf("failed to create shard: %w", err) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + c := &cache{ |
| 77 | + ctx: ctx, |
| 78 | + shardManager: shardManager, |
| 79 | + shards: shards, |
| 80 | + readPool: readPool, |
| 81 | + miscPool: miscPool, |
| 82 | + } |
| 83 | + |
| 84 | + if cacheName != "" { |
| 85 | + metrics := newCacheMetrics(ctx, cacheName, metricsScrapeInterval, c.getCacheSizeInfo) |
| 86 | + for _, s := range c.shards { |
| 87 | + s.metrics = metrics |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + return c, nil |
| 92 | +} |
| 93 | + |
| 94 | +func (c *cache) getCacheSizeInfo() (bytes uint64, entries uint64) { |
| 95 | + for _, s := range c.shards { |
| 96 | + b, e := s.getSizeInfo() |
| 97 | + bytes += b |
| 98 | + entries += e |
| 99 | + } |
| 100 | + return bytes, entries |
| 101 | +} |
| 102 | + |
| 103 | +func (c *cache) BatchSet(updates []CacheUpdate) error { |
| 104 | + // Sort entries by shard index so each shard is locked only once. |
| 105 | + shardMap := make(map[uint64][]CacheUpdate) |
| 106 | + for i := range updates { |
| 107 | + idx := c.shardManager.Shard(updates[i].Key) |
| 108 | + shardMap[idx] = append(shardMap[idx], updates[i]) |
| 109 | + } |
| 110 | + |
| 111 | + var wg sync.WaitGroup |
| 112 | + for shardIndex, shardEntries := range shardMap { |
| 113 | + wg.Add(1) |
| 114 | + err := c.miscPool.Submit(c.ctx, func() { |
| 115 | + defer wg.Done() |
| 116 | + c.shards[shardIndex].BatchSet(shardEntries) |
| 117 | + }) |
| 118 | + if err != nil { |
| 119 | + return fmt.Errorf("failed to submit batch set: %w", err) |
| 120 | + } |
| 121 | + } |
| 122 | + wg.Wait() |
| 123 | + |
| 124 | + return nil |
| 125 | +} |
| 126 | + |
| 127 | +func (c *cache) BatchGet(read Reader, keys map[string]types.BatchGetResult) error { |
| 128 | + work := make(map[uint64]map[string]types.BatchGetResult) |
| 129 | + for key := range keys { |
| 130 | + idx := c.shardManager.Shard([]byte(key)) |
| 131 | + if work[idx] == nil { |
| 132 | + work[idx] = make(map[string]types.BatchGetResult) |
| 133 | + } |
| 134 | + work[idx][key] = types.BatchGetResult{} |
| 135 | + } |
| 136 | + |
| 137 | + var wg sync.WaitGroup |
| 138 | + for shardIndex, subMap := range work { |
| 139 | + wg.Add(1) |
| 140 | + |
| 141 | + err := c.miscPool.Submit(c.ctx, func() { |
| 142 | + defer wg.Done() |
| 143 | + err := c.shards[shardIndex].BatchGet(read, subMap) |
| 144 | + if err != nil { |
| 145 | + for key := range subMap { |
| 146 | + subMap[key] = types.BatchGetResult{Error: err} |
| 147 | + } |
| 148 | + } |
| 149 | + }) |
| 150 | + if err != nil { |
| 151 | + return fmt.Errorf("failed to submit batch get: %w", err) |
| 152 | + } |
| 153 | + } |
| 154 | + wg.Wait() |
| 155 | + |
| 156 | + for _, subMap := range work { |
| 157 | + for key, result := range subMap { |
| 158 | + keys[key] = result |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + return nil |
| 163 | +} |
| 164 | + |
| 165 | +func (c *cache) Delete(key []byte) { |
| 166 | + shardIndex := c.shardManager.Shard(key) |
| 167 | + shard := c.shards[shardIndex] |
| 168 | + shard.Delete(key) |
| 169 | +} |
| 170 | + |
| 171 | +func (c *cache) Get(read Reader, key []byte, updateLru bool) ([]byte, bool, error) { |
| 172 | + shardIndex := c.shardManager.Shard(key) |
| 173 | + shard := c.shards[shardIndex] |
| 174 | + |
| 175 | + value, ok, err := shard.Get(read, key, updateLru) |
| 176 | + if err != nil { |
| 177 | + return nil, false, fmt.Errorf("failed to get value from shard: %w", err) |
| 178 | + } |
| 179 | + if !ok { |
| 180 | + return nil, false, nil |
| 181 | + } |
| 182 | + return value, ok, nil |
| 183 | +} |
| 184 | + |
| 185 | +func (c *cache) Set(key []byte, value []byte) { |
| 186 | + shardIndex := c.shardManager.Shard(key) |
| 187 | + shard := c.shards[shardIndex] |
| 188 | + |
| 189 | + if value == nil { |
| 190 | + shard.Delete(key) |
| 191 | + } else { |
| 192 | + shard.Set(key, value) |
| 193 | + } |
| 194 | +} |
0 commit comments