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
3 changes: 3 additions & 0 deletions src/main/java/com/ttuk/global/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ public enum ErrorCode {
GROUP_PURCHASE_FULL(HttpStatus.CONFLICT, "정원이 마감된 공동구매입니다."),
ALREADY_JOINED(HttpStatus.CONFLICT, "이미 참여한 공동구매입니다."),

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

;

private final HttpStatus status;
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/com/ttuk/grouppurchase/GroupPurchase.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.time.Duration;
import java.time.LocalDateTime;

@Entity
Expand All @@ -22,6 +23,8 @@
})
public class GroupPurchase extends BaseTimeEntity {

public static final Duration CANCELABLE_BEFORE_CLOSE = Duration.ofHours(1);

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Expand Down Expand Up @@ -104,4 +107,8 @@ private GroupPurchase(Member seller, Category category, String title, String des
public boolean isJoinableAt(LocalDateTime now){
return status == GroupPurchaseStatus.OPEN && now.isBefore(closeAt);
}

public LocalDateTime cancelDeadline(){
return closeAt.minus(CANCELABLE_BEFORE_CLOSE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,12 @@ public ResponseEntity<ApiResponse<ParticipationCreateResponse>> join(@PathVariab

}

@DeleteMapping("/me")
@RequireRole(MemberRole.BUYER)
public ResponseEntity<Void> cancel(@PathVariable Long groupPurchaseId, @Login LoginMember loginMember) {
participationService.cancel(groupPurchaseId, loginMember.memberId());
return ResponseEntity.noContent().build();
}


}
21 changes: 21 additions & 0 deletions src/main/java/com/ttuk/participation/ParticipationRepository.java
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

같은 트랜잭션 안에서 이 UPDATE 다음에 findById 로 같은 참여를 다시 조회하면 status 가 뭐로 보일까요?

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.

이 UPDATE는 벌크 연산이라 SQL을 DB에 바로 실행하고 영속성 컨텍스트의 엔티티는 건드리지 않습니다. 그래서 같은 트랜잭션에서 UPDATE 전에 그 참여를 조회해 뒀다면, findById는 1차 캐시를 먼저 보기 때문에 SELECT 없이 옛 엔티티를 돌려줘 DB는 CANCELED인데 JOINED로 보입니다. UPDATE 전에 조회한 적이 없다면 DB를 다시 읽어 CANCELED로 보입니다.
지금은 서비스에 트랜잭션이 없어 cancelJoined가 리포지토리의 @transactional로 혼자 짧은 트랜잭션에서 실행되므로 이 문제가 생기지 않지만, 나중에 같은 트랜잭션에서 조회 후 UPDATE하는 흐름이 생기면 문제가 될 수 있습니다. 그래서 @Modifying에 clearAutomatically = true를 주어 UPDATE 후 영속성 컨텍스트를 비우고, 비울 때 반영 안 된 변경이 버려지지 않도록 flushAutomatically = true도 함께 주겠습니다.

@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
""")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

조회한 뒤 if 로 확인하고 UPDATE 하는 방식과, 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.

조회 후 if로 확인하고 UPDATE하면 확인과 변경이 두 단계로 나뉘어, 같은 취소 요청 두 개가 동시에 오면 InnoDB의 일반 SELECT는 잠금 없이 커밋된 스냅샷을 읽기 때문에 둘 다 JOINED를 보고 통과합니다. 그러면 실제 취소는 한 번인데 두 요청 모두 성공으로 처리되고, canceled_at이 덮어써지거나 취소에 딸린 후속 처리가 두 번 실행될 수 있습니다.
WHERE 절에 status = 'JOINED' 조건을 넣은 UPDATE는 확인과 변경이 한 문장이라, 먼저 실행한 요청이 행에 배타 잠금을 걸고 바꾸면 뒤의 요청은 잠금을 기다렸다가 최신 커밋 데이터로 조건을 다시 판단해 0행이 됩니다. 그래서 바뀐 행 수만 보면 내가 처리했는지, 이미 처리됐는지를 정확히 구분할 수 있고, 쿼리도 한 번으로 끝나 이 방식을 선택했습니다.

int cancelJoined(@Param("groupPurchaseId") Long groupPurchaseId,
@Param("memberId") Long memberId,
@Param("now") LocalDateTime now);
}
45 changes: 45 additions & 0 deletions src/main/java/com/ttuk/participation/ParticipationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

참여(join)는 DB 저장이 실패하면 Redis 를 되돌렸는데, 취소는 되돌리지 않고 재요청 때 DB 를 마무리해요. 두 방식의 차이는 뭔가요?

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 저장이 실패했는데 Redis를 그대로 두면, 사용자는 실패 응답을 받았는데 Redis에서는 자리 하나를 차지한 채로 남아 다른 사람이 그 자리에 들어올 수 없고 단가도 한 명 많은 기준으로 계산됩니다. 재요청해도 이미 참여로 막혀 풀리지 않아서, 바로 Redis를 되돌려 자리를 반납합니다.
반대로 취소는 Redis에서 이미 자리를 비웠기 때문에, 그 사이 다른 사람이 그 자리에 참여했을 수 있습니다. 이때 Redis를 되돌려 다시 참여 상태로 만들면 정원을 넘기거나 기한이 지난 뒤 참여 상태로 돌아갈 수 있습니다. 또 사용자의 의도가 취소이므로, Redis는 취소된 그대로 두고 재요청이 오면 Lua가 참여 중 아님을 돌려줄 때 DB만 마무리하도록 했습니다. 재요청이 없더라도 정산 때 Redis 참여자와 DB JOINED를 대조해 정리됩니다.

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) {

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 INSERT 가 아직 안 끝났을 때 취소가 들어오면 여기로 와요. 그 뒤에 INSERT 가 끝나면 DB 에 JOINED 가 남아요. 재요청하면 마무리되긴 하지만, 이런 경우가 있다는 걸 로그 문구에 적어두면 나중에 찾기 쉬울 것 같아요.

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.

말씀해 주신 대로 참여 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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 을 채우게 고치는 게 먼저일 것 같아요.

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.

말씀해 주신 대로 NOT_JOINED 경로는 "참여자 Set에 없으면 Redis에서는 이미 취소가 끝났다"는 전제로 기한과 상태를 다시 확인하지 않는데, 지금 lazy init은 참여자 Set을 비운 채로 초기화해서 Redis가 사라진 뒤에는 기존 참여자 모두가 이 경로로 빠집니다. 그러면 마감이 지났거나 CLOSED여도 DB 취소가 되고, Redis 인원은 줄지 않아 다시 어긋나게 됩니다.
finishPendingCancel에 기한 확인을 넣으면 기한 안에 Redis 취소는 끝났는데 DB만 실패한 경우의 재요청을 마무리할 수 없어서, "Set에 없음"이 정확한 의미를 갖도록 lazy init이 DB의 JOINED 참여자로 참여자 Set과 인원, 단가를 채우게 고치는 걸 먼저 하겠습니다. 그러면 기존 참여자는 정상 취소 경로로 가서 기한과 상태를 확인받고, NOT_JOINED 경로는 실제로 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()) {
Expand Down
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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.

See more on https://sonarcloud.io/project/issues?id=f-lab-edu_TTUK&issues=AaHpJAktdImgLu6q5YR7&open=AaHpJAktdImgLu6q5YR7&pullRequest=44

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.

See more on https://sonarcloud.io/project/issues?id=f-lab-edu_TTUK&issues=AaHpJAktdImgLu6q5YR8&open=AaHpJAktdImgLu6q5YR8&pullRequest=44
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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.

See more on https://sonarcloud.io/project/issues?id=f-lab-edu_TTUK&issues=AaHpJAktdImgLu6q5YR9&open=AaHpJAktdImgLu6q5YR9&pullRequest=44
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");
}

}
Loading