github.com/koko1123/flow-go-1@v0.29.6/network/cache/rcvcache.go (about)

     1  package netcache
     2  
     3  import (
     4  	"github.com/rs/zerolog"
     5  
     6  	"github.com/koko1123/flow-go-1/model/flow"
     7  	"github.com/koko1123/flow-go-1/module"
     8  	herocache "github.com/koko1123/flow-go-1/module/mempool/herocache/backdata"
     9  	"github.com/koko1123/flow-go-1/module/mempool/herocache/backdata/heropool"
    10  	"github.com/koko1123/flow-go-1/module/mempool/stdmap"
    11  )
    12  
    13  // ReceiveCache implements an LRU cache of the received eventIDs that delivered to their engines
    14  type ReceiveCache struct {
    15  	c *stdmap.Backend
    16  }
    17  
    18  // receiveCacheEntry represents an entry for the ReceiveCache
    19  type receiveCacheEntry struct {
    20  	eventID flow.Identifier
    21  }
    22  
    23  func (r receiveCacheEntry) ID() flow.Identifier {
    24  	return r.eventID
    25  }
    26  
    27  func (r receiveCacheEntry) Checksum() flow.Identifier {
    28  	return r.eventID
    29  }
    30  
    31  // NewHeroReceiveCache returns a new HeroCache-based receive cache.
    32  func NewHeroReceiveCache(sizeLimit uint32, logger zerolog.Logger, collector module.HeroCacheMetrics) *ReceiveCache {
    33  	backData := herocache.NewCache(sizeLimit,
    34  		herocache.DefaultOversizeFactor,
    35  		heropool.LRUEjection, // receive cache must be LRU.
    36  		logger.With().Str("mempool", "receive-cache").Logger(),
    37  		collector)
    38  	backend := stdmap.NewBackend(stdmap.WithBackData(backData))
    39  	return NewReceiveCache(uint(sizeLimit), func(cache *ReceiveCache) {
    40  		cache.c = backend
    41  	})
    42  }
    43  
    44  // NewReceiveCache creates and returns a new ReceiveCache
    45  func NewReceiveCache(sizeLimit uint, opts ...func(cache *ReceiveCache)) *ReceiveCache {
    46  	cache := &ReceiveCache{
    47  		c: stdmap.NewBackend(stdmap.WithLimit(sizeLimit)),
    48  	}
    49  
    50  	for _, opt := range opts {
    51  		opt(cache)
    52  	}
    53  
    54  	return cache
    55  }
    56  
    57  // Add adds a new message to the cache if not already present. Returns true if the message is new and unseen, and false if message is duplicate, and
    58  // already has been seen by the node.
    59  func (r *ReceiveCache) Add(eventID []byte) bool {
    60  	return r.c.Add(receiveCacheEntry{eventID: flow.HashToID(eventID)}) // ignore eviction status
    61  }
    62  
    63  func (r ReceiveCache) Size() uint {
    64  	return r.c.Size()
    65  }