Class: StatelyDB::Common::Auth::AuthTokenProvider::Actor

Inherits:
Object
  • Object
show all
Defined in:
lib/common/auth/auth_token_provider.rb

Overview

Actor for managing the token refresh This is designed to be used with Async::Actor and run on a dedicated thread.

Instance Method Summary collapse

Constructor Details

#initialize(endpoint:, access_key:, base_retry_backoff_secs:) ⇒ Actor



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/common/auth/auth_token_provider.rb', line 60

def initialize(endpoint:, access_key:, base_retry_backoff_secs:)
  super()

  if access_key.nil?
    raise StatelyDB::Error.new(
      "Unable to find an access key in the STATELY_ACCESS_KEY " \
      "environment variable. Either pass your credentials in " \
      "the options when creating a client or set this environment variable.",
      code: GRPC::Core::StatusCodes::UNAUTHENTICATED,
      stately_code: "Unauthenticated"
    )
  end

  @token_fetcher = StatelyDB::Common::Auth::StatelyAccessTokenFetcher.new(
    endpoint: endpoint,
    access_key: access_key,
    base_retry_backoff_secs: base_retry_backoff_secs
  )
  @token_state = nil
  @pending_refresh = nil
end

Instance Method Details

#closeObject

Close the token provider and kill any background operations



91
92
93
94
# File 'lib/common/auth/auth_token_provider.rb', line 91

def close
  @scheduled&.stop
  @token_fetcher&.close
end

#get_token(force: false) ⇒ String

Get the current access token



99
100
101
102
103
104
105
106
107
108
# File 'lib/common/auth/auth_token_provider.rb', line 99

def get_token(force: false)
  if force
    @token_state = nil
  else
    token, ok = valid_access_token
    return token if ok
  end

  refresh_token.wait
end

#initObject

Initialize the actor. This runs on the actor thread which means we can dispatch async operations here.



84
85
86
87
88
# File 'lib/common/auth/auth_token_provider.rb', line 84

def init
  # disable the async lib logger. We do our own error handling and propagation
  Console.logger.disable(Async::Task)
  refresh_token
end

#refresh_tokenTask

Refresh the access token



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/common/auth/auth_token_provider.rb', line 121

def refresh_token
  Async do
    # we use an Async::Condition to dedupe multiple requests here
    # if the condition exists, we wait on it to complete
    # otherwise we create a condition, make the request, then signal the condition with the result
    # If there is an error then we signal that instead so we can raise it for the waiters.
    if @pending_refresh.nil?
      begin
        @pending_refresh = Async::Condition.new
        new_access_token = refresh_token_impl
        # now broadcast the new token to any waiters
        @pending_refresh.signal(new_access_token)
        new_access_token
      rescue StandardError => e
        @pending_refresh.signal(e)
        raise e
      ensure
        # delete the condition to restart the process
        @pending_refresh = nil
      end
    else
      res = @pending_refresh.wait
      # if the refresh result is an error, re-raise it.
      # otherwise return the token
      raise res if res.is_a?(StandardError)

      res
    end
  end
end

#refresh_token_implString

Refresh the access token implementation



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/common/auth/auth_token_provider.rb', line 154

def refresh_token_impl
  Sync do
    token_result = @token_fetcher.fetch
    new_expires_in_secs = token_result.expires_in_secs
    new_expires_at_unix_secs = Time.now.to_i + new_expires_in_secs

    # only update the token state if the new expiry is later than the current one
    if @token_state.nil? || new_expires_at_unix_secs > @token_state.expires_at_unix_secs
      @token_state = TokenState.new(token: token_result.token, expires_at_unix_secs: new_expires_at_unix_secs)
    else
      # otherwise use the existing expiry time for scheduling the refresh
      new_expires_in_secs = @token_state.expires_at_unix_secs - Time.now.to_i
    end

    # Schedule a refresh of the token ahead of the expiry time
    # Calculate a random multiplier between 0.9 and 0.95 to to apply to the expiry
    # so that we refresh in the background ahead of expiration, but avoid
    # multiple processes hammering the service at the same time.
    jitter = (Random.rand * 0.05) + 0.9
    delay_secs = new_expires_in_secs * jitter

    # do this on the fiber scheduler (the root scheduler) to avoid infinite recursion
    @scheduled ||= Fiber.scheduler.async do
      # Kernel.sleep is non-blocking if Ruby 3.1+ and Async 2+
      # https://github.com/socketry/async/issues/305#issuecomment-1945188193
      sleep(delay_secs)
      refresh_token
      @scheduled = nil
    end

    @token_state.token
  end
end

#valid_access_tokenArray

Get the current access token and whether it is valid



112
113
114
115
116
117
# File 'lib/common/auth/auth_token_provider.rb', line 112

def valid_access_token
  return "", false if @token_state.nil?
  return "", false if @token_state.expires_at_unix_secs < Time.now.to_i

  [@token_state.token, true]
end