261029_01_ENH: 템플릿 soft delete 적용 및 발송·예약 건 삭제 차단과 동시성 제어
This commit is contained in:
30
README.md
Normal file
30
README.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# NotiHub Server
|
||||
|
||||
## 이메일 발송 상태 101 운영 참고
|
||||
|
||||
`result_code=101` (`EMAIL_SENDING`)은 서버가 이메일 발송 처리를 시작했지만
|
||||
공급사 접수 결과를 아직 DB에 반영하지 않은 일시적인 상태다.
|
||||
이때 `send_status`는 `0` (`STANDBY`)이다.
|
||||
|
||||
- 즉시 단건 이메일은 `101`로 등록·커밋한 뒤 공급사 API를 호출한다.
|
||||
- 예약·벌크 이메일은 발송 대기 `100`에서 처리 시작 시 `101`로 전환한다.
|
||||
- 공급사 접수 성공과 실제 `return_key` 저장이 완료되면 `111`로 전환한다.
|
||||
이는 접수 성공이며 최종 발송 결과는 poller로 조회한다.
|
||||
- 준비 오류·접수 실패·타임아웃·키 미수신 등이 처리되고 DB 저장까지 완료되면
|
||||
`109`로 전환한다.
|
||||
|
||||
### 내부 장애로 101이 남은 경우
|
||||
|
||||
공급사 API 처리 후 `111` 또는 `109`를 저장하기 전에 서버가 강제 종료되거나
|
||||
DB 저장이 실패하면, 먼저 커밋된 `101`이 남을 수 있다.
|
||||
정상적으로 응답·타임아웃 처리와 DB 저장이 끝난 경우에는 계속 남는 상태가 아니다.
|
||||
|
||||
잔류한 `101`만으로 공급사 접수 여부를 판단할 수 없으므로 운영 확인 대상으로 취급한다.
|
||||
임시 UUID 또는 `RESERVATION_…`는 실제 `return_key`가 아니므로 결과 조회에 사용할 수 없다.
|
||||
공급사 접수·발송 여부를 확인하지 않고 재발송하면 중복 발송될 수 있다.
|
||||
|
||||
이번 템플릿 soft delete 변경에는 별도의 `101` 자동 복구 기능을 추가하지 않는다.
|
||||
미완료 발송(`send_status=0`)이 남아 있으면 해당 템플릿의 삭제를 차단한다.
|
||||
|
||||
기존 비예약 벌크 이메일의 오래된 `101`을 `100`으로 되돌리는 복구 처리는 유지된다.
|
||||
해당 처리는 `bulk_send_key`가 없는 즉시 단건 이메일에는 적용되지 않는다.
|
||||
@@ -21,6 +21,8 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
public interface SendRepository extends JpaRepository<TSendEntity, Long> {
|
||||
|
||||
boolean existsByTmplatIdxAndSendStatus(long tmplatIdx, short sendStatus);
|
||||
|
||||
// 목록과 벌크 집계에서 동일한 상태 기준을 사용한다. 취소 API의 잠금 후 판단이 최종이다.
|
||||
String CANCELABLE_CONDITION = """
|
||||
s.resve = true and s.sendStatus = 0 and s.cancelDt is null
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
package com.kri.notihub.server.persistence.repository;
|
||||
|
||||
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
|
||||
import java.time.LocalDateTime;
|
||||
import jakarta.persistence.LockModeType;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
public interface TemplateRepository extends JpaRepository<TTmplatEntity, Long>,
|
||||
JpaSpecificationExecutor<TTmplatEntity> {
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query("""
|
||||
update TTmplatEntity t
|
||||
set t.del = true,
|
||||
t.delUser = :delUser,
|
||||
t.delDt = :delDt
|
||||
where t.tmplatIdx = :idx
|
||||
and t.del = false
|
||||
""")
|
||||
int softDeleteByTmplatIdx(long idx, String delUser, LocalDateTime delDt);
|
||||
@Lock(LockModeType.PESSIMISTIC_READ)
|
||||
@Query("select t from TTmplatEntity t where t.tmplatIdx = :idx and t.del = false")
|
||||
Optional<TTmplatEntity> findActiveForSend(long idx);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select t from TTmplatEntity t where t.tmplatIdx = :idx and t.del = false")
|
||||
Optional<TTmplatEntity> findActiveForUpdate(long idx);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select t from TTmplatEntity t where t.tmplatIdx = :idx")
|
||||
Optional<TTmplatEntity> findForDelete(long idx);
|
||||
|
||||
List<TTmplatEntity> findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(List<Short> tmplatTyList,
|
||||
String itrntPrjctCd);
|
||||
|
||||
@@ -91,16 +91,9 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
|
||||
|
||||
return SendInternalResultDto.of(cmid, SendStatusType.STANDBY, NotihubConst.EMAIL_STANDBY);
|
||||
} else {
|
||||
PringoSendRequestDto pringoReq = buildPringoSendRequest(
|
||||
sendEml,
|
||||
sendNm,
|
||||
msgTitle,
|
||||
msgBody,
|
||||
tmplatIdx,
|
||||
atchFl,
|
||||
dest
|
||||
);
|
||||
return sendPringoEmail(pringoReq);
|
||||
// 단건도 발송 중 상태를 먼저 저장하고, 커밋 후 트랜잭션 밖에서 외부 발송을 호출한다.
|
||||
return SendInternalResultDto.of(CommonUtil.uuid32(), SendStatusType.STANDBY,
|
||||
NotihubConst.EMAIL_SENDING);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ public abstract class AbstractSendService {
|
||||
protected final TemplateService templateService;
|
||||
protected final PhoneVerificationService phoneVerificationService;
|
||||
|
||||
@Transactional(isolation = Isolation.READ_COMMITTED)
|
||||
public String issueBulkKey(BulkSendCreateRequestDto req) {
|
||||
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
|
||||
@@ -72,7 +73,7 @@ public abstract class AbstractSendService {
|
||||
}
|
||||
}
|
||||
|
||||
TemplateDto tmplat = templateService.getTemplate(req.getTmplatIdx());
|
||||
TemplateDto tmplat = templateService.getTemplateForSend(req.getTmplatIdx());
|
||||
validateTemplateType(tmplat);
|
||||
validateBulkTemplatePurpose(tmplat);
|
||||
|
||||
@@ -105,6 +106,7 @@ public abstract class AbstractSendService {
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(isolation = Isolation.READ_COMMITTED)
|
||||
public SendSingleResponseDto doSendSingle(
|
||||
SendRequestSingleDto req,
|
||||
String regCmpn,
|
||||
@@ -127,7 +129,7 @@ public abstract class AbstractSendService {
|
||||
}
|
||||
}
|
||||
|
||||
TemplateDto tmplat = templateService.getTemplate(req.getTmplatIdx());
|
||||
TemplateDto tmplat = templateService.getTemplateForSend(req.getTmplatIdx());
|
||||
validateTemplateType(tmplat);
|
||||
validateSingleTemplatePurpose(tmplat, req);
|
||||
|
||||
@@ -250,7 +252,7 @@ public abstract class AbstractSendService {
|
||||
.with("sendCnt", bulk.getSendCnt());
|
||||
}
|
||||
|
||||
TemplateDto tmplat = templateService.getTemplate(bulk.getTmplatIdx());
|
||||
TemplateDto tmplat = templateService.getTemplateForSend(bulk.getTmplatIdx());
|
||||
validateTemplateType(tmplat);
|
||||
validateBulkTemplatePurpose(tmplat);
|
||||
|
||||
|
||||
@@ -6,20 +6,32 @@ import com.kri.notihub.server.common.enums.ChannelType;
|
||||
import com.kri.notihub.server.common.enums.SendStatusType;
|
||||
import com.kri.notihub.server.common.enums.SendType;
|
||||
import com.kri.notihub.server.common.external.pringo.PringoApiClient;
|
||||
import com.kri.notihub.server.dto.send.DestInfoDto;
|
||||
import com.kri.notihub.server.dto.send.SendInternalResultDto;
|
||||
import com.kri.notihub.server.dto.send.SendRequestSingleDto;
|
||||
import com.kri.notihub.server.dto.send.SendSingleResponseDto;
|
||||
import com.kri.notihub.server.persistence.entity.TSendEntity;
|
||||
import com.kri.notihub.server.persistence.jdbc.SendBulkJdbcWriter;
|
||||
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
|
||||
import com.kri.notihub.server.persistence.repository.SendRepository;
|
||||
import com.kri.notihub.server.persistence.repository.TemplateRepository;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class SendEmailService extends AbstractPringoSendService {
|
||||
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final SendResultService resultService;
|
||||
|
||||
public SendEmailService(
|
||||
SendBulkJdbcWriter sendBulkJdbcWriter,
|
||||
TemplateRepository templateRepository,
|
||||
@@ -30,11 +42,50 @@ public class SendEmailService extends AbstractPringoSendService {
|
||||
EmailResultPoller emailResultPoller,
|
||||
EmailBodyRenderer emailBodyRenderer,
|
||||
EmailAttachmentService emailAttachmentService,
|
||||
PhoneVerificationService phoneVerificationService
|
||||
PhoneVerificationService phoneVerificationService,
|
||||
PlatformTransactionManager transactionManager,
|
||||
SendResultService resultService
|
||||
) {
|
||||
super(sendBulkJdbcWriter, templateRepository, bulkSendRepository, sendRepository, templateService,
|
||||
pringoApiClient, emailResultPoller, emailBodyRenderer, emailAttachmentService,
|
||||
phoneVerificationService);
|
||||
this.transactionManager = transactionManager;
|
||||
this.resultService = resultService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(propagation = Propagation.NOT_SUPPORTED)
|
||||
public SendSingleResponseDto doSendSingle(SendRequestSingleDto req, String regCmpn, String regUser) {
|
||||
TransactionTemplate registration = new TransactionTemplate(transactionManager);
|
||||
registration.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
|
||||
SendSingleResponseDto registered = Objects.requireNonNull(registration.execute(status ->
|
||||
super.doSendSingle(req, regCmpn, regUser)));
|
||||
if (Boolean.TRUE.equals(req.getResve())) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
TSendEntity send = sendRepository.findById(registered.sendIdx()).orElseThrow();
|
||||
SendInternalResultDto result;
|
||||
try {
|
||||
result = sendPringoEmail(buildPringoSendRequest(
|
||||
send.getSendEml(), send.getSendNm(), send.getMsgTitle(), send.getMsgBody(),
|
||||
send.getTmplatIdx(), send.getAtchFl(), DestInfoDto.from(send)));
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("Single email preparation failed (sendIdx={})", send.getSendIdx());
|
||||
try {
|
||||
resultService.record(send.getSendIdx(), send.getCmid(), SendStatusType.FAIL,
|
||||
NotihubConst.EMAIL_SEND_FAIL, null);
|
||||
} catch (RuntimeException recordFailure) {
|
||||
ex.addSuppressed(recordFailure);
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
TSendEntity persisted = resultService.record(send.getSendIdx(), result.cmid(),
|
||||
result.status(), result.resultCode(), null);
|
||||
if (persisted != null) {
|
||||
afterPersistSendEntities(List.of(persisted));
|
||||
}
|
||||
return SendSingleResponseDto.of(registered.sendIdx(), result.cmid(), registered.data());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.notihub.server.common.consts.NotihubConst;
|
||||
import com.kri.notihub.server.common.enums.ChannelType;
|
||||
import com.kri.notihub.server.common.enums.SendStatusType;
|
||||
import com.kri.notihub.server.common.enums.SendType;
|
||||
import com.kri.notihub.server.common.enums.TemplateEventType;
|
||||
import com.kri.notihub.server.common.enums.TemplatePurpose;
|
||||
@@ -15,6 +16,7 @@ import com.kri.notihub.server.dto.template.TemplateDto;
|
||||
import com.kri.notihub.server.dto.template.TemplateSummaryDto;
|
||||
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
|
||||
import com.kri.notihub.server.persistence.entity.TTmplatEventLogEntity;
|
||||
import com.kri.notihub.server.persistence.repository.SendRepository;
|
||||
import com.kri.notihub.server.persistence.repository.TemplateEventLogRepository;
|
||||
import com.kri.notihub.server.persistence.repository.TemplateRepository;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -23,8 +25,10 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Log4j2
|
||||
@@ -33,6 +37,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
public class TemplateService {
|
||||
|
||||
private final TemplateRepository templateRepository;
|
||||
private final SendRepository sendRepository;
|
||||
private final TemplateEventLogRepository templateEventLogRepository;
|
||||
private final FileService fileService;
|
||||
private final EmailAttachmentService emailAttachmentService;
|
||||
@@ -136,6 +141,15 @@ public class TemplateService {
|
||||
);
|
||||
}
|
||||
|
||||
// 발송 등록 트랜잭션이 커밋될 때까지 템플릿 공유 잠금을 유지한다.
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public TemplateDto getTemplateForSend(long tmplatIdx) {
|
||||
return templateRepository.findActiveForSend(tmplatIdx)
|
||||
.map(TemplateDto::from)
|
||||
.orElseThrow(() -> BusinessException.notFound(
|
||||
"TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.").with("tmplatIdx", tmplatIdx));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public EmailAttachmentDto downloadAttachment(long tmplatIdx, String fileName) {
|
||||
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx)
|
||||
@@ -162,7 +176,7 @@ public class TemplateService {
|
||||
long tmplatIdx = template.getTmplatIdx();
|
||||
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
|
||||
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx)
|
||||
TTmplatEntity entity = templateRepository.findActiveForUpdate(tmplatIdx)
|
||||
.orElseThrow(() ->
|
||||
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
|
||||
.with("tmplatIdx", tmplatIdx)
|
||||
@@ -220,12 +234,28 @@ public class TemplateService {
|
||||
return after;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Transactional(isolation = Isolation.READ_COMMITTED)
|
||||
public void deleteTemplate(long tmplatIdx, String delUser) {
|
||||
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
if (delUser == null || delUser.isBlank() || delUser.length() > 32) {
|
||||
throw BusinessException.forbidden("TEMPLATE_DELETE_FORBIDDEN", "삭제 처리자 정보가 필요합니다.");
|
||||
}
|
||||
TTmplatEntity entity = templateRepository.findForDelete(tmplatIdx)
|
||||
.orElseThrow(() -> BusinessException.notFound(
|
||||
"TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.").with("tmplatIdx", tmplatIdx));
|
||||
if (Boolean.TRUE.equals(entity.getDel())) {
|
||||
return;
|
||||
}
|
||||
if (sendRepository.existsByTmplatIdxAndSendStatus(tmplatIdx, SendStatusType.STANDBY.getCode())) {
|
||||
throw BusinessException.conflict("TEMPLATE_IN_USE", "발송 중이거나 예약된 발송이 있어 삭제할 수 없습니다.")
|
||||
.with("tmplatIdx", tmplatIdx);
|
||||
}
|
||||
|
||||
templateRepository.softDeleteByTmplatIdx(tmplatIdx, delUser, now);
|
||||
saveLog(tmplatIdx, TemplateEventType.DELETE_TEMPLATE, null, null, delUser, now);
|
||||
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
TemplateDto snapshot = TemplateDto.from(entity);
|
||||
entity.setDel(true);
|
||||
entity.setDelUser(delUser);
|
||||
entity.setDelDt(now);
|
||||
saveLog(tmplatIdx, TemplateEventType.DELETE_TEMPLATE, snapshot, snapshot, delUser, now);
|
||||
}
|
||||
|
||||
private void saveLog(
|
||||
|
||||
Reference in New Issue
Block a user