github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/module/mempool/queue/heroStore.go (about)

     1  package queue
     2  
     3  import (
     4  	"github.com/rs/zerolog"
     5  
     6  	"github.com/onflow/flow-go/engine"
     7  	"github.com/onflow/flow-go/module"
     8  )
     9  
    10  var defaultMsgEntityFactoryFunc = NewMessageEntity
    11  
    12  type HeroStoreOption func(heroStore *HeroStore)
    13  
    14  func WithMessageEntityFactory(f func(message *engine.Message) MessageEntity) HeroStoreOption {
    15  	return func(heroStore *HeroStore) {
    16  		heroStore.msgEntityFactory = f
    17  	}
    18  }
    19  
    20  // HeroStore is a FIFO (first-in-first-out) size-bound queue for maintaining engine.Message types.
    21  // It is based on HeroQueue.
    22  type HeroStore struct {
    23  	q                *HeroQueue
    24  	msgEntityFactory func(message *engine.Message) MessageEntity
    25  }
    26  
    27  func NewHeroStore(sizeLimit uint32, logger zerolog.Logger, collector module.HeroCacheMetrics, opts ...HeroStoreOption) *HeroStore {
    28  	h := &HeroStore{
    29  		q:                NewHeroQueue(sizeLimit, logger, collector),
    30  		msgEntityFactory: defaultMsgEntityFactoryFunc,
    31  	}
    32  
    33  	for _, opt := range opts {
    34  		opt(h)
    35  	}
    36  
    37  	return h
    38  }
    39  
    40  // Put enqueues the message into the message store.
    41  //
    42  // Boolean returned variable determines whether enqueuing was successful, i.e.,
    43  // put may be dropped if queue is full or already exists.
    44  func (c *HeroStore) Put(message *engine.Message) bool {
    45  	return c.q.Push(c.msgEntityFactory(message))
    46  }
    47  
    48  // Get pops the queue, i.e., it returns the head of queue, and updates the head to the next element.
    49  // Boolean return value determines whether pop is successful, i.e., popping an empty queue returns false.
    50  func (c *HeroStore) Get() (*engine.Message, bool) {
    51  	head, ok := c.q.Pop()
    52  	if !ok {
    53  		return nil, false
    54  	}
    55  
    56  	msg := head.(MessageEntity).Msg
    57  	return &msg, true
    58  }