Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.Optional;

import com.mr.global.event.NotificationEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -117,6 +119,16 @@ public boolean complete(
eventPublisher.publishEvent(
AnalysisCompletedEvent.of(analysis.getUser().getUserId())
);

String practiceName = "자유 연주";

if (analysis.getPlaying() != null && analysis.getPlaying().getBackingTrack() != null) {
practiceName = analysis.getPlaying().getBackingTrack().getTitle();
}

eventPublisher.publishEvent(
NotificationEvent.forAnalysis(analysis.getUser().getUserId(), practiceName)
);
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,19 @@ interface PracticeTotals {
}

Optional<Playing> findByIdAndDeletedAtIsNull(Long playingId);

@Query("""
select coalesce(sum(p.durationSec), 0) from Playing p
where p.user.userId = :userId
and p.status = :status
and p.deletedAt is null
and p.endedAt >= :since
and p.id != :excludePlayingId
""")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Long sumDurationSecExcludeCurrent(
@Param("userId") Long userId,
@Param("status") PlayingStatus status,
@Param("since") LocalDateTime since,
@Param("excludePlayingId") Long excludePlayingId
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
33 changes: 33 additions & 0 deletions src/main/java/com/mr/domain/playing/service/PlayingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,16 @@
import com.mr.domain.user.entity.User;
import com.mr.domain.user.repository.UserRepository;
import com.mr.global.apipayload.exception.GeneralException;
import com.mr.global.event.NotificationEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Clock;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import static com.mr.domain.backingtrack.entity.enums.AccessLevel.PUBLIC;
Expand All @@ -32,6 +38,10 @@ public class PlayingService {
private final UserRepository userRepository;
private final BackingTrackRepository backingTrackRepository;

private final ApplicationEventPublisher eventPublisher;

private final Clock clock;

@Transactional
public PlayingStartResponse startPlaying(
Long userId, PlayingStartRequest request
Expand Down Expand Up @@ -80,6 +90,29 @@ public MidiEventSaveResponse saveMidiEvents(

playing.completeWithMidiData(midiEvents);

int intervalHours = 10; // 10시간 단위로 알림
int intervalSeconds = intervalHours * 3600;

LocalDateTime weekStart = LocalDate.now(clock).with(DayOfWeek.MONDAY).atStartOfDay();

// 방금 끝낸 연주를 제외한 이전 누적 시간
Long previousWeeklySeconds = playingRepository.sumDurationSecExcludeCurrent(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 P3
📍 PlayingService.java (saveMidiEvents 내 마일스톤 계산 블록)

문제상황: 주간 연습 시간 마일스톤 계산이 previousWeeklySeconds = sumDurationSecExcludeCurrent(...) 조회 → 계산 → 알림 발행 흐름인데, 이 집계 쿼리에 아무 락도 없습니다.

문제가 되는 이유: 같은 유저가 서로 다른 연주 세션 두 개를 거의 동시에 완료(saveMidiEvents)하는 경우(연속으로 빠르게 제출하거나 멀티 탭 등), 두 트랜잭션이 서로의 커밋을 못 본 채로 동일한 previousWeeklySeconds를 읽어서 같은 10시간 마일스톤 경계를 각자 "처음 넘었다"고 판단하고 알림을 중복 발행할 수 있습니다. (같은 playingId 재요청은 completeWithMidiData가 상태 검증으로 막아주지만, 서로 다른 playingId 두 개가 겹치는 경우는 안 막힙니다.) PR #119(멘토 스트리밍)에서는 비슷한 "동시 진행 상태" 문제를 토큰 기반으로 막아뒀는데, 여기는 그런 보호가 없어요.

수정 방향: 알림 자체가 크리티컬한 데이터는 아니라서 지금 당장 락을 걸 정도는 아니라고 봅니다. 다만 실제로 중복 알림이 이슈가 되면, Playing 저장 시 유저 행에 락을 걸거나, 혹은 알림 발행 자체를 "이번 주 이 마일스톤을 이미 보냈는지" 별도 상태로 멱등하게 관리하는 방향을 고려하면 좋을 것 같습니다.

Tip: 발생 확률이 낮고(정확히 같은 유저가 10시간 단위 경계를 걸치는 두 세션을 동시에 완료해야 함) 영향도도 낮아서(푸시 알림 한 번 더 가는 정도), 이번 PR을 막을 이슈는 아니라고 생각합니다. 그냥 참고만 하시면 될 것 같아요.

userId, playing.getStatus(), weekStart, playing.getId()
);

Long currentDuration = playing.getDurationSec() != null ? playing.getDurationSec() : 0L;
Long totalWeeklySeconds = previousWeeklySeconds + currentDuration;

Long previousMilestones = previousWeeklySeconds / intervalSeconds;
Long currentMilestones = totalWeeklySeconds / intervalSeconds;

if (currentMilestones > previousMilestones) {
int achievedHours = (int)(currentMilestones * intervalHours); // 달성한 시간: 10 시간 단위
eventPublisher.publishEvent(
NotificationEvent.forPractice(userId, playing.getUser().getNickname(), achievedHours)
);
}

return MidiEventSaveResponse.of(
playing.getId(),
playing.getMidiData().size()
Expand Down
Loading