261020_04_FIX: BusinessException 적용 및 원본 예외 보존, 결과 파일 만료 기준을 최종 수정 시각으로 변경

This commit is contained in:
2026-10-20 16:38:11 +09:00
parent 64d830fe67
commit 70ddcdd9c3
17 changed files with 62 additions and 58 deletions

View File

@@ -117,7 +117,7 @@ public class ContactSurveyApiClient {
} }
} }
throw new IllegalStateException("Unsupported contact survey target profile"); throw BusinessException.internalError("UNSUPPORTED_CONTACT_SURVEY_PROFILE", "Unsupported contact survey target profile");
} }
private Map<String, String> headers() { private Map<String, String> headers() {

View File

@@ -1,5 +1,6 @@
package com.kri.contact.server.persistence.jdbc; package com.kri.contact.server.persistence.jdbc;
import com.kri.common.feature.web.BusinessException;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
@@ -150,7 +151,7 @@ public class ListAssignJdbcSupport {
return List.of(); return List.of();
} }
if (chunkSize <= 0) { if (chunkSize <= 0) {
throw new IllegalArgumentException("chunkSize must be greater than 0"); throw BusinessException.internalError("INVALID_LIST_CHUNK_SIZE", "chunkSize must be greater than 0");
} }
List<String> sidList = sids instanceof List<String> list ? list : new ArrayList<>(sids); List<String> sidList = sids instanceof List<String> list ? list : new ArrayList<>(sids);

View File

@@ -1,5 +1,6 @@
package com.kri.contact.server.persistence.jdbc; package com.kri.contact.server.persistence.jdbc;
import com.kri.common.feature.web.BusinessException;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.Query; import jakarta.persistence.Query;
import java.util.ArrayList; import java.util.ArrayList;
@@ -123,7 +124,7 @@ public class ListResetJdbcSupport {
return List.of(); return List.of();
} }
if (chunkSize <= 0) { if (chunkSize <= 0) {
throw new IllegalArgumentException("chunkSize must be greater than 0"); throw BusinessException.internalError("INVALID_LIST_CHUNK_SIZE", "chunkSize must be greater than 0");
} }
List<String> sidList = new ArrayList<>(sids); List<String> sidList = new ArrayList<>(sids);

View File

