diff --git a/src/utils/cache.go b/src/utils/cache.go index 488ce80..00edf06 100644 --- a/src/utils/cache.go +++ b/src/utils/cache.go @@ -102,10 +102,18 @@ func ExtractTTLFromResponse(responseBody []byte) time.Duration { defaultTTL := 30 * time.Minute if json.Unmarshal(responseBody, &tokenResp) == nil && tokenResp.ExpiresIn > 0 { - safeTTL := time.Duration(tokenResp.ExpiresIn-300) * time.Second - if safeTTL > 5*time.Minute { - return safeTTL + expires := time.Duration(tokenResp.ExpiresIn) * time.Second + skew := expires / 10 + if skew > 5*time.Minute { + skew = 5 * time.Minute } + if skew < 10*time.Second { + skew = 10 * time.Second + } + if expires > skew { + return expires - skew + } + return expires / 2 } return defaultTTL diff --git a/src/utils/cache_test.go b/src/utils/cache_test.go index e31a81e..a5b2a8b 100644 --- a/src/utils/cache_test.go +++ b/src/utils/cache_test.go @@ -34,6 +34,10 @@ func TestExtractTTLFromResponse(t *testing.T) { t.Fatalf("TTL = %s, want 55m", ttl) } + if ttl := ExtractTTLFromResponse([]byte(`{"expires_in":300}`)); ttl != 270*time.Second { + t.Fatalf("short TTL = %s, want 270s", ttl) + } + if ttl := ExtractTTLFromResponse([]byte(`{}`)); ttl != 30*time.Minute { t.Fatalf("default TTL = %s", ttl) }