|
5 | 5 | import com.databricks.sdk.core.http.FormRequest; |
6 | 6 | import com.databricks.sdk.core.http.HttpClient; |
7 | 7 | import com.databricks.sdk.core.http.Request; |
| 8 | +import com.databricks.sdk.core.utils.ClockSupplier; |
| 9 | +import com.databricks.sdk.core.utils.UtcClockSupplier; |
| 10 | +import java.time.Duration; |
8 | 11 | import java.time.Instant; |
9 | 12 | import java.util.Base64; |
10 | 13 | import java.util.Map; |
| 14 | +import java.util.concurrent.CompletableFuture; |
11 | 15 | import org.apache.http.HttpHeaders; |
| 16 | +import org.slf4j.Logger; |
| 17 | +import org.slf4j.LoggerFactory; |
12 | 18 |
|
13 | 19 | /** |
14 | 20 | * An OAuth TokenSource which can be refreshed. |
15 | 21 | * |
16 | | - * <p>Calls to getToken() will first check if the token is still valid (currently defined by having |
17 | | - * at least 10 seconds until expiry). If not, refresh() is called first to refresh the token. |
| 22 | + * <p>This class supports both synchronous and asynchronous token refresh. When async is enabled, |
| 23 | + * stale tokens will trigger a background refresh, while expired tokens will block until a new token |
| 24 | + * is fetched. |
18 | 25 | */ |
19 | 26 | public abstract class RefreshableTokenSource implements TokenSource { |
20 | | - protected Token token; |
21 | 27 |
|
| 28 | + /** |
| 29 | + * Enum representing the state of the token. FRESH: Token is valid and not close to expiry. STALE: |
| 30 | + * Token is valid but will expire soon - an async refresh will be triggered if enabled. EXPIRED: |
| 31 | + * Token has expired and must be refreshed using a blocking call. |
| 32 | + */ |
| 33 | + protected enum TokenState { |
| 34 | + FRESH, |
| 35 | + STALE, |
| 36 | + EXPIRED |
| 37 | + } |
| 38 | + |
| 39 | + private static final Logger logger = LoggerFactory.getLogger(RefreshableTokenSource.class); |
| 40 | + // Default duration before expiry to consider a token as 'stale'. |
| 41 | + private static final Duration DEFAULT_STALE_DURATION = Duration.ofMinutes(3); |
| 42 | + // Default additional buffer before expiry to consider a token as expired. |
| 43 | + private static final Duration DEFAULT_EXPIRY_BUFFER = Duration.ofSeconds(40); |
| 44 | + |
| 45 | + // The current OAuth token. May be null if not yet fetched. |
| 46 | + protected volatile Token token; |
| 47 | + // Whether asynchronous refresh is enabled. |
| 48 | + private boolean asyncEnabled = false; |
| 49 | + // Duration before expiry to consider a token as 'stale'. |
| 50 | + private Duration staleDuration = DEFAULT_STALE_DURATION; |
| 51 | + // Additional buffer before expiry to consider a token as expired. |
| 52 | + private Duration expiryBuffer = DEFAULT_EXPIRY_BUFFER; |
| 53 | + // Whether a refresh is currently in progress (for async refresh). |
| 54 | + private boolean refreshInProgress = false; |
| 55 | + // Whether the last refresh attempt succeeded. |
| 56 | + private boolean lastRefreshSucceeded = true; |
| 57 | + // Clock supplier for current time. |
| 58 | + private ClockSupplier clockSupplier = new UtcClockSupplier(); |
| 59 | + |
| 60 | + /** Constructs a new {@code RefreshableTokenSource} with no initial token. */ |
22 | 61 | public RefreshableTokenSource() {} |
23 | 62 |
|
| 63 | + /** |
| 64 | + * Constructor with initial token. |
| 65 | + * |
| 66 | + * @param token The initial token to use. |
| 67 | + */ |
24 | 68 | public RefreshableTokenSource(Token token) { |
25 | 69 | this.token = token; |
26 | 70 | } |
27 | 71 |
|
| 72 | + /** |
| 73 | + * Set the clock supplier for current time. |
| 74 | + * |
| 75 | + * <p><b>Experimental:</b> This method may change or be removed in future releases. |
| 76 | + * |
| 77 | + * @param clockSupplier The clock supplier to use. |
| 78 | + * @return this instance for chaining |
| 79 | + */ |
| 80 | + public RefreshableTokenSource withClockSupplier(ClockSupplier clockSupplier) { |
| 81 | + this.clockSupplier = clockSupplier; |
| 82 | + return this; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Enable or disable asynchronous token refresh. |
| 87 | + * |
| 88 | + * <p><b>Experimental:</b> This method may change or be removed in future releases. |
| 89 | + * |
| 90 | + * @param enabled true to enable async refresh, false to disable |
| 91 | + * @return this instance for chaining |
| 92 | + */ |
| 93 | + public RefreshableTokenSource withAsyncRefresh(boolean enabled) { |
| 94 | + this.asyncEnabled = enabled; |
| 95 | + return this; |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Set the expiry buffer. If the token's lifetime is less than this buffer, it is considered |
| 100 | + * expired. |
| 101 | + * |
| 102 | + * <p><b>Experimental:</b> This method may change or be removed in future releases. |
| 103 | + * |
| 104 | + * @param buffer the expiry buffer duration |
| 105 | + * @return this instance for chaining |
| 106 | + */ |
| 107 | + public RefreshableTokenSource withExpiryBuffer(Duration buffer) { |
| 108 | + this.expiryBuffer = buffer; |
| 109 | + return this; |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Refresh the OAuth token. Subclasses must implement this to define how the token is refreshed. |
| 114 | + * |
| 115 | + * <p>This method may throw an exception if the token cannot be refreshed. The specific exception |
| 116 | + * type depends on the implementation. |
| 117 | + * |
| 118 | + * @return The newly refreshed Token. |
| 119 | + */ |
| 120 | + protected abstract Token refresh(); |
| 121 | + |
| 122 | + /** |
| 123 | + * Gets the current token, refreshing if necessary. If async refresh is enabled, may return a |
| 124 | + * stale token while a refresh is in progress. |
| 125 | + * |
| 126 | + * <p>This method may throw an exception if the token cannot be refreshed, depending on the |
| 127 | + * implementation of {@link #refresh()}. |
| 128 | + * |
| 129 | + * @return The current valid token |
| 130 | + */ |
| 131 | + public Token getToken() { |
| 132 | + if (asyncEnabled) { |
| 133 | + return getTokenAsync(); |
| 134 | + } |
| 135 | + return getTokenBlocking(); |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Determine the state of the current token (fresh, stale, or expired). |
| 140 | + * |
| 141 | + * @return The token state |
| 142 | + */ |
| 143 | + protected TokenState getTokenState(Token t) { |
| 144 | + if (t == null) { |
| 145 | + return TokenState.EXPIRED; |
| 146 | + } |
| 147 | + Duration lifeTime = Duration.between(Instant.now(clockSupplier.getClock()), t.getExpiry()); |
| 148 | + if (lifeTime.compareTo(expiryBuffer) <= 0) { |
| 149 | + return TokenState.EXPIRED; |
| 150 | + } |
| 151 | + if (lifeTime.compareTo(staleDuration) <= 0) { |
| 152 | + return TokenState.STALE; |
| 153 | + } |
| 154 | + return TokenState.FRESH; |
| 155 | + } |
| 156 | + |
| 157 | + /** |
| 158 | + * Get the current token, blocking to refresh if expired. |
| 159 | + * |
| 160 | + * <p>This method may throw an exception if the token cannot be refreshed, depending on the |
| 161 | + * implementation of {@link #refresh()}. |
| 162 | + * |
| 163 | + * @return The current valid token |
| 164 | + */ |
| 165 | + protected Token getTokenBlocking() { |
| 166 | + // Use double-checked locking to minimize synchronization overhead on reads: |
| 167 | + // 1. Check if the token is expired without locking. |
| 168 | + // 2. If expired, synchronize and check again (another thread may have refreshed it). |
| 169 | + // 3. If still expired, perform the refresh. |
| 170 | + if (getTokenState(token) != TokenState.EXPIRED) { |
| 171 | + return token; |
| 172 | + } |
| 173 | + synchronized (this) { |
| 174 | + if (getTokenState(token) != TokenState.EXPIRED) { |
| 175 | + return token; |
| 176 | + } |
| 177 | + lastRefreshSucceeded = false; |
| 178 | + try { |
| 179 | + token = refresh(); |
| 180 | + } catch (Exception e) { |
| 181 | + logger.error("Failed to refresh token synchronously", e); |
| 182 | + throw e; |
| 183 | + } |
| 184 | + lastRefreshSucceeded = true; |
| 185 | + return token; |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + /** |
| 190 | + * Get the current token, possibly triggering an async refresh if stale. If the token is expired, |
| 191 | + * blocks to refresh. |
| 192 | + * |
| 193 | + * <p>This method may throw an exception if the token cannot be refreshed, depending on the |
| 194 | + * implementation of {@link #refresh()}. |
| 195 | + * |
| 196 | + * @return The current valid or stale token |
| 197 | + */ |
| 198 | + protected Token getTokenAsync() { |
| 199 | + Token currentToken = token; |
| 200 | + |
| 201 | + switch (getTokenState(currentToken)) { |
| 202 | + case FRESH: |
| 203 | + return currentToken; |
| 204 | + case STALE: |
| 205 | + triggerAsyncRefresh(); |
| 206 | + return currentToken; |
| 207 | + case EXPIRED: |
| 208 | + return getTokenBlocking(); |
| 209 | + default: |
| 210 | + throw new IllegalStateException("Invalid token state."); |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + /** |
| 215 | + * Trigger an asynchronous refresh of the token if not already in progress and last refresh |
| 216 | + * succeeded. |
| 217 | + */ |
| 218 | + private synchronized void triggerAsyncRefresh() { |
| 219 | + // Check token state again inside the synchronized block to avoid triggering a refresh if |
| 220 | + // another thread updated the token in the meantime. |
| 221 | + if (!refreshInProgress && lastRefreshSucceeded && getTokenState(token) != TokenState.FRESH) { |
| 222 | + refreshInProgress = true; |
| 223 | + CompletableFuture.runAsync( |
| 224 | + () -> { |
| 225 | + try { |
| 226 | + // Attempt to refresh the token in the background |
| 227 | + Token newToken = refresh(); |
| 228 | + synchronized (this) { |
| 229 | + token = newToken; |
| 230 | + refreshInProgress = false; |
| 231 | + } |
| 232 | + } catch (Exception e) { |
| 233 | + synchronized (this) { |
| 234 | + lastRefreshSucceeded = false; |
| 235 | + refreshInProgress = false; |
| 236 | + logger.error("Asynchronous token refresh failed", e); |
| 237 | + } |
| 238 | + } |
| 239 | + }); |
| 240 | + } |
| 241 | + } |
| 242 | + |
28 | 243 | /** |
29 | 244 | * Helper method implementing OAuth token refresh. |
30 | 245 | * |
| 246 | + * @param hc The HTTP client to use for the request. |
31 | 247 | * @param clientId The client ID to authenticate with. |
32 | 248 | * @param clientSecret The client secret to authenticate with. |
33 | 249 | * @param tokenUrl The authorization URL for fetching tokens. |
34 | 250 | * @param params Additional request parameters. |
35 | 251 | * @param headers Additional headers. |
36 | 252 | * @param position The position of the authentication parameters in the request. |
37 | 253 | * @return The newly fetched Token. |
| 254 | + * @throws DatabricksException if the refresh fails |
| 255 | + * @throws IllegalArgumentException if the OAuth response contains an error |
38 | 256 | */ |
39 | 257 | protected static Token retrieveToken( |
40 | 258 | HttpClient hc, |
@@ -75,13 +293,4 @@ protected static Token retrieveToken( |
75 | 293 | throw new DatabricksException("Failed to refresh credentials: " + e.getMessage(), e); |
76 | 294 | } |
77 | 295 | } |
78 | | - |
79 | | - protected abstract Token refresh(); |
80 | | - |
81 | | - public synchronized Token getToken() { |
82 | | - if (token == null || !token.isValid()) { |
83 | | - token = refresh(); |
84 | | - } |
85 | | - return token; |
86 | | - } |
87 | 296 | } |
0 commit comments