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: 2 additions & 1 deletion docs/유스케이스 시나리오.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,14 @@

- **액터:** 예약 만료 처리 스케줄러
- **선행 조건:** 결제 대기 상태의 예약이 존재한다.
- **실행 시점:** 스케줄러가 1초마다 실행한다.
- **성공 시나리오**
1. 시스템은 결제 제한 시각이 도래한 결제 대기 예약을 확인한다.
2. 시스템은 예약 상태를 만료로 변경한다.
3. 시스템은 만료된 예약이 확보한 티켓 수량을 다시 판매할 수 있도록 처리한다.
- **확장**
- **2a. 예약 상태가 이미 변경된 경우:** 시스템은 해당 예약을 중복 만료 처리하지 않는다.
- **3a. 만료 처리에 실패한 경우:** 시스템은 예약 상태와 판매 수량의 정합성을 유지할 수 있도록 처리한다.
- **3a. 만료 처리에 실패한 경우:** 시스템은 해당 공연의 예약 상태와 판매 수량 변경을 모두 취소하고 다음 실행에서 다시 처리한다. 다른 공연의 만료 처리는 계속한다.

## 4. 결제 관리

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.ticketing.reservation.global.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration(proxyBeanMethods = false)
@EnableScheduling
@ConditionalOnProperty(name = "app.scheduling.enabled", havingValue = "true", matchIfMissing = true)
public class SchedulingConfig {}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@ public void reserve(int quantity) {
this.reservedQuantity += quantity;
}

public void release(int quantity) {
if (quantity < 0 || quantity > reservedQuantity) {
throw new IllegalStateException(
"복구할 수량은 0 이상 예약 수량 이하여야 합니다: quantity="
+ quantity
+ ", reservedQuantity="
+ reservedQuantity);
}
this.reservedQuantity -= quantity;
}

