API 카탈로그 캐시 설정 클래스 및 관련 테스트 추가
- TTL 프로퍼티 가져오기 로직 추가 (0~3600 클램프 처리) - 캐시 테스트 코드 작성: TTL/캐시 비활성화/객체 불변성 확인 - ApiSpec 데이터그룹 정보 검증 로직 포함 - 캐시 TTL 프로퍼티 해석 실패 시 기본값 적용 (120초)
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package com.eactive.apim.portal.apps.apis.service;
|
||||
|
||||
import com.eactive.apim.portal.portalproperty.service.PortalPropertyService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* API 카탈로그 캐시({@link ApiSearchFacadeImpl#loadAllApiData()}) 설정.
|
||||
*
|
||||
* <p>TTL 은 PTL_PROPERTY({@code Portal} / {@code apis.catalog.cache-ttl-seconds})로 조절하며,
|
||||
* 최초 접근 시 기본값(120초)으로 row 가 자동 생성된다. {@code 0} 이면 캐시를 쓰지 않는다.</p>
|
||||
*
|
||||
* <p>카탈로그 조회는 readOnly 트랜잭션 안(예: API Status 조회 서비스)에서도 호출되므로,
|
||||
* 최초 row 생성(INSERT)이 묻히지 않도록 별도 트랜잭션({@code REQUIRES_NEW})에서 읽는다.</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiCatalogCacheSettings {
|
||||
|
||||
public static final String PROPERTY_GROUP = "Portal";
|
||||
|
||||
public static final String KEY_TTL_SECONDS = "apis.catalog.cache-ttl-seconds";
|
||||
|
||||
static final int DEFAULT_TTL_SECONDS = 120;
|
||||
|
||||
private static final int MAX_TTL_SECONDS = 3600;
|
||||
|
||||
private final PortalPropertyService portalPropertyService;
|
||||
|
||||
/**
|
||||
* 캐시 TTL(초). 0~3600 으로 clamp 하며, 값이 비었거나 이상하면 기본 120초.
|
||||
*/
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public int getTtlSeconds() {
|
||||
try {
|
||||
String value = portalPropertyService.getOrCreateProperty(
|
||||
PROPERTY_GROUP, KEY_TTL_SECONDS, String.valueOf(DEFAULT_TTL_SECONDS),
|
||||
"API 카탈로그(API 그룹·스펙 목록) 메모리 캐시 시간(초). OPEN API 목록·상세, API Status 에 적용. 0 = 캐시 안 함 (0~3600)");
|
||||
int seconds = Integer.parseInt(StringUtils.trimToEmpty(value));
|
||||
return Math.max(0, Math.min(MAX_TTL_SECONDS, seconds));
|
||||
} catch (Exception e) {
|
||||
log.warn("API 카탈로그 캐시 TTL 프로퍼티 해석 실패 - 기본값 {}초 사용", DEFAULT_TTL_SECONDS, e);
|
||||
return DEFAULT_TTL_SECONDS;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import com.eactive.apim.portal.apps.apiservice.dto.ApiServiceDTO;
|
||||
import com.eactive.apim.portal.apps.apiservice.service.ApiServiceService;
|
||||
import com.eactive.apim.portal.apps.auth.service.ApiPermissionFilter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -21,14 +22,60 @@ import java.util.stream.Collectors;
|
||||
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiSearchFacadeImpl implements ApiSearchFacade {
|
||||
|
||||
private final ApiService apiService;
|
||||
private final ApiServiceService apiServiceService;
|
||||
private final ApiCatalogCacheSettings cacheSettings;
|
||||
|
||||
/** 카탈로그 캐시. 사용자와 무관한 원본만 담고, 권한 필터는 {@link #searchApis} 가 요청마다 적용한다 */
|
||||
private volatile CachedApiData cachedApiData;
|
||||
|
||||
/**
|
||||
* API 그룹 + 스펙 전체(카탈로그). TTL({@link ApiCatalogCacheSettings}) 동안 메모리에 캐시한다.
|
||||
*
|
||||
* <p>OPEN API 목록·상세와 API Status 가 요청마다 이 조회를 반복하므로(그룹 N+1 포함) 캐시로 묶는다.
|
||||
* 관리자 화면에서 API 그룹·스펙을 바꾸면 최대 TTL 만큼 늦게 반영된다.</p>
|
||||
*
|
||||
* <p>반환 객체는 여러 요청이 공유하므로 호출자는 수정하지 않는다.</p>
|
||||
*/
|
||||
@Override
|
||||
public ApiSearchData loadAllApiData() {
|
||||
CachedApiData current = cachedApiData;
|
||||
if (current != null && current.isFresh(nowMillis())) {
|
||||
return current.getData();
|
||||
}
|
||||
|
||||
// TTL 은 캐시가 만료됐을 때만 읽는다 (프로퍼티 변경은 다음 갱신부터 반영)
|
||||
int ttlSeconds = cacheSettings.getTtlSeconds();
|
||||
if (ttlSeconds <= 0) {
|
||||
cachedApiData = null;
|
||||
return queryAllApiData();
|
||||
}
|
||||
|
||||
synchronized (this) {
|
||||
current = cachedApiData;
|
||||
if (current != null && current.isFresh(nowMillis())) {
|
||||
return current.getData();
|
||||
}
|
||||
long startedAt = nowMillis();
|
||||
ApiSearchData data = queryAllApiData();
|
||||
cachedApiData = new CachedApiData(data, nowMillis() + ttlSeconds * 1000L);
|
||||
log.debug("API 카탈로그 캐시 갱신 - 그룹 {}개, API {}개, {}ms (TTL {}초)",
|
||||
data.getAllServices().size(), data.getApiSpecsById().size(),
|
||||
nowMillis() - startedAt, ttlSeconds);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
long nowMillis() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
|
||||
private ApiSearchData queryAllApiData() {
|
||||
|
||||
List<ApiServiceDTO> allServices = apiServiceService.searchApiGroups(new ApiGroupSearch());
|
||||
|
||||
@@ -57,7 +104,20 @@ public class ApiSearchFacadeImpl implements ApiSearchFacade {
|
||||
}
|
||||
});
|
||||
|
||||
return new ApiSearchData(allServices, apiSpecsById, servicesByApiId);
|
||||
// 소속 그룹 정보는 캐시에 담기 전에 채운다. 캐시된 객체를 요청마다 고치지 않기 위함.
|
||||
// mainIcon(CLOB, base64)은 카드 수만큼 복제하지 않는다. 렌더링은
|
||||
// apiGroupId 기준 /api-services/{id}/icon 스트리밍 엔드포인트를 사용한다.
|
||||
apiSpecsById.values().forEach(api -> {
|
||||
ApiServiceDTO service = servicesByApiId.get(api.getApiId());
|
||||
if (service != null) {
|
||||
api.setApiGroupId(service.getId());
|
||||
api.setApiGroupName(service.getGroupName());
|
||||
}
|
||||
});
|
||||
|
||||
return new ApiSearchData(Collections.unmodifiableList(allServices),
|
||||
Collections.unmodifiableMap(apiSpecsById),
|
||||
Collections.unmodifiableMap(servicesByApiId));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -112,16 +172,6 @@ public class ApiSearchFacadeImpl implements ApiSearchFacade {
|
||||
.map(ApiSpecInfoDto::getApiId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
filteredApis.forEach(api -> {
|
||||
ApiServiceDTO service = apiData.getServicesByApiId().get(api.getApiId());
|
||||
if (service != null) {
|
||||
// mainIcon(CLOB, base64)은 카드 수만큼 복제하지 않는다. 렌더링은
|
||||
// apiGroupId 기준 /api-services/{id}/icon 스트리밍 엔드포인트를 사용한다.
|
||||
api.setApiGroupId(service.getId());
|
||||
api.setApiGroupName(service.getGroupName());
|
||||
}
|
||||
});
|
||||
|
||||
List<ApiServiceDTO> servicesToReturn = apiData.getAllServices().stream()
|
||||
.map(service -> {
|
||||
ApiServiceDTO filteredService = new ApiServiceDTO();
|
||||
@@ -209,4 +259,23 @@ public class ApiSearchFacadeImpl implements ApiSearchFacade {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/** 카탈로그 캐시 항목 (불변) */
|
||||
private static final class CachedApiData {
|
||||
|
||||
private final ApiSearchData data;
|
||||
private final long expiresAtMillis;
|
||||
|
||||
private CachedApiData(ApiSearchData data, long expiresAtMillis) {
|
||||
this.data = data;
|
||||
this.expiresAtMillis = expiresAtMillis;
|
||||
}
|
||||
|
||||
private ApiSearchData getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
private boolean isFresh(long nowMillis) {
|
||||
return nowMillis < expiresAtMillis;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,9 +24,9 @@ spring:
|
||||
restart:
|
||||
enabled: false
|
||||
livereload:
|
||||
enabled: true
|
||||
enabled: false
|
||||
thymeleaf:
|
||||
cache: false
|
||||
cache: true
|
||||
|
||||
app:
|
||||
resource-versioning:
|
||||
|
||||
@@ -27072,6 +27072,36 @@ input[type=checkbox]:checked + .custom-checkbox {
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--as-pill);
|
||||
}
|
||||
.api-status .as-skeleton {
|
||||
display: block;
|
||||
background: var(--as-gray-bg);
|
||||
border-radius: 6px;
|
||||
animation: as-skeleton-pulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.api-status .as-skeleton {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
.api-status .as-skeleton-line {
|
||||
width: 60%;
|
||||
height: 14px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.api-status .as-skeleton-line:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.api-status .as-skeleton-line.is-title {
|
||||
width: 40%;
|
||||
height: 20px;
|
||||
}
|
||||
.api-status .as-skeleton-line.is-short {
|
||||
width: 30%;
|
||||
}
|
||||
.api-status .as-skeleton-bars {
|
||||
flex: 1 1 auto;
|
||||
align-self: stretch;
|
||||
}
|
||||
.api-status .as-empty {
|
||||
color: var(--as-muted);
|
||||
font-size: 14px;
|
||||
@@ -27106,11 +27136,6 @@ input[type=checkbox]:checked + .custom-checkbox {
|
||||
background: var(--as-info-bg);
|
||||
color: var(--as-info);
|
||||
}
|
||||
.api-status .as-api-pills .as-api-pill.is-unlinked {
|
||||
background: #f3f5f8;
|
||||
color: var(--as-muted);
|
||||
cursor: default;
|
||||
}
|
||||
.api-status .as-api-pills .as-api-pill.is-gw {
|
||||
background: #fff;
|
||||
border: 1px dashed var(--as-border-strong);
|
||||
@@ -27894,6 +27919,14 @@ input[type=checkbox]:checked + .custom-checkbox {
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes as-skeleton-pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
.nt-page,
|
||||
.nt-page h1,
|
||||
.nt-page h2,
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -9,9 +9,6 @@
|
||||
const apiDetailBase = page.getAttribute('data-api-detail-base') || '/apis/detail';
|
||||
const noticeDetailBase = page.getAttribute('data-notice-detail-base') || '/portalnotice/detail';
|
||||
|
||||
/** 오픈 API 목록에 노출되는 API (링크 가능 대상) */
|
||||
const linkableApiIds = new Set();
|
||||
|
||||
const KIND_LABEL = { INCIDENT: '장애', DELAY: '지연', MAINTENANCE: '점검' };
|
||||
const KIND_CLASS = { INCIDENT: 'is-incident', DELAY: 'is-degraded', MAINTENANCE: 'is-maintenance' };
|
||||
const PAGE_SIZE = 10;
|
||||
@@ -186,9 +183,6 @@
|
||||
|
||||
const pills = (apis || []).map(function (api) {
|
||||
const text = escapeHtml(api.apiName || api.apiId);
|
||||
if (!linkableApiIds.has(api.apiId)) {
|
||||
return '<span class="as-api-pill is-unlinked">' + text + '</span>';
|
||||
}
|
||||
return '<a class="as-api-pill" href="' + apiDetailBase + '?id=' + encodeURIComponent(api.apiId) + '">'
|
||||
+ text + '</a>';
|
||||
}).join('');
|
||||
@@ -290,7 +284,15 @@
|
||||
});
|
||||
}
|
||||
|
||||
/** 목록 로딩 스켈레톤. 조회 결과(또는 에러 메시지)로 innerHTML 을 교체하면서 사라진다 */
|
||||
const LIST_SKELETON_HTML = ('<div class="as-card" aria-hidden="true">'
|
||||
+ '<span class="as-skeleton as-skeleton-line is-title"></span>'
|
||||
+ '<span class="as-skeleton as-skeleton-line"></span>'
|
||||
+ '<span class="as-skeleton as-skeleton-line is-short"></span>'
|
||||
+ '</div>').repeat(2);
|
||||
|
||||
function loadIssues() {
|
||||
listEl.innerHTML = LIST_SKELETON_HTML;
|
||||
const query = buildQuery({
|
||||
date: state.date,
|
||||
apiId: state.apiId,
|
||||
@@ -322,7 +324,6 @@
|
||||
return fetchJson(base + '/apis.json')
|
||||
.then(function (apis) {
|
||||
apiOptions = (apis || []).filter(function (api) { return api.apiId; });
|
||||
apiOptions.forEach(function (api) { linkableApiIds.add(api.apiId); });
|
||||
// URL 로 들어온 apiId 는 옵션(오픈 API 목록)에 없어도 필터를 유지한다.
|
||||
// My APIs(기관 계약 API)처럼 오픈 API 목록 밖의 API 로도 진입하기 때문.
|
||||
renderApiInput();
|
||||
@@ -493,6 +494,8 @@
|
||||
kindSelect.value = state.kind;
|
||||
renderIndexBarSelection();
|
||||
loadIndexBar();
|
||||
// 영향 API 태그의 링크 여부 판단에 오픈 API 목록이 필요하므로 옵션을 먼저 받는다
|
||||
loadApiOptions().then(loadIssues);
|
||||
// 콤보박스 옵션과 이슈 목록은 서로 독립이라 병렬로 받는다.
|
||||
// (영향 API 링크 여부는 서버가 공개 API 만 내려주므로 옵션을 기다릴 필요가 없다)
|
||||
loadApiOptions();
|
||||
loadIssues();
|
||||
})();
|
||||
|
||||
@@ -10,9 +10,6 @@
|
||||
const apiDetailBase = page.getAttribute('data-api-detail-base') || '/apis/detail';
|
||||
const noticeDetailBase = page.getAttribute('data-notice-detail-base') || '/portalnotice/detail';
|
||||
|
||||
/** 오픈 API 목록에 노출되는 API (링크 가능 대상) */
|
||||
const linkableApiIds = new Set();
|
||||
|
||||
const KIND_LABEL = { INCIDENT: '장애', DELAY: '지연', MAINTENANCE: '점검' };
|
||||
const KIND_CLASS = { INCIDENT: 'is-incident', DELAY: 'is-degraded', MAINTENANCE: 'is-maintenance' };
|
||||
|
||||
@@ -99,9 +96,6 @@
|
||||
|
||||
const pills = (apis || []).map(function (api) {
|
||||
const text = escapeHtml(api.apiName || api.apiId);
|
||||
if (!linkableApiIds.has(api.apiId)) {
|
||||
return '<span class="as-api-pill is-unlinked">' + text + '</span>';
|
||||
}
|
||||
return '<a class="as-api-pill" href="' + apiDetailBase + '?id=' + encodeURIComponent(api.apiId) + '">'
|
||||
+ text + '</a>';
|
||||
}).join('');
|
||||
@@ -367,15 +361,9 @@
|
||||
}
|
||||
|
||||
// ---------------- 초기 로딩 ----------------
|
||||
// 영향 API 태그의 링크 여부를 판단해야 하므로 오픈 API 목록을 먼저 받는다
|
||||
fetchJson(base + '/apis.json')
|
||||
.then(function (apis) {
|
||||
(apis || []).forEach(function (api) {
|
||||
if (api.apiId) linkableApiIds.add(api.apiId);
|
||||
});
|
||||
})
|
||||
.catch(function () { /* 실패 시 전부 링크 없이 표시된다 */ })
|
||||
.then(loadSections);
|
||||
// 섹션별 조회는 서로 독립이라 바로 병렬로 시작한다.
|
||||
// (영향 API 링크 여부는 서버가 공개 API 만 내려주므로 apis.json 을 먼저 받을 필요가 없다)
|
||||
loadSections();
|
||||
|
||||
function loadSections() {
|
||||
fetchJson(base + '/active.json')
|
||||
|
||||
@@ -207,6 +207,33 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 로딩 스켈레톤 ----------------
|
||||
// 섹션 컨테이너의 초기 마크업. 렌더 함수가 innerHTML 을 교체하면서 사라진다.
|
||||
.as-skeleton {
|
||||
display: block;
|
||||
background: var(--as-gray-bg);
|
||||
border-radius: 6px;
|
||||
animation: as-skeleton-pulse 1.4s ease-in-out infinite;
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { animation: none; }
|
||||
}
|
||||
|
||||
.as-skeleton-line {
|
||||
width: 60%;
|
||||
height: 14px;
|
||||
margin-top: 12px;
|
||||
|
||||
&:first-child { margin-top: 0; }
|
||||
&.is-title { width: 40%; height: 20px; }
|
||||
&.is-short { width: 30%; }
|
||||
}
|
||||
|
||||
// 90일 막대 자리 (.as-bar-chart 높이를 그대로 채운다)
|
||||
.as-skeleton-bars {
|
||||
flex: 1 1 auto;
|
||||
align-self: stretch;
|
||||
}
|
||||
|
||||
.as-empty {
|
||||
color: var(--as-muted);
|
||||
font-size: 14px;
|
||||
@@ -247,13 +274,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
// 목록에 없는 API — 링크 없음, 채도를 낮춰 구분
|
||||
.as-api-pill.is-unlinked {
|
||||
background: #f3f5f8;
|
||||
color: var(--as-muted);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
// 개발자포탈에 게시되지 않은 GW 인터페이스 묶음 ("GW 인터페이스 3건")
|
||||
.as-api-pill.is-gw {
|
||||
background: #fff;
|
||||
@@ -973,3 +993,9 @@
|
||||
.as-tl-item .as-dot { left: -18px; }
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes as-skeleton-pulse {
|
||||
0%,
|
||||
100% { opacity: 1; }
|
||||
50% { opacity: 0.45; }
|
||||
}
|
||||
|
||||
@@ -28,8 +28,15 @@
|
||||
th:attr="data-window-days=${windowDays},data-base=@{/apistatus},data-api-detail-base=@{/apis/detail},data-notice-detail-base=@{/portalnotice/detail}"
|
||||
th:classappend="${authenticated} ? 'is-authenticated' : ''">
|
||||
|
||||
<!-- 섹션 컨테이너의 초기 마크업은 로딩 스켈레톤이다. api-status.js 가 innerHTML 을 교체하면서 사라진다 -->
|
||||
|
||||
<!-- ❶ 진행 중 장애 -->
|
||||
<div id="activeIncidents"></div>
|
||||
<div id="activeIncidents">
|
||||
<section class="as-card" aria-hidden="true">
|
||||
<span class="as-skeleton as-skeleton-line is-title"></span>
|
||||
<span class="as-skeleton as-skeleton-line is-short"></span>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ❷ 90일 서비스 상태 -->
|
||||
<section class="as-card as-uptime">
|
||||
@@ -41,7 +48,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="as-bar-chart" id="uptimeChart"></div>
|
||||
<div class="as-bar-chart" id="uptimeChart">
|
||||
<span class="as-skeleton as-skeleton-bars" aria-hidden="true"></span>
|
||||
</div>
|
||||
<div class="as-axis">
|
||||
<span id="uptimeFromLabel" th:text="|${windowDays}일 전|">90일 전</span>
|
||||
<span>오늘</span>
|
||||
@@ -62,7 +71,12 @@
|
||||
<span class="as-desc">예정 또는 진행 중인 점검</span>
|
||||
<span class="as-count" id="maintenanceCount"></span>
|
||||
</div>
|
||||
<div class="as-maint-list" id="maintenanceList"></div>
|
||||
<div class="as-maint-list" id="maintenanceList">
|
||||
<div class="as-card" aria-hidden="true">
|
||||
<span class="as-skeleton as-skeleton-line is-title"></span>
|
||||
<span class="as-skeleton as-skeleton-line"></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ❹ My APIs (로그인 사용자) -->
|
||||
@@ -93,7 +107,13 @@
|
||||
<span class="as-desc">종결된 장애·점검 내역</span>
|
||||
<span class="as-count">최근 5건</span>
|
||||
</div>
|
||||
<div class="as-issue-list" id="recentIssueList"></div>
|
||||
<div class="as-issue-list" id="recentIssueList">
|
||||
<div class="as-card" aria-hidden="true" th:each="i : ${#numbers.sequence(1, 2)}">
|
||||
<span class="as-skeleton as-skeleton-line is-title"></span>
|
||||
<span class="as-skeleton as-skeleton-line"></span>
|
||||
<span class="as-skeleton as-skeleton-line is-short"></span>
|
||||
</div>
|
||||
</div>
|
||||
<a class="as-more-link" th:href="@{/apistatus/issues}">전체 이력 보기 →</a>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.eactive.apim.portal.apps.apis.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.eactive.apim.portal.apps.apis.dto.ApiSearchData;
|
||||
import com.eactive.apim.portal.apps.apis.dto.ApiSpecInfoDto;
|
||||
import com.eactive.apim.portal.apps.apiservice.dto.ApiGroupSearch;
|
||||
import com.eactive.apim.portal.apps.apiservice.dto.ApiServiceApiDTO;
|
||||
import com.eactive.apim.portal.apps.apiservice.dto.ApiServiceDTO;
|
||||
import com.eactive.apim.portal.apps.apiservice.service.ApiServiceService;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
/**
|
||||
* API 카탈로그 캐시({@link ApiSearchFacadeImpl#loadAllApiData()}).
|
||||
*
|
||||
* <p>OPEN API 목록·상세와 API Status 가 요청마다 반복하던 그룹 N+1 조회를 TTL 동안 한 번으로 묶는지,
|
||||
* TTL 0 이면 캐시 없이 매번 조회하는지, 캐시된 객체를 요청 처리 중에 고치지 않는지를 검증한다.</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ApiSearchFacadeImplCacheTest {
|
||||
|
||||
@Mock private ApiService apiService;
|
||||
@Mock private ApiServiceService apiServiceService;
|
||||
@Mock private ApiCatalogCacheSettings cacheSettings;
|
||||
|
||||
private ApiSearchFacadeImpl facade;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
facade = spy(new ApiSearchFacadeImpl(apiService, apiServiceService, cacheSettings));
|
||||
when(apiServiceService.searchApiGroups(any(ApiGroupSearch.class)))
|
||||
.thenAnswer(invocation -> Collections.singletonList(group("G1", "결제", "API1")));
|
||||
when(apiService.findApisForApiIds(anyList()))
|
||||
.thenAnswer(invocation -> Collections.singletonList(spec("API1", "결제 승인")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadAllApiData_withinTtl_queriesOnceAndReturnsSameSnapshot() {
|
||||
when(cacheSettings.getTtlSeconds()).thenReturn(120);
|
||||
|
||||
ApiSearchData first = facade.loadAllApiData();
|
||||
ApiSearchData second = facade.loadAllApiData();
|
||||
|
||||
assertSame(first, second);
|
||||
verify(apiServiceService, times(1)).searchApiGroups(any(ApiGroupSearch.class));
|
||||
verify(apiService, times(1)).findApisForApiIds(anyList());
|
||||
// TTL 은 캐시가 비었거나 만료됐을 때만 읽는다
|
||||
verify(cacheSettings, times(1)).getTtlSeconds();
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadAllApiData_afterTtl_reloads() {
|
||||
when(cacheSettings.getTtlSeconds()).thenReturn(120);
|
||||
doReturn(1_000_000L).when(facade).nowMillis();
|
||||
ApiSearchData first = facade.loadAllApiData();
|
||||
|
||||
doReturn(1_000_000L + 119_999L).when(facade).nowMillis();
|
||||
assertSame(first, facade.loadAllApiData());
|
||||
|
||||
doReturn(1_000_000L + 120_000L).when(facade).nowMillis();
|
||||
ApiSearchData reloaded = facade.loadAllApiData();
|
||||
|
||||
assertEquals("API1", reloaded.getApiSpecsById().get("API1").getApiId());
|
||||
verify(apiServiceService, times(2)).searchApiGroups(any(ApiGroupSearch.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadAllApiData_ttlZero_disablesCache() {
|
||||
when(cacheSettings.getTtlSeconds()).thenReturn(0);
|
||||
|
||||
facade.loadAllApiData();
|
||||
facade.loadAllApiData();
|
||||
|
||||
verify(apiServiceService, times(2)).searchApiGroups(any(ApiGroupSearch.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadAllApiData_fillsGroupInfoBeforeCaching_andIsReadOnly() {
|
||||
when(cacheSettings.getTtlSeconds()).thenReturn(120);
|
||||
|
||||
ApiSearchData data = facade.loadAllApiData();
|
||||
|
||||
ApiSpecInfoDto api = data.getApiSpecsById().get("API1");
|
||||
assertEquals("G1", api.getApiGroupId());
|
||||
assertEquals("결제", api.getApiGroupName());
|
||||
assertThrows(UnsupportedOperationException.class, () -> data.getAllServices().clear());
|
||||
assertThrows(UnsupportedOperationException.class, () -> data.getApiSpecsById().clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchApis_usesCachedCatalog_andKeepsGroupInfo() {
|
||||
when(cacheSettings.getTtlSeconds()).thenReturn(120);
|
||||
|
||||
facade.searchApis(new ApiGroupSearch());
|
||||
Map<String, Object> result = facade.searchApis(new ApiGroupSearch());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<ApiSpecInfoDto> apis = (List<ApiSpecInfoDto>) result.get("apis");
|
||||
assertEquals(1, apis.size());
|
||||
assertEquals("G1", apis.get(0).getApiGroupId());
|
||||
assertEquals("결제", apis.get(0).getApiGroupName());
|
||||
verify(apiServiceService, times(1)).searchApiGroups(any(ApiGroupSearch.class));
|
||||
}
|
||||
|
||||
private static ApiServiceDTO group(String id, String name, String... apiIds) {
|
||||
ApiServiceDTO group = new ApiServiceDTO();
|
||||
group.setId(id);
|
||||
group.setGroupName(name);
|
||||
group.setDisplayOrder(1);
|
||||
List<ApiServiceApiDTO> apis = new ArrayList<>();
|
||||
for (String apiId : apiIds) {
|
||||
ApiServiceApiDTO api = new ApiServiceApiDTO();
|
||||
api.setApiGroupId(id);
|
||||
api.setApiId(apiId);
|
||||
apis.add(api);
|
||||
}
|
||||
group.setApiGroupApiList(apis);
|
||||
return group;
|
||||
}
|
||||
|
||||
private static ApiSpecInfoDto spec(String apiId, String apiName) {
|
||||
ApiSpecInfoDto spec = new ApiSpecInfoDto();
|
||||
spec.setApiId(apiId);
|
||||
spec.setApiName(apiName);
|
||||
return spec;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user