github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/kbfs/libkbfs/keycache.go (about)

     1  // Copyright 2016 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package libkbfs
     6  
     7  import (
     8  	lru "github.com/hashicorp/golang-lru"
     9  	"github.com/keybase/client/go/kbfs/kbfscrypto"
    10  	"github.com/keybase/client/go/kbfs/kbfsmd"
    11  	"github.com/keybase/client/go/kbfs/tlf"
    12  )
    13  
    14  // KeyCacheStandard is an LRU-based implementation of the KeyCache interface.
    15  type KeyCacheStandard struct {
    16  	lru *lru.Cache
    17  }
    18  
    19  type keyCacheKey struct {
    20  	tlf    tlf.ID
    21  	keyGen kbfsmd.KeyGen
    22  }
    23  
    24  var _ KeyCache = (*KeyCacheStandard)(nil)
    25  
    26  // NewKeyCacheStandard constructs a new KeyCacheStandard with the given
    27  // cache capacity.
    28  func NewKeyCacheStandard(capacity int) *KeyCacheStandard {
    29  	head, err := lru.New(capacity)
    30  	if err != nil {
    31  		panic(err.Error())
    32  	}
    33  	return &KeyCacheStandard{head}
    34  }
    35  
    36  // GetTLFCryptKey implements the KeyCache interface for KeyCacheStandard.
    37  func (k *KeyCacheStandard) GetTLFCryptKey(tlf tlf.ID, keyGen kbfsmd.KeyGen) (
    38  	kbfscrypto.TLFCryptKey, error) {
    39  	cacheKey := keyCacheKey{tlf, keyGen}
    40  	if entry, ok := k.lru.Get(cacheKey); ok {
    41  		if key, ok := entry.(kbfscrypto.TLFCryptKey); ok {
    42  			return key, nil
    43  		}
    44  		// shouldn't really be possible
    45  		return kbfscrypto.TLFCryptKey{}, KeyCacheHitError{tlf, keyGen}
    46  	}
    47  	return kbfscrypto.TLFCryptKey{}, KeyCacheMissError{tlf, keyGen}
    48  }
    49  
    50  // PutTLFCryptKey implements the KeyCache interface for KeyCacheStandard.
    51  func (k *KeyCacheStandard) PutTLFCryptKey(
    52  	tlf tlf.ID, keyGen kbfsmd.KeyGen, key kbfscrypto.TLFCryptKey) error {
    53  	cacheKey := keyCacheKey{tlf, keyGen}
    54  	k.lru.Add(cacheKey, key)
    55  	return nil
    56  }