Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 8 additions & 23 deletions x/blockdb/cache_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package blockdb

import (
"slices"
"sync"
"sync/atomic"

"go.uber.org/zap"

Expand All @@ -22,11 +22,9 @@ var _ database.HeightIndex = (*cacheDB)(nil)
// the cache and database contain different values. This limitation is acceptable
// because concurrent writes to the same height are not an intended use case.
type cacheDB struct {
db *Database
cache *lru.Cache[BlockHeight, BlockData]

closeMu sync.RWMutex
closed bool
db *Database
cache *lru.Cache[BlockHeight, BlockData]
closed atomic.Bool
}

func newCacheDB(db *Database, size uint16) *cacheDB {
Expand All @@ -37,10 +35,7 @@ func newCacheDB(db *Database, size uint16) *cacheDB {
}

func (c *cacheDB) Get(height BlockHeight) (BlockData, error) {
c.closeMu.RLock()
defer c.closeMu.RUnlock()

if c.closed {
if c.closed.Load() {
c.db.log.Error("Failed Get: database closed", zap.Uint64("height", height))
return nil, database.ErrClosed
}
Expand All @@ -57,10 +52,7 @@ func (c *cacheDB) Get(height BlockHeight) (BlockData, error) {
}

func (c *cacheDB) Put(height BlockHeight, data BlockData) error {
c.closeMu.RLock()
defer c.closeMu.RUnlock()

if c.closed {
if c.closed.Load() {
c.db.log.Error("Failed Put: database closed", zap.Uint64("height", height))
return database.ErrClosed
}
Expand All @@ -74,10 +66,7 @@ func (c *cacheDB) Put(height BlockHeight, data BlockData) error {
}

func (c *cacheDB) Has(height BlockHeight) (bool, error) {
c.closeMu.RLock()
defer c.closeMu.RUnlock()

if c.closed {
if c.closed.Load() {
c.db.log.Error("Failed Has: database closed", zap.Uint64("height", height))
return false, database.ErrClosed
}
Expand All @@ -89,13 +78,9 @@ func (c *cacheDB) Has(height BlockHeight) (bool, error) {
}

func (c *cacheDB) Close() error {
c.closeMu.Lock()
defer c.closeMu.Unlock()

if c.closed {
if !c.closed.CompareAndSwap(false, true) {
return database.ErrClosed
}
c.closed = true
c.cache.Flush()
return c.db.Close()
}