github.com/thanos-io/thanos@v0.32.5/internal/cortex/chunk/cache/tiered.go (about)

     1  // Copyright (c) The Cortex Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package cache
     5  
     6  import "context"
     7  
     8  type tiered []Cache
     9  
    10  // NewTiered makes a new tiered cache.
    11  func NewTiered(caches []Cache) Cache {
    12  	if len(caches) == 1 {
    13  		return caches[0]
    14  	}
    15  
    16  	return tiered(caches)
    17  }
    18  
    19  // IsEmptyTieredCache is used to determine whether the current Cache is implemented by an empty tiered.
    20  func IsEmptyTieredCache(cache Cache) bool {
    21  	c, ok := cache.(tiered)
    22  	return ok && len(c) == 0
    23  }
    24  
    25  func (t tiered) Store(ctx context.Context, keys []string, bufs [][]byte) {
    26  	for _, c := range []Cache(t) {
    27  		c.Store(ctx, keys, bufs)
    28  	}
    29  }
    30  
    31  func (t tiered) Fetch(ctx context.Context, keys []string) ([]string, [][]byte, []string) {
    32  	found := make(map[string][]byte, len(keys))
    33  	missing := keys
    34  	previousCaches := make([]Cache, 0, len(t))
    35  
    36  	for _, c := range []Cache(t) {
    37  		var (
    38  			passKeys []string
    39  			passBufs [][]byte
    40  		)
    41  
    42  		passKeys, passBufs, missing = c.Fetch(ctx, missing)
    43  		tiered(previousCaches).Store(ctx, passKeys, passBufs)
    44  
    45  		for i, key := range passKeys {
    46  			found[key] = passBufs[i]
    47  		}
    48  
    49  		if len(missing) == 0 {
    50  			break
    51  		}
    52  
    53  		previousCaches = append(previousCaches, c)
    54  	}
    55  
    56  	resultKeys := make([]string, 0, len(found))
    57  	resultBufs := make([][]byte, 0, len(found))
    58  	for _, key := range keys {
    59  		if buf, ok := found[key]; ok {
    60  			resultKeys = append(resultKeys, key)
    61  			resultBufs = append(resultBufs, buf)
    62  		}
    63  	}
    64  
    65  	return resultKeys, resultBufs, missing
    66  }
    67  
    68  func (t tiered) Stop() {
    69  	for _, c := range []Cache(t) {
    70  		c.Stop()
    71  	}
    72  }