github.com/onflow/flow-go@v0.33.17/storage/pebble/registers_cache.go (about)

     1  package pebble
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/pkg/errors"
     7  
     8  	"github.com/onflow/flow-go/model/flow"
     9  	"github.com/onflow/flow-go/module"
    10  	"github.com/onflow/flow-go/storage"
    11  )
    12  
    13  const (
    14  	registerResourceName = "registers"
    15  )
    16  
    17  type RegistersCache struct {
    18  	*Registers
    19  	cache *ReadCache
    20  }
    21  
    22  var _ storage.RegisterIndex = (*RegistersCache)(nil)
    23  
    24  // NewRegistersCache wraps a read cache around Get requests to a underlying Registers object.
    25  func NewRegistersCache(registers *Registers, cacheType CacheType, size uint, metrics module.CacheMetrics) (*RegistersCache, error) {
    26  	if size == 0 {
    27  		return nil, errors.New("cache size cannot be 0")
    28  	}
    29  
    30  	cache, err := newReadCache(
    31  		metrics,
    32  		registerResourceName,
    33  		cacheType,
    34  		size,
    35  		func(key string) (flow.RegisterValue, error) {
    36  			return registers.lookupRegister([]byte(key))
    37  		},
    38  	)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("could not create cache: %w", err)
    41  	}
    42  
    43  	return &RegistersCache{
    44  		Registers: registers,
    45  		cache:     cache,
    46  	}, nil
    47  }
    48  
    49  // Get returns the most recent updated payload for the given RegisterID.
    50  // "most recent" means the updates happens most recent up the given height.
    51  //
    52  // For example, if there are 2 values stored for register A at height 6 and 11, then
    53  // GetPayload(13, A) would return the value at height 11.
    54  //
    55  // - storage.ErrNotFound if no register values are found
    56  // - storage.ErrHeightNotIndexed if the requested height is out of the range of stored heights
    57  func (c *RegistersCache) Get(
    58  	reg flow.RegisterID,
    59  	height uint64,
    60  ) (flow.RegisterValue, error) {
    61  	return c.cache.Get(newLookupKey(height, reg).String())
    62  }