github.com/mailgun/holster/v4@v4.20.0/httpsign/nonce.go (about)

     1  package httpsign
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/mailgun/holster/v4/collections"
     7  )
     8  
     9  type nonceCache struct {
    10  	sync.Mutex
    11  
    12  	cache    *collections.TTLMap
    13  	cacheTTL int
    14  }
    15  
    16  // Return a new nonceCache. Allows you to control cache capacity, ttl, as well as the TimeProvider.
    17  func newNonceCache(capacity, cacheTTL int) (*nonceCache, error) {
    18  	return &nonceCache{
    19  		cache:    collections.NewTTLMap(capacity),
    20  		cacheTTL: cacheTTL,
    21  	}, nil
    22  }
    23  
    24  // inCache checks if a nonce is in the cache. If not, it adds it to the
    25  // cache and returns false. Otherwise it returns true.
    26  func (n *nonceCache) inCache(nonce string) (exists bool, err error) {
    27  	n.Lock()
    28  	defer n.Unlock()
    29  
    30  	// check if the nonce is already in the cache
    31  	_, exists = n.cache.Get(nonce)
    32  	if exists {
    33  		return
    34  	}
    35  
    36  	// it's not, so let's put it in the cache
    37  	err = n.cache.Set(nonce, "", n.cacheTTL)
    38  	return
    39  }