@@ -62,7 +62,7 @@ public class ListResetPersistenceSupport {
TListResetLogEntity log = listResetLogRepository.findById(listResetLogId) TListResetLogEntity log = listResetLogRepository.findById(listResetLogId)
.orElseThrow(() -> BusinessException.internalError("List reset log not found.")); .orElseThrow(() -> BusinessException.internalError("List reset log not found."));
if (!java.util.Objects.equals(log.getPrjctIdx(), prjctIdx) || !java.util.Objects.equals(log.getMode(), mode.getCode())) { if (!java.util.Objects.equals(log.getPrjctIdx(), prjctIdx) || !java.util.Objects.equals(log.getMode(), mode.getCode())) {
throw new IllegalArgumentException("Reset log does not match project and mode"); throw BusinessException.internalError("RESET_LOG_PROJECT_OR_MODE_MISMATCH", "Reset log does not match project and mode");
} }
log.setListCnt(accumulate ? Math.addExact(log.getListCnt(), resetCount) : resetCount); log.setListCnt(accumulate ? Math.addExact(log.getListCnt(), resetCount) : resetCount);
listResetLogRepository.saveAndFlush(log); listResetLogRepository.saveAndFlush(log);

View File

@@ -238,7 +238,7 @@ public class ListUpdateService {
private void lockSurveyHistoryUntilTransactionCompletion(ListEventHistFromSurveyDto request) { private void lockSurveyHistoryUntilTransactionCompletion(ListEventHistFromSurveyDto request) {
if (!TransactionSynchronizationManager.isSynchronizationActive()) { if (!TransactionSynchronizationManager.isSynchronizationActive()) {
throw new IllegalStateException("설문 이력 처리는 활성 트랜잭션 동기화가 필요합니다."); throw BusinessException.internalError("SURVEY_HISTORY_TRANSACTION_REQUIRED", "설문 이력 처리는 활성 트랜잭션 동기화가 필요합니다.");
} }
SurveyHistoryKey key = new SurveyHistoryKey(request.getPrjctSurveyIdx(), request.getSid()); SurveyHistoryKey key = new SurveyHistoryKey(request.getPrjctSurveyIdx(), request.getSid());
@@ -254,13 +254,15 @@ public class ListUpdateService {
long timeoutSeconds = listEventHistoryProperties.getSurveyLockWaitTimeoutSeconds(); long timeoutSeconds = listEventHistoryProperties.getSurveyLockWaitTimeoutSeconds();
if (!lock.semaphore.tryAcquire(timeoutSeconds, TimeUnit.SECONDS)) { if (!lock.semaphore.tryAcquire(timeoutSeconds, TimeUnit.SECONDS)) {
releaseSurveyHistoryLockReference(key, lock); releaseSurveyHistoryLockReference(key, lock);
throw new IllegalStateException("설문 이력 잠금 대기 시간이 " + timeoutSeconds + "초를 초과했습니다."); throw BusinessException.conflict("SURVEY_HISTORY_LOCK_TIMEOUT", "설문 이력 잠금 대기 시간이 " + timeoutSeconds + "초를 초과했습니다.");
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
// 허가를 얻지 못했으므로 semaphore.release() 없이 참조만 정리한다. // 허가를 얻지 못했으므로 semaphore.release() 없이 참조만 정리한다.
releaseSurveyHistoryLockReference(key, lock); releaseSurveyHistoryLockReference(key, lock);
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
throw new IllegalStateException("설문 이력 잠금 대기 중 요청이 중단되었습니다.", e); var failure = BusinessException.internalError("SURVEY_HISTORY_LOCK_INTERRUPTED", "설문 이력 잠금 대기 중 요청이 중단되었습니다.");
failure.addSuppressed(e);
throw failure;
} }
try { try {
@@ -284,7 +286,7 @@ public class ListUpdateService {
// 대기자와 보유자가 모두 사라진 키만 제거해 잠금 맵이 계속 커지지 않게 한다. // 대기자와 보유자가 모두 사라진 키만 제거해 잠금 맵이 계속 커지지 않게 한다.
surveyHistoryLocks.compute(key, (ignored, current) -> { surveyHistoryLocks.compute(key, (ignored, current) -> {
if (current != lock) { if (current != lock) {
throw new IllegalStateException("설문 이력 잠금 참조가 예상과 다르게 변경되었습니다."); throw BusinessException.internalError("SURVEY_HISTORY_LOCK_REFERENCE_CHANGED", "설문 이력 잠금 참조가 예상과 다르게 변경되었습니다.");
} }
return --current.users == 0 ? null : current; return --current.users == 0 ? null : current;
}); });

View File

@@ -580,7 +580,7 @@ public class ListUploadService {
public PreparedUpload prepareAsync(Long projectId, Path source, ListUploadRequestDto request, public PreparedUpload prepareAsync(Long projectId, Path source, ListUploadRequestDto request,
String logId, Runnable checkCancelled) { String logId, Runnable checkCancelled) {
if (request.getUploadMode() == null) { if (request.getUploadMode() == null) {
throw new IllegalArgumentException("Upload mode is required"); throw BusinessException.badRequest("ASYNC_UPLOAD_MODE_REQUIRED", "Upload mode is required");
} }
try { try {
checkCancelled.run(); checkCancelled.run();
@@ -604,9 +604,10 @@ public class ListUploadService {
assignService.findAllowedUserRolesByAssignRole(new LinkedHashSet<>(roles.values())), assignService.findAllowedUserRolesByAssignRole(new LinkedHashSet<>(roles.values())),
companies, logId, checkCancelled, request.getUploadMode() != ListUploadMode.RESET_AND_INSERT); companies, logId, checkCancelled, request.getUploadMode() != ListUploadMode.RESET_AND_INSERT);
checkCancelled.run(); checkCancelled.run();
var log = listUploadLogRepository.findById(logId).orElseThrow(); var log = listUploadLogRepository.findById(logId).orElseThrow(() ->
BusinessException.internalError("LIST_UPLOAD_LOG_NOT_FOUND", "업로드 로그를 찾을 수 없습니다."));
if (!Objects.equals(log.getPrjctIdx(), projectId)) { if (!Objects.equals(log.getPrjctIdx(), projectId)) {
throw new IllegalArgumentException("Upload log project mismatch"); throw BusinessException.internalError("UPLOAD_LOG_PROJECT_MISMATCH", "Upload log project mismatch");
} }
markValidated(log, validation.totalCount()); markValidated(log, validation.totalCount());
return new PreparedUpload(validation.totalCount(), Set.copyOf(validation.uploadedSids()), return new PreparedUpload(validation.totalCount(), Set.copyOf(validation.uploadedSids()),
@@ -652,9 +653,10 @@ public class ListUploadService {
createAsyncHeaders(projectId, prepared, user, time); createAsyncHeaders(projectId, prepared, user, time);
} }
listContentItemService.refreshListContentItem(projectId, prepared.headers()); listContentItemService.refreshListContentItem(projectId, prepared.headers());
var log = listUploadLogRepository.findById(logId).orElseThrow(); var log = listUploadLogRepository.findById(logId).orElseThrow(() ->
BusinessException.internalError("LIST_UPLOAD_LOG_NOT_FOUND", "업로드 로그를 찾을 수 없습니다."));
if (!Objects.equals(log.getPrjctIdx(), projectId)) { if (!Objects.equals(log.getPrjctIdx(), projectId)) {
throw new IllegalArgumentException("Upload log project mismatch"); throw BusinessException.internalError("UPLOAD_LOG_PROJECT_MISMATCH", "Upload log project mismatch");
} }
markSuccess(log, prepared.totalCount()); markSuccess(log, prepared.totalCount());
} }

View File

@@ -83,7 +83,7 @@ public class ListAsyncDownloadService {
case CONTACT_HISTORY_DOWNLOAD -> " 컨택 이력.xlsx"; case CONTACT_HISTORY_DOWNLOAD -> " 컨택 이력.xlsx";
case UPDATE_HISTORY_DOWNLOAD -> " 수정 이력.xlsx"; case UPDATE_HISTORY_DOWNLOAD -> " 수정 이력.xlsx";
case ITEM_ZIP_DOWNLOAD -> " item_files.zip"; case ITEM_ZIP_DOWNLOAD -> " item_files.zip";
default -> throw new IllegalArgumentException("Unsupported download type"); default -> throw BusinessException.internalError("UNSUPPORTED_LIST_DOWNLOAD_TYPE", "Unsupported download type");
}; };
String key = executor.submit(projectId, user.getUserId(), type, snapshot, null, String key = executor.submit(projectId, user.getUserId(), type, snapshot, null,
context -> generate(projectId, type, savedFilter, includeResult, savedEvent, name, user, context)); context -> generate(projectId, type, savedFilter, includeResult, savedEvent, name, user, context));
@@ -118,7 +118,7 @@ public class ListAsyncDownloadService {
event.getHistoryOrder(), includeResult, checked, observer); event.getHistoryOrder(), includeResult, checked, observer);
case UPDATE_HISTORY_DOWNLOAD -> downloads.writeSidWithUpdateHist(projectId, filter, checked, observer); case UPDATE_HISTORY_DOWNLOAD -> downloads.writeSidWithUpdateHist(projectId, filter, checked, observer);
case ITEM_ZIP_DOWNLOAD -> downloads.writeItemFile(projectId, filter, checked, observer); case ITEM_ZIP_DOWNLOAD -> downloads.writeItemFile(projectId, filter, checked, observer);
default -> throw new IllegalArgumentException("Unsupported download type"); default -> throw BusinessException.internalError("UNSUPPORTED_LIST_DOWNLOAD_TYPE", "Unsupported download type");
} }
context.checkCancelled(); context.checkCancelled();
}); });

View File

@@ -88,11 +88,11 @@ public class ListAsyncJobExecutor implements ApplicationRunner {
throw BusinessException.conflict("LIST_JOBS_UNAVAILABLE", "작업 접수를 준비 중입니다."); throw BusinessException.conflict("LIST_JOBS_UNAVAILABLE", "작업 접수를 준비 중입니다.");
} }
if (TransactionSynchronizationManager.isActualTransactionActive()) { if (TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("Submit outside a business transaction"); throw BusinessException.internalError("LIST_JOB_SUBMIT_TRANSACTION_ACTIVE", "Submit outside a business transaction");
} }
if (projectId == null || user == null || user.isBlank() || user.length() > 32 if (projectId == null || user == null || user.isBlank() || user.length() > 32
|| type == null || request == null || work == null) { || type == null || request == null || work == null) {
throw new IllegalArgumentException("Invalid job submission"); throw BusinessException.internalError("INVALID_LIST_JOB_SUBMISSION", "Invalid job submission");
} }
Map<String, Object> snapshot = mapper.convertValue(request, new TypeReference<>() {}); Map<String, Object> snapshot = mapper.convertValue(request, new TypeReference<>() {});
String key = UUID.randomUUID().toString().replace("-", ""); String key = UUID.randomUUID().toString().replace("-", "");

View File

@@ -230,7 +230,7 @@ public class ListAsyncJobStore {
TListAsyncJobEntity job = lock(key); TListAsyncJobEntity job = lock(key);
requireRunning(job); requireRunning(job);
if (stage == null || stage.isBlank() || stage.length() > 32 || (totalSids != null && totalSids < 0)) { if (stage == null || stage.isBlank() || stage.length() > 32 || (totalSids != null && totalSids < 0)) {
throw new IllegalArgumentException("Invalid job progress"); throw BusinessException.internalError("INVALID_LIST_JOB_PROGRESS", "Invalid job progress");
} }
job.setJobStage(stage); job.setJobStage(stage);
job.setTotalSidCnt(totalSids); job.setTotalSidCnt(totalSids);
@@ -261,7 +261,7 @@ public class ListAsyncJobStore {
if (chunkNo < 1 || operation == null || operation.isBlank() || operation.length() > 32 if (chunkNo < 1 || operation == null || operation.isBlank() || operation.length() > 32
|| sids.isEmpty() || sids.stream().anyMatch(java.util.Objects::isNull) || sids.isEmpty() || sids.stream().anyMatch(java.util.Objects::isNull)
|| new HashSet<>(sids).size() != sids.size()) { || new HashSet<>(sids).size() != sids.size()) {
throw new IllegalArgumentException("Invalid job chunk"); throw BusinessException.internalError("INVALID_LIST_JOB_CHUNK", "Invalid job chunk");
} }
checkCancelled.run(); checkCancelled.run();
changes.run(); changes.run();
@@ -269,7 +269,7 @@ public class ListAsyncJobStore {
TListAsyncJobEntity job = lock(key); TListAsyncJobEntity job = lock(key);
requireRunning(job); requireRunning(job);
if (chunkNo != job.getCompletedChunkCnt() + 1) { if (chunkNo != job.getCompletedChunkCnt() + 1) {
throw new IllegalArgumentException("Chunk number must follow the last committed chunk"); throw BusinessException.internalError("INVALID_LIST_JOB_CHUNK_SEQUENCE", "Chunk number must follow the last committed chunk");
} }
TListAsyncJobChunkEntity chunk = new TListAsyncJobChunkEntity(); TListAsyncJobChunkEntity chunk = new TListAsyncJobChunkEntity();
chunk.setId(new TListAsyncJobChunkId(key, chunkNo)); chunk.setId(new TListAsyncJobChunkId(key, chunkNo));
@@ -328,19 +328,19 @@ public class ListAsyncJobStore {
public void messageBatch(String key, int number, Map<String, Object> batch) { public void messageBatch(String key, int number, Map<String, Object> batch) {
var job = lock(key); var job = lock(key);
if (job.getJobStatus() != ListAsyncJobStatus.RUNNING && job.getJobStatus() != ListAsyncJobStatus.CANCEL_REQUESTED) { if (job.getJobStatus() != ListAsyncJobStatus.RUNNING && job.getJobStatus() != ListAsyncJobStatus.CANCEL_REQUESTED) {
throw new IllegalStateException("Message job is not active"); throw BusinessException.conflict("MESSAGE_JOB_NOT_ACTIVE", "Message job is not active");
} }
var detail = new java.util.LinkedHashMap<String, Object>(job.getErrorDetailJson() == null ? Map.of() : job.getErrorDetailJson()); var detail = new java.util.LinkedHashMap<String, Object>(job.getErrorDetailJson() == null ? Map.of() : job.getErrorDetailJson());
var batches = new java.util.ArrayList<Map<String, Object>>(); var batches = new java.util.ArrayList<Map<String, Object>>();
if (detail.get("messageBatches") instanceof List<?> old) { if (detail.get("messageBatches") instanceof List<?> old) {
for (Object entry : old) batches.add(new java.util.LinkedHashMap<>((Map<String,Object>) entry)); for (Object entry : old) batches.add(new java.util.LinkedHashMap<>((Map<String,Object>) entry));
} }
if (number < 1 || number > batches.size() + 1) throw new IllegalArgumentException("Invalid dispatch sequence"); if (number < 1 || number > batches.size() + 1) throw BusinessException.internalError("INVALID_MESSAGE_DISPATCH_SEQUENCE", "Invalid dispatch sequence");
var entryValue = new java.util.LinkedHashMap<String,Object>(batch); var entryValue = new java.util.LinkedHashMap<String,Object>(batch);
entryValue.put("batchNo", number); entryValue.put("batchNo", number);
if (number == batches.size() + 1) batches.add(Map.copyOf(entryValue)); if (number == batches.size() + 1) batches.add(Map.copyOf(entryValue));
else { else {
if (Boolean.TRUE.equals(batches.get(number - 1).get("completed"))) throw new IllegalStateException("Dispatch already recorded"); if (Boolean.TRUE.equals(batches.get(number - 1).get("completed"))) throw BusinessException.conflict("MESSAGE_DISPATCH_ALREADY_RECORDED", "Dispatch already recorded");
batches.set(number - 1, Map.copyOf(entryValue)); batches.set(number - 1, Map.copyOf(entryValue));
} }
detail.put("messageBatches", batches); detail.put("messageBatches", batches);
@@ -372,14 +372,14 @@ public class ListAsyncJobStore {
if (chunkNo < 1 || operation == null || operation.isBlank() || operation.length() > 32 if (chunkNo < 1 || operation == null || operation.isBlank() || operation.length() > 32
|| requested.isEmpty() || requested.stream().anyMatch(java.util.Objects::isNull) || requested.isEmpty() || requested.stream().anyMatch(java.util.Objects::isNull)
|| new HashSet<>(requested).size() != requested.size()) { || new HashSet<>(requested).size() != requested.size()) {
throw new IllegalArgumentException("Invalid fixed SID chunk"); throw BusinessException.internalError("INVALID_LIST_JOB_FIXED_SID_CHUNK", "Invalid fixed SID chunk");
} }
checkCancelled.run(); checkCancelled.run();
TListAsyncJobEntity job = lock(key); TListAsyncJobEntity job = lock(key);
requireRunning(job); requireRunning(job);
if (!java.util.Objects.equals(projectId, job.getPrjctIdx()) if (!java.util.Objects.equals(projectId, job.getPrjctIdx())
|| chunkNo != job.getCompletedChunkCnt() + 1) { || chunkNo != job.getCompletedChunkCnt() + 1) {
throw new IllegalArgumentException("Invalid project or chunk sequence"); throw BusinessException.internalError("INVALID_LIST_JOB_PROJECT_OR_CHUNK", "Invalid project or chunk sequence");
} }
var existing = lists.findForUpdate(projectId, requested).stream() var existing = lists.findForUpdate(projectId, requested).stream()
.map(row -> row.getId().getSid()).collect(java.util.stream.Collectors.toSet()); .map(row -> row.getId().getSid()).collect(java.util.stream.Collectors.toSet());
@@ -422,7 +422,7 @@ public class ListAsyncJobStore {
throw new CancellationException(); throw new CancellationException();
} }
if (job.getJobStatus() != ListAsyncJobStatus.RUNNING) { if (job.getJobStatus() != ListAsyncJobStatus.RUNNING) {
throw new IllegalStateException("Job is not running"); throw BusinessException.conflict("LIST_JOB_NOT_RUNNING", "Job is not running");
} }
} }
} }

View File

@@ -153,7 +153,7 @@ public class ListAsyncMaintenanceService {
access.requireProject(projectId, user); access.requireProject(projectId, user);
var sids = chunk.sids(); var sids = chunk.sids();
if (!prepared.sids().containsAll(sids) || sids.stream().anyMatch(sid -> !seen.add(sid))) { if (!prepared.sids().containsAll(sids) || sids.stream().anyMatch(sid -> !seen.add(sid))) {
throw new IllegalStateException("Validated upload SIDs changed"); throw BusinessException.conflict("VALIDATED_UPLOAD_SIDS_CHANGED", "Validated upload SIDs changed");
} }
int attempt = attempted.incrementAndGet(); int attempt = attempted.incrementAndGet();
int chunkNo = number.get() + 1; int chunkNo = number.get() + 1;
@@ -184,7 +184,7 @@ public class ListAsyncMaintenanceService {
throw failure; throw failure;
} }
if (!seen.equals(prepared.sids())) { if (!seen.equals(prepared.sids())) {
throw new IllegalStateException("Validated upload SID count changed"); throw BusinessException.conflict("VALIDATED_UPLOAD_SID_COUNT_CHANGED", "Validated upload SID count changed");
} }
var finalProgress = new java.util.LinkedHashMap<String,Object>(context.job().getProgressJson() == null ? Map.of() : context.job().getProgressJson()); var finalProgress = new java.util.LinkedHashMap<String,Object>(context.job().getProgressJson() == null ? Map.of() : context.job().getProgressJson());
finalProgress.put("dataApplied", true); finalProgress.put("dataApplied", true);

View File

@@ -80,7 +80,7 @@ public class ListAsyncMessageService {
var found = new HashSet<String>(); var found = new HashSet<String>();
for (var row : rows) { for (var row : rows) {
context.checkCancelled(); context.checkCancelled();
if (!filter.getSidSet().contains(row.sid()) || !found.add(row.sid())) throw new IllegalStateException("Unexpected message target"); if (!filter.getSidSet().contains(row.sid()) || !found.add(row.sid())) throw BusinessException.internalError("UNEXPECTED_MESSAGE_TARGET", "Unexpected message target");
List<NotiHubDestInfoDto> candidates; List<NotiHubDestInfoDto> candidates;
try { candidates = messages.prepareAsyncRow(row, request, messageContext, channel); } try { candidates = messages.prepareAsyncRow(row, request, messageContext, channel); }
catch (RuntimeException failure) { catch (RuntimeException failure) {
@@ -141,7 +141,7 @@ public class ListAsyncMessageService {
context.reject("MESSAGE_SETUP_FAILED", "발송 작업 생성에 실패하여 수신처 요청을 전달하지 못했습니다.", context.job().getErrorDetailJson()); context.reject("MESSAGE_SETUP_FAILED", "발송 작업 생성에 실패하여 수신처 요청을 전달하지 못했습니다.", context.job().getErrorDetailJson());
return; return;
} }
if (bulkKey == null || bulkKey.isBlank()) throw new IllegalStateException("Missing bulk key"); if (bulkKey == null || bulkKey.isBlank()) throw BusinessException.internalError("MISSING_MESSAGE_BULK_KEY", "Missing bulk key");
progress.put("bulkSendKey", bulkKey); progress.put("bulkSendKey", bulkKey);
context.progress("DISPATCHING", null, progress); context.progress("DISPATCHING", null, progress);
long failed = failedSids.size(); long failed = failedSids.size();
@@ -175,7 +175,9 @@ public class ListAsyncMessageService {
if (failed > 0) context.reject("MESSAGE_PARTIAL_FAILURE", "전체 대상 처리를 마쳤으며 실패 또는 접수 불명 대상이 있습니다.", context.job().getErrorDetailJson()); if (failed > 0) context.reject("MESSAGE_PARTIAL_FAILURE", "전체 대상 처리를 마쳤으며 실패 또는 접수 불명 대상이 있습니다.", context.job().getErrorDetailJson());
else context.complete(() -> {}); else context.complete(() -> {});
} catch (IOException failure) { } catch (IOException failure) {
throw BusinessException.internalError("MESSAGE_PREPARATION_FAILED", "발송 준비 파일 처리에 실패했습니다."); var wrapped = BusinessException.internalError("MESSAGE_PREPARATION_FAILED", "발송 준비 파일 처리에 실패했습니다.");
wrapped.addSuppressed(failure);
throw wrapped;
} }
} }

View File

@@ -72,7 +72,7 @@ public abstract class AbstractFileService {
Path target = normalizedDir.resolve(fileName).normalize(); Path target = normalizedDir.resolve(fileName).normalize();
if (!target.startsWith(normalizedDir)) { if (!target.startsWith(normalizedDir)) {
throw new IllegalStateException("잘못된 파일 경로입니다."); throw BusinessException.badRequest("WRONG_FILE_PATH", "잘못된 파일 경로입니다.");
} }
file.transferTo(target.toFile()); file.transferTo(target.toFile());
@@ -106,7 +106,7 @@ public abstract class AbstractFileService {
Path target = normalizedTargetDir.resolve(fileName).normalize(); Path target = normalizedTargetDir.resolve(fileName).normalize();
if (!source.startsWith(normalizedSourceDir) || !target.startsWith(normalizedTargetDir)) { if (!source.startsWith(normalizedSourceDir) || !target.startsWith(normalizedTargetDir)) {
throw new IllegalStateException("잘못된 파일 경로입니다."); throw BusinessException.badRequest("WRONG_FILE_PATH", "잘못된 파일 경로입니다.");
} }
if (!Files.exists(source)) { if (!Files.exists(source)) {
return; return;
@@ -124,7 +124,7 @@ public abstract class AbstractFileService {
Path target = normalizedDir.resolve(fileName).normalize(); Path target = normalizedDir.resolve(fileName).normalize();
if (!target.startsWith(normalizedDir)) { if (!target.startsWith(normalizedDir)) {
throw new IllegalStateException("잘못된 파일 경로입니다."); throw BusinessException.badRequest("WRONG_FILE_PATH", "잘못된 파일 경로입니다.");
} }
Files.deleteIfExists(target); Files.deleteIfExists(target);

View File

@@ -1,5 +1,6 @@
package com.kri.contact.server.service.file; package com.kri.contact.server.service.file;
import com.kri.common.feature.web.BusinessException;
import com.kri.common.feature.file.FileUtil; import com.kri.common.feature.file.FileUtil;
import com.kri.contact.server.config.FileStorageProperties; import com.kri.contact.server.config.FileStorageProperties;
import java.io.IOException; import java.io.IOException;
@@ -62,7 +63,9 @@ public class ContactScenarioFileService extends AbstractFileService {
String fileName = saveFile(getTempDir(prjctCd), file); String fileName = saveFile(getTempDir(prjctCd), file);
return publicBaseUrlPrefix + "/" + prjctCd + "/Temp/" + fileName; return publicBaseUrlPrefix + "/" + prjctCd + "/Temp/" + fileName;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("파일 저장 실패", e); var failure = BusinessException.internalError("SCENARIO_FILE_SAVE_FAILED", "파일 저장 실패");
failure.addSuppressed(e);
throw failure;
} }
} }

View File

@@ -1,5 +1,6 @@
package com.kri.contact.server.service.file; package com.kri.contact.server.service.file;
import com.kri.common.feature.web.BusinessException;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.contact.server.common.external.notihub.dto.NotiHubDestInfoDto; import com.kri.contact.server.common.external.notihub.dto.NotiHubDestInfoDto;
@@ -29,12 +30,12 @@ public class ListAsyncMessageSpool {
private Path root() throws IOException { private Path root() throws IOException {
Path path = Path.of(properties.getResultBaseDir()).toAbsolutePath().normalize().resolve("message-preparation"); Path path = Path.of(properties.getResultBaseDir()).toAbsolutePath().normalize().resolve("message-preparation");
Files.createDirectories(path); Files.createDirectories(path);
if (!path.toRealPath().equals(path)) throw new IOException("Message preparation storage must not contain symbolic links"); if (!path.toRealPath().equals(path)) throw BusinessException.internalError("UNSAFE_MESSAGE_PREPARATION_STORAGE", "Message preparation storage must not contain symbolic links");
return path; return path;
} }
public Prepared open(String jobKey) throws IOException { public Prepared open(String jobKey) throws IOException {
if (jobKey == null || !jobKey.matches("[0-9a-f]{32}")) throw new IllegalArgumentException("Invalid job key"); if (jobKey == null || !jobKey.matches("[0-9a-f]{32}")) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_JOB_KEY", "Invalid job key");
Path directory = root().resolve(jobKey); Path directory = root().resolve(jobKey);
Files.createDirectory(directory); Files.createDirectory(directory);
return new Prepared(directory); return new Prepared(directory);
@@ -51,7 +52,7 @@ public class ListAsyncMessageSpool {
} }
private void cleanup(Path directory) throws IOException { private void cleanup(Path directory) throws IOException {
if (!directory.toRealPath().getParent().equals(root())) throw new IOException("Invalid preparation directory"); if (!directory.toRealPath().getParent().equals(root())) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_DIRECTORY", "Invalid preparation directory");
try (var entries = Files.newDirectoryStream(directory)) { try (var entries = Files.newDirectoryStream(directory)) {
for (Path entry : entries) { for (Path entry : entries) {
if (entry.getFileName().toString().matches("[1-9][0-9]*\\.json(?:\\.part)?") && !Files.isSymbolicLink(entry)) { if (entry.getFileName().toString().matches("[1-9][0-9]*\\.json(?:\\.part)?") && !Files.isSymbolicLink(entry)) {
@@ -71,8 +72,8 @@ public class ListAsyncMessageSpool {
public int batches() { return batches; } public int batches() { return batches; }
public int targets() { return targets; } public int targets() { return targets; }
public void append(List<NotiHubDestInfoDto> destinations) throws IOException { public void append(List<NotiHubDestInfoDto> destinations) throws IOException {
if (closed) throw new IllegalStateException("Preparation is closed"); if (closed) throw BusinessException.internalError("MESSAGE_PREPARATION_CLOSED", "Preparation is closed");
if (destinations.isEmpty() || destinations.size() > 1000) throw new IllegalArgumentException("Invalid message batch"); if (destinations.isEmpty() || destinations.size() > 1000) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_BATCH", "Invalid message batch");
int number = batches + 1; int number = batches + 1;
Path temporary = directory.resolve(number + ".json.part"); Path temporary = directory.resolve(number + ".json.part");
mapper.writeValue(temporary.toFile(), destinations.stream().map(Destination::from).toList()); mapper.writeValue(temporary.toFile(), destinations.stream().map(Destination::from).toList());
@@ -81,8 +82,8 @@ public class ListAsyncMessageSpool {
targets = Math.addExact(targets, destinations.size()); targets = Math.addExact(targets, destinations.size());
} }
public List<NotiHubDestInfoDto> read(int number) throws IOException { public List<NotiHubDestInfoDto> read(int number) throws IOException {
if (closed) throw new IllegalStateException("Preparation is closed"); if (closed) throw BusinessException.internalError("MESSAGE_PREPARATION_CLOSED", "Preparation is closed");
if (number < 1 || number > batches) throw new IllegalArgumentException("Invalid batch number"); if (number < 1 || number > batches) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_BATCH_NUMBER", "Invalid batch number");
List<Destination> values = mapper.readValue(directory.resolve(number + ".json").toFile(), new TypeReference<>() {}); List<Destination> values = mapper.readValue(directory.resolve(number + ".json").toFile(), new TypeReference<>() {});
return values.stream().map(Destination::toRequest).toList(); return values.stream().map(Destination::toRequest).toList();
} }

View File

@@ -9,7 +9,6 @@ import java.nio.file.Files;
import java.nio.file.LinkOption; import java.nio.file.LinkOption;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileTime; import java.nio.file.attribute.FileTime;
import java.time.Clock; import java.time.Clock;
import java.time.Duration; import java.time.Duration;
@@ -55,11 +54,11 @@ public class ListAsyncResultFileService {
public ListAsyncResultFileDto create(String type, String name, FileWriter writer) throws IOException { public ListAsyncResultFileDto create(String type, String name, FileWriter writer) throws IOException {
if (type == null || type.isBlank() || name == null || name.isBlank() if (type == null || type.isBlank() || name == null || name.isBlank()
|| name.length() > 255 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0) { || name.length() > 255 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0) {
throw new IllegalArgumentException("Invalid result file metadata"); throw BusinessException.badRequest("INVALID_RESULT_FILE_METADATA", "결과 파일 정보가 올바르지 않습니다.");
} }
Files.createDirectories(root); Files.createDirectories(root);
if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) { if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) {
throw new IOException("Result storage must not contain symbolic links"); throw BusinessException.internalError("UNSAFE_RESULT_STORAGE", "결과 파일 저장소 설정이 올바르지 않습니다.");
} }
String ref = UUID.randomUUID().toString().replace("-", "") + ".result"; String ref = UUID.randomUUID().toString().replace("-", "") + ".result";
Path target = resolve(ref); Path target = resolve(ref);
@@ -71,14 +70,7 @@ public class ListAsyncResultFileService {
writer.write(output); writer.write(output);
} }
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE); Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE);
Instant completed = clock.instant(); Files.setLastModifiedTime(target, FileTime.from(clock.instant()));
BasicFileAttributeView attributes = Files.getFileAttributeView(
target, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
attributes.setTimes(null, null, FileTime.from(completed));
Instant recorded = attributes.readAttributes().creationTime().toInstant();
if (Duration.between(recorded, completed).abs().compareTo(Duration.ofSeconds(2)) > 0) {
throw new IOException("Filesystem cannot record result file completion as creation time");
}
return new ListAsyncResultFileDto(type, ref, name, Files.size(target), true); return new ListAsyncResultFileDto(type, ref, name, Files.size(target), true);
} catch (IOException | RuntimeException failure) { } catch (IOException | RuntimeException failure) {
try { try {
@@ -138,7 +130,7 @@ public class ListAsyncResultFileService {
return 0; return 0;
} }
if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) { if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) {
throw new IOException("Unsafe result storage"); throw BusinessException.internalError("UNSAFE_RESULT_STORAGE", "결과 파일 저장소 설정이 올바르지 않습니다.");
} }
int removed = 0; int removed = 0;
Instant cutoff = clock.instant().minus(RETENTION); Instant cutoff = clock.instant().minus(RETENTION);
@@ -154,7 +146,7 @@ public class ListAsyncResultFileService {
try { try {
if (safeRegularFile(file) && !Files.readAttributes(file, if (safeRegularFile(file) && !Files.readAttributes(file,
java.nio.file.attribute.BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS) java.nio.file.attribute.BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
.creationTime().toInstant().isAfter(cutoff)) { .lastModifiedTime().toInstant().isAfter(cutoff)) {
Files.deleteIfExists(file); Files.deleteIfExists(file);
removed++; removed++;
} }
@@ -174,7 +166,7 @@ public class ListAsyncResultFileService {
return; return;
} }
if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) { if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) {
throw new IOException("Unsafe result storage"); throw BusinessException.internalError("UNSAFE_RESULT_STORAGE", "결과 파일 저장소 설정이 올바르지 않습니다.");
} }
try (var paths = Files.list(root)) { try (var paths = Files.list(root)) {
var iterator = paths.filter(path -> path.getFileName().toString() var iterator = paths.filter(path -> path.getFileName().toString()

View File

@@ -79,7 +79,7 @@ public class ListFileService extends AbstractFileService {
public void deleteOnRegistrationRollback(Long projectId, String fileName) { public void deleteOnRegistrationRollback(Long projectId, String fileName) {
if (!TransactionSynchronizationManager.isActualTransactionActive()) { if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("Source registration requires an active transaction"); throw BusinessException.internalError("SOURCE_REGISTER_TRANSACTION_REQUIRED", "Source registration requires an active transaction");
} }
TransactionSynchronizationManager.registerSynchronization( TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() { new TransactionSynchronization() {

View File

@@ -92,7 +92,7 @@ public class ListItemFileService extends AbstractFileService {
public void deleteItemFileAfterCommit(String filePath, String fileName) { public void deleteItemFileAfterCommit(String filePath, String fileName) {
if (!TransactionSynchronizationManager.isActualTransactionActive() if (!TransactionSynchronizationManager.isActualTransactionActive()
|| !TransactionSynchronizationManager.isSynchronizationActive()) { || !TransactionSynchronizationManager.isSynchronizationActive()) {
throw new IllegalStateException("File deletion requires an active transaction"); throw BusinessException.internalError("FILE_DELETE_TRANSACTION_REQUIRED", "File deletion requires an active transaction");
} }
TransactionSynchronizationManager.registerSynchronization( TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() { new TransactionSynchronization() {