Repository navigation
#50 판매자 공동구매 취소 API #52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: feature/49
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,12 +6,18 @@ | |
| import com.ttuk.global.error.ErrorCode; | ||
| import com.ttuk.global.storage.S3ImageStorage; | ||
| import com.ttuk.grouppurchase.GroupPurchaseImageValidator.ValidatedImage; | ||
| import com.ttuk.grouppurchase.dto.GroupPurchaseCancelRequest; | ||
| import com.ttuk.grouppurchase.dto.GroupPurchaseCancelResponse; | ||
| import com.ttuk.grouppurchase.dto.GroupPurchaseCreateRequest; | ||
| import com.ttuk.grouppurchase.dto.GroupPurchaseCreateResponse; | ||
| import com.ttuk.grouppurchase.event.GroupPurchaseCreatedEvent; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseCancelOutcome; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseCancelResult; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseRedisRepository; | ||
| import com.ttuk.member.Member; | ||
| import com.ttuk.member.MemberRepository; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.context.ApplicationEventPublisher; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.support.TransactionTemplate; | ||
|
|
@@ -22,7 +28,9 @@ | |
| import java.time.Clock; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class GroupPurchaseService { | ||
|
|
@@ -39,6 +47,7 @@ public class GroupPurchaseService { | |
| private final TransactionTemplate transactionTemplate; | ||
| private final ApplicationEventPublisher eventPublisher; | ||
| private final Clock clock; | ||
| private final GroupPurchaseRedisRepository groupPurchaseRedisRepository; | ||
|
|
||
| public GroupPurchaseCreateResponse create(Long sellerId, GroupPurchaseCreateRequest request, | ||
| List<MultipartFile> images) { | ||
|
|
@@ -58,6 +67,41 @@ public GroupPurchaseCreateResponse create(Long sellerId, GroupPurchaseCreateRequ | |
| } | ||
| } | ||
|
|
||
| public GroupPurchaseCancelResponse cancel(Long sellerId, Long groupPurchaseId, GroupPurchaseCancelRequest request) { | ||
|
|
||
| Optional<GroupPurchase> found = groupPurchaseRepository.findById(groupPurchaseId); | ||
| if(found.isEmpty()){ | ||
| throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_FOUND); | ||
| } | ||
|
|
||
| GroupPurchase groupPurchase = found.get(); | ||
| if(!groupPurchase.isSoldBy(sellerId)){ | ||
| throw new BusinessException(ErrorCode.NOT_GROUP_PURCHASE_OWNER); | ||
| } | ||
|
|
||
| if(groupPurchase.getStatus() != GroupPurchaseStatus.OPEN){ | ||
| throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| } | ||
|
|
||
| LocalDateTime now = LocalDateTime.now(clock); | ||
|
|
||
| GroupPurchaseCancelResult result = groupPurchaseRedisRepository.cancelGroupPurchase(groupPurchaseId); | ||
| if(result.outcome() == GroupPurchaseCancelOutcome.NOT_INITIALIZED){ | ||
| result = initializeAndRetryCancel(groupPurchase, now); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Redis 키가 없으면 DB 만 CANCELED 로 바꾸는 게 더 간단해요. 굳이 Redis 를 초기화한 뒤 취소하는 이유는 뭔가요?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Redis 키가 있으면 참여 Lua는 DB를 보지 않고 Redis status만 보고 참여를 판단하기 때문에, 키가 없을 때도 취소는 Redis를 먼저 바꾸도록 했습니다. DB만 CANCELED로 바꾸면, 거의 같은 시점에 참여 요청이 lazy init 경로에서 DB를 OPEN으로 읽고 Redis를 OPEN으로 초기화한 뒤 참여에 성공할 수 있습니다. 그러면 DB는 CANCELED인데 Redis는 OPEN이 되고, 이후 참여 요청은 meta가 있어 lazy init을 타지 않으므로 DB를 확인하지 않고 계속 참여를 받게 됩니다. |
||
| } | ||
|
|
||
| return switch (result.outcome()) { | ||
| case CANCELED -> saveCanceled(groupPurchaseId, request.reason(), result, now); | ||
| case ALREADY_CANCELED -> finishPendingCancel(groupPurchaseId, request.reason(), result, now); | ||
| case NOT_OPEN -> throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| case INVALID_STATE -> throw new IllegalStateException( | ||
| "Redis 인원·단가 값이 올바르지 않습니다. groupPurchaseId=" + groupPurchaseId); | ||
| case NOT_INITIALIZED -> throw new IllegalStateException( | ||
| "초기화 후에도 Redis 키가 없습니다. groupPurchaseId=" + groupPurchaseId); | ||
| }; | ||
|
|
||
| } | ||
|
|
||
| private List<String> uploadImages(List<ValidatedImage> images) { | ||
| List<String> keys = new ArrayList<>(images.size()); | ||
| try { | ||
|
|
@@ -123,4 +167,66 @@ private void validateCloseAt(LocalDateTime closeAt) { | |
| throw new BusinessException(ErrorCode.INVALID_CLOSE_AT); | ||
| } | ||
| } | ||
|
|
||
| private GroupPurchaseCancelResult initializeAndRetryCancel(GroupPurchase groupPurchase, LocalDateTime now){ | ||
|
|
||
| if(!groupPurchase.isJoinableAt(now)){ | ||
| throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| } | ||
|
|
||
| groupPurchaseRedisRepository.initialize(groupPurchase); | ||
| return groupPurchaseRedisRepository.cancelGroupPurchase(groupPurchase.getId()); | ||
|
|
||
| } | ||
|
|
||
| private GroupPurchaseCancelResponse saveCanceled(Long groupPurchaseId, String reason, GroupPurchaseCancelResult result, LocalDateTime now) { | ||
|
|
||
| int updated; | ||
|
|
||
| try { | ||
| updated = groupPurchaseRepository.cancelOpen(groupPurchaseId, reason, result.headcount(), result.price(), now); | ||
| } catch (RuntimeException e) { | ||
| reopenRedis(groupPurchaseId, e); | ||
| throw e; | ||
| } | ||
|
|
||
| if(updated == 0){ | ||
| BusinessException notOpen = new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| log.warn("판매자 취소: Redis는 OPEN이었는데 DB가 OPEN이 아님. groupPurchaseId={}", groupPurchaseId); | ||
| reopenRedis(groupPurchaseId, notOpen); | ||
| throw notOpen; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. PR 본문은 연타 문제가 "DB 실패"가 있을 때만 생긴다고 했는데, 실패 없이 순서만으로도 생겨요. 요청1 Lua CANCELED → 요청2 Lua ALREADY_CANCELED → 요청2 DB UPDATE 1행(200) → 요청1 DB UPDATE 0행 → 여기서 reopen. 결과적으로 DB 는 CANCELED, Redis 는 OPEN 이 돼요. 0행이면 reopen 하기 전에 DB 상태를 다시 조회해서, CANCELED 면 되돌리지 말고 200으로 끝내면 어떨까요?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 확인해 보니 말씀해 주신 대로 DB 실패 없이 순서만으로도 생기고, PR 본문의 설명이 틀렸습니다. cancelOpen은 WHERE status = 'OPEN'이라 0행이면 그 순간 DB가 이미 OPEN이 아니라는 뜻인데, 지금 코드는 0행을 DB 실패로 보고 reopen해서 DB는 CANCELED, Redis는 OPEN이 됩니다. |
||
| } | ||
|
|
||
| return cancelResponse(groupPurchaseId, reason, result, now); | ||
|
|
||
| } | ||
|
|
||
| private GroupPurchaseCancelResponse finishPendingCancel(Long groupPurchaseId, String reason, GroupPurchaseCancelResult result, LocalDateTime now) { | ||
|
|
||
| if(groupPurchaseRepository.cancelOpen(groupPurchaseId, reason, result.headcount(), result.price(), now) == 0){ | ||
| throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| } | ||
| log.info("판매자 취소: Redis에서 이미 취소된 공동구매의 DB 기록을 마무리함. groupPurchaseId={}", groupPurchaseId); | ||
| return cancelResponse(groupPurchaseId, reason, result, now); | ||
|
|
||
| } | ||
|
|
||
| private void reopenRedis(Long groupPurchaseId, RuntimeException cause){ | ||
|
|
||
| try { | ||
| if(!groupPurchaseRedisRepository.reopenGroupPurchase(groupPurchaseId)){ | ||
| log.warn("판매자 취소 보상: 되돌릴 CANCELED 상태가 없음. groupPurchaseId={}", groupPurchaseId); | ||
| } | ||
| } catch (RuntimeException reopenFailure){ | ||
| cause.addSuppressed(reopenFailure); | ||
| log.error("판매자 취소 보상 실패: Redis는 CANCELED, DB는 OPEN. 판매자가 다시 요청하면 마무리됨. groupPurchaseId={}", groupPurchaseId, reopenFailure); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| private GroupPurchaseCancelResponse cancelResponse(Long groupPurchaseId, String reason, GroupPurchaseCancelResult result, LocalDateTime now) { | ||
|
|
||
| return new GroupPurchaseCancelResponse(groupPurchaseId, GroupPurchaseStatus.CANCELED, reason, now, result.participantCount()); | ||
|
|
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.ttuk.grouppurchase.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
| import jakarta.validation.constraints.Size; | ||
|
|
||
| public record GroupPurchaseCancelRequest( | ||
|
|
||
| @NotBlank | ||
| @Size(max = 200) | ||
| String reason | ||
|
|
||
| ) { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.ttuk.grouppurchase.dto; | ||
|
|
||
| import com.ttuk.grouppurchase.GroupPurchaseStatus; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| public record GroupPurchaseCancelResponse ( | ||
|
|
||
| Long groupPurchaseId, | ||
| GroupPurchaseStatus status, | ||
| String cancelReason, | ||
| LocalDateTime canceledAt, | ||
| int notifiedCount | ||
|
|
||
| ) { | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
나중에 cancelOpen 이 어차피 WHERE status = 'OPEN' 으로 다시 확인하는데, 여기서 미리 확인하는 이유는 뭔가요? 이 확인만 있고 WHERE 조건이 없다면요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
미리 확인하는 건 이미 취소되거나 정산된 공동구매를 Redis에 손대기 전에 바로 409로 거절하기 위해서입니다. 이 확인이 없으면 DB가 이미 끝난 상태여도 Redis 취소 Lua나 lazy init까지 진행하고, Redis가 OPEN으로 남아 있던 경우에는 Lua가 Redis를 CANCELED로 바꾼 뒤 cancelOpen이 0행이 되어 reopen으로 되돌리는 불필요한 쓰기와 보상이 생깁니다.
다만 미리 확인은 잠금 없이 읽은 값이라, 읽은 뒤 UPDATE 전에 다른 요청이 끼어드는 것은 막지 못합니다. WHERE 조건 없이 이 확인만 있다면 판매자가 취소를 두 번 눌렀을 때 두 요청이 모두 OPEN을 읽고 둘 다 UPDATE에 성공해, 취소 사유와 시각, 최종 인원·단가가 나중 요청 값으로 덮어써지고 나중에 취소 알림을 붙이면 두 번 나가게 됩니다. 그 사이 정산이 먼저 끝났다면 CLOSED를 CANCELED로 덮어쓸 수도 있습니다. WHERE status = 'OPEN' 조건부 UPDATE는 행에 잠금을 걸고 최신 값으로 다시 판단하기 때문에 먼저 실행된 한 요청만 반영되도록 하는 최종 방어선이고, 미리 확인은 그 앞에서 빠르게 거절하는 역할로 둘 다 두었습니다.