Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
@Profile("admin")
public class HandleLogFeatureUseCase {

private static final ZoneId BASE_DATE_ZONE = ZoneId.of("Asia/Seoul");

private final CalculateLogChurnScoreService calculateLogChurnScoreService;

/**
Expand Down Expand Up @@ -58,7 +60,7 @@ private long resolveEventId(LogFeatureWebhookRequest request) {
private LocalDate resolveBaseDate(Instant timestamp) {
return Optional.ofNullable(timestamp)
.orElseGet(Instant::now)
.atZone(ZoneId.of("Asia/Seoul"))
.atZone(BASE_DATE_ZONE)
.toLocalDate();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
import org.springframework.core.task.TaskRejectedException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import site.holliverse.customer.persistence.entity.UserLogAdminDispatchOutbox;
import site.holliverse.customer.persistence.entity.UserLogDispatchStatus;
import site.holliverse.customer.persistence.repository.UserLogAdminDispatchOutboxRepository;
import site.holliverse.customer.web.dto.log.UserLogRequest;
import site.holliverse.shared.monitoring.CustomerMetrics;

Expand All @@ -31,7 +29,6 @@ public class UserLogAdminDispatchOutboxService {
private final ObjectMapper objectMapper;
private final CustomerMetrics customerMetrics;

@Transactional
public void enqueueBatch(Long memberId, List<UserLogRequest> requests) {
if (requests == null || requests.isEmpty()) {
return;
Expand Down Expand Up @@ -62,17 +59,15 @@ public void enqueueBatch(Long memberId, List<UserLogRequest> requests) {
}

try {
repository.saveAll(rows);
rows.forEach(ignored -> customerMetrics.recordAdminLogFeatureOutbox("stored"));
stateService.storeBatch(rows);
} catch (DataIntegrityViolationException e) {
log.warn("[UserLog][Outbox] batch store fallback. size={}", rows.size(), e);
rows.forEach(this::storeRow);
rows.forEach(stateService::store);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

🛑 Blocking Issue: Fallback 로직의 예외 전파 차단

  • [문제 이유]: stateService.store(row) 호출 시 발생하는 예외(특히 UnexpectedRollbackException)가 forEach 루프 내부에서 처리되지 않습니다. 중복 데이터 등으로 인해 한 건이라도 실패하면 전체 루프가 중단되고 나머지 로그들이 저장되지 못합니다.
  • [해결 제안]: 루프 내부에서 개별적으로 예외를 처리하여 실패한 건을 제외한 나머지 데이터는 정상적으로 저장될 수 있도록 보장해야 합니다.
            rows.forEach(row -> {
                try {
                    stateService.store(row);
                } catch (Exception e) {
                    log.warn("[UserLog][Outbox] individual store failed. event_id={}", row.getEventId());
                }
            });

}
}

@Transactional
public void enqueue(Long eventId, Long memberId, UserLogEventName eventName, UserLogRequest request) {
storeRow(buildOutboxRow(eventId, memberId, eventName, request));
stateService.store(buildOutboxRow(eventId, memberId, eventName, request));
}

public void dispatchReadyBatch(int batchSize) {
Expand Down Expand Up @@ -115,21 +110,6 @@ private UserLogAdminDispatchOutbox buildOutboxRow(
.build();
}

private void storeRow(UserLogAdminDispatchOutbox row) {
try {
repository.save(row);
customerMetrics.recordAdminLogFeatureOutbox("stored");
} catch (DataIntegrityViolationException e) {
customerMetrics.recordAdminLogFeatureOutbox("duplicate");
log.debug("[UserLog][Outbox] duplicate event_id={} memberId={} eventName={}",
row.getEventId(), row.getMemberId(), row.getEventName());
} catch (Exception e) {
customerMetrics.recordAdminLogFeatureOutbox("store_error");
log.warn("[UserLog][Outbox] store failed event_id={} memberId={} eventName={}",
row.getEventId(), row.getMemberId(), row.getEventName(), e);
}
}

private boolean isAdminTarget(UserLogEventName eventName) {
return eventName == UserLogEventName.CLICK_COMPARE
|| eventName == UserLogEventName.CLICK_PENALTY
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package site.holliverse.customer.application.usecase.log;

import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -14,6 +16,7 @@
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@Profile("customer")
@RequiredArgsConstructor
Expand All @@ -28,6 +31,28 @@ public class UserLogAdminDispatchOutboxStateService {
@Value("${app.userlog.admin-dispatch.max-attempts:5}")
private int maxAttempts;

@Transactional(propagation = Propagation.REQUIRES_NEW)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

🛡️ Code Review Report

1. 🔍 요약

Outbox 패턴의 트랜잭션 원자성 보장 및 예외 처리 방식에 대한 개선이 필요합니다. 특히 REQUIRES_NEW 사용으로 인한 데이터 불일치 가능성과 트랜잭션 내 예외 처리 시 발생하는 UnexpectedRollbackException 문제를 해결해야 합니다.

2. 🛑 Blocking Issues (Must Fix)

  • [위반 규칙]: Application Layer Transaction Boundaries (Style Guide Line 43)
  • [문제 이유]: Propagation.REQUIRES_NEW를 사용하면 비즈니스 트랜잭션이 롤백되더라도 로그 저장 트랜잭션은 독립적으로 커밋됩니다. 이는 실제 수행되지 않은 작업에 대한 로그가 Admin 서비스로 전송되는 결과를 초래하여 데이터 정합성을 깨뜨립니다.
  • [해결 제안]: 기본 전파 속성인 REQUIRED를 사용하여 비즈니스 트랜잭션과 원자성을 유지하도록 수정하세요.
Suggested change
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Transactional
References
  1. Application Layer (UseCase) handles transaction boundaries. @transactional is allowed here. (link)

public void storeBatch(List<UserLogAdminDispatchOutbox> rows) {
repository.saveAllAndFlush(rows);
rows.forEach(ignored -> customerMetrics.recordAdminLogFeatureOutbox("stored"));
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void store(UserLogAdminDispatchOutbox row) {
try {
repository.saveAndFlush(row);
customerMetrics.recordAdminLogFeatureOutbox("stored");
} catch (DataIntegrityViolationException e) {
customerMetrics.recordAdminLogFeatureOutbox("duplicate");
log.debug("[UserLog][Outbox] duplicate event_id={} memberId={} eventName={}",
row.getEventId(), row.getMemberId(), row.getEventName());
} catch (Exception e) {
customerMetrics.recordAdminLogFeatureOutbox("store_error");
log.warn("[UserLog][Outbox] store failed event_id={} memberId={} eventName={}",
row.getEventId(), row.getMemberId(), row.getEventName(), e);
}
}
Comment on lines +40 to +54
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

🛑 Blocking Issue: 트랜잭션 내 예외 처리 및 UnexpectedRollbackException

  • [문제 이유]: @Transactional 메서드 내부에서 런타임 예외(DataIntegrityViolationException)를 catch하고 다시 던지지 않으면, 트랜잭션은 이미 rollback-only로 마킹된 상태에서 커밋을 시도하게 되어 UnexpectedRollbackException이 발생합니다. 이로 인해 호출부의 fallback 로직(forEach)이 첫 번째 실패 건에서 중단되어 나머지 데이터 처리가 불가능해집니다.
  • [해결 제안]: store 메서드 내부의 try-catch를 제거하고, 예외 처리를 트랜잭션 경계 밖인 UserLogAdminDispatchOutboxService로 이동시키세요.
    @Transactional
    public void store(UserLogAdminDispatchOutbox row) {
        repository.saveAndFlush(row);
        customerMetrics.recordAdminLogFeatureOutbox("stored");
    }


@Transactional
public List<Long> claimReadyBatch(int batchSize) {
List<Long> ids = repository.findReadyEventIdsForUpdate(batchSize);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class UserLogAdminDispatchOutbox extends BaseEntity {
private JsonNode payload;

@Enumerated(EnumType.STRING)
@JdbcTypeCode(SqlTypes.NAMED_ENUM)
@Column(name = "status", nullable = false, length = 20)
private UserLogDispatchStatus status;

Expand Down
Loading