diff --git a/src/main/java/com/kri/notihub/server/common/consts/NotihubConst.java b/src/main/java/com/kri/notihub/server/common/consts/NotihubConst.java index 620430b..cc52f4d 100644 --- a/src/main/java/com/kri/notihub/server/common/consts/NotihubConst.java +++ b/src/main/java/com/kri/notihub/server/common/consts/NotihubConst.java @@ -19,7 +19,8 @@ public final class NotihubConst { public static final List KKO_TYPE_CODE_LIST = List.of(SendType.KKO_AT.getCode()); public static final List EMAIL_TYPE_CODE_LIST = List.of(SendType.EMAIL.getCode()); public static final String EMAIL_RESERVATION_PREFIX = "RESERVATION_"; - public static final short EMAIL_STANDBY = 100; + public static final short EMAIL_STANDBY = 100; // 발송 전 대기 + public static final short EMAIL_SENDING = 101; // worker 점유/발송 시도 중 public static final short EMAIL_PENDING = (short) 111; // 발송요청은 성공했으나 json_return 미조회 public static final short EMAIL_SEND_FAIL = (short) 109; // 발송요청 실패(또는 return_key 미수신) public static final short EMAIL_NOT_RESULT = (short) 119; // json_return 조회 실패/결과없음(최종상태 확보 실패) diff --git a/src/main/java/com/kri/notihub/server/persistence/repository/SendRepository.java b/src/main/java/com/kri/notihub/server/persistence/repository/SendRepository.java index 3d4c7bf..d505ea8 100644 --- a/src/main/java/com/kri/notihub/server/persistence/repository/SendRepository.java +++ b/src/main/java/com/kri/notihub/server/persistence/repository/SendRepository.java @@ -8,8 +8,10 @@ import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; public interface SendRepository extends JpaRepository { @@ -55,6 +57,55 @@ public interface SendRepository extends JpaRepository { Pageable pageable ); + @Query(""" + select s + from TSendEntity s + where s.sendTy = :sendTy + and s.resultCode = :resultCode + and s.resve = false + and s.bulkSendKey is not null + and s.sendDt <= :now + order by s.sendIdx asc + """) + List findBulkStandbySendEmail( + short sendTy, + short resultCode, + LocalDateTime now, + Pageable pageable + ); + + @Transactional + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(""" + update TSendEntity s + set s.resultCode = :sendingResultCode + where s.sendIdx = :sendIdx + and s.resultCode = :standbyResultCode + """) + int markEmailSending( + Long sendIdx, + short standbyResultCode, + short sendingResultCode + ); + + @Transactional + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(""" + update TSendEntity s + set s.resultCode = :standbyResultCode + where s.sendTy = :sendTy + and s.resultCode = :sendingResultCode + and s.resve = false + and s.bulkSendKey is not null + and s.sendDt <= :staleBefore + """) + int recoverStaleBulkEmailSending( + short sendTy, + short sendingResultCode, + short standbyResultCode, + LocalDateTime staleBefore + ); + /** * Poller 복구용: STANDBY_EMAIL 상태로 남아있는 최근 발송건을 다시 enqueue 하기 위해 사용 */ diff --git a/src/main/java/com/kri/notihub/server/scheduler/EmailBulkSendScheduler.java b/src/main/java/com/kri/notihub/server/scheduler/EmailBulkSendScheduler.java new file mode 100644 index 0000000..69434ec --- /dev/null +++ b/src/main/java/com/kri/notihub/server/scheduler/EmailBulkSendScheduler.java @@ -0,0 +1,150 @@ +package com.kri.notihub.server.scheduler; + +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.notihub.server.common.consts.NotihubConst; +import com.kri.notihub.server.common.enums.SendStatusType; +import com.kri.notihub.server.common.enums.SendType; +import com.kri.notihub.server.common.external.pringo.dto.PringoJsonSendRequestDto; +import com.kri.notihub.server.dto.send.DestInfoDto; +import com.kri.notihub.server.dto.send.SendInternalResultDto; +import com.kri.notihub.server.persistence.entity.TBulkSendEntity; +import com.kri.notihub.server.persistence.entity.TSendEntity; +import com.kri.notihub.server.persistence.repository.BulkSendRepository; +import com.kri.notihub.server.persistence.repository.SendRepository; +import com.kri.notihub.server.service.SendEmailService; +import java.time.LocalDateTime; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.PageRequest; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class EmailBulkSendScheduler { + + private final SendEmailService sendEmailService; + private final SendRepository sendRepository; + private final BulkSendRepository bulkSendRepository; + + @Value("${kri.email.bulk-send.batch-size:500}") + private int batchSize; + + @Value("${kri.email.bulk-send.sending-stale-minutes:30}") + private long sendingStaleMinutes; + + @Scheduled(fixedDelayString = "${kri.email.bulk-send.fixed-delay-ms:10000}") + public void sendBulkEmail() { + recoverStaleSending(); + + LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); + List standbyList = sendRepository.findBulkStandbySendEmail( + SendType.EMAIL.getCode(), + NotihubConst.EMAIL_STANDBY, + now, + PageRequest.of(0, Math.max(1, batchSize)) + ); + + for (TSendEntity send : standbyList) { + if (!tryMarkSending(send)) { + continue; + } + + SendInternalResultDto sendResult = sendEmail(send); + applySendResult(send, sendResult); + sendRepository.save(send); + + if (sendResult.getStatus() == SendStatusType.FAIL) { + increaseBulkFailCount(send.getBulkSendKey(), now); + } else { + sendEmailService.afterPersistSendEntities(List.of(send)); + } + + sleepSilently(NotihubConst.EMAIL_DELAY); + } + } + + private void recoverStaleSending() { + LocalDateTime staleBefore = DateTimeUtil.nowKstLocalDateTime() + .minusMinutes(Math.max(1, sendingStaleMinutes)); + sendRepository.recoverStaleBulkEmailSending( + SendType.EMAIL.getCode(), + NotihubConst.EMAIL_SENDING, + NotihubConst.EMAIL_STANDBY, + staleBefore + ); + } + + private boolean tryMarkSending(TSendEntity send) { + if (send == null || send.getSendIdx() == null) { + return false; + } + + int updated = sendRepository.markEmailSending( + send.getSendIdx(), + NotihubConst.EMAIL_STANDBY, + NotihubConst.EMAIL_SENDING + ); + if (updated != 1) { + return false; + } + + send.setResultCode(NotihubConst.EMAIL_SENDING); + return true; + } + + private SendInternalResultDto sendEmail(TSendEntity send) { + PringoJsonSendRequestDto pringoReq = sendEmailService.buildPringoSendRequest( + send.getSendEml(), + send.getSendNm(), + send.getMsgTitle(), + send.getMsgBody(), + DestInfoDto.from(send) + ); + return sendEmailService.sendPringoEmail(pringoReq); + } + + private void applySendResult(TSendEntity send, SendInternalResultDto sendResult) { + send.setCmid(sendResult.getCmid()); + send.setSendStatus(sendResult.getStatus().getCode()); + send.setResultCode(sendResult.getResultCode()); + } + + private void increaseBulkFailCount(String bulkSendKey, LocalDateTime now) { + if (bulkSendKey == null || bulkSendKey.isBlank()) { + return; + } + + bulkSendRepository.findByBulkSendKey(bulkSendKey).ifPresent(bulk -> { + int fail = bulk.getFailCnt() == null ? 0 : bulk.getFailCnt(); + bulk.setFailCnt(fail + 1); + completeBulkIfNeeded(bulk, now); + bulkSendRepository.save(bulk); + }); + } + + private void completeBulkIfNeeded(TBulkSendEntity bulk, LocalDateTime now) { + if (bulk.getCompleteDt() != null) { + return; + } + + int sendCnt = bulk.getSendCnt() == null ? 0 : bulk.getSendCnt(); + int successCnt = bulk.getSuccesCnt() == null ? 0 : bulk.getSuccesCnt(); + int failCnt = bulk.getFailCnt() == null ? 0 : bulk.getFailCnt(); + if (sendCnt <= successCnt + failCnt) { + bulk.setCompleteDt(now); + } + } + + private void sleepSilently(long ms) { + if (ms <= 0) { + return; + } + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/main/java/com/kri/notihub/server/service/AbstractPringoSendService.java b/src/main/java/com/kri/notihub/server/service/AbstractPringoSendService.java index 3491c75..eca4811 100644 --- a/src/main/java/com/kri/notihub/server/service/AbstractPringoSendService.java +++ b/src/main/java/com/kri/notihub/server/service/AbstractPringoSendService.java @@ -64,8 +64,8 @@ public abstract class AbstractPringoSendService extends AbstractSendService { String msgBody, DestInfoDto dest ) { - if (Boolean.TRUE.equals(isResve)) { - //예약 용 cmid 생성 추후 실제 발송 후 갱신 + if (Boolean.TRUE.equals(isResve) || !StringUtil.isNullOrBlank (bulkSendKey)) { + //예약 또는 bulk send 용 cmid 생성 추후 실제 발송 후 갱신 String ts = DateTimeUtil.nowKstLocalDateTime() .format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 0221ae3..93a4139 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -40,6 +40,10 @@ kri: email: reservation-send: cron: "0 */5 * * * *" + bulk-send: + fixed-delay-ms: 10000 + batch-size: 500 + sending-stale-minutes: 30 result-poll: initial-delay-ms: 10000 max-attempts: 0 @@ -50,7 +54,7 @@ kri: sms: result-sync: - fixed-delay-ms: 60000 + fixed-delay-ms: 10000 window-hours: 1 batch-size: 1000