@@ -34,6 +34,14 @@ func WithHTTPClient(client *http.Client) ExchangeClientOpts {
3434 }
3535}
3636
37+ // WithMinimumCacheTTL allows setting the minimum amount of time that a cache
38+ // entry must be valid for in order for it to be reused.
39+ func WithMinimumCacheTTL (ttl time.Duration ) ExchangeClientOpts {
40+ return func (c * TokenExchangeClient ) {
41+ c .minimumTTL = ttl
42+ }
43+ }
44+
3745func NewTokenExchangeClient (cfg TokenExchangeConfig , opts ... ExchangeClientOpts ) (* TokenExchangeClient , error ) {
3846 if cfg .Token == "" {
3947 return nil , fmt .Errorf ("%w: missing required token" , ErrMissingConfig )
@@ -47,8 +55,9 @@ func NewTokenExchangeClient(cfg TokenExchangeConfig, opts ...ExchangeClientOpts)
4755 cache : cache .NewLocalCache (cache.Config {
4856 CleanupInterval : 5 * time .Minute ,
4957 }),
50- cfg : cfg ,
51- singlef : singleflight.Group {},
58+ minimumTTL : 15 * time .Second ,
59+ cfg : cfg ,
60+ singlef : singleflight.Group {},
5261 }
5362
5463 for _ , opt := range opts {
@@ -64,10 +73,11 @@ func NewTokenExchangeClient(cfg TokenExchangeConfig, opts ...ExchangeClientOpts)
6473}
6574
6675type TokenExchangeClient struct {
67- cache cache.Cache
68- cfg TokenExchangeConfig
69- client * http.Client
70- singlef singleflight.Group
76+ cache cache.Cache
77+ minimumTTL time.Duration // Minimum time that token must be valid to be reused.
78+ cfg TokenExchangeConfig
79+ client * http.Client
80+ singlef singleflight.Group
7181}
7282
7383type TokenExchangeRequest struct {
@@ -190,8 +200,6 @@ func (c *TokenExchangeClient) getCache(ctx context.Context, key string) (string,
190200}
191201
192202func (c * TokenExchangeClient ) setCache (ctx context.Context , token string , key string ) error {
193- const cacheLeeway = 15 * time .Second
194-
195203 parsed , err := jwt .ParseSigned (token )
196204 if err != nil {
197205 return fmt .Errorf ("failed to parse token: %v" , err )
@@ -202,7 +210,7 @@ func (c *TokenExchangeClient) setCache(ctx context.Context, token string, key st
202210 return fmt .Errorf ("failed to extract claims from the token: %v" , err )
203211 }
204212
205- return c .cache .Set (ctx , key , []byte (token ), time .Until (claims .Expiry .Time ())- cacheLeeway )
213+ return c .cache .Set (ctx , key , []byte (token ), time .Until (claims .Expiry .Time ())- c . minimumTTL )
206214}
207215
208216var _ TokenExchanger = StaticTokenExchanger {}
0 commit comments