거래 중 토큰 재발급을 분산락 경로로 통합
- 재발급 결과를 캐시에 반영하지 않아 거래마다 발급되고, synchronized 가 JVM 단위라 클러스터에서 노드 수만큼 중복 발급되던 문제 - SessionManager.reissueOutboundAccessToken 추가 : 분산락 안에서 oldToken 을 비교해 이미 갱신됐으면 그 토큰을 쓰고, 아니면 한 번만 발급 후 캐시에 반영 - 발급 구현체는 호출자가 넘긴 어댑터 속성 기준으로 선택 (기존 의미 유지) - HttpClient5AdapterServiceRest : 응답 기반 재발급도 DB 기반 매니저를 쓰도록 정리 - 아웃바운드 토큰 분산락 키를 전역 상수에서 어댑터그룹별로 변경 - 단위테스트 12건 추가 (경합 상황 포함)
This commit is contained in:
+2
-3
@@ -78,7 +78,6 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
@@ -604,8 +603,8 @@ public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupp
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
// 토큰 재발급. 전송 전 조회(:353)와 같은 DB 기반 매니저를 써야 Ignite 캐시가 갱신된다.
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
|
||||
@@ -602,29 +602,48 @@ public class AccessTokenManagerByDB implements Lifecycle {
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public synchronized AccessTokenVO retryAccessTokenVO(String adapterGroupName, Properties properties,
|
||||
String oldToken) throws Exception {
|
||||
public AccessTokenVO retryAccessTokenVO(String adapterGroupName, Properties properties, String oldToken)
|
||||
throws Exception {
|
||||
|
||||
AccessTokenVO accessToken = getAccessTokenVO(adapterGroupName);
|
||||
|
||||
// 동시 요청이 발생할 경우 synchronized 처리를 했기때문에 토큰을 다시 한번 체크한다.
|
||||
if (accessToken == null || accessToken.isExpired()
|
||||
|| StringUtils.equals(accessToken.getAccessToken(), oldToken)) {
|
||||
|
||||
if (isOAuthCredentialRegistered(adapterGroupName) == false) {
|
||||
throw new Exception(
|
||||
"There is no OAuthCredentialRegistered information, or whether to use it is 'N'.");
|
||||
}
|
||||
String type = properties.getProperty("ADAPTER_TOKEN_ISSUING_CLIENT_TYPE");
|
||||
|
||||
HttpClientAccessTokenServiceByDB service = HttpClientAccessTokenServiceFactoryByDB.createFactory(type);
|
||||
OutboundOAuthCredentialVo outboundOAuthCredentialVo = outboundOAuthCredentialVos.get(adapterGroupName);
|
||||
if (service != null) {
|
||||
accessToken = (AccessTokenVO) service.execute(adapterGroupName, properties,
|
||||
outboundOAuthCredentialVo);
|
||||
}
|
||||
if (isOAuthCredentialRegistered(adapterGroupName) == false) {
|
||||
throw new Exception("There is no OAuthCredentialRegistered information, or whether to use it is 'N'.");
|
||||
}
|
||||
|
||||
return accessToken;
|
||||
String type = properties.getProperty("ADAPTER_TOKEN_ISSUING_CLIENT_TYPE");
|
||||
final HttpClientAccessTokenServiceByDB service = HttpClientAccessTokenServiceFactoryByDB.createFactory(type);
|
||||
|
||||
if (service == null) {
|
||||
logger.warn("Token service not found for type: {} and adapter group: {}", type, adapterGroupName);
|
||||
return getAccessTokenVO(adapterGroupName);
|
||||
}
|
||||
|
||||
final OutboundOAuthCredentialVo outboundOAuthCredentialVo = outboundOAuthCredentialVos.get(adapterGroupName);
|
||||
|
||||
// 클러스터 전역에서 한 번만 발급되도록 분산락 안에서 처리한다. 발급 결과는 캐시에 반영되므로
|
||||
// 뒤따르는 거래는 재발급하지 않는다. 구현체는 호출자가 넘긴 어댑터 속성 기준으로 고른다.
|
||||
return SessionManager.getInstance().reissueOutboundAccessToken(adapterGroupName, oldToken,
|
||||
new Function<AccessTokenVO, AccessTokenVO>() {
|
||||
|
||||
@Override
|
||||
public AccessTokenVO apply(AccessTokenVO currentToken) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
try {
|
||||
logger.info("Reissuing token for adapter group: {}, type: {}", adapterGroupName, type);
|
||||
|
||||
AccessTokenVO issued = (AccessTokenVO) service.execute(adapterGroupName, properties,
|
||||
outboundOAuthCredentialVo);
|
||||
|
||||
recordIssueHistory(adapterGroupName, TokenIssueHistory.TRIGGER_RETRY, type, startTime,
|
||||
issued, null);
|
||||
|
||||
return issued;
|
||||
} catch (Exception e) {
|
||||
recordIssueHistory(adapterGroupName, TokenIssueHistory.TRIGGER_RETRY, type, startTime,
|
||||
null, toFailReason(e));
|
||||
logger.error("Token reissue failed for adapter group: {}", adapterGroupName, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,6 +222,20 @@ public abstract class SessionManager implements Lifecycle {
|
||||
*/
|
||||
public abstract AccessTokenVO peekOutboundAccessToken(String key);
|
||||
|
||||
/**
|
||||
* 사용 중이던 토큰이 거부된 경우 재발급한다.
|
||||
*
|
||||
* 분산락 안에서 캐시의 토큰이 oldToken 과 같은지 확인한 뒤에만 발급하므로, 여러 노드가 동시에
|
||||
* 재발급을 시도해도 실제 발급은 한 번만 일어난다. 발급에 성공하면 캐시에 반영한다.
|
||||
*
|
||||
* @param key 어댑터그룹명
|
||||
* @param oldToken 거부된 accessToken 값
|
||||
* @param tokenSupplier 실제 발급 처리
|
||||
* @return 재발급된 토큰. 다른 노드가 이미 갱신했다면 그 토큰.
|
||||
*/
|
||||
public abstract AccessTokenVO reissueOutboundAccessToken(String key, String oldToken,
|
||||
Function<AccessTokenVO, AccessTokenVO> tokenSupplier);
|
||||
|
||||
public abstract void removeOutboundAccessToken(String key);
|
||||
|
||||
public abstract void clearOutboundAccessToken();
|
||||
|
||||
@@ -956,6 +956,12 @@ public class SessionManagerForEhcache extends SessionManager {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenVO reissueOutboundAccessToken(String key, String oldToken,
|
||||
Function<AccessTokenVO, AccessTokenVO> tokenSupplier) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOutboundAccessToken(String key) {
|
||||
throw new UnsupportedOperationException();
|
||||
|
||||
@@ -72,7 +72,12 @@ import ch.qos.logback.classic.Level;
|
||||
|
||||
public class SessionManagerForIgnite extends SessionManager {
|
||||
|
||||
private static final String DISTRIBUTED_TOKEN_LOCK = "DISTRIBUTED_TOKEN_LOCK";
|
||||
|
||||
/** 아웃바운드 토큰 분산락 대기 시간(초). 스케줄러 경로에서 사용한다. */
|
||||
private static final int TOKEN_LOCK_WAIT_SECONDS = 60;
|
||||
|
||||
/** 거래 중 재발급은 거래 스레드를 잡으므로 스케줄러 경로보다 짧게 기다린다. */
|
||||
private static final int REISSUE_LOCK_WAIT_SECONDS = 10;
|
||||
// evictMaster Instance - single socket 관련
|
||||
private static IgniteCache<String, String> evictMasterCache = null;
|
||||
// Socket Session cache 정보
|
||||
@@ -831,6 +836,65 @@ public class SessionManagerForIgnite extends SessionManager {
|
||||
}
|
||||
return cacheOutBoundAccessToken.get(key);
|
||||
}
|
||||
|
||||
/** 토큰으로 쓸 수 있는 값인지 (빈 토큰은 발급 실패로 본다) */
|
||||
private boolean isUsableToken(AccessTokenVO token) {
|
||||
return token != null && StringUtils.isNotBlank(token.getAccessToken());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenVO reissueOutboundAccessToken(String key, String oldToken,
|
||||
Function<AccessTokenVO, AccessTokenVO> tokenSupplier) {
|
||||
|
||||
AccessTokenVO token = cacheOutBoundAccessToken.get(key);
|
||||
|
||||
// 락을 잡기 전에 먼저 확인한다. 다른 노드가 이미 갱신했으면 그 토큰을 쓴다.
|
||||
if (isUsableToken(token) && !StringUtils.equals(token.getAccessToken(), oldToken)) {
|
||||
return token;
|
||||
}
|
||||
|
||||
// 어댑터그룹별로 락을 잡는다. 거래 스레드에서 호출되므로 대기 시간을 짧게 둔다.
|
||||
Lock lock = cacheOutBoundAccessToken.lock(key);
|
||||
boolean acquired = false;
|
||||
|
||||
try {
|
||||
acquired = lock.tryLock(REISSUE_LOCK_WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
|
||||
if (!acquired) {
|
||||
logger.warn("reissueOutboundAccessToken lock timeout. key=" + key);
|
||||
return token;
|
||||
}
|
||||
|
||||
// 락 획득 사이에 다른 노드가 갱신했을 수 있으므로 다시 확인한다.
|
||||
token = cacheOutBoundAccessToken.get(key);
|
||||
if (isUsableToken(token) && !StringUtils.equals(token.getAccessToken(), oldToken)) {
|
||||
logger.debug("reissueOutboundAccessToken already reissued by another node. key=" + key);
|
||||
return token;
|
||||
}
|
||||
|
||||
AccessTokenVO newToken = tokenSupplier.apply(token);
|
||||
|
||||
if (isUsableToken(newToken)) {
|
||||
cacheOutBoundAccessToken.put(key, newToken);
|
||||
return newToken;
|
||||
}
|
||||
|
||||
logger.warn("reissueOutboundAccessToken got empty token. not cached. key=" + key);
|
||||
return newToken;
|
||||
|
||||
} catch (Throwable e) {
|
||||
logger.error("occuring exception in reissueOutboundAccessToken. key=" + key, e);
|
||||
return token;
|
||||
} finally {
|
||||
try {
|
||||
if (acquired) {
|
||||
lock.unlock();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
logger.error("occuring exception in reissueOutboundAccessToken unlock fail.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putWebSocketTimeout(String key, SessionVO value) {
|
||||
@@ -917,13 +981,14 @@ public class SessionManagerForIgnite extends SessionManager {
|
||||
|
||||
// 2. 만료되었거나 없다면 락 획득 시도
|
||||
if (token == null || token.isExpired()) {
|
||||
Lock lock = cacheOutBoundAccessToken.lock(DISTRIBUTED_TOKEN_LOCK); // Ignite 분산 락
|
||||
// 어댑터그룹별로 락을 잡는다. 전역 락 하나를 쓰면 모든 그룹의 토큰 처리가 직렬화된다.
|
||||
Lock lock = cacheOutBoundAccessToken.lock(key); // Ignite 분산 락
|
||||
|
||||
boolean acquired = false;
|
||||
|
||||
try {
|
||||
logger.debug("calling func getOutboundAccessToken = distributed ignite trylock");
|
||||
acquired = lock.tryLock(60, TimeUnit.SECONDS);
|
||||
acquired = lock.tryLock(TOKEN_LOCK_WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
|
||||
if ( acquired ) {
|
||||
logger.debug("calling func getOutboundAccessToken = distributed ignite trylock success=>"+acquired);
|
||||
@@ -972,13 +1037,13 @@ public class SessionManagerForIgnite extends SessionManager {
|
||||
@Override
|
||||
public void removeOutboundAccessToken(String key) {
|
||||
|
||||
Lock lock = cacheOutBoundAccessToken.lock(DISTRIBUTED_TOKEN_LOCK); // Ignite 분산 락
|
||||
Lock lock = cacheOutBoundAccessToken.lock(key); // Ignite 분산 락 (어댑터그룹별)
|
||||
|
||||
boolean acquired = false;
|
||||
try {
|
||||
|
||||
logger.debug("calling func removeOutboundAccessToken = distributed ignite trylock");
|
||||
acquired = lock.tryLock(60, TimeUnit.SECONDS);
|
||||
acquired = lock.tryLock(TOKEN_LOCK_WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
|
||||
if( acquired ) {
|
||||
if (logger.isDebug()) {
|
||||
|
||||
Reference in New Issue
Block a user