github.com/sequix/cortex@v1.1.6/pkg/chunk/cache/tiered.go (about)

     1  package cache
     2  
     3  import "context"
     4  
     5  type tiered []Cache
     6  
     7  // NewTiered makes a new tiered cache.
     8  func NewTiered(caches []Cache) Cache {
     9  	if len(caches) == 1 {
    10  		return caches[0]
    11  	}
    12  
    13  	return tiered(caches)
    14  }
    15  
    16  func (t tiered) Store(ctx context.Context, keys []string, bufs [][]byte) {
    17  	for _, c := range []Cache(t) {
    18  		c.Store(ctx, keys, bufs)
    19  	}
    20  }
    21  
    22  func (t tiered) Fetch(ctx context.Context, keys []string) ([]string, [][]byte, []string) {
    23  	found := make(map[string][]byte, len(keys))
    24  	missing := keys
    25  	previousCaches := make([]Cache, 0, len(t))
    26  
    27  	for _, c := range []Cache(t) {
    28  		var (
    29  			passKeys []string
    30  			passBufs [][]byte
    31  		)
    32  
    33  		passKeys, passBufs, missing = c.Fetch(ctx, missing)
    34  		tiered(previousCaches).Store(ctx, passKeys, passBufs)
    35  
    36  		for i, key := range passKeys {
    37  			found[key] = passBufs[i]
    38  		}
    39  
    40  		if len(missing) == 0 {
    41  			break
    42  		}
    43  
    44  		previousCaches = append(previousCaches, c)
    45  	}
    46  
    47  	resultKeys := make([]string, 0, len(found))
    48  	resultBufs := make([][]byte, 0, len(found))
    49  	for _, key := range keys {
    50  		if buf, ok := found[key]; ok {
    51  			resultKeys = append(resultKeys, key)
    52  			resultBufs = append(resultBufs, buf)
    53  		}
    54  	}
    55  
    56  	return resultKeys, resultBufs, missing
    57  }
    58  
    59  func (t tiered) Stop() error {
    60  	for _, c := range []Cache(t) {
    61  		if err := c.Stop(); err != nil {
    62  			return err
    63  		}
    64  	}
    65  	return nil
    66  }