lib/clerk/jwks_cache.rb in clerk-sdk-ruby-4.0.0.beta3 vs lib/clerk/jwks_cache.rb in clerk-sdk-ruby-4.0.0.beta4
- old
+ new
@@ -1,32 +1,37 @@
-class JWKSCache
- def initialize(lifetime)
- @lifetime = lifetime
- @jwks = nil
- @last_update = nil
- @lock = Concurrent::ReadWriteLock.new
- end
+require "concurrent"
- def fetch(sdk, force_refresh: false, kid_not_found: false)
- should_refresh = @lock.with_read_lock do
- @jwks.nil? || @last_update.nil? || force_refresh ||
- (Time.now.to_i-@last_update > @lifetime) ||
- (kid_not_found && Time.now.to_i-@last_update > 300)
+module Clerk
+ class JWKSCache
+ def initialize(lifetime)
+ @lifetime = lifetime
+ @jwks = nil
+ @last_update = nil
+ @lock = Concurrent::ReadWriteLock.new
end
- if should_refresh
- @lock.with_write_lock do
- @last_update = Time.now.to_i
+ def fetch(sdk, force_refresh: false, kid_not_found: false)
+ should_refresh = @lock.with_read_lock do
+ now = Time.now.to_i
- @jwks = begin
- sdk.jwks.all["keys"]
- rescue Clerk::Errors::Base
- nil
+ @jwks.nil? || @last_update.nil? || force_refresh ||
+ (now - @last_update > @lifetime) ||
+ (kid_not_found && now - @last_update > 300)
+ end
+
+ if should_refresh
+ @lock.with_write_lock do
+ @last_update = Time.now.to_i
+ @jwks = begin
+ sdk.jwks.get.keys.map(&:to_hash)
+ rescue Clerk::Error, ClerkHttpClient::ApiError
+ nil
+ end
end
end
- end
- @lock.with_read_lock do
- @jwks
+ @lock.with_read_lock do
+ @jwks
+ end
end
end
end