260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용
This commit is contained in:
@@ -11,226 +11,273 @@ import com.kri.notihub.server.persistence.repository.BizLogRepository;
|
||||
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
|
||||
import com.kri.notihub.server.persistence.repository.SendRepository;
|
||||
import com.kri.notihub.server.service.SmsSendCursorStore;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BizLogResultScheduler {
|
||||
private final SmsSendCursorStore cursorStore;
|
||||
private final SendRepository sendRepository;
|
||||
private final BizLogRepository bizLogRepository;
|
||||
private final BulkSendRepository bulkSendRepository;
|
||||
|
||||
@Scheduled(fixedDelay = 60 * 1_000) // 나중에 증가시킬 것
|
||||
@Transactional(transactionManager = "transactionManager")
|
||||
public void syncSmsResults() {
|
||||
private final SmsSendCursorStore cursorStore;
|
||||
private final SendRepository sendRepository;
|
||||
private final BizLogRepository bizLogRepository;
|
||||
private final BulkSendRepository bulkSendRepository;
|
||||
|
||||
TimeWindow window = buildWindow(1L); // hours는 추후 파라미터화
|
||||
@Scheduled(fixedDelay = 60 * 1_000) // 나중에 증가시킬 것
|
||||
@Transactional(transactionManager = "transactionManager")
|
||||
public void syncSmsResults() {
|
||||
|
||||
List<Short> sendTyList = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
|
||||
TimeWindow window = buildWindow(1L); // hours는 추후 파라미터화
|
||||
|
||||
while (true) {
|
||||
List<TSendEntity> batch = fetchRefreshTargets(sendTyList, window, 1000);
|
||||
if (batch.isEmpty()) return;
|
||||
List<Short> sendTyList = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
|
||||
|
||||
BulkContext bulkCtx = loadBulkContext(batch);
|
||||
while (true) {
|
||||
List<TSendEntity> batch = fetchRefreshTargets(sendTyList, window, 1000);
|
||||
if (batch.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx);
|
||||
BulkContext bulkCtx = loadBulkContext(batch);
|
||||
|
||||
persistChanges(result, bulkCtx);
|
||||
}
|
||||
BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx);
|
||||
|
||||
persistChanges(result, bulkCtx);
|
||||
}
|
||||
}
|
||||
|
||||
private TimeWindow buildWindow(long hours) {
|
||||
LocalDateTime toDt = LocalDateTime.now();
|
||||
return new TimeWindow(toDt.minusHours(hours), toDt);
|
||||
}
|
||||
|
||||
private List<TSendEntity> fetchRefreshTargets(List<Short> sendTyList, TimeWindow window,
|
||||
int size) {
|
||||
return sendRepository.findSendListToRefreshWithinHours(
|
||||
sendTyList,
|
||||
SendStatusType.STANDBY.getCode(),
|
||||
window.from(),
|
||||
window.to(),
|
||||
PageRequest.of(0, size)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* batch에서 bulkKey 수집 + bulk 엔티티 로딩 + Map 인덱싱
|
||||
*/
|
||||
private BulkContext loadBulkContext(List<TSendEntity> batch) {
|
||||
Set<String> bulkKeys = extractBulkKeys(batch);
|
||||
|
||||
if (bulkKeys.isEmpty()) {
|
||||
return new BulkContext(Set.of(), Map.of());
|
||||
}
|
||||
|
||||
private TimeWindow buildWindow(long hours) {
|
||||
LocalDateTime toDt = LocalDateTime.now();
|
||||
return new TimeWindow(toDt.minusHours(hours), toDt);
|
||||
List<TBulkSendEntity> bulkEntities =
|
||||
bulkSendRepository.findByBulkSendKeyIn(new ArrayList<>(bulkKeys));
|
||||
|
||||
Map<String, TBulkSendEntity> bulkMap = bulkEntities.stream()
|
||||
.collect(Collectors.toMap(
|
||||
TBulkSendEntity::getBulkSendKey,
|
||||
Function.identity(),
|
||||
(a, b) -> a
|
||||
));
|
||||
|
||||
return new BulkContext(bulkKeys, bulkMap);
|
||||
}
|
||||
|
||||
private Set<String> extractBulkKeys(List<TSendEntity> batch) {
|
||||
return batch.stream()
|
||||
.map(TSendEntity::getBulkSendKey)
|
||||
.filter(k -> k != null && !k.isBlank())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* BizLog 반영 + send/bulk delta 수집
|
||||
*/
|
||||
private BatchResult applyResultsAndCollectDeltas(List<TSendEntity> batch, BulkContext bulkCtx) {
|
||||
|
||||
Map<String, Integer> successDelta = new HashMap<>();
|
||||
Map<String, Integer> failDelta = new HashMap<>();
|
||||
List<TSendEntity> updatedSends = new ArrayList<>();
|
||||
|
||||
for (TSendEntity s : batch) {
|
||||
if (!isResultPending(s)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Short beforeStatus = s.getSendStatus();
|
||||
|
||||
bizLogRepository.findTopByCmidOrderByReportTimeDesc(s.getCmid()).ifPresent(log -> {
|
||||
applySmsResultFromBizLog(s, log);
|
||||
updatedSends.add(s);
|
||||
|
||||
accumulateBulkDeltaIfNeeded(s, beforeStatus, bulkCtx.bulkMap(), successDelta, failDelta);
|
||||
});
|
||||
}
|
||||
|
||||
private List<TSendEntity> fetchRefreshTargets(List<Short> sendTyList, TimeWindow window, int size) {
|
||||
return sendRepository.findSendListToRefreshWithinHours(
|
||||
sendTyList,
|
||||
SendStatusType.STANDBY.getCode(),
|
||||
window.from(),
|
||||
window.to(),
|
||||
PageRequest.of(0, size)
|
||||
);
|
||||
return new BatchResult(updatedSends, successDelta, failDelta);
|
||||
}
|
||||
|
||||
private boolean isResultPending(TSendEntity s) {
|
||||
if (s == null) {
|
||||
return false;
|
||||
}
|
||||
Short resultCode = s.getResultCode();
|
||||
return resultCode != null
|
||||
&& (resultCode == NotihubConst.SMS_STANDBY || resultCode == NotihubConst.LMS_MMS_STANDBY);
|
||||
}
|
||||
|
||||
/**
|
||||
* STANDBY -> SUCCESS/FAIL 전이일 때만 bulk delta 누적
|
||||
*/
|
||||
private void accumulateBulkDeltaIfNeeded(
|
||||
TSendEntity s,
|
||||
Short beforeStatus,
|
||||
Map<String, TBulkSendEntity> bulkMap,
|
||||
Map<String, Integer> successDelta,
|
||||
Map<String, Integer> failDelta
|
||||
) {
|
||||
String key = s.getBulkSendKey();
|
||||
if (key == null || key.isBlank()) {
|
||||
return;
|
||||
}
|
||||
if (!bulkMap.containsKey(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** batch에서 bulkKey 수집 + bulk 엔티티 로딩 + Map 인덱싱 */
|
||||
private BulkContext loadBulkContext(List<TSendEntity> batch) {
|
||||
Set<String> bulkKeys = extractBulkKeys(batch);
|
||||
|
||||
if (bulkKeys.isEmpty()) {
|
||||
return new BulkContext(Set.of(), Map.of());
|
||||
}
|
||||
|
||||
List<TBulkSendEntity> bulkEntities =
|
||||
bulkSendRepository.findByBulkSendKeyIn(new ArrayList<>(bulkKeys));
|
||||
|
||||
Map<String, TBulkSendEntity> bulkMap = bulkEntities.stream()
|
||||
.collect(Collectors.toMap(
|
||||
TBulkSendEntity::getBulkSendKey,
|
||||
Function.identity(),
|
||||
(a, b) -> a
|
||||
));
|
||||
|
||||
return new BulkContext(bulkKeys, bulkMap);
|
||||
if (!Objects.equals(beforeStatus, SendStatusType.STANDBY.getCode())) {
|
||||
return;
|
||||
}
|
||||
|
||||
private Set<String> extractBulkKeys(List<TSendEntity> batch) {
|
||||
return batch.stream()
|
||||
.map(TSendEntity::getBulkSendKey)
|
||||
.filter(k -> k != null && !k.isBlank())
|
||||
.collect(Collectors.toSet());
|
||||
if (Objects.equals(s.getSendStatus(), SendStatusType.SUCCESS.getCode())) {
|
||||
successDelta.merge(key, 1, Integer::sum);
|
||||
} else if (Objects.equals(s.getSendStatus(), SendStatusType.FAIL.getCode())) {
|
||||
failDelta.merge(key, 1, Integer::sum);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장 + cursor + bulk 카운트 반영
|
||||
*/
|
||||
private void persistChanges(BatchResult result, BulkContext bulkCtx) {
|
||||
|
||||
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
|
||||
if (!result.updatedSends().isEmpty()) {
|
||||
sendRepository.saveAll(result.updatedSends());
|
||||
sendRepository.flush();
|
||||
|
||||
// 마지막 갱신 sendIdx 기록(현재 로직 유지)
|
||||
cursorStore.set(result.updatedSends().get(result.updatedSends().size() - 1).getSendIdx());
|
||||
}
|
||||
|
||||
/** BizLog 반영 + send/bulk delta 수집 */
|
||||
private BatchResult applyResultsAndCollectDeltas(List<TSendEntity> batch, BulkContext bulkCtx) {
|
||||
|
||||
Map<String, Integer> successDelta = new HashMap<>();
|
||||
Map<String, Integer> failDelta = new HashMap<>();
|
||||
List<TSendEntity> updatedSends = new ArrayList<>();
|
||||
|
||||
for (TSendEntity s : batch) {
|
||||
if (!isResultPending(s)) continue;
|
||||
|
||||
Short beforeStatus = s.getSendStatus();
|
||||
|
||||
bizLogRepository.findTopByCmidOrderByReportTimeDesc(s.getCmid()).ifPresent(log -> {
|
||||
applySmsResultFromBizLog(s, log);
|
||||
updatedSends.add(s);
|
||||
|
||||
accumulateBulkDeltaIfNeeded(s, beforeStatus, bulkCtx.bulkMap(), successDelta, failDelta);
|
||||
});
|
||||
}
|
||||
|
||||
return new BatchResult(updatedSends, successDelta, failDelta);
|
||||
if (bulkCtx.bulkMap().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
private boolean isResultPending(TSendEntity s) {
|
||||
if (s == null) return false;
|
||||
Short resultCode = s.getResultCode();
|
||||
return resultCode != null
|
||||
&& (resultCode == NotihubConst.SMS_STANDBY || resultCode == NotihubConst.LMS_MMS_STANDBY);
|
||||
applyBulkCountDeltas(bulkCtx.bulkMap(), result.successDelta(), result.failDelta(), now);
|
||||
|
||||
bulkSendRepository.saveAll(bulkCtx.bulkMap().values());
|
||||
}
|
||||
|
||||
private void applyBulkCountDeltas(
|
||||
Map<String, TBulkSendEntity> bulkMap,
|
||||
Map<String, Integer> successDelta,
|
||||
Map<String, Integer> failDelta,
|
||||
LocalDateTime now
|
||||
) {
|
||||
Set<String> touched = new HashSet<>();
|
||||
|
||||
successDelta.forEach((k, d) -> {
|
||||
TBulkSendEntity e = bulkMap.get(k);
|
||||
if (e != null) {
|
||||
int cur = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt();
|
||||
e.setSuccesCnt(cur + d);
|
||||
touched.add(k);
|
||||
}
|
||||
});
|
||||
|
||||
failDelta.forEach((k, d) -> {
|
||||
TBulkSendEntity e = bulkMap.get(k);
|
||||
if (e != null) {
|
||||
int cur = e.getFailCnt() == null ? 0 : e.getFailCnt();
|
||||
e.setFailCnt(cur + d);
|
||||
touched.add(k);
|
||||
}
|
||||
});
|
||||
|
||||
// 완료 처리: trgt_cnt <= succes_cnt + fail_cnt 되는 순간 complete_dt 세팅
|
||||
for (String k : touched) {
|
||||
TBulkSendEntity e = bulkMap.get(k);
|
||||
if (e == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (e.getCompleteDt() != null) {
|
||||
continue; // 이미 완료면 재세팅 방지
|
||||
}
|
||||
|
||||
int trgt = e.getTrgtCnt() == null ? 0 : e.getTrgtCnt();
|
||||
int success = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt();
|
||||
int fail = e.getFailCnt() == null ? 0 : e.getFailCnt();
|
||||
|
||||
if (trgt <= (success + fail)) {
|
||||
e.setCompleteDt(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** STANDBY -> SUCCESS/FAIL 전이일 때만 bulk delta 누적 */
|
||||
private void accumulateBulkDeltaIfNeeded(
|
||||
TSendEntity s,
|
||||
Short beforeStatus,
|
||||
Map<String, TBulkSendEntity> bulkMap,
|
||||
Map<String, Integer> successDelta,
|
||||
Map<String, Integer> failDelta
|
||||
) {
|
||||
String key = s.getBulkSendKey();
|
||||
if (key == null || key.isBlank()) return;
|
||||
if (!bulkMap.containsKey(key)) return;
|
||||
private void applySmsResultFromBizLog(TSendEntity s, BizLogEntity log) {
|
||||
// ReportDt(LocalDateTime) 반영
|
||||
// BizLogEntity.reportTime 타입이 Date면 LocalDateTime 변환 로직으로 바꾸세요.
|
||||
s.setReportDt(log.getReportTime());
|
||||
|
||||
if (!Objects.equals(beforeStatus, SendStatusType.STANDBY.getCode())) return;
|
||||
short callStatus = safeParseShort(log.getCallStatus(), NotihubConst.SMS_NOT_RESULT);
|
||||
|
||||
if (Objects.equals(s.getSendStatus(), SendStatusType.SUCCESS.getCode())) {
|
||||
successDelta.merge(key, 1, Integer::sum);
|
||||
} else if (Objects.equals(s.getSendStatus(), SendStatusType.FAIL.getCode())) {
|
||||
failDelta.merge(key, 1, Integer::sum);
|
||||
}
|
||||
if (callStatus == NotihubConst.SMS_SUCCESS || callStatus == NotihubConst.LMS_MMS_SUCCESS) {
|
||||
s.setSendStatus(SendStatusType.SUCCESS.getCode());
|
||||
s.setResultCode(callStatus);
|
||||
} else {
|
||||
s.setSendStatus(SendStatusType.FAIL.getCode());
|
||||
s.setResultCode(callStatus); // “그 외 실패”이지만, 실제 코드 보존이 운영/분석에 유리
|
||||
}
|
||||
}
|
||||
|
||||
/** 저장 + cursor + bulk 카운트 반영 */
|
||||
private void persistChanges(BatchResult result, BulkContext bulkCtx) {
|
||||
|
||||
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
|
||||
if (!result.updatedSends().isEmpty()) {
|
||||
sendRepository.saveAll(result.updatedSends());
|
||||
sendRepository.flush();
|
||||
|
||||
// 마지막 갱신 sendIdx 기록(현재 로직 유지)
|
||||
cursorStore.set(result.updatedSends().get(result.updatedSends().size() - 1).getSendIdx());
|
||||
}
|
||||
|
||||
if (bulkCtx.bulkMap().isEmpty()) return;
|
||||
|
||||
applyBulkCountDeltas(bulkCtx.bulkMap(), result.successDelta(), result.failDelta(), now);
|
||||
|
||||
bulkSendRepository.saveAll(bulkCtx.bulkMap().values());
|
||||
private short safeParseShort(String v, short fallback) {
|
||||
if (v == null || v.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private void applyBulkCountDeltas(
|
||||
Map<String, TBulkSendEntity> bulkMap,
|
||||
Map<String, Integer> successDelta,
|
||||
Map<String, Integer> failDelta,
|
||||
LocalDateTime now
|
||||
) {
|
||||
Set<String> touched = new HashSet<>();
|
||||
|
||||
successDelta.forEach((k, d) -> {
|
||||
TBulkSendEntity e = bulkMap.get(k);
|
||||
if (e != null) {
|
||||
int cur = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt();
|
||||
e.setSuccesCnt(cur + d);
|
||||
touched.add(k);
|
||||
}
|
||||
});
|
||||
|
||||
failDelta.forEach((k, d) -> {
|
||||
TBulkSendEntity e = bulkMap.get(k);
|
||||
if (e != null) {
|
||||
int cur = e.getFailCnt() == null ? 0 : e.getFailCnt();
|
||||
e.setFailCnt(cur + d);
|
||||
touched.add(k);
|
||||
}
|
||||
});
|
||||
|
||||
// 완료 처리: trgt_cnt <= succes_cnt + fail_cnt 되는 순간 complete_dt 세팅
|
||||
for (String k : touched) {
|
||||
TBulkSendEntity e = bulkMap.get(k);
|
||||
if (e == null) continue;
|
||||
|
||||
if (e.getCompleteDt() != null) continue; // 이미 완료면 재세팅 방지
|
||||
|
||||
int trgt = e.getTrgtCnt() == null ? 0 : e.getTrgtCnt();
|
||||
int success = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt();
|
||||
int fail = e.getFailCnt() == null ? 0 : e.getFailCnt();
|
||||
|
||||
if (trgt <= (success + fail)) {
|
||||
e.setCompleteDt(now);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return Short.parseShort(v.trim());
|
||||
} catch (Exception e) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private void applySmsResultFromBizLog(TSendEntity s, BizLogEntity log) {
|
||||
// ReportDt(LocalDateTime) 반영
|
||||
// BizLogEntity.reportTime 타입이 Date면 LocalDateTime 변환 로직으로 바꾸세요.
|
||||
s.setReportDt(log.getReportTime());
|
||||
private record TimeWindow(LocalDateTime from, LocalDateTime to) {
|
||||
|
||||
short callStatus = safeParseShort(log.getCallStatus(), NotihubConst.SMS_NOT_RESULT);
|
||||
}
|
||||
|
||||
if (callStatus == NotihubConst.SMS_SUCCESS || callStatus == NotihubConst.LMS_MMS_SUCCESS) {
|
||||
s.setSendStatus(SendStatusType.SUCCESS.getCode());
|
||||
s.setResultCode(callStatus);
|
||||
} else {
|
||||
s.setSendStatus(SendStatusType.FAIL.getCode());
|
||||
s.setResultCode(callStatus); // “그 외 실패”이지만, 실제 코드 보존이 운영/분석에 유리
|
||||
}
|
||||
}
|
||||
private record BulkContext(Set<String> bulkKeys, Map<String, TBulkSendEntity> bulkMap) {
|
||||
|
||||
private short safeParseShort(String v, short fallback) {
|
||||
if (v == null || v.isBlank()) return fallback;
|
||||
try { return Short.parseShort(v.trim()); } catch (Exception e) { return fallback; }
|
||||
}
|
||||
}
|
||||
|
||||
private record TimeWindow(LocalDateTime from, LocalDateTime to) {}
|
||||
private record BulkContext(Set<String> bulkKeys, Map<String, TBulkSendEntity> bulkMap) {}
|
||||
private record BatchResult(List<TSendEntity> updatedSends,
|
||||
Map<String, Integer> successDelta,
|
||||
Map<String, Integer> failDelta) {}
|
||||
private record BatchResult(List<TSendEntity> updatedSends,
|
||||
Map<String, Integer> successDelta,
|
||||
Map<String, Integer> failDelta) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user