diff --git a/http/src/main/java/common/ecommerce/http/TokenManager.java b/http/src/main/java/common/ecommerce/http/TokenManager.java
index ac92ac8..a9b4999 100644
--- a/http/src/main/java/common/ecommerce/http/TokenManager.java
+++ b/http/src/main/java/common/ecommerce/http/TokenManager.java
@@ -12,20 +12,35 @@ import java.time.Instant;
import java.util.Optional;
/**
- * 令牌管理模板。
+ * 令牌管理模板。对应设计文档 9.1 的五条要求。
*
*
- * - 按账户隔离缓存
- * - 提前 {@code earlyRefreshSeconds} 续期
- * - 刷新用 {@link LockProvider} 防击穿
- * - 刷新失败不返回旧 token(除显式宽限窗口)
- * - 日志只打印指纹
+ * - 按 AccountKey 隔离缓存:缓存键由适配器按账户维度拼出(如
+ * {@code lingxing:{appKey}}),同一账户共用一个 token
+ * - 提前 {@code earlyRefreshSeconds} 续期:见 {@link AccessToken#needsRefresh}
+ * - 刷新用 {@link LockProvider} 防击穿:拿不到锁说明别的实例正在刷新,
+ * 等锁释放后重读缓存;仍无有效 token 才抛 {@code AuthException}
+ * - 刷新失败不返回旧 token:这里不做宽限期兜底,失败直接把异常抛给调用方
+ * - 日志只打印指纹:token 本体不进日志
+ * - 支持人工失效/重授权:{@link #forceRefresh} 先删缓存再重取
*
+ *
+ * 存储与锁都经 SPI 交给宿主(典型 MySQL / Redis),SDK 自身不落任何状态。
+ * 令牌的加密由宿主的 {@link TokenStore} 实现负责。
*/
public abstract class TokenManager {
private static final Logger LOG = LoggerFactory.getLogger(TokenManager.class);
+ /** 刷新锁的 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;
+
protected final TokenStore tokenStore;
protected final LockProvider lockProvider;
protected final Clock clock;
@@ -40,38 +55,35 @@ public abstract class TokenManager {
/** 拿到可用的 access token;必要时刷新。 */
public AccessToken getOrRefresh(String tokenKey, ChannelSecret secret) {
- Instant now = Instant.now(clock);
- Optional cached = tokenStore.get(tokenKey);
- if (cached.isPresent() && !cached.get().needsRefresh(now, earlyRefreshSeconds)) {
- return cached.get();
+ AccessToken cached = fresh(tokenKey);
+ if (cached != null) {
+ return cached;
}
- Optional lock = lockProvider.tryLock("token-refresh:" + tokenKey, 30);
- if (!lock.isPresent()) {
- // 别的线程在刷新:再读一次,读不到就短等待后重读
- Optional again = tokenStore.get(tokenKey);
- if (again.isPresent() && !again.get().needsRefresh(now, earlyRefreshSeconds)) {
- return again.get();
+ long deadline = System.currentTimeMillis() + WAIT_TIMEOUT_MILLIS;
+ while (true) {
+ Optional lock = lockProvider.tryLock("token-refresh:" + tokenKey, REFRESH_LOCK_TTL_SECONDS);
+ if (lock.isPresent()) {
+ try {
+ return refreshUnderLock(tokenKey, secret, cached);
+ } finally {
+ lock.get().close();
+ }
}
- throw new common.ecommerce.error.AuthException(
- common.ecommerce.error.ChannelException.builder()
- .message("token refresh in progress for " + tokenKey)
- .operation("token.refresh"));
- }
-
- try {
- Optional again = tokenStore.get(tokenKey);
- Instant nowInLock = Instant.now(clock);
- if (again.isPresent() && !again.get().needsRefresh(nowInLock, earlyRefreshSeconds)) {
- return again.get();
+ // 别的实例正在刷新:等它写完再读缓存
+ if (!waitQuietly()) {
+ 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;
}
- AccessToken refreshed = refresh(secret, cached.orElse(null));
- tokenStore.save(tokenKey, refreshed);
- LOG.info("token refreshed for {} [{}]", tokenKey, refreshed.fingerprint());
- return refreshed;
- } finally {
- lock.get().close();
}
+ throw authError("token refresh in progress for " + tokenKey + ", lock held by another instance");
}
/** 401 后作废并强制重取一次。 */
@@ -82,4 +94,43 @@ public abstract class TokenManager {
/** 由平台实现:向平台换取新令牌。 */
protected abstract AccessToken refresh(ChannelSecret secret, AccessToken previous);
+
+ // ---------------------------------------------------------------- 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 cached = tokenStore.get(tokenKey);
+ if (cached.isPresent() && !cached.get().needsRefresh(Instant.now(clock), earlyRefreshSeconds)) {
+ return cached.get();
+ }
+ return null;
+ }
+
+ private static boolean waitQuietly() {
+ try {
+ Thread.sleep(WAIT_INTERVAL_MILLIS);
+ return true;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ }
+ }
+
+ private static common.ecommerce.error.AuthException authError(String message) {
+ return new common.ecommerce.error.AuthException(
+ common.ecommerce.error.ChannelException.builder()
+ .message(message)
+ .operation("token.refresh"));
+ }
}
diff --git a/http/src/test/java/common/ecommerce/http/TokenManagerTest.java b/http/src/test/java/common/ecommerce/http/TokenManagerTest.java
new file mode 100644
index 0000000..ca6667d
--- /dev/null
+++ b/http/src/test/java/common/ecommerce/http/TokenManagerTest.java
@@ -0,0 +1,186 @@
+package common.ecommerce.http;
+
+import common.ecommerce.error.AuthException;
+import common.ecommerce.spi.AccessToken;
+import common.ecommerce.spi.ChannelSecret;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * TokenManager 对应设计文档 9.1 的五条要求。
+ */
+class TokenManagerTest {
+
+ private static final Instant T0 = Instant.parse("2026-10-30T00:00:00Z");
+ private static final ChannelSecret SECRET = ChannelSecret.builder()
+ .appKey("ak").appSecret("sk").build();
+
+ private LocalClock clock;
+ private LocalTokenStore tokenStore;
+ private LocalLockProvider locks;
+ private AtomicInteger refreshes;
+ private TokenManager manager;
+
+ @BeforeEach
+ void setUp() {
+ clock = new LocalClock(T0);
+ tokenStore = new LocalTokenStore();
+ locks = new LocalLockProvider();
+ refreshes = new AtomicInteger();
+ manager = new TokenManager(tokenStore, locks, clock, 600) {
+ @Override
+ protected AccessToken refresh(ChannelSecret secret, AccessToken previous) {
+ int n = refreshes.incrementAndGet();
+ return AccessToken.builder()
+ .value("token-" + n)
+ .expiresAt(Instant.now(clock).plusSeconds(7200))
+ .build();
+ }
+ };
+ }
+
+ @Test
+ void cachesPerTokenKey() {
+ AccessToken a = manager.getOrRefresh("lingxing:ak", SECRET);
+ AccessToken b = manager.getOrRefresh("lingxing:ak", SECRET);
+
+ assertEquals("token-1", a.value());
+ assertEquals("token-1", b.value());
+ assertEquals(1, refreshes.get(), "second call must hit cache");
+ assertEquals(1, locks.acquireCount("token-refresh:lingxing:ak"));
+ }
+
+ @Test
+ void differentTokenKeysDoNotShareCache() {
+ manager.getOrRefresh("lingxing:ak", SECRET);
+ manager.getOrRefresh("lingxing:ak-2", SECRET);
+
+ assertEquals(2, refreshes.get());
+ }
+
+ @Test
+ void refreshesBeforeExpiry() {
+ manager.getOrRefresh("k", SECRET); // 7200s 有效期
+ clock.advance(Duration.ofSeconds(7200 - 600)); // 进入提前续期窗口
+ AccessToken second = manager.getOrRefresh("k", SECRET);
+
+ assertEquals(2, refreshes.get());
+ assertEquals("token-2", second.value());
+ }
+
+ @Test
+ void validTokenNotRefreshedBeforeWindow() {
+ manager.getOrRefresh("k", SECRET);
+ clock.advance(Duration.ofSeconds(7200 - 601));
+ manager.getOrRefresh("k", SECRET);
+
+ assertEquals(1, refreshes.get());
+ }
+
+ @Test
+ void forceRefreshDropsCacheAndReFetches() {
+ manager.getOrRefresh("k", SECRET);
+ AccessToken forced = manager.forceRefresh("k", SECRET);
+
+ assertEquals(2, refreshes.get());
+ assertEquals("token-2", forced.value());
+ assertEquals("token-2", tokenStore.get("k").get().value());
+ }
+
+ @Test
+ void refreshFailurePropagatesAndKeepsNoStaleToken() {
+ TokenManager failing = new TokenManager(tokenStore, locks, clock, 600) {
+ @Override
+ protected AccessToken refresh(ChannelSecret secret, AccessToken previous) {
+ throw new AuthException(common.ecommerce.error.ChannelException.builder()
+ .message("app not exist").operation("token.refresh"));
+ }
+ };
+
+ assertThrows(AuthException.class, () -> failing.getOrRefresh("k", SECRET));
+ assertTrue(!tokenStore.get("k").isPresent(), "no token should be written on failure");
+ }
+
+ @Test
+ void lockHeldByAnotherInstanceIsNotBrokenThrough() {
+ // 模拟另一个实例正在刷新:锁被占,缓存里也没有有效 token
+ locks.tryLock("token-refresh:k", 30);
+ TokenManager quick = new TokenManager(tokenStore, locks, clock, 600) {
+ @Override
+ protected AccessToken refresh(ChannelSecret secret, AccessToken previous) {
+ throw new IllegalStateException("must not be called");
+ }
+ };
+
+ AuthException ex = assertThrows(AuthException.class, () -> quick.getOrRefresh("k", SECRET));
+ assertTrue(ex.getMessage().contains("token refresh in progress"), ex.getMessage());
+ assertEquals(0, refreshes.get());
+ }
+
+ @Test
+ void logOnlyPrintsFingerprint() {
+ AccessToken token = AccessToken.builder()
+ .value("super-secret-token-value")
+ .expiresAt(T0.plusSeconds(3600))
+ .build();
+
+ assertTrue(token.fingerprint().startsWith("token#"));
+ assertTrue(!token.fingerprint().contains("super-secret"), token.fingerprint());
+ }
+
+ // ---------------------------------------------------------------- 本地替身
+ // http 模块不能依赖 testkit(testkit 依赖 http,会成环),这里放最小实现。
+
+ static final class LocalClock extends java.time.Clock {
+ private Instant now;
+
+ LocalClock(Instant now) {
+ this.now = now;
+ }
+
+ @Override public java.time.ZoneId getZone() { return java.time.ZoneOffset.UTC; }
+ @Override public java.time.Clock withZone(java.time.ZoneId zone) { return this; }
+ @Override public Instant instant() { return now; }
+
+ void advance(Duration d) { now = now.plus(d); }
+ }
+
+ static final class LocalTokenStore implements common.ecommerce.spi.TokenStore {
+ private final java.util.Map tokens = new java.util.HashMap();
+
+ @Override public java.util.Optional get(String key) {
+ return java.util.Optional.ofNullable(tokens.get(key));
+ }
+ @Override public void save(String key, AccessToken token) { tokens.put(key, token); }
+ @Override public void remove(String key) { tokens.remove(key); }
+ }
+
+ static final class LocalLockProvider implements common.ecommerce.spi.LockProvider {
+ private final java.util.Set held = new java.util.HashSet();
+ private final java.util.Map counts = new java.util.HashMap();
+
+ @Override public synchronized java.util.Optional tryLock(String key, long ttlSeconds) {
+ if (!held.add(key)) {
+ return java.util.Optional.empty();
+ }
+ Integer c = counts.get(key);
+ counts.put(key, c == null ? 1 : c + 1);
+ return java.util.Optional.of(() -> {
+ synchronized (LocalLockProvider.this) { held.remove(key); }
+ });
+ }
+
+ synchronized int acquireCount(String key) {
+ Integer c = counts.get(key);
+ return c == null ? 0 : c;
+ }
+ }
+}
diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java
index 8a137ff..56a55a6 100644
--- a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java
+++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java
@@ -203,7 +203,7 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab
private HttpRequest signedPost(ChannelContext ctx, String path, String body, String operation) {
ChannelAccount account = ctx.account();
ChannelSecret secret = secretProvider.get(account.credentialRef());
- AccessToken token = tokenManager.getOrRefresh(tokenKey(account), secret);
+ AccessToken token = tokenManager.getOrRefresh(tokenKey(account, secret), secret);
Map common = new LinkedHashMap();
common.put("app_key", secret.appKey());
@@ -226,8 +226,13 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab
.build();
}
- private static String tokenKey(ChannelAccount account) {
- return "lingxing:" + account.externalStoreId();
+ /**
+ * 令牌缓存维度:领星 token 按 app 发放(appId + appSecret 换),
+ * 同一 app 下的多家店铺共用一个 token。用 appKey 而不是 store_id,
+ * 避免同 app 多店铺重复换 token 白烧配额。
+ */
+ private static String tokenKey(ChannelAccount account, ChannelSecret secret) {
+ return "lingxing:" + secret.appKey();
}
private static String urlEncode(String v) {
diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java
index 3cbc3f8..a8c2d24 100644
--- a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java
+++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java
@@ -109,8 +109,8 @@ class LingxingAdapterTest {
adapter.pull(ctx, q);
assertEquals(1, tokenStore.saveCount(), "token should be refreshed only once");
- assertEquals(1, locks.acquireCount("token-refresh:lingxing:1108413237731"));
- assertNotNull(tokenStore.get("lingxing:1108413237731").orElse(null));
+ assertEquals(1, locks.acquireCount("token-refresh:lingxing:test-app-key"));
+ assertNotNull(tokenStore.get("lingxing:test-app-key").orElse(null));
}
@Test