Skip to content

Commit 34d8362

Browse files
committed
Move to RWMutex to allow multiple readers
1 parent 8e479d9 commit 34d8362

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*.dll
55
*.so
66
*.dylib
7+
.DS_Store
78

89
# Test binary, built with `go test -c`
910
*.test

jwks/provider.go

+11-3
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ func (p *Provider) KeyFunc(ctx context.Context) (interface{}, error) {
100100
type CachingProvider struct {
101101
*Provider
102102
CacheTTL time.Duration
103-
mu sync.Mutex
103+
mu sync.RWMutex
104104
cache map[string]cachedJWKS
105105
}
106106

@@ -127,17 +127,25 @@ func NewCachingProvider(issuerURL *url.URL, cacheTTL time.Duration, opts ...Prov
127127
// While it returns an interface to adhere to keyFunc, as long as the
128128
// error is nil the type will be *jose.JSONWebKeySet.
129129
func (c *CachingProvider) KeyFunc(ctx context.Context) (interface{}, error) {
130-
c.mu.Lock()
131-
defer c.mu.Unlock()
130+
c.mu.RLock()
132131

133132
issuer := c.IssuerURL.Hostname()
134133

135134
if cached, ok := c.cache[issuer]; ok {
136135
if !time.Now().After(cached.expiresAt) {
136+
c.mu.RUnlock()
137137
return cached.jwks, nil
138138
}
139139
}
140140

141+
c.mu.RUnlock()
142+
return c.refreshKey(ctx, issuer)
143+
}
144+
145+
func (c *CachingProvider) refreshKey(ctx context.Context, issuer string) (interface{}, error) {
146+
c.mu.Lock()
147+
defer c.mu.Unlock()
148+
141149
jwks, err := c.Provider.KeyFunc(ctx)
142150
if err != nil {
143151
return nil, err

0 commit comments

Comments
 (0)