Repository navigation
#42 공동구매 참여 취소 API 구현 #44
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/41
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 |
|---|---|---|
| @@ -1,6 +1,27 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
| import org.springframework.data.jpa.repository.Modifying; | ||
| import org.springframework.data.jpa.repository.Query; | ||
| import org.springframework.data.repository.query.Param; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| public interface ParticipationRepository extends JpaRepository<Participation, Long> { | ||
|
|
||
| @Transactional | ||
| @Modifying | ||
| @Query(""" | ||
| update Participation p | ||
| set p.status = com.ttuk.participation.ParticipationStatus.CANCELED, | ||
| p.canceledAt = :now, | ||
| p.updatedAt = :now | ||
| where p.groupPurchase.id = :groupPurchaseId | ||
| and p.member.id = :memberId | ||
| and p.status = com.ttuk.participation.ParticipationStatus.JOINED | ||
| """) | ||
|
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. 조회한 뒤 if 로 확인하고 UPDATE 하는 방식과, where 절에 조건을 넣고 바뀐 행 수를 보는 방식은 동시 요청에서 무엇이 다른가요?
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. 조회 후 if로 확인하고 UPDATE하면 확인과 변경이 두 단계로 나뉘어, 같은 취소 요청 두 개가 동시에 오면 InnoDB의 일반 SELECT는 잠금 없이 커밋된 스냅샷을 읽기 때문에 둘 다 JOINED를 보고 통과합니다. 그러면 실제 취소는 한 번인데 두 요청 모두 성공으로 처리되고, canceled_at이 덮어써지거나 취소에 딸린 후속 처리가 두 번 실행될 수 있습니다. |
||
| int cancelJoined(@Param("groupPurchaseId") Long groupPurchaseId, | ||
| @Param("memberId") Long memberId, | ||
| @Param("now") LocalDateTime now); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,8 @@ | |
| import com.ttuk.global.error.ErrorCode; | ||
| import com.ttuk.grouppurchase.GroupPurchase; | ||
| import com.ttuk.grouppurchase.GroupPurchaseRepository; | ||
| import com.ttuk.grouppurchase.GroupPurchaseStatus; | ||
| import com.ttuk.grouppurchase.redis.CancelResult; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseRedisRepository; | ||
| import com.ttuk.grouppurchase.redis.JoinOutcome; | ||
| import com.ttuk.grouppurchase.redis.JoinResult; | ||
|
|
@@ -45,6 +47,49 @@ public ParticipationCreateResponse join(Long groupPurchaseId, Long memberId, int | |
| }; | ||
| } | ||
|
|
||
| public void cancel(Long groupPurchaseId, Long memberId) { | ||
| LocalDateTime now = LocalDateTime.now(clock); | ||
| CancelResult result = groupPurchaseRedisRepository.cancel( | ||
| groupPurchaseId, memberId, now, GroupPurchase.CANCELABLE_BEFORE_CLOSE); | ||
|
|
||
| switch (result.outcome()) { | ||
| case CANCELED -> cancelJoinedParticipation(groupPurchaseId, memberId, now); | ||
| case NOT_JOINED -> finishPendingCancel(groupPurchaseId, memberId, 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. 참여(join)는 DB 저장이 실패하면 Redis 를 되돌렸는데, 취소는 되돌리지 않고 재요청 때 DB 를 마무리해요. 두 방식의 차이는 뭔가요?
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. 참여는 실패한 요청이 정원 자리를 붙잡고 있으면 안 되기 때문에 되돌리고, 취소는 되돌리면 오히려 정원이 틀어질 수 있어 마저 끝내는 쪽을 택했습니다. |
||
| case NOT_INITIALIZED -> cancelWithoutRedis(groupPurchaseId, memberId, now); | ||
| case NOT_OPEN -> throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| case DEADLINE_PASSED -> throw new BusinessException(ErrorCode.CANCEL_DEADLINE_PASSED); | ||
| case INVALID_HEADCOUNT -> throw new IllegalStateException("Redis 참여 인원 값이 올바르지 않습니다. groupPurchaseId=" + groupPurchaseId); | ||
| } | ||
| } | ||
|
|
||
| private void cancelJoinedParticipation(Long groupPurchaseId, Long memberId, LocalDateTime 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 INSERT 가 아직 안 끝났을 때 취소가 들어오면 여기로 와요. 그 뒤에 INSERT 가 끝나면 DB 에 JOINED 가 남아요. 재요청하면 마무리되긴 하지만, 이런 경우가 있다는 걸 로그 문구에 적어두면 나중에 찾기 쉬울 것 같아요.
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. 말씀해 주신 대로 참여 Lua는 성공했지만 참여 DB 저장이 끝나기 전에 취소가 들어오면, 취소 UPDATE는 아직 JOINED 행이 없어 0행이 되고 이후 저장이 끝나면 DB에 JOINED가 남습니다. 취소를 다시 요청하면 Lua가 참여 중 아님을 돌려줘 DB가 마무리되고, 재요청이 없더라도 정산 때 대조로 정리되지만, 지금 로그 문구만으로는 이런 상황인지 알기 어렵네요. 로그에 참여 저장 전에 취소가 들어온 경우일 수 있고 재요청이나 정산 대조로 정리된다는 내용을 적고, 코드에도 이 순서를 주석으로 남기겠습니다. |
||
| if (participationRepository.cancelJoined(groupPurchaseId, memberId, now) == 0) { | ||
| log.warn("참여 취소: Redis에서는 취소됐지만 DB에 JOINED 참여가 없음. groupPurchaseId={}, memberId={}", groupPurchaseId, memberId); | ||
| } | ||
| } | ||
|
|
||
| private void finishPendingCancel(Long groupPurchaseId, Long memberId, LocalDateTime 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. NOT_JOINED 경로는 기한·상태를 확인하지 않고 DB 를 취소해요. 그런데 지금 lazy init 은 참여자 Set 을 비운 채로 초기화해요. 그러면 Redis 가 날아간 뒤 기존 참여자는 모두 NOT_JOINED 로 빠져요. 마감이 지나도, 정원이 차서 CLOSED 여도 DB 취소가 되고, Redis 인원은 줄지 않아요. lazy init 이 DB 참여자로 Set 을 채우게 고치는 게 먼저일 것 같아요.
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. 말씀해 주신 대로 NOT_JOINED 경로는 "참여자 Set에 없으면 Redis에서는 이미 취소가 끝났다"는 전제로 기한과 상태를 다시 확인하지 않는데, 지금 lazy init은 참여자 Set을 비운 채로 초기화해서 Redis가 사라진 뒤에는 기존 참여자 모두가 이 경로로 빠집니다. 그러면 마감이 지났거나 CLOSED여도 DB 취소가 되고, Redis 인원은 줄지 않아 다시 어긋나게 됩니다. |
||
| if (participationRepository.cancelJoined(groupPurchaseId, memberId, now) == 0) { | ||
| throw new BusinessException(ErrorCode.NOT_JOINED); | ||
| } | ||
| log.info("참여 취소: Redis에서 이미 빠진 참여의 DB 기록을 마무리함. groupPurchaseId={}, memberId={}", groupPurchaseId, memberId); | ||
| } | ||
|
|
||
| private void cancelWithoutRedis(Long groupPurchaseId, Long memberId, LocalDateTime now) { | ||
| Optional<GroupPurchase> found = groupPurchaseRepository.findById(groupPurchaseId); | ||
| if (found.isEmpty()) { | ||
| throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_FOUND); | ||
| } | ||
| GroupPurchase groupPurchase = found.get(); | ||
| if (groupPurchase.getStatus() != GroupPurchaseStatus.OPEN) { | ||
| throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| } | ||
| if (!now.isBefore(groupPurchase.cancelDeadline())) { | ||
| throw new BusinessException(ErrorCode.CANCEL_DEADLINE_PASSED); | ||
| } | ||
| finishPendingCancel(groupPurchaseId, memberId, now); | ||
| } | ||
|
|
||
| private JoinResult initializeAndRetry(Long groupPurchaseId, Long memberId) { | ||
| Optional<GroupPurchase> found = groupPurchaseRepository.findById(groupPurchaseId); | ||
| if (found.isEmpty()) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| import com.ttuk.category.Category; | ||
| import com.ttuk.category.CategoryRepository; | ||
| import com.ttuk.grouppurchase.DiscountType; | ||
| import com.ttuk.grouppurchase.GroupPurchase; | ||
| import com.ttuk.grouppurchase.GroupPurchaseRepository; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseRedisKeys; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseRedisRepository; | ||
| import com.ttuk.member.Member; | ||
| import com.ttuk.member.MemberRepository; | ||
| import com.ttuk.member.MemberRole; | ||
| import com.ttuk.support.TestcontainersConfig; | ||
| import jakarta.servlet.http.Cookie; | ||
| import org.junit.jupiter.api.AfterEach; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.boot.test.context.SpringBootTest; | ||
| import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; | ||
| import org.springframework.context.annotation.Import; | ||
| import org.springframework.data.redis.core.StringRedisTemplate; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.jdbc.core.JdbcTemplate; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.test.web.servlet.MockMvc; | ||
| import org.springframework.test.web.servlet.ResultActions; | ||
|
|
||
| import java.time.Clock; | ||
| import java.time.LocalDateTime; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; | ||
| import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; | ||
| import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; | ||
| import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | ||
|
|
||
| @SpringBootTest | ||
| @AutoConfigureMockMvc | ||
| @Import(TestcontainersConfig.class) | ||
| class ParticipationCancelIntegrationTest { | ||
|
|
||
| private static final String PASSWORD = "a123456789"; | ||
| private static final long FRESH_FOOD_ID = 1L; | ||
|
|
||
| @Autowired | ||
| MockMvc mockMvc; | ||
| @Autowired | ||
| MemberRepository memberRepository; | ||
| @Autowired | ||
| CategoryRepository categoryRepository; | ||
| @Autowired | ||
| GroupPurchaseRepository groupPurchaseRepository; | ||
| @Autowired | ||
| ParticipationRepository participationRepository; | ||
| @Autowired | ||
| ParticipationService participationService; | ||
| @Autowired | ||
| GroupPurchaseRedisRepository groupPurchaseRedisRepository; | ||
| @Autowired | ||
| StringRedisTemplate redisTemplate; | ||
| @Autowired | ||
| JdbcTemplate jdbcTemplate; | ||
| @Autowired | ||
| PasswordEncoder passwordEncoder; | ||
| @Autowired | ||
| Clock clock; | ||
|
|
||
| private Member seller; | ||
| private Member buyer; | ||
| private Cookie sellerCookie; | ||
| private Cookie buyerCookie; | ||
|
|
||
| @BeforeEach | ||
| void setUp() throws Exception { | ||
| seller = memberRepository.save(member("seller@ttuk.kr", "진도농장", MemberRole.SELLER, "01011112222")); | ||
| buyer = memberRepository.save(member("buyer@ttuk.kr", "구매자", MemberRole.BUYER, "01033334444")); | ||
| sellerCookie = loginAndGetCookie("seller@ttuk.kr"); | ||
| buyerCookie = loginAndGetCookie("buyer@ttuk.kr"); | ||
| } | ||
|
|
||
| @AfterEach | ||
| void cleanUp() { | ||
| Set<String> keys = redisTemplate.keys("group_purchase:*"); | ||
| redisTemplate.delete(keys); | ||
| participationRepository.deleteAll(); | ||
| groupPurchaseRepository.deleteAll(); | ||
| memberRepository.deleteAll(); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("참여를 취소하면 204이고, DB 참여는 CANCELED·취소 시각이 기록되며 Redis 인원이 줄어든다") | ||
| void cancel() throws Exception { | ||
| Long id = openGroupPurchase(); | ||
| participationService.join(id, buyer.getId(), 2); | ||
|
|
||
| cancel(id, buyerCookie).andExpect(status().isNoContent()); | ||
| Map<String, Object> row = participationRow(); | ||
| assertThat(row.get("status")).isEqualTo("CANCELED"); | ||
| assertThat(row.get("canceled_at")).isNotNull(); | ||
| assertThat(redisTemplate.opsForValue().get(GroupPurchaseRedisKeys.headcount(id))).isEqualTo("0"); | ||
|
|
||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("Redis에서는 이미 취소됐는데 DB가 JOINED로 남아 있으면, 다시 요청할 때 DB를 마무리하고 204다") | ||
| void cancel_finishPendingCancel() throws Exception { | ||
|
Check warning on line 110 in src/test/java/com/ttuk/participation/ParticipationCancelIntegrationTest.java
|
||
|
|
||
| Long id = openGroupPurchase(); | ||
| participationService.join(id, buyer.getId(), 2); | ||
| groupPurchaseRedisRepository.cancel(id, buyer.getId(), LocalDateTime.now(clock), GroupPurchase.CANCELABLE_BEFORE_CLOSE); | ||
| cancel(id, buyerCookie).andExpect(status().isNoContent()); | ||
| assertThat(participationRow().get("status")).isEqualTo("CANCELED"); | ||
|
|
||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("참여하지 않은 공동구매를 취소하면 404 NOT_JOINED다") | ||
| void cancel_notJoined() throws Exception { | ||
|
Check warning on line 122 in src/test/java/com/ttuk/participation/ParticipationCancelIntegrationTest.java
|
||
| Long id = openGroupPurchase(); | ||
|
|
||
| cancel(id, buyerCookie) | ||
| .andExpect(status().isNotFound()) | ||
| .andExpect(jsonPath("$.error.code").value("NOT_JOINED")); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("판매자는 참여 취소를 할 수 없다 (403)") | ||
| void cancel_seller() throws Exception { | ||
|
Check warning on line 132 in src/test/java/com/ttuk/participation/ParticipationCancelIntegrationTest.java
|
||
| Long id = openGroupPurchase(); | ||
|
|
||
| cancel(id, sellerCookie) | ||
| .andExpect(status().isForbidden()); | ||
| } | ||
|
|
||
| private ResultActions cancel(Long groupPurchaseId, Cookie cookie) throws Exception { | ||
| return mockMvc.perform(delete("/api/group-purchases/{id}/participants/me", groupPurchaseId) | ||
| .cookie(cookie)); | ||
| } | ||
|
|
||
| private Map<String, Object> participationRow() { | ||
| return jdbcTemplate.queryForMap("SELECT status, canceled_at FROM participation"); | ||
| } | ||
|
|
||
| private Long openGroupPurchase() { | ||
| Category category = categoryRepository.findById(FRESH_FOOD_ID).orElseThrow(); | ||
| GroupPurchase groupPurchase = groupPurchaseRepository.save(GroupPurchase.builder() | ||
| .seller(seller) | ||
| .category(category) | ||
| .title("대파 한 단") | ||
| .description("진도 대파, 11/12 수확") | ||
| .unit("단") | ||
| .basePrice(3000) | ||
| .floorPrice(2500) | ||
| .discountType(DiscountType.RATE) | ||
| .discountValue(5) | ||
| .discountStepSize(10) | ||
| .maxHeadcount(50) | ||
| .closeAt(LocalDateTime.now(clock).plusDays(3).withNano(0)) | ||
| .build()); | ||
| groupPurchaseRedisRepository.initialize(groupPurchase); | ||
| return groupPurchase.getId(); | ||
| } | ||
|
|
||
| private Member member(String email, String nickname, MemberRole role, String phoneNum) { | ||
| return Member.builder() | ||
| .email(email) | ||
| .encodedPassword(passwordEncoder.encode(PASSWORD)) | ||
| .nickname(nickname) | ||
| .role(role) | ||
| .phoneNum(phoneNum) | ||
| .zipCode("06236") | ||
| .address("서울시 강남구 테헤란로 123") | ||
| .build(); | ||
| } | ||
|
|
||
| private Cookie loginAndGetCookie(String email) throws Exception { | ||
| String json = """ | ||
| { "email": "%s", "password": "%s" } | ||
| """.formatted(email, PASSWORD); | ||
| return mockMvc.perform(post("/api/auth/login") | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(json)) | ||
| .andReturn().getResponse().getCookie("SESSION"); | ||
| } | ||
|
|
||
| } | ||
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.
같은 트랜잭션 안에서 이 UPDATE 다음에 findById 로 같은 참여를 다시 조회하면 status 가 뭐로 보일까요?
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.
이 UPDATE는 벌크 연산이라 SQL을 DB에 바로 실행하고 영속성 컨텍스트의 엔티티는 건드리지 않습니다. 그래서 같은 트랜잭션에서 UPDATE 전에 그 참여를 조회해 뒀다면, findById는 1차 캐시를 먼저 보기 때문에 SELECT 없이 옛 엔티티를 돌려줘 DB는 CANCELED인데 JOINED로 보입니다. UPDATE 전에 조회한 적이 없다면 DB를 다시 읽어 CANCELED로 보입니다.
지금은 서비스에 트랜잭션이 없어 cancelJoined가 리포지토리의 @transactional로 혼자 짧은 트랜잭션에서 실행되므로 이 문제가 생기지 않지만, 나중에 같은 트랜잭션에서 조회 후 UPDATE하는 흐름이 생기면 문제가 될 수 있습니다. 그래서 @Modifying에 clearAutomatically = true를 주어 UPDATE 후 영속성 컨텍스트를 비우고, 비울 때 반영 안 된 변경이 버려지지 않도록 flushAutomatically = true도 함께 주겠습니다.