public boolean hasReservation() {
return reservedQuantity > 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,15 @@ public interface PerformanceStockRepository extends JpaRepository<PerformanceSto
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from PerformanceStock s where s.performanceId = :performanceId")
Optional<PerformanceStock> findByIdForUpdate(@Param("performanceId") Long performanceId);

@Query(
value =
"""
select * from performance_stock
where performance_id = :performanceId
for update skip locked
""",
nativeQuery = true)
Optional<PerformanceStock> findByIdForUpdateSkipLocked(
@Param("performanceId") Long performanceId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.ticketing.reservation.performance.service;

import com.ticketing.reservation.performance.domain.PerformanceStock;
import java.time.LocalDateTime;

public interface OverdueReservationExpirer {

void expireOverdue(PerformanceStock stock, LocalDateTime now);
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public PerformanceDetail register(PerformanceInfo info, int totalQuantity) {
@Transactional
public PerformanceDetail update(
Long performanceId, PerformanceInfo info, int totalQuantity, IfMatch ifMatch) {
PerformanceStock stock = stockLocker.lock(performanceId);
PerformanceStock stock = stockLocker.lockAndExpireOverdue(performanceId);
Performance performance =
performanceRepository
.findById(performanceId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import com.ticketing.reservation.global.error.ErrorCode;
import com.ticketing.reservation.performance.domain.PerformanceStock;
import com.ticketing.reservation.performance.repository.PerformanceStockRepository;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.PessimisticLockingFailureException;
Expand All @@ -17,13 +20,37 @@ public class PerformanceStockLocker {
private static final Logger log = LoggerFactory.getLogger(PerformanceStockLocker.class);

private final PerformanceStockRepository stockRepository;
private final OverdueReservationExpirer overdueReservationExpirer;
private final Clock clock;

public PerformanceStockLocker(PerformanceStockRepository stockRepository) {
public PerformanceStockLocker(
PerformanceStockRepository stockRepository,
OverdueReservationExpirer overdueReservationExpirer,
Clock clock) {
this.stockRepository = stockRepository;
this.overdueReservationExpirer = overdueReservationExpirer;
this.clock = clock;
}

@Transactional(propagation = Propagation.MANDATORY)
public PerformanceStock lock(Long performanceId) {
public PerformanceStock lockAndExpireOverdue(Long performanceId) {
PerformanceStock stock = lock(performanceId);
overdueReservationExpirer.expireOverdue(stock, now());
return stock;
}

@Transactional(propagation = Propagation.MANDATORY)
public void tryLockAndExpireOverdue(Long performanceId) {
stockRepository
.findByIdForUpdateSkipLocked(performanceId)
.ifPresent(stock -> overdueReservationExpirer.expireOverdue(stock, now()));
}

private LocalDateTime now() {
return LocalDateTime.now(clock).truncatedTo(ChronoUnit.MICROS);
}

private PerformanceStock lock(Long performanceId) {
try {
return stockRepository
.findByIdForUpdate(performanceId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ public ReservationStatus statusAt(LocalDateTime now) {
return status;
}

public void expire(LocalDateTime now) {
if (status != ReservationStatus.PENDING_PAYMENT || now.isBefore(paymentDeadlineAt)) {
throw new IllegalStateException("결제 제한 시각이 지난 결제 대기 예약만 만료할 수 있습니다: id=" + id);
}
this.status = ReservationStatus.EXPIRED;
}

public Long getId() {
return id;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import com.ticketing.reservation.reservation.domain.Reservation;
import com.ticketing.reservation.reservation.domain.ReservationStatus;
import jakarta.persistence.LockModeType;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

Expand All @@ -29,4 +31,23 @@ List<Reservation> findAllByMemberIdAndStatusAt(
@Param("now") LocalDateTime now);

Optional<Reservation> findByIdAndMemberId(Long id, Long memberId);

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query(
"""
select r from Reservation r
where r.performanceId = :performanceId
and r.status = PENDING_PAYMENT
and r.paymentDeadlineAt <= :now
""")
List<Reservation> findOverdueForUpdate(
@Param("performanceId") Long performanceId, @Param("now") LocalDateTime now);

@Query(
"""
select distinct r.performanceId from Reservation r
where r.status = PENDING_PAYMENT
and r.paymentDeadlineAt <= :now
""")
List<Long> findPerformanceIdsWithOverdue(@Param("now") LocalDateTime now);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.ticketing.reservation.reservation.service;

import com.ticketing.reservation.performance.domain.PerformanceStock;
import com.ticketing.reservation.performance.service.OverdueReservationExpirer;
import com.ticketing.reservation.reservation.domain.Reservation;
import com.ticketing.reservation.reservation.repository.ReservationRepository;
import java.time.LocalDateTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component
public class ReservationExpirer implements OverdueReservationExpirer {

private static final Logger log = LoggerFactory.getLogger(ReservationExpirer.class);

private final ReservationRepository reservationRepository;

public ReservationExpirer(ReservationRepository reservationRepository) {
this.reservationRepository = reservationRepository;
}

@Override
@Transactional(propagation = Propagation.MANDATORY)
public void expireOverdue(PerformanceStock stock, LocalDateTime now) {
List<Reservation> overdue =
reservationRepository.findOverdueForUpdate(stock.getPerformanceId(), now);
if (overdue.isEmpty()) {
return;
}
overdue.forEach(reservation -> reservation.expire(now));
int quantity = overdue.stream().mapToInt(Reservation::getQuantity).sum();
stock.release(quantity);
log.info(
"Expired overdue reservations: performanceId={}, count={}, quantity={}",
stock.getPerformanceId(),
overdue.size(),
quantity);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.ticketing.reservation.reservation.service;

import com.ticketing.reservation.reservation.repository.ReservationRepository;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ReservationExpiryScheduler {

private static final Logger log = LoggerFactory.getLogger(ReservationExpiryScheduler.class);

private final ReservationRepository reservationRepository;
private final ReservationService reservationService;
private final Clock clock;

public ReservationExpiryScheduler(
ReservationRepository reservationRepository,
ReservationService reservationService,
Clock clock) {
this.reservationRepository = reservationRepository;
this.reservationService = reservationService;
this.clock = clock;
}

@Scheduled(fixedDelay = 1, timeUnit = TimeUnit.SECONDS)
public void expireOverdue() {
LocalDateTime now = LocalDateTime.now(clock).truncatedTo(ChronoUnit.MICROS);
for (Long performanceId : reservationRepository.findPerformanceIdsWithOverdue(now)) {
try {
reservationService.expireOverdue(performanceId);
} catch (RuntimeException e) {
log.error(
"Unexpected error while expiring overdue reservations: performanceId={}",
performanceId,
e);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public ReservationService(

@Transactional
public Reservation reserve(Long memberId, Long performanceId, int quantity) {
PerformanceStock stock = stockLocker.lock(performanceId);
PerformanceStock stock = stockLocker.lockAndExpireOverdue(performanceId);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

예약이 아직 전혀 없는 상황에서 서로 다른 공연 예약이 동시에 들어오면 어떻게 되나요?

Performance performance =
performanceRepository
.findById(performanceId)
Expand All @@ -53,6 +53,11 @@ public Reservation reserve(Long memberId, Long performanceId, int quantity) {
return reservationRepository.save(reservation);
}

@Transactional
public void expireOverdue(Long performanceId) {
stockLocker.tryLockAndExpireOverdue(performanceId);
}

@Transactional(readOnly = true)
public List<ReservationDetail> getMyReservations(Long memberId, Set<ReservationStatus> statuses) {
LocalDateTime now = LocalDateTime.now(clock).truncatedTo(ChronoUnit.MICROS);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE INDEX idx_reservation_status_deadline
ON reservation (status, payment_deadline_at);

CREATE INDEX idx_reservation_performance_status_deadline
ON reservation (performance_id, status, payment_deadline_at);
Loading
Loading