You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
149 lines
6.1 KiB
149 lines
6.1 KiB
|
3 weeks ago
|
package common.ecommerce.http;
|
||
|
|
|
||
|
2 weeks ago
|
import common.ecommerce.shared.spi.AccessToken;
|
||
|
|
import common.ecommerce.shared.spi.ChannelSecret;
|
||
|
|
import common.ecommerce.shared.spi.LockProvider;
|
||
|
|
import common.ecommerce.shared.spi.TokenStore;
|
||
|
3 weeks ago
|
import org.slf4j.Logger;
|
||
|
|
import org.slf4j.LoggerFactory;
|
||
|
|
|
||
|
|
import java.time.Clock;
|
||
|
|
import java.time.Instant;
|
||
|
|
import java.util.Optional;
|
||
|
|
|
||
|
|
/**
|
||
|
3 weeks ago
|
* 令牌管理模板。对应设计文档 9.1 的五条要求。
|
||
|
3 weeks ago
|
*
|
||
|
|
* <ul>
|
||
|
3 weeks ago
|
* <li><b>按 AccountKey 隔离缓存</b>:缓存键由适配器按账户维度拼出(如
|
||
|
|
* {@code lingxing:{appKey}}),同一账户共用一个 token</li>
|
||
|
|
* <li><b>提前 {@code earlyRefreshSeconds} 续期</b>:见 {@link AccessToken#needsRefresh}</li>
|
||
|
|
* <li><b>刷新用 {@link LockProvider} 防击穿</b>:拿不到锁说明别的实例正在刷新,
|
||
|
|
* 等锁释放后重读缓存;仍无有效 token 才抛 {@code AuthException}</li>
|
||
|
|
* <li><b>刷新失败不返回旧 token</b>:这里不做宽限期兜底,失败直接把异常抛给调用方</li>
|
||
|
|
* <li><b>日志只打印指纹</b>:token 本体不进日志</li>
|
||
|
|
* <li><b>支持人工失效/重授权</b>:{@link #forceRefresh} 先删缓存再重取</li>
|
||
|
3 weeks ago
|
* </ul>
|
||
|
3 weeks ago
|
*
|
||
|
|
* <p>存储与锁都经 SPI 交给宿主(典型 MySQL / Redis),SDK 自身不落任何状态。
|
||
|
|
* 令牌的加密由宿主的 {@link TokenStore} 实现负责。</p>
|
||
|
3 weeks ago
|
*/
|
||
|
|
public abstract class TokenManager {
|
||
|
|
|
||
|
|
private static final Logger LOG = LoggerFactory.getLogger(TokenManager.class);
|
||
|
|
|
||
|
3 weeks ago
|
/** 刷新锁的 TTL:足够覆盖一次令牌请求,又不至于长时间阻塞其它实例。 */
|
||
|
|
private static final long REFRESH_LOCK_TTL_SECONDS = 30L;
|
||
|
|
|
||
|
|
/** 等锁的轮询间隔。 */
|
||
|
|
private static final long WAIT_INTERVAL_MILLIS = 50L;
|
||
|
|
|
||
|
|
/** 拿不到锁时最多等待多久;超过即认为对方卡死。 */
|
||
|
|
private static final long WAIT_TIMEOUT_MILLIS = 5_000L;
|
||
|
|
|
||
|
3 weeks ago
|
/** 测试用构造器可缩短等待,生产固定值。 */
|
||
|
|
private final long waitIntervalMillis;
|
||
|
|
private final long waitTimeoutMillis;
|
||
|
|
|
||
|
3 weeks ago
|
protected final TokenStore tokenStore;
|
||
|
|
protected final LockProvider lockProvider;
|
||
|
|
protected final Clock clock;
|
||
|
|
private final long earlyRefreshSeconds;
|
||
|
|
|
||
|
|
protected TokenManager(TokenStore tokenStore, LockProvider lockProvider, Clock clock, long earlyRefreshSeconds) {
|
||
|
3 weeks ago
|
this(tokenStore, lockProvider, clock, earlyRefreshSeconds, WAIT_INTERVAL_MILLIS, WAIT_TIMEOUT_MILLIS);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 仅供测试缩短等待;生产用上面的构造器。 */
|
||
|
|
protected TokenManager(TokenStore tokenStore, LockProvider lockProvider, Clock clock, long earlyRefreshSeconds,
|
||
|
|
long waitIntervalMillis, long waitTimeoutMillis) {
|
||
|
3 weeks ago
|
this.tokenStore = tokenStore;
|
||
|
|
this.lockProvider = lockProvider;
|
||
|
|
this.clock = clock;
|
||
|
|
this.earlyRefreshSeconds = earlyRefreshSeconds;
|
||
|
3 weeks ago
|
this.waitIntervalMillis = waitIntervalMillis;
|
||
|
|
this.waitTimeoutMillis = waitTimeoutMillis;
|
||
|
3 weeks ago
|
}
|
||
|
|
|
||
|
|
/** 拿到可用的 access token;必要时刷新。 */
|
||
|
|
public AccessToken getOrRefresh(String tokenKey, ChannelSecret secret) {
|
||
|
3 weeks ago
|
AccessToken cached = fresh(tokenKey);
|
||
|
|
if (cached != null) {
|
||
|
|
return cached;
|
||
|
3 weeks ago
|
}
|
||
|
|
|
||
|
3 weeks ago
|
long deadline = System.currentTimeMillis() + waitTimeoutMillis;
|
||
|
3 weeks ago
|
while (true) {
|
||
|
|
Optional<LockProvider.Lock> lock = lockProvider.tryLock("token-refresh:" + tokenKey, REFRESH_LOCK_TTL_SECONDS);
|
||
|
|
if (lock.isPresent()) {
|
||
|
|
try {
|
||
|
|
return refreshUnderLock(tokenKey, secret, cached);
|
||
|
|
} finally {
|
||
|
|
lock.get().close();
|
||
|
|
}
|
||
|
3 weeks ago
|
}
|
||
|
3 weeks ago
|
// 别的实例正在刷新:等它写完再读缓存
|
||
|
3 weeks ago
|
if (!waitQuietly(waitIntervalMillis)) {
|
||
|
3 weeks ago
|
throw authError("interrupted while waiting for token refresh: " + tokenKey);
|
||
|
|
}
|
||
|
|
AccessToken refreshedByPeer = fresh(tokenKey);
|
||
|
|
if (refreshedByPeer != null) {
|
||
|
|
LOG.debug("token for {} refreshed by another instance", tokenKey);
|
||
|
|
return refreshedByPeer;
|
||
|
|
}
|
||
|
|
if (System.currentTimeMillis() >= deadline) {
|
||
|
|
break;
|
||
|
3 weeks ago
|
}
|
||
|
|
}
|
||
|
3 weeks ago
|
throw authError("token refresh in progress for " + tokenKey + ", lock held by another instance");
|
||
|
3 weeks ago
|
}
|
||
|
|
|
||
|
|
/** 401 后作废并强制重取一次。 */
|
||
|
|
public AccessToken forceRefresh(String tokenKey, ChannelSecret secret) {
|
||
|
|
tokenStore.remove(tokenKey);
|
||
|
|
return getOrRefresh(tokenKey, secret);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 由平台实现:向平台换取新令牌。 */
|
||
|
|
protected abstract AccessToken refresh(ChannelSecret secret, AccessToken previous);
|
||
|
3 weeks ago
|
|
||
|
|
// ---------------------------------------------------------------- internals
|
||
|
|
|
||
|
|
private AccessToken refreshUnderLock(String tokenKey, ChannelSecret secret, AccessToken previous) {
|
||
|
|
AccessToken again = fresh(tokenKey);
|
||
|
|
if (again != null) {
|
||
|
|
return again;
|
||
|
|
}
|
||
|
|
AccessToken refreshed = refresh(secret, previous);
|
||
|
|
tokenStore.save(tokenKey, refreshed);
|
||
|
|
LOG.info("token refreshed for {} [{}]", tokenKey, refreshed.fingerprint());
|
||
|
|
return refreshed;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 缓存中仍是有效 token 时返回它,否则 null;不做过期兜底。 */
|
||
|
|
private AccessToken fresh(String tokenKey) {
|
||
|
|
Optional<AccessToken> cached = tokenStore.get(tokenKey);
|
||
|
|
if (cached.isPresent() && !cached.get().needsRefresh(Instant.now(clock), earlyRefreshSeconds)) {
|
||
|
|
return cached.get();
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
3 weeks ago
|
private static boolean waitQuietly(long millis) {
|
||
|
3 weeks ago
|
try {
|
||
|
3 weeks ago
|
Thread.sleep(millis);
|
||
|
3 weeks ago
|
return true;
|
||
|
|
} catch (InterruptedException e) {
|
||
|
|
Thread.currentThread().interrupt();
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
2 weeks ago
|
private static common.ecommerce.shared.error.AuthException authError(String message) {
|
||
|
|
return new common.ecommerce.shared.error.AuthException(
|
||
|
|
common.ecommerce.shared.error.ChannelException.builder()
|
||
|
3 weeks ago
|
.message(message)
|
||
|
|
.operation("token.refresh"));
|
||
|
|
}
|
||
|
3 weeks ago
|
}
|