Skip to content

fix: lock room row before reordering on problem deletion - #63

Merged
jaejo merged 2 commits into
developfrom
feature/problem-refactor
Aug 7, 2026
Merged

jaejo merged 2 commits into
developfrom
feature/problem-refactor

Conversation

@Junkov0

@Junkov0 Junkov0 commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

작업 내용

방/카테고리 도메인의 멀티 인스턴스(분산 환경) 대응 점검에서 발견된 동시성 이슈 3건 수정.

변경 사항

  • 방 문제 삭제 시 순번 재정렬 락 누락 (커밋 1): deleteRoomProblem이 방을 락 없이 조회(getRoom)한 뒤 순번을 벌크 재정렬하고 삭제해서, 같은 방에서 삭제 요청이 동시에 들어오면 problemOrder에 gap이 생기거나 순서가 꼬일 수 있었음. 같은 파일의 AI 채번 로직(createRoomProblemsByAi)이 이미 쓰던 roomRepository.findByIdForUpdate 비관적 락 패턴을 재사용해 해결.
  • 방 문제 순번 중복 시 미매핑 예외 (커밋 2): createRoomProblem은 클라이언트가 지정한 순번을 그대로 저장하는데, 동시 요청 시 순번이 겹치면 DB 유니크 제약(UQ_ROOM_PROBLEM_ROOM_ORDER)이 막아주긴 하지만 DataIntegrityViolationException이 그대로 노출됐음. saveAndFlush + DataIntegrityViolationException catch로 감싸서 RoomProblemErrorCode.DUPLICATE_PROBLEM_ORDER(신규, 7005)로 매핑.
  • 카테고리 이름 중복 시 TOCTOU (커밋 2): createCategoryexistsByName 체크 후 save하는 check-then-act라, 동시 요청 시 두 요청 모두 체크를 통과하고 DB 제약에서만 걸릴 수 있었음. 동일하게 saveAndFlush + catch로 감싸 기존 CATEGORY_NAME_DUPLICATED(3003)로 매핑.
  • 두 곳 모두 UserServiceImpl.isDuplicateEmailViolation에 이미 있던 패턴(제약명 문자열 매칭 후 BusinessException 변환)을 그대로 재사용.

체크리스트

  • 테스트 코드 작성 완료
  • 리뷰어 지정 완료

참고 사항

  • updateCategory(ProblemCategoryServiceImpl.java)도 동일한 TOCTOU 패턴이 남아있으나 이번 스코프에서는 제외함 (별도 확인 필요 시 후속 처리).
  • 로컬 ./gradlew.bat :momogo-core:compileJava 빌드 성공 확인 (커밋별로 모두 확인).

관련 이슈

deleteRoomProblem read the room without acquiring a lock, then bulk-
updated problemOrder before deleting the target row. Concurrent
delete requests on the same room could race and leave problemOrder
with gaps or an inconsistent sequence, more likely across multiple
instances.

Switch to roomRepository.findByIdForUpdate, the same pessimistic-lock
pattern already used by createRoomProblemsByAi via
RoomProblemPersister#saveGeneratedProblems, so concurrent deletes on
the same room are serialized.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

방 문제 삭제 시 일반 방 조회를 findByIdForUpdate 기반 조회로 변경했습니다. 방 미존재 예외 처리와 관리자 검증, 문제 삭제 및 순번 재정렬 흐름은 유지됩니다.

Changes

방 문제 삭제 동시성 제어

Layer / File(s) Summary
방 조회 비관적 잠금 적용
momogo-core/src/main/java/com/momogo/core/domain/room/service/RoomProblemServiceImpl.java
삭제 중인 방을 findByIdForUpdate로 조회합니다. 방이 없으면 ROOM_NOT_FOUND를 발생시킵니다. 이후 관리자 검증, 문제 삭제, 순번 재정렬 흐름은 유지됩니다.

Estimated code review effort: 1 (Trivial) | ~5 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 문제 삭제 전에 방 행 잠금을 추가하는 주요 변경 사항을 정확하고 간결하게 설명합니다.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/problem-refactor

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Junkov0
Junkov0 requested review from SungHuii and jaejo August 7, 2026 06:40
…m-problem creation

Both createCategory (name uniqueness) and createRoomProblem (problem
order uniqueness) only guarded against duplicates with a pre-check
(existsByName / relying on the DB constraint alone). Under concurrent
requests the pre-check can pass for both callers, leaving the DB
unique constraint as the only real guard, which surfaced as an
unmapped DataIntegrityViolationException instead of the intended
BusinessException.

Wrap the save in saveAndFlush + catch DataIntegrityViolationException,
matching the existing isDuplicateEmailViolation pattern in
UserServiceImpl: inspect getMostSpecificCause().getMessage() for the
constraint name and rethrow as a BusinessException, otherwise
propagate. Added RoomProblemErrorCode.DUPLICATE_PROBLEM_ORDER (7005);
reused the existing CATEGORY_NAME_DUPLICATED for categories.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

@SungHuii SungHuii left a comment

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.

수고하셨습니다 👍

@jaejo jaejo left a comment

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.

고생하셨습니다!

@jaejo
jaejo merged commit 7135f48 into develop Aug 7, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants