Class: DatagroutConduit::OAuth::TokenProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/datagrout_conduit/oauth.rb

Overview

Lazily fetches and caches OAuth 2.1 client_credentials tokens. Thread-safe via Mutex.

Constant Summary collapse

REFRESH_BUFFER_SECONDS =
60

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id:, client_secret:, token_endpoint:, scope: nil) ⇒ TokenProvider

Returns a new instance of TokenProvider.



15
16
17
18
19
20
21
22
23
# File 'lib/datagrout_conduit/oauth.rb', line 15

def initialize(client_id:, client_secret:, token_endpoint:, scope: nil)
  @client_id = client_id
  @client_secret = client_secret
  @token_endpoint = token_endpoint
  @scope = scope
  @mutex = Mutex.new
  @cached_token = nil
  @expires_at = nil
end

Instance Attribute Details

#client_idObject (readonly)

Returns the value of attribute client_id.



13
14
15
# File 'lib/datagrout_conduit/oauth.rb', line 13

def client_id
  @client_id
end

#token_endpointObject (readonly)

Returns the value of attribute token_endpoint.



13
14
15
# File 'lib/datagrout_conduit/oauth.rb', line 13

def token_endpoint
  @token_endpoint
end

Class Method Details

.derive_token_endpoint(mcp_url) ⇒ Object

Derive the token endpoint from an MCP URL.

"https://app.datagrout.ai/servers/abc/mcp"
=> "https://app.datagrout.ai/servers/abc/oauth/token"


29
30
31
32
33
# File 'lib/datagrout_conduit/oauth.rb', line 29

def self.derive_token_endpoint(mcp_url)
  idx = mcp_url.index("/mcp")
  base = idx ? mcp_url[0...idx] : mcp_url.chomp("/")
  "#{base}/oauth/token"
end

Instance Method Details

#get_tokenObject

Return a valid bearer token, fetching or refreshing as needed.



36
37
38
39
40
41
42
43
# File 'lib/datagrout_conduit/oauth.rb', line 36

def get_token
  @mutex.synchronize do
    return @cached_token if token_valid?

    fetch_token!
    @cached_token
  end
end

#invalidate!Object

Force-invalidate the cached token (e.g. on receipt of a 401).



46
47
48
49
50
51
# File 'lib/datagrout_conduit/oauth.rb', line 46

def invalidate!
  @mutex.synchronize do
    @cached_token = nil
    @expires_at = nil
  end
end