k8s.io/apiserver@v0.31.1/pkg/authentication/token/cache/cache_striped.go (about)

     1  /*
     2  Copyright 2017 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cache
    18  
    19  import (
    20  	"hash/fnv"
    21  	"time"
    22  )
    23  
    24  // split cache lookups across N striped caches
    25  type stripedCache struct {
    26  	stripeCount uint32
    27  	hashFunc    func(string) uint32
    28  	caches      []cache
    29  }
    30  
    31  type hashFunc func(string) uint32
    32  type newCacheFunc func() cache
    33  
    34  func newStripedCache(stripeCount int, hash hashFunc, newCacheFunc newCacheFunc) cache {
    35  	caches := []cache{}
    36  	for i := 0; i < stripeCount; i++ {
    37  		caches = append(caches, newCacheFunc())
    38  	}
    39  	return &stripedCache{
    40  		stripeCount: uint32(stripeCount),
    41  		hashFunc:    hash,
    42  		caches:      caches,
    43  	}
    44  }
    45  
    46  func (c *stripedCache) get(key string) (*cacheRecord, bool) {
    47  	return c.caches[c.hashFunc(key)%c.stripeCount].get(key)
    48  }
    49  func (c *stripedCache) set(key string, value *cacheRecord, ttl time.Duration) {
    50  	c.caches[c.hashFunc(key)%c.stripeCount].set(key, value, ttl)
    51  }
    52  func (c *stripedCache) remove(key string) {
    53  	c.caches[c.hashFunc(key)%c.stripeCount].remove(key)
    54  }
    55  
    56  func fnvHashFunc(key string) uint32 {
    57  	f := fnv.New32()
    58  	f.Write([]byte(key))
    59  	return f.Sum32()
    60  }