|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package com.azure.core.experimental.credential; |
| 5 | + |
| 6 | +import com.azure.core.credential.AccessToken; |
| 7 | +import com.azure.core.util.logging.ClientLogger; |
| 8 | +import reactor.core.publisher.Flux; |
| 9 | +import reactor.core.publisher.Mono; |
| 10 | +import reactor.core.publisher.MonoProcessor; |
| 11 | +import reactor.core.publisher.Signal; |
| 12 | + |
| 13 | +import java.time.Duration; |
| 14 | +import java.time.OffsetDateTime; |
| 15 | +import java.util.Objects; |
| 16 | +import java.util.concurrent.atomic.AtomicReference; |
| 17 | +import java.util.function.Function; |
| 18 | +import java.util.function.Predicate; |
| 19 | +import java.util.function.Supplier; |
| 20 | + |
| 21 | +/** |
| 22 | + * A token cache that supports caching a token and refreshing it. |
| 23 | + */ |
| 24 | +public class AccessTokenCache { |
| 25 | + // The delay after a refresh to attempt another token refresh |
| 26 | + private static final Duration REFRESH_DELAY = Duration.ofSeconds(30); |
| 27 | + // the offset before token expiry to attempt proactive token refresh |
| 28 | + private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); |
| 29 | + private volatile AccessToken cache; |
| 30 | + private volatile OffsetDateTime nextTokenRefresh = OffsetDateTime.now(); |
| 31 | + private final AtomicReference<MonoProcessor<AccessToken>> wip; |
| 32 | + private final Supplier<Mono<AccessToken>> tokenSupplier; |
| 33 | + private final Predicate<AccessToken> shouldRefresh; |
| 34 | + private final ClientLogger logger = new ClientLogger(AccessTokenCache.class); |
| 35 | + |
| 36 | + /** |
| 37 | + * Creates an instance of AccessTokenCache with default scheme "Bearer". |
| 38 | + * |
| 39 | + * @param tokenSupplier a method to get a new token |
| 40 | + */ |
| 41 | + public AccessTokenCache(Supplier<Mono<AccessToken>> tokenSupplier) { |
| 42 | + Objects.requireNonNull(tokenSupplier, "The token supplier cannot be null"); |
| 43 | + this.wip = new AtomicReference<>(); |
| 44 | + this.tokenSupplier = tokenSupplier; |
| 45 | + this.shouldRefresh = accessToken -> OffsetDateTime.now() |
| 46 | + .isAfter(accessToken.getExpiresAt().minus(REFRESH_OFFSET)); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Asynchronously get a token from either the cache or replenish the cache with a new token. |
| 51 | + * @return a Publisher that emits an AccessToken |
| 52 | + */ |
| 53 | + public Mono<AccessToken> getToken() { |
| 54 | + return getToken(this.tokenSupplier, false); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Asynchronously get a token from either the cache or replenish the cache with a new token. |
| 59 | + * |
| 60 | + * @param tokenSupplier The method to get a new token |
| 61 | + * @param forceRefresh The flag indicating if the cache needs to be skipped and a token needs to be fetched via the |
| 62 | + * credential. |
| 63 | + * @return The Publisher that emits an AccessToken |
| 64 | + */ |
| 65 | + public Mono<AccessToken> getToken(Supplier<Mono<AccessToken>> tokenSupplier, boolean forceRefresh) { |
| 66 | + return Mono.defer(retrieveToken(tokenSupplier, forceRefresh)) |
| 67 | + // Keep resubscribing as long as Mono.defer [token acquisition] emits empty(). |
| 68 | + .repeatWhenEmpty((Flux<Long> longFlux) -> longFlux.concatMap(ignored -> Flux.just(true))); |
| 69 | + } |
| 70 | + |
| 71 | + private Supplier<Mono<? extends AccessToken>> retrieveToken(Supplier<Mono<AccessToken>> tokenSupplier, |
| 72 | + boolean forceRefresh) { |
| 73 | + return () -> { |
| 74 | + try { |
| 75 | + if (wip.compareAndSet(null, MonoProcessor.create())) { |
| 76 | + final MonoProcessor<AccessToken> monoProcessor = wip.get(); |
| 77 | + OffsetDateTime now = OffsetDateTime.now(); |
| 78 | + Mono<AccessToken> tokenRefresh; |
| 79 | + Mono<AccessToken> fallback; |
| 80 | + if (forceRefresh) { |
| 81 | + tokenRefresh = Mono.defer(tokenSupplier); |
| 82 | + fallback = Mono.empty(); |
| 83 | + } else if (cache != null && !shouldRefresh.test(cache)) { |
| 84 | + // fresh cache & no need to refresh |
| 85 | + tokenRefresh = Mono.empty(); |
| 86 | + fallback = Mono.just(cache); |
| 87 | + } else if (cache == null || cache.isExpired()) { |
| 88 | + // no token to use |
| 89 | + if (now.isAfter(nextTokenRefresh)) { |
| 90 | + // refresh immediately |
| 91 | + tokenRefresh = Mono.defer(tokenSupplier); |
| 92 | + } else { |
| 93 | + // wait for timeout, then refresh |
| 94 | + tokenRefresh = Mono.defer(tokenSupplier) |
| 95 | + .delaySubscription(Duration.between(now, nextTokenRefresh)); |
| 96 | + } |
| 97 | + // cache doesn't exist or expired, no fallback |
| 98 | + fallback = Mono.empty(); |
| 99 | + } else { |
| 100 | + // token available, but close to expiry |
| 101 | + if (now.isAfter(nextTokenRefresh)) { |
| 102 | + // refresh immediately |
| 103 | + tokenRefresh = Mono.defer(tokenSupplier); |
| 104 | + } else { |
| 105 | + // still in timeout, do not refresh |
| 106 | + tokenRefresh = Mono.empty(); |
| 107 | + } |
| 108 | + // cache hasn't expired, ignore refresh error this time |
| 109 | + fallback = Mono.just(cache); |
| 110 | + } |
| 111 | + return tokenRefresh |
| 112 | + .materialize() |
| 113 | + .flatMap(processTokenRefreshResult(monoProcessor, now, fallback)) |
| 114 | + .doOnError(monoProcessor::onError) |
| 115 | + .doFinally(ignored -> wip.set(null)); |
| 116 | + } else if (cache != null && !cache.isExpired() && !forceRefresh) { |
| 117 | + // another thread might be refreshing the token proactively, but the current token is still valid |
| 118 | + return Mono.just(cache); |
| 119 | + } else { |
| 120 | + // another thread is definitely refreshing the expired token |
| 121 | + //If this thread, needs to force refresh, then it needs to resubscribe. |
| 122 | + if (forceRefresh) { |
| 123 | + return Mono.empty(); |
| 124 | + } |
| 125 | + MonoProcessor<AccessToken> monoProcessor = wip.get(); |
| 126 | + if (monoProcessor == null) { |
| 127 | + // the refreshing thread has finished |
| 128 | + return Mono.just(cache); |
| 129 | + } else { |
| 130 | + // wait for refreshing thread to finish but defer to updated cache in case just missed onNext() |
| 131 | + return monoProcessor.switchIfEmpty(Mono.defer(() -> Mono.just(cache))); |
| 132 | + } |
| 133 | + } |
| 134 | + } catch (Throwable t) { |
| 135 | + return Mono.error(t); |
| 136 | + } |
| 137 | + }; |
| 138 | + } |
| 139 | + |
| 140 | + private Function<Signal<AccessToken>, Mono<? extends AccessToken>> processTokenRefreshResult( |
| 141 | + MonoProcessor<AccessToken> monoProcessor, OffsetDateTime now, Mono<AccessToken> fallback) { |
| 142 | + return signal -> { |
| 143 | + AccessToken accessToken = signal.get(); |
| 144 | + Throwable error = signal.getThrowable(); |
| 145 | + if (signal.isOnNext() && accessToken != null) { // SUCCESS |
| 146 | + logger.info(refreshLog(cache, now, "Acquired a new access token")); |
| 147 | + cache = accessToken; |
| 148 | + monoProcessor.onNext(accessToken); |
| 149 | + monoProcessor.onComplete(); |
| 150 | + nextTokenRefresh = OffsetDateTime.now().plus(REFRESH_DELAY); |
| 151 | + return Mono.just(accessToken); |
| 152 | + } else if (signal.isOnError() && error != null) { // ERROR |
| 153 | + logger.error(refreshLog(cache, now, "Failed to acquire a new access token")); |
| 154 | + nextTokenRefresh = OffsetDateTime.now().plus(REFRESH_DELAY); |
| 155 | + return fallback.switchIfEmpty(Mono.error(error)); |
| 156 | + } else { // NO REFRESH |
| 157 | + monoProcessor.onComplete(); |
| 158 | + return fallback; |
| 159 | + } |
| 160 | + }; |
| 161 | + } |
| 162 | + |
| 163 | + private static String refreshLog(AccessToken cache, OffsetDateTime now, String log) { |
| 164 | + StringBuilder info = new StringBuilder(log); |
| 165 | + if (cache == null) { |
| 166 | + info.append("."); |
| 167 | + } else { |
| 168 | + Duration tte = Duration.between(now, cache.getExpiresAt()); |
| 169 | + info.append(" at ").append(tte.abs().getSeconds()).append(" seconds ") |
| 170 | + .append(tte.isNegative() ? "after" : "before").append(" expiry. ") |
| 171 | + .append("Retry may be attempted after ").append(REFRESH_DELAY.getSeconds()).append(" seconds."); |
| 172 | + if (!tte.isNegative()) { |
| 173 | + info.append(" The token currently cached will be used."); |
| 174 | + } |
| 175 | + } |
| 176 | + return info.toString(); |
| 177 | + } |
| 178 | +} |
0 commit comments