Skip to content
Open
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
4 changes: 3 additions & 1 deletion src/main/java/com/ttuk/global/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ public enum ErrorCode {
INVALID_IMAGE(HttpStatus.BAD_REQUEST, "이미지는 1~5장, 장당 5MB 이하의 jpg·png·webp 파일만 등록할 수 있습니다."),
GROUP_PURCHASE_NOT_FOUND(HttpStatus.NOT_FOUND, "공동구매를 찾을 수 없습니다."),

GROUP_PURCHASE_NOT_OPEN(HttpStatus.CONFLICT, "참여할 수 없는 상태의 공동구매입니다."),
GROUP_PURCHASE_NOT_OPEN(HttpStatus.CONFLICT, "진행 중인 공동구매가 아닙니다."),
GROUP_PURCHASE_FULL(HttpStatus.CONFLICT, "정원이 마감된 공동구매입니다."),
ALREADY_JOINED(HttpStatus.CONFLICT, "이미 참여한 공동구매입니다."),

NOT_JOINED(HttpStatus.NOT_FOUND, "참여하지 않은 공동구매입니다."),
CANCEL_DEADLINE_PASSED(HttpStatus.CONFLICT, "취소 가능 시간이 지났습니다."),

NOT_GROUP_PURCHASE_OWNER(HttpStatus.FORBIDDEN, "본인이 등록한 공동구매가 아닙니다."),

;

private final HttpStatus status;
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/ttuk/grouppurchase/GroupPurchase.java
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,8 @@ public LocalDateTime cancelDeadline(){
public DiscountPolicy discountPolicy() {
return new DiscountPolicy(basePrice, floorPrice, discountType, discountValue, discountStepSize);
}

public boolean isSoldBy(Long memberId){
return seller.getId().equals(memberId);
}
}
12 changes: 12 additions & 0 deletions src/main/java/com/ttuk/grouppurchase/GroupPurchaseController.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,16 @@ public ResponseEntity<ApiResponse<GroupPurchaseDetailResponse>> detail(@PathVari
return ResponseEntity.ok(ApiResponse.success(groupPurchaseQueryService.findDetail(groupPurchaseId, loginMember.memberId())));
}

@PostMapping("/{groupPurchaseId}/cancel")
@RequireRole(MemberRole.SELLER)
public ResponseEntity<ApiResponse<GroupPurchaseCancelResponse>> cancel(
@PathVariable Long groupPurchaseId,
@Login LoginMember loginMember,
@Valid @RequestBody GroupPurchaseCancelRequest request) {

GroupPurchaseCancelResponse response =
groupPurchaseService.cancel(loginMember.memberId(), groupPurchaseId, request);
return ResponseEntity.ok(ApiResponse.success(response));

}
}
19 changes: 19 additions & 0 deletions src/main/java/com/ttuk/grouppurchase/GroupPurchaseRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,23 @@ int closeOpen(@Param("groupPurchaseId") Long groupPurchaseId,
""")
List<Long> findSettlementTargetIds(@Param("threshold") LocalDateTime threshold, Limit limit);

@Transactional
@Modifying
@Query("""
update GroupPurchase g
set g.status = com.ttuk.grouppurchase.GroupPurchaseStatus.CANCELED,
g.cancelReason = :reason,
g.canceledAt = :now,
g.finalHeadcount = :finalHeadcount,
g.finalPrice = :finalPrice,
g.updatedAt = :now
where g.id = :groupPurchaseId
and g.status = com.ttuk.grouppurchase.GroupPurchaseStatus.OPEN
""")
int cancelOpen(@Param("groupPurchaseId") Long groupPurchaseId,
@Param("reason") String reason,
@Param("finalHeadcount") int finalHeadcount,
@Param("finalPrice") int finalPrice,
@Param("now") LocalDateTime now);

}
106 changes: 106 additions & 0 deletions src/main/java/com/ttuk/grouppurchase/GroupPurchaseService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand All @@ -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) {
Expand All @@ -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);
}

Copy link
Copy Markdown

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 조건이 없다면요?

Copy link
Copy Markdown
Collaborator Author

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는 행에 잠금을 걸고 최신 값으로 다시 판단하기 때문에 먼저 실행된 한 요청만 반영되도록 하는 최종 방어선이고, 미리 확인은 그 앞에서 빠르게 거절하는 역할로 둘 다 두었습니다.


LocalDateTime now = LocalDateTime.now(clock);

GroupPurchaseCancelResult result = groupPurchaseRedisRepository.cancelGroupPurchase(groupPurchaseId);
if(result.outcome() == GroupPurchaseCancelOutcome.NOT_INITIALIZED){
result = initializeAndRetryCancel(groupPurchase, now);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Redis 키가 없으면 DB 만 CANCELED 로 바꾸는 게 더 간단해요. 굳이 Redis 를 초기화한 뒤 취소하는 이유는 뭔가요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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를 확인하지 않고 계속 참여를 받게 됩니다.
초기화 Lua는 meta가 이미 있으면 아무것도 하지 않고, 참여 Lua와 취소 Lua는 Redis에서 하나씩 순서대로 실행되기 때문에, 초기화한 뒤 Redis에서 취소하면 취소가 먼저면 이후 참여가 거절되고, 참여가 먼저면 참여자로 들어간 뒤 취소되어 알림 대상에 포함됩니다. 어느 쪽이든 취소 뒤에 참여가 성공하는 순서는 생기지 않아서, 명세에서도 Redis를 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 {
Expand Down Expand Up @@ -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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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으로 끝내면 어떨까요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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이 됩니다.
그래서 0행일 때는 reopen하지 않도록 고치겠습니다. reopen은 cancelOpen이 예외로 실패해 DB가 OPEN으로 남은 경우에만 합니다. 응답은 200 대신 409로 두려고 합니다. 이미 취소된 공동구매에 다시 요청하면 메서드 시작의 상태 확인에서 409가 나가고, ALREADY_CANCELED 경로도 0행이면 409라서, 0행일 때도 409로 맞춰야 같은 "이미 취소됨" 상황에 타이밍과 상관없이 같은 응답이 나갑니다. 200으로 맞추려면 앞의 확인까지 바꿔야 하는데, 그때 응답의 알림 대상 수는 DB에 저장된 값이 없어 정확히 돌려줄 수 없다고 판단했습니다.

}

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

) {
}
Loading
Loading