| 1 | package tokencache |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "sync" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/sassoftware/relic/v7/token" |
| 10 | ) |
| 11 | |
| 12 | // Cache keys fetched from an underlying token |
| 13 | type Cache struct { |
| 14 | token.Token |
| 15 | keys map[string]cachedKey |
| 16 | mu sync.Mutex |
| 17 | expiry time.Duration |
| 18 | } |
| 19 | |
| 20 | func New(base token.Token, expiry time.Duration) *Cache { |
| 21 | return &Cache{ |
| 22 | Token: base, |
| 23 | keys: make(map[string]cachedKey), |
| 24 | expiry: expiry, |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | type cachedKey struct { |
| 29 | expires time.Time |
| 30 | key token.Key |
| 31 | } |
| 32 | |
| 33 | func (c *Cache) GetKey(ctx context.Context, keyName string) (token.Key, error) { |
| 34 | c.mu.Lock() |
| 35 | defer c.mu.Unlock() |
| 36 | wantKeyID := token.KeyID(ctx) |
| 37 | cached := c.keys[keyName] |
| 38 | if cached.key != nil && cached.expires.After(time.Now()) { |
| 39 | // if caller is looking for a particular key ID, make sure the cached |
| 40 | // one matches before returning it |
| 41 | haveKeyID := cached.key.GetID() |
| 42 | if len(wantKeyID) == 0 || bytes.Equal(wantKeyID, haveKeyID) { |
| 43 | return cached.key, nil |
| 44 | } |
| 45 | } |
| 46 | key, err := c.Token.GetKey(ctx, keyName) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | if c.expiry > 0 && len(wantKeyID) == 0 { |
| 51 | // only cache if the caller did not request a specific key ID |
| 52 | c.keys[keyName] = cachedKey{ |
| 53 | expires: time.Now().Add(c.expiry), |
| 54 | key: key, |
| 55 | } |
| 56 | } |
| 57 | return key, nil |
| 58 | } |