github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/libkbfs/kcache_measured.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  	"github.com/keybase/client/go/kbfs/kbfscrypto"
     9  	"github.com/keybase/client/go/kbfs/kbfsmd"
    10  	"github.com/keybase/client/go/kbfs/tlf"
    11  	metrics "github.com/rcrowley/go-metrics"
    12  )
    13  
    14  // KeyCacheMeasured delegates to another KeyCache instance but
    15  // also keeps track of stats.
    16  type KeyCacheMeasured struct {
    17  	delegate      KeyCache
    18  	getTimer      metrics.Timer
    19  	putTimer      metrics.Timer
    20  	hitCountMeter metrics.Meter
    21  }
    22  
    23  var _ KeyCache = KeyCacheMeasured{}
    24  
    25  // NewKeyCacheMeasured creates and returns a new KeyCacheMeasured
    26  // instance with the given delegate and registry.
    27  func NewKeyCacheMeasured(delegate KeyCache, r metrics.Registry) KeyCacheMeasured {
    28  	getTimer := metrics.GetOrRegisterTimer("KeyCache.GetTLFCryptKey", r)
    29  	putTimer := metrics.GetOrRegisterTimer("KeyCache.PutTLFCryptKey", r)
    30  	// TODO: Implement RatioGauge (
    31  	// http://metrics.dropwizard.io/3.1.0/manual/core/#ratio-gauges
    32  	// ) so we can actually display a hit ratio.
    33  	hitCountMeter := metrics.GetOrRegisterMeter("KeyCache.HitCount", r)
    34  	return KeyCacheMeasured{
    35  		delegate:      delegate,
    36  		getTimer:      getTimer,
    37  		putTimer:      putTimer,
    38  		hitCountMeter: hitCountMeter,
    39  	}
    40  }
    41  
    42  // GetTLFCryptKey implements the KeyCache interface for
    43  // KeyCacheMeasured.
    44  func (b KeyCacheMeasured) GetTLFCryptKey(
    45  	tlfID tlf.ID, keyGen kbfsmd.KeyGen) (key kbfscrypto.TLFCryptKey, err error) {
    46  	b.getTimer.Time(func() {
    47  		key, err = b.delegate.GetTLFCryptKey(tlfID, keyGen)
    48  	})
    49  	if err == nil {
    50  		b.hitCountMeter.Mark(1)
    51  	}
    52  	return key, err
    53  }
    54  
    55  // PutTLFCryptKey implements the KeyCache interface for
    56  // KeyCacheMeasured.
    57  func (b KeyCacheMeasured) PutTLFCryptKey(
    58  	tlfID tlf.ID, keyGen kbfsmd.KeyGen, key kbfscrypto.TLFCryptKey) (err error) {
    59  	b.putTimer.Time(func() {
    60  		err = b.delegate.PutTLFCryptKey(tlfID, keyGen, key)
    61  	})
    62  	return err
    63  }