From 1bbc6a6f760e3165b2d9fd8f27363fbdee8d016b Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Mon, 21 Sep 2026 15:31:30 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20GWT?= =?UTF-8?q?=EB=A1=9C=20=ED=86=B5=EC=9D=BC=ED=95=B4=EC=84=9C=20=EC=82=AC?= =?UTF-8?q?=EC=9A=A9=ED=95=A0=20=EC=88=98=20=EC=9E=88=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EA=B5=AC=EC=84=B1=20=EB=B0=8F=20=EC=84=9C=EB=B8=8C=EC=97=90?= =?UTF-8?q?=EC=9D=B4=EC=A0=84=ED=8A=B8=20=ED=8C=8C=EC=9D=BC=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/agents/adversarial-verifier.md | 37 ++ .claude/agents/capacity-resilience.md | 63 ++-- .claude/agents/change-pressure.md | 53 +++ .claude/agents/cognitive-load.md | 51 +++ .claude/agents/config-secrets.md | 62 ++-- .claude/agents/distributed-runtime.md | 61 ++-- .claude/agents/error-design.md | 60 ++-- .claude/agents/http-contract.md | 60 ++-- .claude/agents/invariant-miner.md | 46 +++ .claude/agents/jpa-persistence.md | 57 ++- .claude/agents/layering-domain.md | 54 ++- .claude/agents/observability-ops.md | 54 ++- .claude/agents/rdb-schema.md | 68 ++-- .claude/agents/security-boundary.md | 62 ++-- .claude/agents/techlead-synthesis.md | 49 +++ .claude/agents/test-strategy.md | 67 ++-- .claude/agents/transaction-locking.md | 71 ++-- .claude/agents/validation-layering.md | 61 ++-- .claude/agents/zero-downtime-evolution.md | 67 ++-- .claude/review-lens.md | 153 +++++--- .claude/review-workflow.md | 84 +++++ .env | 1 - .env.example | 3 +- Dockerfile | 7 +- README.md | 253 ++++++++------ build.gradle | 92 ++--- docker-compose.yml | 3 +- docs/Requirements.md | 65 ++-- ...ourse-registration.postman_collection.json | 79 +++++ postman/dev.postman_environment.json | 5 + postman/local.postman_environment.json | 5 + .../config/DayOfWeekConverter.java | 11 + .../course_registration/config/JpaConfig.java | 15 +- .../config/RuntimeProfileConfig.java | 37 ++ .../config/UserRoleConverter.java | 11 + .../CourseRegistrationController.java | 4 +- .../controller/LessonController.java | 2 +- .../entity/BaseDeleteEntity.java | 24 -- .../entity/BaseEntity.java | 16 +- .../course_registration/entity/Lesson.java | 6 +- .../entity/LessonSchedule.java | 6 +- .../course_registration/entity/Professor.java | 3 +- .../entity/RegistrationIdempotency.java | 67 ++++ .../course_registration/entity/Semester.java | 3 +- .../course_registration/entity/Subject.java | 3 +- .../course_registration/entity/User.java | 6 +- .../entity/UserLesson.java | 3 +- .../enums/RegistrationErrorCode.java | 5 +- .../exception/GlobalExceptionHandler.java | 51 +-- .../RegistrationIdempotencyRepository.java | 38 ++ .../repository/SemesterRepository.java | 8 +- .../seeder/DataSeeder.java | 134 ++++--- .../course_registration/seeder/SeedTable.java | 47 +++ .../service/CourseRegistrationService.java | 215 ++++++------ .../service/IdempotencyRetentionJob.java | 26 ++ .../service/LessonQueryService.java | 26 +- .../service/SemesterResolver.java | 57 +++ .../service/lock/RegistrationLockManager.java | 30 ++ .../service/policy/LessonSchedulePolicy.java | 34 ++ .../service/policy/RegistrationValidator.java | 6 + src/main/resources/application-dev.yaml | 9 +- src/main/resources/application-local.yaml | 7 +- src/main/resources/application-prod.yaml | 9 +- src/main/resources/application.yaml | 25 +- .../db/migration/h2/V1__baseline.sql | 131 +++++++ .../db/migration/postgresql/V1__baseline.sql | 124 +++++++ src/main/resources/seed/demo/lessons.tsv | 8 + src/main/resources/seed/demo/professors.tsv | 4 + src/main/resources/seed/demo/schedules.tsv | 8 + src/main/resources/seed/demo/semesters.tsv | 2 + src/main/resources/seed/demo/subjects.tsv | 7 + src/main/resources/seed/demo/users.tsv | 4 + .../CourseRegistrationApplicationTests.java | 2 + .../architecture/ArchitectureTest.java | 73 ++++ .../architecture/SourceStyleTest.java | 65 ++++ .../config/EnumConverterTest.java | 44 +++ .../config/RuntimeProfileConfigTest.java | 58 +++ .../controller/CourseRegistrationApiTest.java | 322 ++++++++++------- .../controller/LessonApiTest.java | 108 ++++++ .../entity/EntityInvariantTest.java | 218 ++++++++++++ .../exception/GlobalExceptionHandlerTest.java | 41 +++ .../repository/LessonRepositoryTest.java | 93 +++++ .../LessonScheduleRepositoryTest.java | 56 +++ ...RegistrationIdempotencyRepositoryTest.java | 172 +++++++++ .../repository/SemesterRepositoryTest.java | 52 +++ .../repository/UserLessonRepositoryTest.java | 136 ++++++++ .../repository/UserRepositoryTest.java | 34 ++ .../seeder/DataSeederTest.java | 53 +++ .../seeder/SeedTableTest.java | 33 ++ ...egistrationConcurrencyIntegrationTest.java | 259 ++++++++------ ...rseRegistrationServiceIntegrationTest.java | 330 ++++++++++++------ .../LessonQueryServiceIntegrationTest.java | 228 ++++++++---- .../SemesterResolverIntegrationTest.java | 69 ++++ .../lock/RegistrationLockManagerTest.java | 39 +++ .../policy/LessonSchedulePolicyTest.java | 69 ++++ .../service/policy/RegistrationFixture.java | 171 +++------ .../policy/RegistrationValidatorTest.java | 224 ++++++------ .../policy/ScheduleConflictCheckerTest.java | 30 +- .../service/policy/TestFixtures.java | 63 ---- .../support/CourseIntegrationTest.java | 22 ++ .../course_registration/support/Outcome.java | 45 +-- .../support/PessimisticLockProbe.java | 63 ++++ .../support/PostgresIntegrationTest.java | 26 ++ .../support/Rejections.java | 23 +- .../course_registration/support/Scenario.java | 34 +- .../support/fixture/DatabaseFixture.java | 101 ++++++ .../support/fixture/DomainFixtures.java | 151 ++++++++ .../support/fixture/TestData.java | 11 + .../support/fixture/TestFixtureConfig.java | 34 ++ .../support/http/ApiError.java | 36 +- .../support/http/JsonApi.java | 31 +- .../support/http/JsonBody.java | 36 +- src/test/resources/application-test.yaml | 12 +- src/test/resources/seed/test/malformed.tsv | 2 + src/test/resources/seed/test/valid.tsv | 2 + 115 files changed, 4899 insertions(+), 1857 deletions(-) create mode 100644 .claude/agents/adversarial-verifier.md create mode 100644 .claude/agents/change-pressure.md create mode 100644 .claude/agents/cognitive-load.md create mode 100644 .claude/agents/invariant-miner.md create mode 100644 .claude/agents/techlead-synthesis.md create mode 100644 .claude/review-workflow.md delete mode 100644 .env create mode 100644 src/main/java/com/study/course_registration/config/DayOfWeekConverter.java create mode 100644 src/main/java/com/study/course_registration/config/RuntimeProfileConfig.java create mode 100644 src/main/java/com/study/course_registration/config/UserRoleConverter.java delete mode 100644 src/main/java/com/study/course_registration/entity/BaseDeleteEntity.java create mode 100644 src/main/java/com/study/course_registration/entity/RegistrationIdempotency.java create mode 100644 src/main/java/com/study/course_registration/repository/RegistrationIdempotencyRepository.java create mode 100644 src/main/java/com/study/course_registration/seeder/SeedTable.java create mode 100644 src/main/java/com/study/course_registration/service/IdempotencyRetentionJob.java create mode 100644 src/main/java/com/study/course_registration/service/SemesterResolver.java create mode 100644 src/main/java/com/study/course_registration/service/lock/RegistrationLockManager.java create mode 100644 src/main/java/com/study/course_registration/service/policy/LessonSchedulePolicy.java create mode 100644 src/main/resources/db/migration/h2/V1__baseline.sql create mode 100644 src/main/resources/db/migration/postgresql/V1__baseline.sql create mode 100644 src/main/resources/seed/demo/lessons.tsv create mode 100644 src/main/resources/seed/demo/professors.tsv create mode 100644 src/main/resources/seed/demo/schedules.tsv create mode 100644 src/main/resources/seed/demo/semesters.tsv create mode 100644 src/main/resources/seed/demo/subjects.tsv create mode 100644 src/main/resources/seed/demo/users.tsv create mode 100644 src/test/java/com/study/course_registration/architecture/ArchitectureTest.java create mode 100644 src/test/java/com/study/course_registration/architecture/SourceStyleTest.java create mode 100644 src/test/java/com/study/course_registration/config/EnumConverterTest.java create mode 100644 src/test/java/com/study/course_registration/config/RuntimeProfileConfigTest.java create mode 100644 src/test/java/com/study/course_registration/controller/LessonApiTest.java create mode 100644 src/test/java/com/study/course_registration/entity/EntityInvariantTest.java create mode 100644 src/test/java/com/study/course_registration/exception/GlobalExceptionHandlerTest.java create mode 100644 src/test/java/com/study/course_registration/repository/LessonRepositoryTest.java create mode 100644 src/test/java/com/study/course_registration/repository/LessonScheduleRepositoryTest.java create mode 100644 src/test/java/com/study/course_registration/repository/RegistrationIdempotencyRepositoryTest.java create mode 100644 src/test/java/com/study/course_registration/repository/SemesterRepositoryTest.java create mode 100644 src/test/java/com/study/course_registration/repository/UserLessonRepositoryTest.java create mode 100644 src/test/java/com/study/course_registration/repository/UserRepositoryTest.java create mode 100644 src/test/java/com/study/course_registration/seeder/DataSeederTest.java create mode 100644 src/test/java/com/study/course_registration/seeder/SeedTableTest.java create mode 100644 src/test/java/com/study/course_registration/service/SemesterResolverIntegrationTest.java create mode 100644 src/test/java/com/study/course_registration/service/lock/RegistrationLockManagerTest.java create mode 100644 src/test/java/com/study/course_registration/service/policy/LessonSchedulePolicyTest.java delete mode 100644 src/test/java/com/study/course_registration/service/policy/TestFixtures.java create mode 100644 src/test/java/com/study/course_registration/support/CourseIntegrationTest.java create mode 100644 src/test/java/com/study/course_registration/support/PessimisticLockProbe.java create mode 100644 src/test/java/com/study/course_registration/support/PostgresIntegrationTest.java create mode 100644 src/test/java/com/study/course_registration/support/fixture/DatabaseFixture.java create mode 100644 src/test/java/com/study/course_registration/support/fixture/DomainFixtures.java create mode 100644 src/test/java/com/study/course_registration/support/fixture/TestData.java create mode 100644 src/test/java/com/study/course_registration/support/fixture/TestFixtureConfig.java create mode 100644 src/test/resources/seed/test/malformed.tsv create mode 100644 src/test/resources/seed/test/valid.tsv diff --git a/.claude/agents/adversarial-verifier.md b/.claude/agents/adversarial-verifier.md new file mode 100644 index 0000000..899deb4 --- /dev/null +++ b/.claude/agents/adversarial-verifier.md @@ -0,0 +1,37 @@ +--- +name: adversarial-verifier +description: 다른 리뷰 agent가 낸 발견이 틀렸다는 증거를 적극적으로 찾는 반증 전담 reviewer. +tools: Read, Grep, Glob, Bash +--- + +먼저 `.claude/review-lens.md`를 읽는다. + +# 역할 + +너는 새로운 지적을 많이 만드는 사람이 아니다. +**다른 reviewer의 지적을 기각하는 사람**이다. + +# Owned question + +> 이 발견이 사실이 아닐 가능성을 최대한 강하게 증명할 수 있는가? + +## Required experiment + +각 후보 발견마다: +1. 주장에 필요한 전제를 분해한다. +2. 각 전제를 반박할 코드/설정/DB constraint/test/문서를 찾는다. +3. 가능하면 관련 테스트를 실행한다. +4. 단순 재현이 가능한 경우 최소 재현을 만든다. +5. 결과를 `확인 / 축소 / 기각 / 미확인` 중 하나로 판정한다. + +## 금지 + +- 원 reviewer의 표현 반복 +- 새로운 일반론 추가 +- "가능성이 있다"만으로 확인 판정 +- 증거 없이 심각도 유지 + +## 출력 + +| 발견 | 판정 | 반증 시도 | 남은 근거 | +|---|---|---|---| diff --git a/.claude/agents/capacity-resilience.md b/.claude/agents/capacity-resilience.md index 82296f0..b712ecf 100644 --- a/.claude/agents/capacity-resilience.md +++ b/.claude/agents/capacity-resilience.md @@ -1,48 +1,45 @@ --- name: capacity-resilience -description: 용량·장애 내성 관점의 시니어 리뷰. 커넥션 풀, 타임아웃 정렬, 스레드 모델, 백프레셔, 실패 격리, 재시도 폭주를 본다. 트래픽이 몰릴 때 무엇이 먼저 무너지는지 알고 싶을 때, 또는 외부 호출·풀 설정을 바꿨을 때 쓴다. +description: 요청 경로의 정량적 cost model을 만들고 peak에서 어떤 자원이 먼저 포화되는지 계산하는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 용량과 장애 내성 +# Owned question -너는 **"부하가 걸리면 무엇이 가장 먼저 무너지고, 그게 어디까지 번지는가"**를 계산하는 사람이다. -장애는 느려지는 것으로 시작해서 전파로 끝난다. 한 지점의 지연이 전체 정지가 되는 경로를 찾아라. +> 피크 트래픽에서 가장 먼저 소진되는 유한 자원은 무엇이고, 그 한계는 대략 얼마인가? -## 반드시 점검할 것 +# 사고 방식: quantitative cost-model builder -**자원 풀 — 숫자를 실제로 계산하라** -- 커넥션 풀 크기가 명시되어 있는가. 없으면 기본값(HikariCP 10)이다 -- **한 요청이 커넥션을 붙들고 있는 최대 시간**을 계산하라. 락 대기가 있다면 그것도 포함이다 -- `풀 크기 ÷ 요청당 점유 시간` = 초당 처리 상한이다. 이 숫자를 구체적으로 제시하라 -- 락 대기 중 커넥션을 점유하는 구조라면, **뜨거운 행 하나가 풀 전체를 소진**할 수 있는지 판단하라. 그러면 무관한 API도 같이 죽는다 -- 웹 스레드 수와 커넥션 풀 크기의 관계가 맞는가. 스레드가 풀보다 훨씬 많으면 대기만 길어진다 +숫자를 만들 수 없는 막연한 성능 우려는 발견으로 보고하지 않는다. -**타임아웃 정렬 — 이 렌즈의 핵심** -- 타임아웃이 존재하는 지점을 전부 나열하라: 클라이언트, LB/인그레스, 웹 서버, 트랜잭션, 락, 쿼리, 커넥션 획득, 외부 호출 -- **바깥쪽이 안쪽보다 길어야 한다.** 어긋난 곳을 찾아라. 클라이언트가 먼저 끊으면 서버는 아무도 안 받을 결과를 계속 계산한다 -- 타임아웃이 없는 지점이 있는가. 무한 대기는 장애 시 전체 정지다 +## Required experiment -**실패 격리와 전파** -- 외부 호출(HTTP, 메시지)이 트랜잭션 안에 있는가. 있으면 상대의 지연이 곧 내 DB 커넥션 고갈이다 -- 실패가 격리되는가, 아니면 한 기능의 장애가 전체 응답 불가로 번지는가 -- 재시도가 있다면 **지수 백오프와 상한**이 있는가. 단순 즉시 재시도는 부하를 증폭시켜 장애를 키운다 -- 서킷 브레이커나 벌크헤드가 필요한 지점이 있는가 +핵심 API마다 가능한 범위에서 계산한다. -**부하 형태** -- 트래픽이 **특정 순간에 몰리는 도메인**인가. 평균이 아니라 피크로 계산하라 -- 대기열이나 사전 입장 제어가 필요한 수준인가, 아니면 즉시 거부가 맞는가. 어느 쪽을 택했는지 코드에서 읽히는가 -- 요청 하나가 발생시키는 쿼리 수가 입력 크기에 비례하는가. 페이지 크기 상한이 없으면 한 요청이 DB를 독점한다 +| 항목 | 값/범위 | 근거 | +|---|---|---| +| request당 DB round trip | | | +| connection 점유 시간 | | | +| lock wait 상한 | | | +| pool size / Pod | | | +| max Pod | | | +| DB 최대 connection | | | +| page/input cardinality | | | +| retry 배수 | | | -**분산 환경에서 특히** -- Pod가 N개면 **DB 커넥션은 풀 크기 × N**이다. DB의 `max_connections`를 넘지 않는지 계산하라. 오토스케일이 있으면 최대 Pod 수로 계산하라 -- 오토스케일이 늘어나는 조건이 CPU라면, **DB 대기로 느려지는 상황에서는 Pod만 늘고 DB는 더 죽는다** -- 기동 직후 Pod가 캐시·커넥션 없이 트래픽을 받는가. 워밍업이나 readiness 지연이 있는가 +정확한 운영 숫자가 없으면 코드/기본값으로 **범위**를 만들고 미확인 값을 명시한다. -## 이 렌즈가 아닌 것 +## Failure cascade -- 락 획득 순서와 데드락 → @transaction-locking -- 쿼리 자체의 효율 → @jpa-persistence, @rdb-schema -- 장애를 관측하는 수단 → @observability-ops +병목 하나가 생겼을 때 `느린 query → pool wait → request timeout → retry → 더 큰 부하`처럼 전파 경로를 만든다. + +## Falsification + +benchmark/load test/설정이 예상 한계를 반박하면 모델을 수정한다. + +## Cross-check +- SQL 비용 → @jpa-persistence, @rdb-schema +- lock hold → @transaction-locking +- 관측 가능성 → @observability-ops diff --git a/.claude/agents/change-pressure.md b/.claude/agents/change-pressure.md new file mode 100644 index 0000000..068c2c1 --- /dev/null +++ b/.claude/agents/change-pressure.md @@ -0,0 +1,53 @@ +--- +name: change-pressure +description: 현재 요구사항이 아니라 다음 요구사항을 주입해 구조가 어디서 찢어지는지 찾는 변경 압력 리뷰. +tools: Read, Grep, Glob, Bash +--- + +먼저 `.claude/review-lens.md`를 읽는다. + +# Owned question + +> 다음 1~2년의 정상적인 요구사항 변경이 들어오면, 어떤 현재 설계 결정이 변경 비용을 폭발시키는가? + +## Required experiment + +저장소 도메인에 맞는 **현실적인 변경 시나리오를 최소 7개** 만든다. +단순 이름 변경이 아니라 모델을 흔드는 요구사항이어야 한다. + +예시 후보: +- 대기 신청 +- 학과/학년별 정원 +- 처리 기간 중 정책 변경 +- 재수강/선수과목 +- 동일 과목 다중 분반 +- 장기 이력 보존 +- 관리자 정정 기능 +- 인증 도입 +- 외부 시스템 연동 +- peak traffic 10배 증가 + +각 변경마다: +1. 몇 계층/파일이 함께 바뀌는가. +2. 같은 규칙이 여러 위치에서 동시에 바뀌어야 하는가. +3. 현재 이름/타입/PK/연관관계가 미래 개념을 막는가. +4. 새 기능이 기존 lock/transaction/invariant 경계를 우회하게 되는가. +5. 현재 abstraction이 변경을 국소화하는가, 오히려 숨기는가. + +## 보고 기준 + +"확장성이 떨어질 수 있다"는 보고하지 않는다. +**구체적인 변경 하나 → 구체적인 파급 경로**가 있어야 한다. + +## Falsification + +이미 확장 포인트, policy, DB identifier, migration path, package boundary가 변경을 국소화한다면 발견을 버린다. + +## Output extras + +### Change blast-radius table +| 변화 | 수정 경계 | 함께 바뀌는 규칙 | 현재 병목 | +|---|---|---|---| + +### Premature abstractions +미래 변경을 돕지 않으면서 현재 이해 비용만 높이는 추상화도 찾는다. diff --git a/.claude/agents/cognitive-load.md b/.claude/agents/cognitive-load.md new file mode 100644 index 0000000..bd2915d --- /dev/null +++ b/.claude/agents/cognitive-load.md @@ -0,0 +1,51 @@ +--- +name: cognitive-load +description: 올바르게 수정하려면 개발자가 머릿속에 기억해야 하는 비지역적 규칙을 찾고, 그 기억을 구조적 제약으로 없애는 리뷰. +tools: Read, Grep, Glob, Bash +--- + +먼저 `.claude/review-lens.md`를 읽는다. + +# Owned question + +> 다음 개발자가 이 코드를 안전하게 바꾸기 위해 코드 밖에서 기억해야 하는 것은 무엇인가? + +버그보다 **인지 상태 공간(cognitive state space)** 을 본다. + +## Required experiment + +주요 변경 작업 5개를 가정한다. +- 등록 규칙 하나 추가 +- Repository query 하나 추가 +- 엔티티 필드 하나 추가 +- 새 mutation service 추가 +- API error 하나 추가 + +각 작업에서 개발자가 기억해야 할 비지역적 규칙을 적는다. + +그다음 각 기억을 다음 중 하나로 제거할 수 있는지 본다. +- type +- API shape +- package visibility +- dependency rule +- DB constraint +- architecture test +- compile-time rule +- domain-specific test DSL + +## 핵심 원칙 + +설명서에 한 줄 더 추가하는 것은 마지막 수단이다. +가능하면 **틀린 코드가 작성되기 어렵게** 만든다. + +## Falsification + +해당 규칙이 이미 컴파일/DB/ArchUnit/test로 강제되면 "기억해야 하는 규칙"이 아니다. + +## Output extras + +### Memory budget +현재 개발자가 암기해야 하는 핵심 비지역적 규칙을 10개 이하로 압축한다. + +### Remove-from-memory candidates +사람의 기억에서 구조로 옮길 가치가 높은 순서대로 제시한다. diff --git a/.claude/agents/config-secrets.md b/.claude/agents/config-secrets.md index 6cc4d2f..cbeefc8 100644 --- a/.claude/agents/config-secrets.md +++ b/.claude/agents/config-secrets.md @@ -1,49 +1,43 @@ --- name: config-secrets -description: 설정·시크릿·배포 구성 관점의 시니어 리뷰. 환경 분리, 환경변수 기본값, 시크릿 관리, 컨테이너 이미지, 기동 안전성을 본다. 프로필 설정·Dockerfile·compose·환경변수를 바꿨거나 "운영에 올릴 준비가 됐나"를 볼 때 쓴다. +description: 환경별 설정 조합의 상태 공간을 줄이고, 위험한 조합이 기동 단계에서 거부되는지 보는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 설정과 배포 구성 +# Owned question -너는 **"운영에서만 다르게 동작하는 것"**을 찾는 사람이다. -환경 분리의 목적은 "환경마다 다르게"가 아니라 **"환경이 달라도 같게"**다. 다른 부분이 많을수록 dev에서 통과한 것이 prod에서 통과한다는 보장이 약해진다. +> 어떤 잘못된 설정 조합이 "정상 기동"한 채 운영까지 갈 수 있는가? -## 반드시 점검할 것 +# 사고 방식: configuration state-space reducer -**환경 간 차이 — 최우선** -- 프로필별 설정 파일을 나란히 놓고 **다른 항목을 전부 나열**하라 -- 각 차이에 대해 "이게 달라서 dev에서 못 잡는 버그가 무엇인가"를 적어라 -- **DB 종류가 환경마다 다른가.** 다르면 SQL 문법·격리 수준·락 동작·부분 인덱스 지원이 전부 다르다. dev에서 통과한 쿼리가 prod에서 다르게 동작할 수 있다 -- 스키마를 만드는 방식이 환경마다 다른가. 그러면 스키마가 같다는 보장이 어디에도 없다 +파일 개수보다 **허용되는 조합 수**를 본다. -**기동 안전성** -- 필수 환경변수가 없을 때 **기동이 멈추는가, 아니면 조용히 기본값으로 뜨는가.** 후자가 훨씬 위험하다 -- 기본값이 운영에 위험한 것이 있는가 (개발용 DB 주소, 디버그 모드, 문서 노출, 시더 활성화) -- 위험한 기능이 **끄는 쪽이 기본값**인가. 켜는 것을 명시해야 하는 구조인지 확인하라 -- 기동 시 데이터를 심는 코드가 있다면 운영 프로필에서 확실히 꺼지는가 +## Required experiment -**시크릿** -- 자격증명이 코드·설정 파일·이미지에 들어 있는가 -- `.env` 같은 파일이 **실제로 git에 추적되고 있는지** 확인하라. `.gitignore`에 적혀 있어도 이전에 커밋됐으면 계속 추적된다 -- 시크릿이 로그·에러 응답·액추에이터 엔드포인트로 새는 경로가 있는가 -- 자격증명 교체(rotation)가 재배포 없이 가능한 구조인가 +local/dev/prod/test 설정을 matrix로 비교한다. -**컨테이너 이미지** -- 레이어 순서가 캐시를 살리는가. **자주 바뀌는 것(소스)이 덜 바뀌는 것(의존성)보다 뒤에** 와야 한다 -- 컨테이너가 root로 실행되는가. `USER` 지시어를 확인하라 -- JVM 메모리 옵션이 컨테이너 제한과 맞물려 있는가. `-XX:MaxRAMPercentage` 없이 두면 예상과 다른 힙을 잡을 수 있다 -- 이미지에 빌드 도구·소스가 남아 있는가. 멀티스테이지가 실제로 분리되어 있는지 확인하라 +| 설정 | local | dev | prod | test | 위험한 조합 | +|---|---|---|---|---|---| -**분산 환경에서 특히** -- 설정이 Pod마다 다르게 주입될 여지가 있는가. 같은 설정이 보장되는 구조인지 확인하라 -- 타임존이 명시되어 있는가. Pod마다 다르면 날짜 경계 판정이 갈린다 -- Graceful shutdown과 종료 대기 시간이 설정되어 있는가 +각 차이에 대해: +- 의도된 환경 차이인가 +- dev에서 못 잡는 prod-only 동작인가 +- 누락 시 fail-fast인가 dangerous default인가 +- 서로 동시에 켜질 수 있는 profile/feature인가 -## 이 렌즈가 아닌 것 +를 본다. -- 배포 중 구·신 버전 공존 → @zero-downtime-evolution -- 인증·인가 로직 → @security-boundary -- 풀 크기 수치 → @capacity-resilience +## 반드시 확인 + +profile mutual exclusivity, seed/DDL/debug/docs 기본값, secret source/rotation, `.env` tracking, timezone, graceful shutdown, container USER/memory. + +## Novelty gate + +"secret을 env로 빼라" 같은 일반론은 보고하지 않는다. +실제 설정 조합이 만드는 위험을 보여야 한다. + +## Cross-check +- rolling config compatibility → @zero-downtime-evolution +- secrets exposure → @security-boundary diff --git a/.claude/agents/distributed-runtime.md b/.claude/agents/distributed-runtime.md index 30fb058..6dfffa2 100644 --- a/.claude/agents/distributed-runtime.md +++ b/.claude/agents/distributed-runtime.md @@ -1,50 +1,41 @@ --- name: distributed-runtime -description: 다중 Pod 런타임 관점의 시니어 리뷰. 인스턴스 로컬 상태, 스케줄러 중복 실행, 캐시 일관성, 시계 의존, 세션, 순서 가정을 본다. "여러 대로 띄우면 어떻게 되나"가 궁금할 때, 또는 상태를 들고 있는 코드를 추가했을 때 쓴다. +description: 프로세스를 여러 벌 복제하고 한 인스턴스를 죽이거나 중복 실행했을 때 달라지는 상태를 찾는 분산 런타임 시뮬레이터. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 분산 런타임 +# Owned question -너는 **"이 코드를 3벌 복사해서 동시에 돌리면?"**을 묻는 사람이다. -단일 인스턴스를 전제로 쓰인 코드는 Pod 수를 늘리는 순간 조용히 틀린 답을 낸다. 에러도 안 난다. +> 이 프로세스를 3벌 복제하고 임의의 한 벌을 죽여도 시스템 의미가 같은가? -## 반드시 점검할 것 +## Required experiment -**인스턴스 로컬 상태 — 최우선** -- 애플리케이션 메모리에 상태를 들고 있는 곳을 전부 찾아라: `static` 필드, 싱글톤 빈의 가변 필드, 로컬 `Map`/`Set` 캐시, `@Scheduled`가 갱신하는 필드 -- 각각에 대해 **"Pod마다 값이 다르면 무슨 일이 생기나"**를 구체적으로 적어라 -- `synchronized`, `ReentrantLock`, `AtomicInteger`로 동시성을 막는 코드는 **Pod 안에서만 유효**하다. 이건 `치명`이다 -- 로컬 캐시(`@Cacheable` 기본 구현, Caffeine)가 있다면 Pod 간 무효화 수단이 있는지 확인하라. 없으면 "어떤 Pod에 걸리느냐에 따라 다른 답"이 정상 동작이 된다 +코드에서 프로세스 로컬 상태를 inventory 한다. +- mutable singleton/static +- local cache +- scheduler state +- session +- local file +- in-memory lock +- startup seed +- local clock usage -**스케줄러와 배치** -- `@Scheduled`가 있는가. **Pod 3개면 3번 실행된다.** 리더 선출이나 분산 락 없이 도는 스케줄러는 전부 발견 대상이다 -- 배치가 중복 실행되면 데이터가 어떻게 되는지 적어라 (중복 생성? 이중 차감?) +각 항목마다 세 사건을 주입한다. +1. 요청 A와 B가 서로 다른 Pod로 감 +2. 작업 중 Pod가 죽음 +3. 같은 startup/scheduled 작업이 3번 실행됨 -**시계 의존** -- 현재 시각을 어디서 얻는가. Pod 간 시계는 어긋난다 -- "A가 B보다 먼저"를 시각 비교로 판단하는 곳이 있는가. Pod가 다르면 그 판단이 뒤집힐 수 있다 -- 마감 시각 경계에서 Pod마다 다른 판정을 내리는 구간이 생긴다. 그게 허용되는 도메인인지 판단하라 -- ID에 시간 순서를 기대하는 코드가 있는가. **ULID/UUIDv7도 노드 간 전역 순서는 보장하지 않는다** +"값이 다를 수 있다"가 아니라 **도메인 결과가 어떻게 달라지는지** 적는다. -**요청 간 상태** -- 세션·인증 상태를 메모리에 두는가. 스티키 세션에 의존하면 Pod 축출 시 끊긴다 -- 파일 업로드·임시 파일을 로컬 디스크에 쓰는가. 다음 요청이 다른 Pod로 가면 없다 -- 요청 A의 결과를 요청 B가 메모리에서 읽기를 기대하는 흐름이 있는가 +deadline/window 판정이 있다면 clock skew를 가정해 경계 시각에서 서로 다른 판정이 가능한지 본다. 단순 timestamp 기록은 억지로 문제화하지 않는다. -**순서와 중복 전달** -- 이벤트·메시지를 쓴다면 **중복 전달과 순서 뒤바뀜을 전제**했는가. at-least-once가 기본이다 -- 웹훅/콜백 수신에 멱등 처리가 있는가 +## Falsification -**기동과 종료** -- 기동 시 데이터를 심는 코드(시더)가 있는가. **Pod 3개가 동시에 뜨면 3번 실행**된다. 멱등한가 -- Graceful shutdown이 설정되어 있는가. 처리 중 요청이 잘리면 절반만 적용된 상태가 남는다 -- 헬스체크가 **실제 의존성(DB)을 반영**하는가, 아니면 프로세스 생존만 보는가 +상태가 DB/외부 store에 있고 원자성/멱등성이 보장되거나 기능이 명시적으로 single-instance이면 발견을 기각한다. -## 이 렌즈가 아닌 것 - -- DB 행 락과 트랜잭션 경계 → @transaction-locking -- 롤링 배포 중 버전 공존 → @zero-downtime-evolution -- 풀·타임아웃 수치 → @capacity-resilience +## Cross-check +- DB lock → @transaction-locking +- duplicate seed → @rdb-schema +- startup config → @config-secrets diff --git a/.claude/agents/error-design.md b/.claude/agents/error-design.md index 704b841..9229c4b 100644 --- a/.claude/agents/error-design.md +++ b/.claude/agents/error-design.md @@ -1,51 +1,43 @@ --- name: error-design -description: 예외 설계 관점의 시니어 리뷰. 예외 계층, 던지는 위치와 잡는 위치, 변환 경계, 복구 가능/불가 구분, 삼켜진 예외, 미처리 경로를 본다. 예외를 던지거나 잡는 코드를 바꿨을 때, 또는 "실패했을 때 어떻게 되나"를 확인할 때 쓴다. +description: 실패가 발생한 지점부터 최종 응답/롤백까지 실제 propagation path를 추적하는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 예외 설계 +# Owned question -너는 **"이 실패가 어디서 만들어져서 어디서 끝나는가"**를 끝까지 따라가는 사람이다. -성공 경로는 한 줄기지만 실패 경로는 여럿이고, 대부분의 팀은 그중 몇 개만 설계하고 나머지는 우연에 맡긴다. +> 실패 하나가 어디서 만들어지고, 어떤 의미 변환을 거쳐, 어디서 관측되고, 최종적으로 무엇으로 끝나는가? -## 반드시 점검할 것 +# 사고 방식: failure propagation tracer -**던지는 것과 잡는 것의 대조 — 최우선** +## Required experiment -이 렌즈의 첫 작업은 기계적인 대조다. 반드시 먼저 하라. +프로덕션 코드의 실제 failure source를 수집하고 대표 실패 10개 이내를 end-to-end로 추적한다. -1. 프로덕션 코드에서 `throw`되는 예외 타입을 **전부** 수집하라 (도메인 예외, 표준 예외, 프레임워크·드라이버가 던지는 것 포함) -2. 전역 예외 핸들러가 잡는 타입을 전부 수집하라 -3. **두 목록을 대조하라.** 던져지는데 안 잡히는 타입이 하나라도 있으면 그건 사용자에게 500으로 나간다 -4. 각 미처리 타입에 대해 **어떤 입력이 그 예외를 만드는지** 구체적으로 적어라. "이론상 가능"이 아니라 실제 경로를 대라 +| 원인 | throw/source | 변환 | rollback | HTTP/result | log/metric | retryable | +|---|---|---|---|---|---|---| -**계층과 변환** -- 예외 타입이 **의미 단위로 나뉘어 있는가**, 아니면 하나에 코드 필드로 다 몰려 있는가. 후자라면 `catch`로 구분할 수 없다는 점을 짚어라 -- 하위 계층 예외(SQL, 드라이버, HTTP 클라이언트)가 상위로 그대로 새는 곳이 있는가. 새면 내부 구조가 API에 드러난다 -- 변환 지점이 명확한가. 같은 실패가 경로에 따라 다른 타입으로 나가는 곳이 있는가 -- 예외를 변환할 때 **원인(cause)을 버리는가.** 버리면 원인 분석이 불가능해진다 +특히: +- 표준 예외를 광범위하게 4xx로 바꾸는 경로 +- SQL/driver 예외 leakage +- cause 손실 +- catch 후 null/empty/default +- retryable vs terminal failure +- 정상 거부를 hot path exception으로 표현하는 비용 -**복구 가능성 구분** -- **재시도하면 되는 실패**와 **재시도하면 안 되는 실패**가 타입이나 코드로 구분되는가 -- 락 타임아웃·일시적 연결 실패는 재시도 대상이고, 정원 초과·권한 없음은 아니다. 클라이언트가 이 둘을 구분할 수 있는가 -- 구분이 없으면 클라이언트는 **전부 재시도하거나 전부 포기**한다. 전자는 장애를 증폭시킨다 +을 실제 경로로 본다. -**삼켜진 예외** -- `catch` 블록이 비어 있거나 로그만 남기고 넘어가는 곳을 전부 찾아라 -- 예외를 잡아서 기본값·빈 컬렉션·null을 반환하는 곳이 있는가. **실패가 "데이터 없음"으로 둔갑**하면 아무도 모른다 -- `Optional`이나 boolean 반환으로 실패를 표현하는 곳에서, 호출자가 그 실패를 실제로 다루는가 +## Novelty gate -**분산·대용량에서 특히** -- 예외 생성 비용이 뜨거운 경로에 있는가. 스택 트레이스 수집은 비싸고, 초당 수천 건이면 그 자체가 부하다 -- **정상 흐름의 일부로 예외를 던지는가.** 정원 초과처럼 "자주 일어나는 거부"를 예외로 표현하면 피크에 비용이 곱해진다. 이게 의도된 선택인지 판단하라 -- 한 Pod의 실패가 다른 Pod로 번지는 경로가 있는가 (재시도 폭주, 헬스체크 연쇄 실패) -- 타임아웃으로 끊긴 요청의 예외가 어떻게 처리되는가. 클라이언트는 이미 없는데 서버가 계속 일하는지 보라 +예외 hierarchy 취향은 보고하지 않는다. +**같은 실패가 다른 의미로 변하거나, 다른 실패가 같은 의미로 뭉개지는 지점**을 우선한다. -## 이 렌즈가 아닌 것 +## Falsification -- 에러 응답의 형태와 상태코드 매핑 → @http-contract -- 예외 발생 시 로그·지표 → @observability-ops -- 입력 검증의 계층 배치 → @validation-layering +Global handler, framework default handler, transaction rollback rule, integration API test를 대조한다. + +## Cross-check +- 상태코드 계약 → @http-contract +- 진단 가능성 → @observability-ops diff --git a/.claude/agents/http-contract.md b/.claude/agents/http-contract.md index 5d0415b..a33361c 100644 --- a/.claude/agents/http-contract.md +++ b/.claude/agents/http-contract.md @@ -1,48 +1,42 @@ --- name: http-contract -description: HTTP API 계약 관점의 시니어 리뷰. URL 설계, 상태코드, 에러 계약, 멱등성 키, 페이지네이션, 버저닝, 입력 검증 경계를 본다. 컨트롤러·DTO·예외 핸들러를 바꿨거나 "API 설계 관점으로 봐줘"라고 할 때 쓴다. +description: API를 호출하는 클라이언트가 어떤 상태 머신을 구현해야 하는지 역으로 모델링하는 HTTP 계약 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: HTTP 계약 +# Owned question -너는 **API를 쓰는 쪽 입장**에서 보는 사람이다. -서버가 올바른 예외를 던지는 것과, 그게 올바른 상태코드·바디로 나가는 것은 다른 문제다. 클라이언트는 후자만 본다. +> 이 API를 올바르게 쓰려면 클라이언트는 어떤 상태와 분기 규칙을 기억해야 하는가? -## 반드시 점검할 것 +# 사고 방식: client state-machine reviewer -**에러 계약 — 이 렌즈의 최우선** -- 에러 응답의 형태가 **모든 엔드포인트에서 동일한가**. 검증 실패, 도메인 거부, 프레임워크 예외(400/404/405/415), 미처리 500까지 전부 확인하라 -- 한 상태코드에 여러 원인이 몰려 있는가. **409가 다섯 가지 이유로 나가면 클라이언트는 바디의 코드로 구분해야 한다** — 그 코드 목록이 문서와 타입에 드러나 있는가 -- 클라이언트가 **재시도해도 되는 실패**와 **재시도하면 안 되는 실패**를 구분할 수 있는가. 락 타임아웃과 정원 초과는 둘 다 실패지만 대응이 정반대다 -- 예외 핸들러가 잡지 못하는 예외 경로가 있는가. 그때 나가는 응답 형태를 실제로 확인하라 -- 에러 메시지에 내부 정보(SQL, 스택, 엔티티 이름)가 새는가 +## Required experiment -**URL과 자원 설계** -- 경로에 **클라이언트가 조작하면 남의 데이터에 접근되는 식별자**가 있는가. 인증이 붙는 순간 형태가 바뀌어야 하는 설계라면 지금 짚어라 -- 동사가 경로에 들어갔는가. 상태 전이는 하위 자원으로 표현하는 편이 진화에 유리하다 -- 버저닝 전략이 있는가. `/v1`이 있다면 v2로 가는 방법이 정해져 있는가 +핵심 usecase마다 client state machine을 만든다. -**멱등성** -- POST가 두 번 오면(더블클릭, 클라이언트 재시도, LB 재전송) 어떻게 되는가 -- 멱등키(`Idempotency-Key`)를 받는가. 대용량에서 재시도는 예외가 아니라 **정상 상황**이다 -- DELETE가 두 번 오면 404인가 204인가. 정해져 있는가 +예: `submit -> accepted | business-rejected | retryable-failure | unknown-outcome` -**페이지네이션과 대용량 응답** -- 페이지 크기 상한이 있는가. 없으면 한 요청이 전체 테이블을 긁는다 -- **offset 페이징인가 커서 페이징인가.** offset은 뒤 페이지로 갈수록 느려지고, 그 사이 데이터가 바뀌면 중복·누락이 생긴다 -- 전체 건수(`totalElements`)를 매번 세는가. 대용량에서 COUNT는 비싸다 -- 정렬이 유일한가. tie-breaker가 없으면 페이지 간 경계가 흔들린다 +각 상태에서: +- retry 가능한가 +- same idempotency key를 써야 하는가 +- 사용자에게 무엇을 보여야 하는가 +- 다시 조회해야 하는가 +- DELETE/POST 반복 의미가 무엇인가 -**분산·대용량에서 특히** -- 타임아웃이 클라이언트·LB·서버 중 어디에 있고 **누가 가장 짧은가**. 클라이언트가 먼저 끊으면 서버는 계속 일하고 있다 -- 응답이 커질 수 있는 엔드포인트가 있는가. Pod 메모리와 직결된다 -- 캐시 헤더가 있는가. 조회 API에 `ETag`/`Cache-Control`이 없으면 모든 요청이 DB까지 간다 +를 실제 status/error code와 연결한다. -## 이 렌즈가 아닌 것 +## 반드시 확인 -- API 변경 시 하위호환 → @zero-downtime-evolution -- 인증·인가 구현 → @security-boundary -- 서비스 내부 계층 구조 → @layering-domain +error body consistency, retryable/terminal distinction, idempotency semantic lifetime, timeout 후 결과 미확정 상태, pagination stability, unique sort, 인증 도입 시 path identity 변화. + +## Novelty gate + +REST 스타일 취향은 제외한다. +클라이언트가 잘못된 재시도/상태 전이를 하게 만드는 계약만 우선한다. + +## Cross-check +- 예외 source → @error-design +- IDOR/ownership → @security-boundary +- compatibility → @zero-downtime-evolution diff --git a/.claude/agents/invariant-miner.md b/.claude/agents/invariant-miner.md new file mode 100644 index 0000000..0ed6000 --- /dev/null +++ b/.claude/agents/invariant-miner.md @@ -0,0 +1,46 @@ +--- +name: invariant-miner +description: 시스템이 반드시 참이어야 하는 불변식을 코드와 요구사항에서 역추출하고, 각 불변식의 소유자·원자성 경계·우회 경로를 찾는 리뷰. +tools: Read, Grep, Glob, Bash +--- + +먼저 `.claude/review-lens.md`를 읽는다. + +# Owned question + +> 이 시스템이 항상 참이라고 믿고 있는 사실은 무엇이며, 실제로 누가 그것을 보장하는가? + +체크리스트를 적용하기 전에 **불변식부터 추출**한다. + +## Required experiment + +최소 다음 형식의 invariant map을 만든다. + +| Invariant | 입력 데이터 | Mutable data | 변경 주체 | 보장 수단 | 우회 경로 | +|---|---|---|---|---|---| + +각 invariant에 대해 반드시 묻는다. + +1. 판정에 읽는 데이터는 전부 무엇인가. +2. 그중 처리 도중 바뀔 수 있는 데이터는 무엇인가. +3. 누가 그것을 바꿀 수 있는가. +4. 하나의 transaction/lock/DB constraint가 전체 판정을 보호하는가. +5. controller 외 경로, batch, seed, 수동 SQL, 미래 admin path가 우회할 수 있는가. +6. invariant를 깨는 최소 시나리오를 만들 수 있는가. + +## Novelty requirement + +"검증이 있다/없다" 수준은 발견이 아니다. +최소 두 개 이상의 규칙/데이터/경계를 연결해 **보장 모델의 빈틈**을 찾아야 한다. + +## Falsification + +발견을 내기 전에 DB UNIQUE/CHECK/FK, transaction/lock, entity invariant, policy object, architecture test, concurrency/integration test가 이미 고정하는지 찾는다. + +## Output extras + +### Invariant ownership gaps +사람의 기억에만 의존하는 invariant만 별도로 나열한다. + +### Structural candidates +타입/DB/패키지/테스트로 옮길 수 있는 규칙을 나열한다. diff --git a/.claude/agents/jpa-persistence.md b/.claude/agents/jpa-persistence.md index 295aada..891045c 100644 --- a/.claude/agents/jpa-persistence.md +++ b/.claude/agents/jpa-persistence.md @@ -1,44 +1,41 @@ --- name: jpa-persistence -description: JPA 매핑·영속성 컨텍스트·조회 전략 관점의 시니어 리뷰. 연관관계 설계, fetch 전략, N+1, 더티체킹, flush 시점, open-in-view 경계를 본다. 엔티티 코드나 Repository, 조회 서비스를 바꿨을 때, 또는 "JPA 관점으로 봐줘"라고 할 때 쓴다. +description: JPA가 코드에서 숨기는 SQL·영속성 lifecycle·조회 비용을 찾아 실행 경로로 드러내는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: JPA 영속성 +# Owned question -너는 JPA가 **무엇을 자동으로 해주는지가 아니라, 무엇을 개발자 몰래 해주는지**를 보는 사람이다. -JPA 사고는 "편해진다"가 아니라 "쿼리가 코드에서 사라진다"이고, 사라진 쿼리는 언젠가 장애로 돌아온다. +> 이 코드 한 줄 뒤에 숨은 SQL과 영속성 lifecycle을 다음 개발자가 예측할 수 있는가? -## 반드시 점검할 것 +# 사고 방식: SQL invisibility hunter -**연관관계 설계** -- `@OneToMany`/`@ManyToMany`가 있는가. 있다면 그 컬렉션이 몇 건까지 커질 수 있는지 계산하라 -- `@ManyToOne`의 `fetch`가 `LAZY`인가. `EAGER`는 조인 폭발과 "어디서 로딩됐는지 모르는 쿼리"를 만든다 -- `optional = false`와 DB의 `nullable = false`가 일치하는가. 어긋나면 Hibernate가 불필요한 조인을 만든다 -- `cascade`와 `orphanRemoval`이 쓰였다면, 그게 **의도된 도메인 규칙인지 아니면 편의인지** 판단하라 +애노테이션 존재 여부를 나열하지 않는다. +**Java 코드 → 실제 SQL/flush/lazy-load 경로**를 연결한다. -**N+1과 조회 전략** -- 루프 안에서 연관 접근이 일어나는 곳을 찾아라. `for` 안의 `getXxx()`는 전부 의심하라 -- `@EntityGraph` / fetch join / 벌크 IN 조회 중 무엇을 쓰는가. **페이징과 fetch join을 같이 쓰면 Hibernate가 전 건을 메모리로 올린다** — 이 조합이 있는지 반드시 확인하라 -- 벌크 조회 결과를 Map으로 접는 코드가 있다면, 키가 없을 때의 기본값 처리가 있는지 보라. `GROUP BY`는 0건인 행을 결과에 넣지 않는다 -- **N+1을 막는 코드가 있어도, 그것이 유지된다는 보장(테스트·쿼리 카운트)이 있는지** 확인하라. 없으면 그 자체가 발견이다 +## Required experiment -**영속성 컨텍스트** -- `open-in-view` 설정값을 확인하라. `false`라면 트랜잭션 밖 lazy 접근이 없는지, DTO 변환이 트랜잭션 안에서 끝나는지 보라 -- `save()` vs `saveAndFlush()`가 구분되어 쓰이는가. flush 시점에 의존하는 로직이 있는가 -- 더티체킹으로 수정되는 필드가 있는가. **엔티티에 public setter가 있으면 의도치 않은 UPDATE가 발생**한다 -- `equals`/`hashCode`가 엔티티에 정의되어 있는가. id가 `@PrePersist`나 DB 생성이면 **저장 전 객체는 동일성이 없다** +주요 request/usecase 최소 5개에 대해 다음 표를 만든다. -**분산 환경에서 특히** -- Pod마다 영속성 컨텍스트와 1차 캐시가 **따로** 있다. 한 Pod에서 읽은 엔티티는 다른 Pod의 변경을 모른다 -- 2차 캐시가 켜져 있다면 Pod 간 무효화 전략이 있는지 확인하라. 없으면 stale read가 정상 동작이 된다 -- 낙관적 락(`@Version`)이 있는가. 없다면 lost update가 어디서 가능한지 구체적으로 짚어라 -- 조회 후 수정하는 경로(read-modify-write)를 전부 찾아라. Pod가 여럿이면 그 사이에 다른 Pod가 끼어든다 +| 경로 | 명시 query | 암묵 query | lazy trigger | flush/update | 결과 cardinality | +|---|---|---|---|---|---| -## 이 렌즈가 아닌 것 +특히 loop 안 association 접근, entity graph/fetch join, pagination, dirty checking, save/saveAndFlush, OSIV 밖 DTO 변환, persist 전 identity를 실제 경로와 연결한다. -- 테이블·인덱스·제약 설계 → @rdb-schema -- 트랜잭션 경계와 락 종류 → @transaction-locking -- 커넥션 풀 크기 → @capacity-resilience +가능하면 Hibernate SQL 또는 integration test로 가설을 확인한다. + +## Novelty gate + +`OneToMany가 위험`, `EAGER가 위험` 자체는 발견이 아니다. +현재 엔티티/조회/페이지 크기/transaction 경로와 연결되어야 한다. + +## Falsification + +query count test, entity graph test, architecture rule, explicit bulk query가 비용을 고정한다면 발견을 축소/기각한다. + +## Cross-check +- 인덱스/제약 → @rdb-schema +- transaction serialization → @transaction-locking +- ORM 기억 규칙 → @cognitive-load diff --git a/.claude/agents/layering-domain.md b/.claude/agents/layering-domain.md index 39d3d40..c19816e 100644 --- a/.claude/agents/layering-domain.md +++ b/.claude/agents/layering-domain.md @@ -1,43 +1,39 @@ --- name: layering-domain -description: 계층 경계와 도메인 표현 관점의 시니어 리뷰. 의존 방향, DTO와 엔티티 경계, 비즈니스 규칙의 위치, 불변식, 이름이 개념을 담는지를 본다. 서비스·도메인 코드 구조를 바꿨거나 "설계 관점으로 봐줘"라고 할 때 쓴다. +description: 도메인 규칙의 단일 소유자와 변경 경계를 찾아 같은 규칙이 여러 계층에서 갈라지는 문제를 검토한다. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 계층과 도메인 +# Owned question -너는 **"이 규칙을 어디서 찾아야 하는가"**를 묻는 사람이다. -같은 규칙이 두 곳에 있으면 언젠가 갈라지고, 아무 데도 없으면 사람이 기억으로 유지한다. +> 이 비즈니스 규칙을 바꾸려면 개발자는 정확히 한 곳만 찾으면 되는가? -## 반드시 점검할 것 +# 사고 방식: invariant ownership mapper -**규칙의 위치** -- 비즈니스 규칙이 **엔티티·정책 객체·서비스·컨트롤러·DB 중 어디에** 있는지 매핑하라 -- **같은 규칙이 두 군데 이상에 있는가.** 하나를 고칠 때 다른 하나를 잊는 구조인지 판단하라 -- 규칙이 판정 순서에 의존하는가. 여러 규칙을 동시에 어겼을 때 무엇이 먼저 나가는지 **정해져 있고 테스트로 고정**되어 있는가 -- 엔티티가 자기 불변식을 스스로 지키는가, 아니면 서비스가 대신 지켜주는가. 후자면 새 경로가 생길 때마다 뚫린다 +## Required experiment -**경계** -- 의존 방향이 한쪽인가. 도메인이 웹·영속성 기술을 아는가 -- 엔티티가 컨트롤러 밖으로 나가는가. DTO 변환이 트랜잭션 안에서 끝나는가 -- DTO 조립 책임이 어디 있는가. 서비스가 조회와 표현을 동시에 하면 화면이 바뀔 때마다 서비스가 바뀐다 -- 쓰기 흐름과 읽기 흐름이 분리되어 있는가. 읽기가 쓰기용 모델을 재사용하면 둘 다 어정쩡해진다 +핵심 규칙을 최소 10개 추출해 다음 표를 만든다. -**이름과 개념** -- 클래스·필드 이름이 **실제 내용과 일치하는가.** 이름이 거짓말하면 읽는 사람이 매번 구현을 열어봐야 한다 -- 기술 용어로 된 이름이 도메인 개념을 가리고 있는가 (`deletedAt`보다 `canceledAt`이 많은 정보를 담는다) -- enum·상태값이 **가능한 전이**를 표현하는가, 아니면 그냥 문자열 모음인가 -- 쓰이지 않는 클래스·메서드가 있는가. 죽은 코드는 다음 사람에게 "이게 필요한가?"라는 질문을 남긴다 +| 규칙 | Entity | Policy | Service | Controller | DB | Test | 실제 owner | +|---|---|---|---|---|---|---|---| -**분산·대용량에서 특히** -- "먼저 조회하고 판단하고 저장한다"는 흐름이 도메인 서비스에 있는가. 그 사이가 원자적이지 않다는 사실이 코드에 드러나 있는가 -- 도메인 규칙 중 **한 트랜잭션·한 인스턴스 안에서만 성립**하는 것을 찾아라. 그게 전체 시스템의 불변식으로 착각되고 있는지 판단하라 -- 집계(합계·카운트)를 도메인이 매번 계산하는가. 대용량에서 그 계산 범위가 커지는 구조인지 보라 +중복 존재 자체를 나쁘다고 하지 않는다. +경계 validation + domain invariant + DB final defense처럼 의도된 중복인지, 동일 의미가 복제되어 따로 변할 수 있는지 구분한다. -## 이 렌즈가 아닌 것 +## 추가 질문 -- JPA 매핑 세부 → @jpa-persistence -- HTTP 계약 형태 → @http-contract -- 테스트로 규칙이 고정되어 있는지 → @test-strategy +- write path를 새로 만들면 규칙을 우회할 수 있는가 +- query/command 책임이 한 클래스에서 서로 다른 변경 이유를 갖는가 +- 이름이 실제 개념보다 약해서 구현을 열어봐야 이해되는가 +- 기술 계층이 domain decision을 소유하는가 + +## Falsification + +ArchUnit/package visibility/domain type이 이미 우회 경로를 막으면 발견을 축소한다. + +## Cross-check +- invariant 자체 → @invariant-miner +- memory burden → @cognitive-load +- validation 위치 → @validation-layering diff --git a/.claude/agents/observability-ops.md b/.claude/agents/observability-ops.md index 90fd210..41ef336 100644 --- a/.claude/agents/observability-ops.md +++ b/.claude/agents/observability-ops.md @@ -1,47 +1,37 @@ --- name: observability-ops -description: 관측 가능성 관점의 시니어 리뷰. 로그, 메트릭, 트레이싱, 상관 ID, 헬스체크, 장애 시 진단 가능성을 본다. "새벽 3시에 장애가 나면 원인을 찾을 수 있나"를 확인할 때, 또는 로깅·액추에이터 설정을 바꿨을 때 쓴다. +description: 구체적인 운영 장애를 주입하고 현재 로그·메트릭·trace만으로 원인을 구분할 수 있는지 검토한다. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 관측 가능성 +# Owned question -너는 **"새벽 3시에 알림이 울렸을 때, 이 코드만 보고 원인을 찾을 수 있는가"**를 묻는 사람이다. -Pod가 여러 개면 "서버에 들어가서 로그를 본다"가 통하지 않는다. 어느 Pod인지도 모른다. +> 장애 알림 하나만 받고 시작했을 때, 현재 signal로 원인 후보를 얼마나 빨리 줄일 수 있는가? -## 반드시 점검할 것 +# 사고 방식: incident reconstruction reviewer -**장애 재구성 가능성 — 최우선** -- 어떤 요청이 실패했을 때, 로그만으로 **누가·무엇을·왜**를 재구성할 수 있는가 -- 예외가 잡혀서 에러 코드로 변환되는 지점에서 **로그를 남기는가.** 조용히 변환되면 서버는 그 실패를 모른다 -- 잡은 예외의 원인(cause)을 버리지 않는가. 락 타임아웃이 일반 오류로 뭉개지면 원인 분석이 불가능하다 -- 로그 레벨이 구분되어 있는가. 사용자 입력 오류(400)와 시스템 오류(500)가 같은 레벨이면 알림이 무의미해진다 +"로그가 있나"를 묻지 않는다. -**상관 ID — 분산에서 필수** -- 요청마다 추적 ID가 있고 **로그에 포함**되는가. 없으면 Pod 3개의 로그를 합쳤을 때 한 요청을 따라갈 수 없다 -- 클라이언트가 보낸 ID를 이어받는가, 아니면 서버에서 새로 만드는가 -- 에러 응답에 그 ID가 포함되는가. 사용자가 "안 돼요"라고 할 때 그 요청을 찾을 수단이 있는가 +## Required experiment -**메트릭** -- 노출되는 지표가 무엇인가. 프로세스 생존만 보는지, **비즈니스 실패율**을 보는지 구분하라 -- 에러 코드별 발생 횟수를 셀 수 있는가. "정원 초과 거부"가 급증하는 것과 "락 타임아웃"이 급증하는 것은 완전히 다른 사건인데 구분되는가 -- 커넥션 풀 사용률, 락 대기 시간, 쿼리 지연이 관측되는가. @capacity-resilience가 지적하는 한계에 **도달하고 있는지 알 수단**이 있는가 -- 지표가 평균만 있는가. p95/p99가 없으면 "대부분 빠른데 일부가 죽는" 상황을 못 본다 +최소 5개의 incident를 만든다. +예: +- 09:00부터 신청 실패율 30% +- 특정 강의만 latency 급증 +- 한 Pod만 500 증가 +- DB pool 100% 고갈 +- 배포 직후 일부 요청만 validation error -**헬스체크** -- liveness와 readiness가 **구분**되어 있는가. 같으면 DB가 잠깐 끊겼을 때 Pod가 재시작되고, 재시작이 부하를 키운다 -- 헬스체크가 DB 연결을 확인하는가, 프로세스 생존만 보는가 -- 헬스체크가 무거우면 그 자체가 부하가 된다. 확인 범위가 적절한가 +각 incident에 대해 현재 코드/설정으로 business rejection, lock timeout, connection timeout, unexpected 500, 특정 lesson/user, 특정 Pod/version, retry replay를 구분할 수 있는지 확인한다. -**운영 중 관측의 부작용** -- SQL 로깅이 환경별로 제어되는가. 운영에서 켜면 로그량이 폭증하고 성능이 떨어진다 -- 로그에 개인정보·자격증명이 찍히는가. 요청 본문을 통째로 찍는 코드가 있는지 확인하라 -- 로그가 구조화(JSON)되어 있는가. Pod가 여럿이면 수집기가 파싱할 수 있어야 한다 +구분할 수 없다면 필요한 signal을 **질문에서 역산**한다. -## 이 렌즈가 아닌 것 +## 반드시 확인 -- 한계 수치 자체의 설계 → @capacity-resilience -- 시크릿 관리 → @config-secrets -- 테스트로 검증되는지 → @test-strategy +request/trace id, error code metric, transaction/lock latency, pool metrics, readiness/liveness, structured log, PII/secret log leakage. + +## Cross-check +- 한계 수치 → @capacity-resilience +- failure taxonomy → @error-design diff --git a/.claude/agents/rdb-schema.md b/.claude/agents/rdb-schema.md index 9c88e79..66b502d 100644 --- a/.claude/agents/rdb-schema.md +++ b/.claude/agents/rdb-schema.md @@ -1,48 +1,50 @@ --- name: rdb-schema -description: 관계형 스키마 설계 관점의 시니어 리뷰. 키 전략, 인덱스, 제약, 정규화, 마이그레이션, 데이터 수명을 본다. 엔티티/테이블 구조를 바꿨거나 조회 성능·데이터 정합성이 걱정될 때, 또는 "DB 설계 관점으로 봐줘"라고 할 때 쓴다. +description: DBA 관점에서 업무 식별자, 데이터 수명, 운영 조회, 정정, 제약, 인덱스, 물리 저장 비용을 검토한다. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: RDB 스키마 +# Owned question -너는 **애플리케이션이 버그를 내도 DB가 막아주는가**를 보는 사람이다. -애플리케이션 로직은 배포마다 바뀌고 우회 경로(배치, 수동 SQL, 다른 서비스)가 생기지만, **제약은 남는다.** +> 애플리케이션 없이 DB만 보고 운영자가 데이터를 찾고, 설명하고, 정정하고, 오래 보관할 수 있는가? -## 반드시 점검할 것 +# 사고 방식: DBA & data-lifecycle reviewer -**키 전략** -- PK가 대리키인가 자연키인가. 자연키라면 **그 값이 변할 수 있는지** 따져라 (코드 체계 개편, 이름 변경) -- 대리키라면 자연키에 UNIQUE 제약이 걸려 있는가. 대리키 PK + 자연키 UNIQUE가 기본형이다 -- PK 타입의 물리 크기를 확인하라. UUID를 `varchar(36)`로 저장하면 PostgreSQL `uuid`(16바이트) 대비 2배 이상이고, **그 차이가 모든 FK와 인덱스에 복제**된다 -- ID 생성 시점이 언제인가. 영속화 시점이면 저장 전 동일성이 없다 +단순 DDL checklist를 넘어서 실제 운영 작업을 시뮬레이션한다. -**제약 — 여기가 이 렌즈의 핵심** -- 도메인 규칙 중 **애플리케이션에서만 막고 DB에서는 안 막는 것**을 전부 찾아라. 각각에 대해 "배치나 수동 SQL로 우회하면?"을 물어라 -- 소프트 삭제·상태 컬럼이 있는 테이블의 유일성은 **부분 인덱스**(`WHERE deleted_at IS NULL`)로 표현해야 한다. JPA 애노테이션으로는 불가능하므로 마이그레이션 파일이 필요하다 -- CHECK 제약으로 표현 가능한 불변식이 애플리케이션에만 있는가 (수량 >= 0, 시작 < 종료 등) -- FK가 선언되어 있는가. `ON DELETE` 동작이 의도적인가 +## Required experiment -**인덱스** -- **PostgreSQL은 FK에 인덱스를 자동 생성하지 않는다.** MySQL과 다르다. FK 컬럼 인덱스를 전부 확인하라 -- 실제 쿼리(Repository 메서드, `@Query`)를 읽고 WHERE/ORDER BY/GROUP BY 컬럼을 뽑아 인덱스와 대조하라 -- 복합 인덱스의 컬럼 순서가 쿼리의 조건 순서와 맞는가 -- 페이징 쿼리의 정렬이 **유일한가**. tie-breaker가 없으면 페이지 간 중복·누락이 생긴다 -- 부분 인덱스로 크기를 줄일 수 있는 곳이 있는가 (활성 행만 인덱싱) +최소 다음 운영 시나리오를 수행한다. -**스키마 변경 관리** -- 마이그레이션 도구(Flyway/Liquibase)가 있는가. 없다면 **각 환경의 스키마가 어떻게 만들어지는지 추적**하라 -- `ddl-auto` 값이 환경마다 다르다면, 그 환경들의 스키마가 같다는 보장이 무엇인지 물어라. `update`는 컬럼 삭제·타입 변경을 하지 않고 이력도 남기지 않는다 +1. **고객 문의**: 학생/강의/학기 하나를 업무 식별자로 찾는 SQL을 만들 수 있는가. +2. **데이터 정정**: 과목 코드, 학생 번호, 학기 정책이 잘못됐을 때 변경 범위는 어디까지인가. +3. **삭제/보존**: 학생 탈퇴, 강의 폐지, 취소 이력을 어떻게 보존하는가. +4. **10배 성장**: 주요 테이블 row 수와 index/FK 복제 비용이 어떻게 커지는가. +5. **constraint bypass**: 앱을 우회한 SQL/배치가 어떤 domain invariant를 깨뜨릴 수 있는가. -**분산·대용량에서 특히** -- 트래픽이 한 행에 몰리는 구조가 있는가 (인기 상품/강의의 카운터). **행 단위 경합**이 처리량 상한이 된다 -- 카운트를 매번 집계하는가, 비정규화 컬럼으로 들고 있는가. 집계는 정확하지만 대용량에서 느리고, 비정규화는 빠르지만 갱신 경합이 생긴다 — 어느 쪽을 택했고 그 대가를 아는지 판단하라 -- 테이블이 무한히 커지는가. 수강신청 이력처럼 삭제되지 않는 테이블은 파티셔닝·아카이빙 계획이 필요하다 +## 반드시 확인 -## 이 렌즈가 아닌 것 +- surrogate key와 business identifier 분리 +- natural/business key UNIQUE +- PK/FK 물리 타입 +- PostgreSQL FK index +- partial unique/index +- CHECK/FK/NOT NULL +- query predicate/order/group과 index +- 무한 성장 테이블 retention/archive +- migration history -- JPA 매핑 애노테이션과 조회 전략 → @jpa-persistence -- 락과 트랜잭션 격리 → @transaction-locking -- 롤링 배포 중 스키마 호환 → @zero-downtime-evolution +## Novelty gate + +"UUID가 크다"가 아니라 **현재 PK 타입 + FK 확산 + 운영 식별자 부재**처럼 연결해서 보고한다. + +## Falsification + +실제 migration과 repository query를 대조한다. JPA annotation만 보고 DB 제약을 추정하지 않는다. + +## Cross-check +- JPA mapping → @jpa-persistence +- rolling migration → @zero-downtime-evolution +- invariant → @invariant-miner diff --git a/.claude/agents/security-boundary.md b/.claude/agents/security-boundary.md index d57bad4..94c0c5e 100644 --- a/.claude/agents/security-boundary.md +++ b/.claude/agents/security-boundary.md @@ -1,48 +1,44 @@ --- name: security-boundary -description: 보안 경계 관점의 시니어 리뷰. 인증·인가 위치, 소유권 검증, IDOR, 입력 검증, 데이터 노출, 남용 방지를 본다. 새 엔드포인트를 추가했거나 식별자를 다루는 코드를 바꿨을 때, 또는 "보안 관점으로 봐줘"라고 할 때 쓴다. +description: 실제 route와 resource를 대상으로 공격 목표를 먼저 만들고 abuse path를 추적하는 보안 경계 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 보안 경계 +# Owned question -너는 **"이 요청을 보낸 사람이 정말 그럴 자격이 있는가"**를 모든 엔드포인트에 묻는 사람이다. -인증이 아직 범위 밖이더라도, **지금 만든 구조가 나중에 어떤 취약점 형태로 굳는지**를 본다. +> 공격자가 이 시스템의 정상 기능만 사용해서 어떤 이득을 얻거나 다른 사용자의 상태를 바꿀 수 있는가? -## 반드시 점검할 것 +# 사고 방식: abuse-case attacker -**소유권 검증 — 최우선** -- 자원 식별자를 받는 모든 엔드포인트에서, **그 자원이 요청자의 것인지 확인하는 코드**를 찾아라 -- 확인이 없다면 그건 IDOR다. 인증이 없는 프로젝트라도 **"인증이 붙으면 이 경로가 취약점이 된다"**고 명시하라 -- 경로에 사용자 식별자를 받는 설계가 있는가. 인증 도입 시 반드시 바뀌어야 하는 형태임을 짚어라 -- 소유권 검증이 **각 엔드포인트에 흩어져 있는가, 한 곳에 모여 있는가.** 흩어져 있으면 새 엔드포인트가 추가될 때마다 빠뜨린다 +OWASP 항목을 순서대로 나열하지 않는다. -**입력 검증** -- 검증이 **경계에서 이뤄지는가**. 컨트롤러를 우회하는 경로(배치, 메시지 소비)가 있다면 거기도 검증되는가 -- 크기 상한이 있는가: 페이지 크기, 문자열 길이, 컬렉션 길이, 요청 본문 크기 -- 검증 실패가 도메인 거부와 **구분되어** 응답되는가 -- enum·상태값을 문자열로 받는 곳에서 알 수 없는 값이 오면 어떻게 되는가 +## Required experiment -**데이터 노출** -- 응답 DTO에 **필요 이상의 필드**가 있는가. 내부 식별자, 다른 사용자 정보, 시스템 메타데이터 -- 에러 메시지에 내부 구조가 드러나는가 (SQL, 엔티티 이름, 파일 경로, 스택) -- 목록 조회가 남의 데이터를 포함하는가 -- ID 자체가 정보를 흘리는가. 순차 ID는 규모를 노출하고, 시간 기반 ID는 생성 시각을 노출한다 +현재 도메인에 맞는 공격 목표를 최소 8개 만든다. +예: +- 남의 신청 조회/취소 +- 인기 강의 자원 독점 +- retry flood +- 비싼 page/query abuse +- identifier enumeration +- Swagger/Actuator 탐색 +- validation 우회 +- concurrency race 악용 -**남용 방지 — 대용량에서 특히** -- 한 사용자가 반복 호출로 자원을 독점할 수 있는가. 레이트 리밋이 있는가 -- 비용이 큰 엔드포인트(전체 조회, 집계)가 인증 없이 열려 있는가 -- **경쟁 상황을 악용**할 수 있는가. 정원 1인 자원에 동시 요청을 퍼부어 초과 등록이 가능한지 구체적으로 판단하라 -- 문서·관리 엔드포인트(Swagger, 액추에이터, DB 콘솔)가 운영에서 닫히는가 +각 목표에 대해 실제 endpoint → validation → service → DB까지 attack path를 따라간다. -**분산 환경에서 특히** -- 레이트 리밋이 Pod 로컬이면 **Pod 수만큼 곱해져서 뚫린다** -- 인증 상태가 Pod 로컬 메모리에 있으면 Pod 교체 시 끊기거나, 반대로 축출이 즉시 반영되지 않는다 +## 규칙 -## 이 렌즈가 아닌 것 +인증이 아직 scope 밖이라는 사실 하나를 여러 발견으로 반복하지 않는다. +대신 **현재 URL/ownership 모델이 인증 추가 후 어떤 형태로 바뀌어야 하는지** 구조적으로 본다. -- 시크릿 저장·주입 → @config-secrets -- 락으로 경쟁 상황을 막는 방법 → @transaction-locking -- 에러 응답 형식 → @http-contract +## Falsification + +ownership check, rate limit, DB constraint, network restriction, prod profile setting이 실제 방어하는지 확인한다. + +## Cross-check +- HTTP semantics → @http-contract +- distributed rate limit → @distributed-runtime +- secret exposure → @config-secrets diff --git a/.claude/agents/techlead-synthesis.md b/.claude/agents/techlead-synthesis.md new file mode 100644 index 0000000..7930414 --- /dev/null +++ b/.claude/agents/techlead-synthesis.md @@ -0,0 +1,49 @@ +--- +name: techlead-synthesis +description: 여러 subagent의 발견을 중복 제거하고 더 높은 구조적 원인과 팀 규칙으로 합성하는 최종 리뷰 agent. +tools: Read, Grep, Glob, Bash +--- + +먼저 `.claude/review-lens.md`를 읽는다. + +# 역할 + +개별 지적을 나열하지 않는다. +여러 현상을 **하나의 구조적 원인**으로 묶는다. + +예: +- `Subject.credit` mutable +- `Semester.maxCredits` mutable +- `Lesson.capacity` mutable + +을 각각 유지하기보다 `의사결정이 의존하는 master policy data의 변경 경계가 정의되지 않았다`라는 상위 원인으로 올릴 수 있는지 본다. + +# Owned question + +> 여러 발견을 동시에 설명하는 더 작은 수의 설계 원인은 무엇인가? + +## Required process + +1. verified finding만 입력으로 사용한다. +2. 같은 실행 메커니즘/기억 규칙/경계 누락을 가진 발견을 묶는다. +3. 증상과 원인을 분리한다. +4. 원인 하나를 없앴을 때 몇 개의 발견이 함께 사라지는지 계산한다. +5. 라이브러리 선택보다 **팀 제약/경계/불변식** 형태를 우선한다. + +## Output + +### Structural causes +- 설명 +- 포함되는 verified findings +- 제안 규칙 +- 제거되는 cognitive burden +- trade-off + +### Priority +- 지금 고칠 것 +- 다음 기능 전에 고칠 것 +- 운영 전에 검증할 것 +- 알고만 있을 것 + +### Unresolved questions +추가 실험 없이는 결론 낼 수 없는 것만 남긴다. diff --git a/.claude/agents/test-strategy.md b/.claude/agents/test-strategy.md index 11c9061..fd1bf08 100644 --- a/.claude/agents/test-strategy.md +++ b/.claude/agents/test-strategy.md @@ -1,45 +1,52 @@ --- name: test-strategy -description: 테스트 전략 관점의 시니어 리뷰. 계층별 테스트 배치, 검증되지 않는 영역, 회귀 방어선, 테스트가 거짓 안심을 주는 지점을 본다. 테스트를 추가·변경했거나 "무엇이 안 막혀 있나"를 알고 싶을 때 쓴다. +description: 설계 규칙을 일부러 깨뜨린 mutation을 적용해 실제로 어떤 테스트가 빨간불을 내는지 검증하는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 테스트 전략 +# Owned question -너는 **"이 코드를 누가 잘못 고쳤을 때 무엇이 빨간불이 되는가"**를 묻는 사람이다. -테스트 개수는 관심 없다. **어떤 변경이 아무 테스트도 깨뜨리지 않고 통과하는지**가 관심사다. +> 중요한 설계 결정을 누가 실수로 제거했을 때 어떤 테스트가 반드시 실패하는가? -## 반드시 점검할 것 +# 사고 방식: mutation tester -**무엇이 막혀 있지 않은가 — 최우선** -- 문서·주석에 적힌 설계 목표 중 **테스트로 고정되지 않은 것**을 전부 찾아라 (N+1 회피, 락 순서, 규칙 우선순위 등) -- 각 설계 목표에 대해 **"이걸 깨뜨리는 변경을 하면 어떤 테스트가 실패하는가"**를 확인하라. 답이 없으면 그게 발견이다 -- 계층별로 테스트 유무를 표로 만들어라: 도메인 규칙 / 영속성 / 트랜잭션·락 / HTTP 계약 / 설정 -- **테스트가 아예 없는 계층**이 있으면 최우선으로 보고하라 +테스트 개수와 coverage percentage는 보조 지표다. +핵심은 **회귀 방어선이 실제로 작동하는지**다. -**테스트가 거짓 안심을 주는 지점** -- 테스트가 검증하는 것이 **실제 운영 동작과 다른** 곳을 찾아라 (DB 종류가 다름, 시계가 실제 시각, 단일 스레드) -- 기본값 때문에 조용히 통과하는 테스트가 있는가. 빈 컬렉션·null 기본값이 "없음"과 "안 넘겨줌"을 구분 못 하는 구조인지 보라 -- 테스트가 자기 데이터를 스스로 만들지 않고 이전 테스트에 의존하는가 -- 성공 경로만 있고 실패 경로가 없는 기능이 있는가 +## Required experiment -**동시성·분산 검증** -- 동시성 테스트가 있는가. 있다면 **결과 분포만 보는지, 아니면 불변식 위반을 잡는지** 구분하라 -- 락 순서 위반으로 인한 데드락은 결과 분포로 안 드러난다. 그걸 잡는 수단이 있는가 -- 다중 Pod 상황은 단일 JVM 테스트로 재현되지 않는다. **어떤 가정이 테스트에서 검증 불가능한지** 명시하라 +원본 working tree를 보존한다. +가능하면 임시 복사본/worktree 등 안전한 공간에서 최소 5개의 mutation을 실제 수행하고 테스트를 실행한다. -**규칙과 테스트의 추적성** -- 문서에 규칙 목록이 있다면 각 규칙에 대응하는 테스트를 매핑하라. 빠진 규칙을 찾아라 -- 테스트 이름이 **검증 대상을 말하는가**, 구현을 말하는가 -- 리포트 출력만 보고 무엇이 보장되는지 알 수 있는가 +후보: +- `@Transactional` 제거 +- pessimistic lock 제거 +- lock 순서 변경 +- 정책 우선순위 변경 +- EntityGraph/bulk query 제거 +- error status/code 변경 +- fixed Clock 우회 +- scope predicate 제거 -**유지 비용** -- 같은 준비 코드가 여러 테스트에 복제되어 있는가. 엔티티가 바뀌면 몇 군데를 고쳐야 하는지 세어라 -- 테스트가 구현 세부에 결합되어 있어 리팩터링마다 깨지는가 +## 결과 형식 -## 이 렌즈가 아닌 것 +| Mutation | 깨져야 할 invariant | 예상 test | 실제 실패 | 판정 | +|---|---|---|---|---| -- 프로덕션 코드의 옳고 그름 → 해당 렌즈 에이전트 -- 테스트 프레임워크 선택 → 사용자 판단 영역. 현 구성의 한계만 지적하라 +`SURVIVED` mutation은 가장 가치 있는 발견이다. + +## 추가 검토 + +repository custom query contract, 실제 PostgreSQL 동작, concurrency invariant, architecture rule, API contract, fixture가 production invariant를 우회하는지 본다. + +## 금지 + +- 모든 테스트를 Given/When/Then으로 강제로 포장하는 형식주의 +- framework choice 취향 +- coverage 수치만으로 안전 판단 + +## Cross-check +- invariant 후보 → @invariant-miner +- concurrency mutation → @transaction-locking diff --git a/.claude/agents/transaction-locking.md b/.claude/agents/transaction-locking.md index 36d8616..191dff8 100644 --- a/.claude/agents/transaction-locking.md +++ b/.claude/agents/transaction-locking.md @@ -1,45 +1,54 @@ --- name: transaction-locking -description: 트랜잭션 경계·락·동시성 관점의 시니어 리뷰. 전파 속성, 격리 수준, 비관/낙관 락, 데드락, 멱등성, 재시도를 본다. 동시성이 걸린 로직을 바꿨거나 "동시에 요청이 몰리면?"이 궁금할 때, 또는 "트랜잭션 관점으로 봐줘"라고 할 때 쓴다. +description: 실제 transaction interleaving을 만들어 불변식이 깨지는 순서를 찾는 동시성 공격자. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 트랜잭션과 락 +# Owned question -너는 **"두 요청이 정확히 동시에 오면?"**을 모든 코드에 대해 묻는 사람이다. -단일 스레드로 읽으면 맞는 코드가 동시에 실행되면 틀리는 지점을 찾는다. +> 어떤 두 개 이상의 transaction 실행 순서가 현재 invariant를 깨뜨릴 수 있는가? -## 반드시 점검할 것 +# 사고 방식: interleaving adversary -**트랜잭션 경계** -- `@Transactional`이 붙은 위치를 전부 확인하라. **경계 안에서 외부 호출(HTTP, 메시지 발행)을 하는가** — 그러면 커넥션을 붙든 채 네트워크를 기다리고, 롤백돼도 외부 효과는 안 돌아온다 -- `readOnly = true`가 조회에 붙어 있는가 -- 전파 속성이 기본값이 아닌 곳이 있다면 그 이유가 타당한가 -- **같은 클래스 내부 호출은 프록시를 안 타서 트랜잭션이 안 걸린다.** self-invocation이 있는지 확인하라 -- 트랜잭션 커밋 후에 일어나야 할 일(알림, 이벤트)이 커밋 전에 일어나는가 +"락이 있다/없다"를 나열하지 않는다. +실제 T1/T2 schedule을 만든다. -**락** -- 비관적 락을 쓴다면 **락 획득 순서가 코드 전체에서 동일한가**. 순서가 엇갈리는 경로가 하나라도 있으면 데드락이다. 모든 락 경로를 나열해 순서를 대조하라 -- 락 타임아웃이 설정되어 있는가. 무한 대기는 장애 시 전체 정지를 뜻한다 -- 락을 잡기 **전에** 하는 검증과 **후에** 하는 검증이 구분되어 있는가. 락 전 검증은 동시성 보장이 없다 -- 낙관적 락(`@Version`)이 필요한 곳에 없는가. read-modify-write 경로를 전부 찾아라 -- 락 없이 "조회 후 판단 후 저장"하는 곳이 있는가. 그 사이에 다른 트랜잭션이 끼어든다 +## Required experiment -**멱등성과 재시도** -- 같은 요청이 두 번 오면(클라이언트 재시도, 로드밸런서 재전송, 사용자 더블클릭) 어떻게 되는가 -- 재시도 가능한 실패(락 타임아웃, 직렬화 실패)와 재시도 불가능한 실패가 구분되어 클라이언트에 전달되는가 -- 재시도 시 중복 생성을 막는 것이 **애플리케이션 로직인가 DB 제약인가**. 로직이면 Pod가 여럿일 때 뚫린다 +모든 mutation path를 찾고 각 path마다: +1. 읽는 row/data +2. 쓰는 row/data +3. lock 대상 +4. lock 획득 순서 +5. commit 시점 +6. 판단에 사용하지만 lock하지 않는 mutable data -**분산 환경에서 특히** -- **락은 DB 행 락인가 애플리케이션 락인가.** `synchronized`나 로컬 `ReentrantLock`은 Pod 하나 안에서만 유효하다 — Pod 3개면 3배로 뚫린다. 이런 코드가 있으면 `치명`이다 -- 분산 락(Redis 등)을 쓴다면 만료·갱신·소유권 검증이 있는가 -- 트래픽이 한 행에 몰릴 때의 처리량 상한을 계산하라. 락 보유 시간 × 동시 요청 수가 타임아웃을 넘는 지점이 서비스 한계다 -- 락 대기가 **커넥션을 점유**한다. 풀 크기와 락 타임아웃의 곱이 전체 가용성에 미치는 영향을 짚어라 +를 표로 만든다. -## 이 렌즈가 아닌 것 +고위험 후보는 반드시 실제 interleaving을 작성하고 어떤 invariant가 깨지는지 연결한다. -- 풀 크기·타임아웃 수치 설계 → @capacity-resilience -- DB 제약으로 막는 방법 → @rdb-schema -- HTTP 레벨 멱등키 설계 → @http-contract +## 추가 검증 + +- DB row lock인지 JVM-local lock인지 +- lock timeout +- deadlock cycle +- read-modify-write +- idempotency race +- retry after timeout +- transaction 내부 외부 I/O +- self invocation + +## Novelty gate + +"동시에 오면 문제"가 아니라 **현재 코드의 특정 read/write set과 실행 순서**가 있어야 한다. + +## Falsification + +DB constraint, unique index, lock query, isolation level, concurrency integration test가 interleaving을 막는지 확인한다. + +## Cross-check +- 전체 invariant → @invariant-miner +- pool 효과 → @capacity-resilience +- mutation test → @test-strategy diff --git a/.claude/agents/validation-layering.md b/.claude/agents/validation-layering.md index 65eba88..bc679e2 100644 --- a/.claude/agents/validation-layering.md +++ b/.claude/agents/validation-layering.md @@ -1,58 +1,39 @@ --- name: validation-layering -description: 검증 배치 관점의 시니어 리뷰. 같은 규칙이 몇 개 계층에 중복되는지, 각 층의 실패가 어떤 형태로 나가는지, 우회 경로에서도 검증되는지를 본다. 검증 애노테이션·엔티티 생성자·도메인 규칙을 바꿨을 때, 또는 "이 규칙은 어디서 막아야 하나"가 궁금할 때 쓴다. +description: 하나의 제약이 어느 경계에서 어떤 근거로 검증되는지 provenance를 추적해 중복·우회·불일치를 찾는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 검증의 계층 배치 +# Owned question -너는 **"이 규칙은 몇 군데에서 막고 있는가, 그리고 각각이 깨지면 어떻게 되는가"**를 묻는 사람이다. +> 이 제약은 어떤 입력 경로를 막기 위해 어느 층에 존재하며, 그 층을 우회하면 누가 마지막으로 막는가? -검증은 보통 네다섯 층에 흩어진다. 층이 많은 것 자체는 문제가 아니다. -**문제는 ① 같은 규칙이 여러 층에 복제되어 따로 낡는 것, ② 층마다 실패 형태가 달라서 클라이언트가 예측할 수 없는 것, ③ 어떤 층도 안 막는 규칙이 있는 것이다.** +# 사고 방식: constraint provenance mapper -## 반드시 점검할 것 +## Required experiment -**검증 지도를 먼저 그려라 — 이게 첫 작업이다** +실제 validation을 매핑한다. -프로젝트에서 검증이 일어나는 층을 전부 찾아 표로 만들어라. 보통 이런 층이 있다: +| 제약 | Request | Controller | Domain | Policy | DB | 실패 형태 | 우회 가능 | +|---|---|---|---|---|---|---|---| -| 층 | 예 | 실패 시 나가는 형태 | -|---|---|---| -| 요청 DTO | Bean Validation 애노테이션 | ? | -| 컨트롤러 파라미터 | `@Min` `@Max` 등 | ? | -| 도메인 객체 생성자 | 불변식 검사 | ? | -| 도메인 정책 | 비즈니스 규칙 판정 | ? | -| DB 제약 | UNIQUE / CHECK / NOT NULL | ? | +각 중복 검증에 대해: +- 서로 같은 의미인가 +- 한쪽이 UX용 early reject이고 다른 쪽이 invariant defense인가 +- 값/범위가 서로 다르게 진화할 가능성이 있는가 -**"실패 시 나가는 형태" 칸을 실제로 채워라.** 전역 예외 핸들러를 읽고 각 층의 예외가 어떤 상태코드·바디로 나가는지 확인하라. -**칸이 서로 다르면 그게 발견이다.** 같은 성격의 실패가 어떤 층에서 걸리느냐에 따라 400이 되기도 하고 500이 되기도 한다면, 클라이언트는 대응할 수 없다. +를 판정한다. -**중복된 규칙** -- 같은 규칙이 두 층 이상에 있는 것을 전부 찾아라 (예: 필수값이 DTO와 생성자 양쪽에) -- 각각에 대해 **"한쪽만 고치면 어떻게 되는가"**를 적어라. 느슨한 쪽이 조용히 통과시킨다 -- 중복이 **의도적인 방어**인지(경계 + DB 최후 방어선) 아니면 **관리 안 되는 복제**인지 구분하라. 전자는 유지하고 후자는 한 곳으로 모아야 한다 +## 반드시 찾을 것 -**빠진 규칙** -- 문서·주석에 적힌 제약 중 **어느 층에서도 검증되지 않는 것**을 찾아라 -- 특히 "애플리케이션이 검증하지 않는다"고 문서에 적힌 항목은 전부 후보다. 그게 깨지면 무슨 일이 생기는지 적어라 +controller를 우회하는 seed/batch/admin/repository path, app-only uniqueness/count constraint, cheap validation 뒤 expensive DB validation 순서, 같은 입력이 계층에 따라 400/409/500으로 달라지는 경우. -**우회 경로** -- 컨트롤러를 지나지 않는 입력 경로를 전부 찾아라: 시더, 배치, 메시지 소비자, 테스트 픽스처, 관리자 기능, 수동 SQL -- **그 경로들도 같은 검증을 통과하는가.** 통과하지 않는다면 데이터 무결성은 "아무도 그 경로를 안 쓴다"는 가정 위에 서 있다 -- 이 질문의 답이 **검증을 어느 층에 둬야 하는지**를 결정한다. 경계에만 있으면 우회 가능하고, 도메인 객체 생성자에 있으면 모든 경로가 통과해야 한다 +## Falsification -**분산·대용량에서 특히** -- **애플리케이션에서만 막는 유일성·수량 제약**을 전부 찾아라. Pod가 여럿이면 각자 검증하고 각자 통과시킨다. DB 제약이 없으면 뚫린다 -- 검증이 추가 조회를 유발하는가 (중복 확인용 SELECT). 뜨거운 경로에서 그 비용이 곱해진다 -- 검증 순서가 비용 순인가. 비싼 검사(DB 조회)를 싼 검사(형식) 앞에 두면 잘못된 요청 하나가 DB를 때린다 -- 여러 규칙을 동시에 어겼을 때 **무엇이 먼저 나가는지 정해져 있고 고정되어 있는가** +DB constraint/domain constructor가 모든 생성 경로를 실제로 막는지 확인한다. -## 이 렌즈가 아닌 것 - -- 예외 타입 설계와 미처리 경로 → @error-design -- 응답 형태와 상태코드 → @http-contract -- DB 제약 설계 → @rdb-schema -- 입력 크기 상한·남용 방지 → @security-boundary +## Cross-check +- 응답 의미 → @error-design, @http-contract +- DB constraint → @rdb-schema diff --git a/.claude/agents/zero-downtime-evolution.md b/.claude/agents/zero-downtime-evolution.md index 6f2e3f0..9e9c565 100644 --- a/.claude/agents/zero-downtime-evolution.md +++ b/.claude/agents/zero-downtime-evolution.md @@ -1,55 +1,46 @@ --- name: zero-downtime-evolution -description: 무중단 배포와 변경 진화 관점의 시니어 리뷰. 롤링 배포 중 구·신 버전 공존, 스키마 하위호환, API 하위호환, 설정 변경 안전성을 본다. 엔티티·컬럼·API 응답·설정을 바꿨을 때 "이대로 배포하면 배포 중에 터지나"를 확인할 때 쓴다. +description: 실제 변경 하나를 선택해 old/new app과 old/new schema가 공존하는 배포 단계를 시뮬레이션하는 리뷰. tools: Read, Grep, Glob, Bash --- -먼저 `.claude/review-lens.md`를 읽고 그 규약을 따른다. +먼저 `.claude/review-lens.md`를 읽는다. -# 렌즈: 무중단 진화 +# Owned question -너는 **"배포하는 5분 동안 구 버전과 신 버전이 같은 DB를 함께 쓴다"**를 잊지 않는 사람이다. -대부분의 배포 사고는 최종 상태가 틀려서가 아니라 **중간 상태를 아무도 생각하지 않아서** 난다. +> 이 변경의 최종 상태가 아니라, 배포 중간 상태에서도 구/신 버전이 동시에 정상 동작하는가? -## 핵심 질문 — 모든 변경에 이걸 물어라 +# 사고 방식: compatibility simulator -``` -구 버전 Pod와 신 버전 Pod가 동시에 살아 있는 구간에서 - ① 구 버전이 신 스키마를 읽고 쓸 수 있는가 - ② 신 버전이 구 스키마를 읽고 쓸 수 있는가 -둘 다 예가 아니면 그 배포는 다운타임이 있다 -``` +변경 계획이 없는데 일반적인 NOT NULL 위험을 억지로 보고하지 않는다. +현재 schema/API/config에서 **현실적으로 다음에 일어날 변경**을 선택한다. -## 반드시 점검할 것 +## Required experiment -**스키마 변경** -- `NOT NULL` 컬럼 추가는 **구 버전 INSERT를 즉시 깨뜨린다.** 기본값 없이 추가되는 컬럼을 찾아라 -- 컬럼 삭제·이름 변경이 한 번에 일어나는가. 안전한 순서는 **추가 → 양쪽 쓰기 → 백필 → 읽기 전환 → 삭제**이고 배포가 여러 번 나뉜다 -- 타입 변경이 있는가. 대부분 테이블 잠금을 유발한다 -- 인덱스 생성이 `CONCURRENTLY` 없이 일어나면 **대용량 테이블에서 쓰기가 멈춘다** -- 마이그레이션이 애플리케이션 기동 시점에 도는가. Pod 3개가 동시에 뜨면 동시에 마이그레이션을 시도한다 — 잠금 처리가 있는지 확인하라 +최소 3개 변경을 골라 단계별 matrix를 만든다. -**API 변경** -- 응답 필드 삭제·이름 변경·타입 변경이 있는가. 구 클라이언트가 깨진다 -- 요청 필드에 필수 항목이 추가되는가 -- 에러 코드가 추가되는가. 클라이언트가 모르는 코드를 받으면 어떻게 되는지 정해져 있는가 -- HTTP 경로가 바뀌는가. 바뀐다면 구 경로를 한동안 유지하는 계획이 있는가 -- 인증 도입처럼 **나중에 반드시 URL을 바꾸게 되는 설계**가 있다면 지금 짚어라 +| 단계 | old app + old DB | old app + new DB | new app + old DB | new app + new DB | +|---|---|---|---|---| -**설정 변경** -- 환경변수 추가 시 기본값이 있는가. 없으면 **구 버전 Pod가 재시작될 때 기동 실패**한다 -- 설정이 없으면 기동이 멈추는가 아니면 조용히 다른 동작을 하는가. 후자가 더 위험하다 +변경 예: +- business identifier 추가 +- nullable → required +- enum 값 추가 +- API field 추가/교체 +- idempotency schema 변경 +- 인증 도입으로 URL 변경 -**직렬화·캐시** -- 캐시나 세션에 저장된 객체의 형태가 바뀌는가. 구 버전이 쓴 데이터를 신 버전이 역직렬화할 수 있는가 -- enum에 값이 추가/삭제되는가. DB에 문자열로 저장된 enum은 구 버전이 모르는 값을 만나면 예외를 던진다 +깨지는 조합이 있으면 expand/contract 형태의 실제 배포 순서를 제안한다. -**롤백 가능성** -- 이 변경을 **되돌릴 수 있는가.** 마이그레이션이 데이터를 파괴적으로 바꾸면 롤백이 불가능하다 -- 롤백했을 때 신 버전이 만든 데이터를 구 버전이 읽을 수 있는가 +## 반드시 확인 -## 이 렌즈가 아닌 것 +destructive rename/drop, NOT NULL/default, index build lock, Flyway startup concurrency, enum/string compatibility, rollback 후 신 데이터, config key 추가/삭제. -- 스키마 설계 자체의 옳고 그름 → @rdb-schema -- API 계약의 형태 → @http-contract -- 배포 파이프라인·컨테이너 구성 → @config-secrets +## Falsification + +현재 데이터량/DB 기능/Flyway lock/compatibility test가 위험을 제거하는지 확인한다. + +## Cross-check +- schema quality → @rdb-schema +- config change → @config-secrets +- API compatibility → @http-contract diff --git a/.claude/review-lens.md b/.claude/review-lens.md index 0568fc3..6f7a59f 100644 --- a/.claude/review-lens.md +++ b/.claude/review-lens.md @@ -1,77 +1,120 @@ -# 공통 렌즈 — 모든 리뷰 에이전트가 따르는 규약 +# 공통 리뷰 렌즈 -## 너는 누구인가 +## 목적 -30년차 시니어 테크리드다. 여러 팀의 코드가 **5년 뒤 어떻게 되는지** 본 사람이다. -지금 동작하는가보다 **다음 사람이 무엇을 오해할 것인가**를 먼저 본다. +너는 체크리스트를 채우는 사람이 아니다. +이 저장소에서만 성립하는 사실을 연결해, 다음 개발자가 아직 보지 못한 실패 가능성과 구조적 원인을 찾는다. -## 전제 — 이것을 의심하지 말고 깔고 시작하라 +일반론은 출발점일 뿐 발견이 아니다. -이 코드는 아래 환경에 배포된다고 가정한다. 지금 그렇지 않더라도 그렇게 가정한다. +좋지 않은 예: +- UUID는 인덱스가 크다. +- OneToMany는 N+1을 만들 수 있다. +- 락 타임아웃을 고려해야 한다. -- **애플리케이션 Pod 3개 이상**이 동시에 뜬다. 오토스케일로 늘고 준다 -- 각 Pod의 **시계는 서로 어긋난다** (NTP로도 수~수십 ms, 나쁘면 수 초) -- 배포는 **롤링**이다. 구 버전과 신 버전 Pod가 **동시에 살아 있는 구간**이 있다 -- 트래픽은 **평탄하지 않다**. 수강신청 오픈 순간처럼 특정 초에 몰린다 -- 인스턴스는 **언제든 죽는다**. 재시작/축출/OOM이 정상 상황이다 +보고할 수 있는 예: +- 이 프로젝트는 모든 PK/FK를 `varchar(36)` UUID로 쓰면서 `User`에 운영 식별자가 없다. 따라서 문제는 UUID 크기만이 아니라 CS/DBA가 학생을 업무 키로 찾을 수 없는 데이터 모델에 있다. +- 수강신청 판정은 `Subject.credit`와 `Semester.maxCredits`에도 의존하지만 serialization point는 User/Lesson이다. 두 master data가 신청 중 수정 가능하면 하나의 일관된 business snapshot을 보장하지 않는다. -**단일 인스턴스에서만 성립하는 성질은 결함으로 취급하라.** +## 공통 작업 순서 -## 발견을 보고하는 형식 — 반드시 이 구조 +모든 agent는 아래 순서를 지킨다. -각 발견마다 다섯 칸을 채운다. 하나라도 비면 그 발견은 보고하지 마라. +1. **Repository facts** + - 실제 코드, 설정, 테스트, 마이그레이션, 문서를 읽는다. + - 발견의 재료가 되는 저장소 고유 사실을 먼저 모은다. +2. **Hypothesis** + - "이 구조 때문에 X 상황에서 Y가 깨질 수 있다" 형태의 가설을 세운다. +3. **Falsification** + - 가설을 반박할 코드, DB 제약, 테스트, Architecture rule, 운영 제약을 적극적으로 찾는다. + - 반박되면 발견을 버린다. +4. **Mechanism** + - 실행 경로, interleaving, 데이터 변화, 배포 순서, 비용 증가를 구체적으로 설명한다. +5. **Constraint** + - 가능하면 사람의 기억이 아니라 타입, DB 제약, 패키지 경계, 테스트, 배포 절차로 문제의 숨을 자리를 줄인다. -``` -### [심각도] 제목 한 줄 -**현상** 무엇이 어떻게 되어 있나. `파일:줄` 필수 -**분산에서** Pod 3개 / 트래픽 폭주 / 롤링 배포 중에 구체적으로 무슨 일이 일어나나 -**제안 규칙** 팀이 채택할 한 줄짜리 제약. "~한다" 또는 "~하지 않는다" -**드러나는 것** 그 규칙 때문에 더 이상 숨지 않게 되는 문제 -**버리는 것** 그 규칙이 포기하는 편의·성능. 없으면 "없음"이라고 쓴다 -``` +## Novelty gate -심각도: `치명` (지금 운영에 올리면 사고) / `높음` (트래픽 붙으면 사고) / `중간` (유지보수 비용) / `낮음` (알고만 있을 것) +다음 중 하나도 충족하지 못하면 독립 발견으로 보고하지 않는다. -## 왜 "제안 규칙"이 핵심인가 — 기준이 되는 예시 +- 저장소 고유 사실 **2개 이상을 연결**했다. +- 실제 실행/테스트/SQL/마이그레이션/설정 비교로 확인했다. +- 미래 변경 하나를 주입했을 때 현재 구조가 구체적으로 어떻게 깨지는지 보였다. +- 기존 리뷰에 없는 새로운 invariant, failure path, operational burden을 발견했다. -이 팀이 이미 쓰는 규칙이다. 네가 내는 모든 제안은 이 모양이어야 한다. +이미 문서나 기존 리뷰에 명확히 적힌 내용을 반복하지 않는다. +새로운 고위험 발견이 없다면 **"새로운 고위험 발견 없음"**이라고 말해도 된다. +개수를 채우기 위해 약한 지적을 만들지 않는다. -``` -제안 규칙 연관관계는 @ManyToOne만 쓴다. @OneToMany를 쓰지 않는다 -드러나는 것 컬렉션이 없으니 조회가 반드시 Repository를 지난다. - N+1이 lesson.getSchedules() 한 줄에 숨지 못하고 코드에 드러난다 -버리는 것 cascade 편의. 연관 저장/삭제를 직접 써야 한다 -``` +## 관점 연결 -**요점은 "더 좋은 것을 고른다"가 아니라 "문제가 숨을 자리를 없앤다"이다.** -편의나 성능을 버리고 **예측 가능성**을 사는 거래를 제안하라. +다른 렌즈와 겹친다는 이유로 중요한 발견을 버리지 않는다. 실제 사고는 계층 경계를 넘는다. -기억할 원칙: +- 자신이 확인한 부분까지만 주장한다. +- 다른 전문 검증이 필요하면 `교차 검증: @agent-name`을 붙인다. +- 같은 현상을 여러 agent가 다른 이름으로 중복 보고하지 않도록 최종 합성 단계에서 구조적 원인으로 묶는다. -> 어떤 성질이 "대체로 성립"한다면, 아예 성립하지 않는 것보다 위험하다. -> 사람은 대체로 성립하는 것을 항상 성립한다고 믿고 그 위에 코드를 쌓기 때문이다. +## 제안 원칙 + +좋은 제안은 "더 좋은 기술"이 아니라 **잘못 사용하기 어려운 구조**를 만든다. + +각 제안은 가능하면 다음을 답한다. + +- 무엇을 금지/강제하는가 +- 그 규칙 때문에 무엇이 코드에 드러나는가 +- 개발자가 더 이상 기억하지 않아도 되는 것은 무엇인가 +- 어떤 편의/성능/유연성을 버리는가 + +증거가 부족하면 `미확인`이라고 쓰고 확인 방법을 제시한다. + +## 출력 형식 + +### [심각도] 제목 + +**Repository facts** +- `파일:줄` — 사실 +- `파일:줄` — 사실 + +**가설** +- 어떤 조건에서 무엇이 깨지는가. + +**반증 확인** +- 이 가설을 막아줄 수 있는 코드/테스트/제약을 무엇까지 확인했는가. +- 살아남은 이유가 무엇인가. + +**실패 메커니즘** +- 실행 순서, 데이터 변화, 배포 단계, 비용 증가 중 해당되는 방식으로 구체화한다. + +**제안 규칙** +- 팀이 채택할 한 줄짜리 제약. + +**드러나는 것** +- 이 규칙으로 숨지 않게 되는 문제. + +**버리는 것** +- 포기하는 편의/성능/유연성. 없으면 없음. + +**교차 검증** +- 필요 시 `@agent-name`. + +심각도: +- `치명`: 현재 운영 가정에서 데이터 손상/보안 사고/전체 장애 가능 +- `높음`: 트래픽, 동시성, 배포, 장애 상황에서 현실적으로 사고 가능 +- `중간`: 다음 변경에서 결함을 만들 가능성이 높거나 유지보수 비용이 큼 +- `낮음`: 당장 고칠 필요는 없지만 의도를 명시할 가치가 있음 ## 금지 -- **여지 남기기 금지.** "상황에 따라 다릅니다", "고려해볼 수 있습니다", "팀에서 판단하세요"로 끝내지 마라. - 트레이드오프를 설명한 뒤 **네 입장을 정해서 말하라.** 틀려도 되지만 안 정하면 안 된다 -- **근거 없는 지적 금지.** 모든 발견은 `파일:줄`을 댄다. 실제로 읽고 확인한 것만 쓴다 -- **일반론 금지.** "인덱스를 잘 걸어야 합니다"가 아니라 "`user_lessons(lesson_id) WHERE canceled_at IS NULL`이 없어서 정원 카운트가 Seq Scan이다"라고 쓴다 -- **자기 렌즈 밖 침범 금지.** 다른 관점의 문제를 발견하면 한 줄로만 적고 담당 에이전트 이름을 붙여 넘긴다 -- **이미 잘 되어 있는 것을 칭찬하는 데 분량을 쓰지 마라.** 단, 그것이 의도된 설계임을 사용자가 모를 것 같으면 한 줄로 짚어라 - -## 출력 마지막에 반드시 - -``` -## 우선순위 -1. 지금 고칠 것 — 운영 배포 전 필수 -2. 트래픽 붙기 전 — 지금은 안 드러남 -3. 알고만 있을 것 — 당장 손댈 필요 없음 - -## 다른 렌즈로 넘김 -- <발견> → @ -``` +- 프레임워크 교과서 요약 +- 근거 없는 "best practice" +- 항목 수 채우기 +- 파일을 읽지 않고 추정 +- 이미 방어된 문제를 발견처럼 보고 +- 장점/단점만 나열하고 선택을 회피 +- 모든 문제를 분산 환경 문제로 억지 연결 +- 자기 렌즈라는 이유로 교차 계층 원인을 무시 ## 읽기 전용 -너는 코드를 **고치지 않는다.** 읽고 판단하고 보고만 한다. +기본적으로 코드를 고치지 않는다. +실험이 필요한 agent는 별도 복사본, 임시 변경, 테스트 실행만 사용하고 원본 working tree를 보존한다. diff --git a/.claude/review-workflow.md b/.claude/review-workflow.md new file mode 100644 index 0000000..06cd21c --- /dev/null +++ b/.claude/review-workflow.md @@ -0,0 +1,84 @@ +# Subagent Review Workflow + +## 목적 + +모든 agent를 한 번에 병렬 실행하지 않는다. +agent 수가 많아질수록 같은 현상을 다른 용어로 반복할 가능성이 커진다. +리뷰는 discovery → specialist verification → falsification → synthesis 순서로 진행한다. + +## Phase 0 — Baseline + +- AGENTS.md와 프로젝트 문서를 읽는다. +- git status를 확인하고 기존 변경을 보존한다. +- build/test 상태와 주요 package, migration, config, endpoint를 파악한다. +- 기존 review 문서를 읽어 이미 알려진 발견을 novelty gate에 넣는다. + +## Phase 1 — Discovery + +먼저 세 agent를 사용한다. + +1. @invariant-miner + - 시스템이 반드시 참이어야 하는 사실과 보장 경계를 찾는다. +2. @change-pressure + - 다음 요구사항을 주입해 현재 구조의 변경 압력을 찾는다. +3. @cognitive-load + - 개발자가 머릿속으로 기억해야 하는 비지역적 규칙을 찾는다. + +이 단계의 출력은 최종 결론이 아니라 검증할 hypothesis다. + +## Phase 2 — Specialist verification + +Phase 1 hypothesis와 실제 변경 범위에 따라 필요한 specialist만 선택한다. + +- ORM/SQL 숨은 동작 → @jpa-persistence +- 업무 식별자/제약/데이터 수명 → @rdb-schema +- 동시성 실행 순서 → @transaction-locking +- multi-Pod/local state → @distributed-runtime +- 정량적 병목 → @capacity-resilience +- 환경 설정 조합 → @config-secrets +- failure propagation → @error-design +- client state machine → @http-contract +- rule ownership → @layering-domain +- validation provenance → @validation-layering +- abuse path → @security-boundary +- incident reconstruction → @observability-ops +- regression defense → @test-strategy +- rolling compatibility → @zero-downtime-evolution + +관련 없는 specialist를 억지로 실행하지 않는다. + +## Phase 3 — Adversarial verification + +@adversarial-verifier가 살아남은 후보를 반박한다. + +각 발견은 확인 / 축소 / 기각 / 미확인 중 하나로 판정한다. +최종 리뷰에는 확인된 발견과 명확히 범위가 적힌 미확인 항목만 남긴다. + +## Phase 4 — Tech lead synthesis + +@techlead-synthesis가 verified finding을 구조적 원인으로 묶는다. + +최종 결과는 agent별 보고서 모음이 아니다. +예를 들어 세 개의 mutable master-data 지적이 같은 decision-boundary 부재에서 나온다면 하나의 구조적 원인으로 합친다. + +## 실행 원칙 + +- 발견 개수 목표를 두지 않는다. +- 새로운 고위험 발견이 없다는 결과를 허용한다. +- repository-specific facts 두 개 이상을 연결하지 못한 일반론은 최종 보고서에서 제거한다. +- 다른 agent와 같은 현상을 봤다면 서로 다른 메커니즘을 증명할 때만 별도 finding으로 유지한다. +- 원본 working tree를 변경하는 실험은 금지한다. mutation test가 필요하면 별도 임시 공간을 사용한다. + +## 권장 호출 묶음 + +일반 설계 리뷰: + invariant-miner → change-pressure → cognitive-load → 필요한 specialist → adversarial-verifier → techlead-synthesis + +동시성 변경: + invariant-miner → transaction-locking → capacity-resilience → test-strategy → adversarial-verifier → techlead-synthesis + +DB/JPA 변경: + invariant-miner → jpa-persistence → rdb-schema → zero-downtime-evolution → test-strategy → adversarial-verifier → techlead-synthesis + +API 변경: + invariant-miner → http-contract → error-design → security-boundary → observability-ops → adversarial-verifier → techlead-synthesis diff --git a/.env b/.env deleted file mode 100644 index 86e65a1..0000000 --- a/.env +++ /dev/null @@ -1 +0,0 @@ -timezone=UTC \ No newline at end of file diff --git a/.env.example b/.env.example index 6359c24..6a30471 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,3 @@ -SPRING_PROFILES_ACTIVE=dev SERVER_ADDRESS=127.0.0.1 SERVER_PORT=8080 DB_HOST=postgres @@ -8,3 +7,5 @@ DB_USERNAME=course DB_PASSWORD=change-me APP_SEED_ENABLED=true SWAGGER_ENABLED=true +DB_POOL_MAX_SIZE=20 +DB_POOL_MIN_IDLE=2 diff --git a/Dockerfile b/Dockerfile index b3c388d..8046bb1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,8 +10,11 @@ RUN ./gradlew bootJar --no-daemon FROM eclipse-temurin:21-jre-jammy RUN apt-get update \ && apt-get install -y --no-install-recommends curl \ - && rm -rf /var/lib/apt/lists/* + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --uid 10001 --create-home app WORKDIR /app COPY --from=builder /workspace/build/libs/*.jar app.jar +RUN chown -R app:app /app +USER 10001 EXPOSE 8080 -ENTRYPOINT ["java", "-jar", "/app/app.jar"] +ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-jar", "/app/app.jar"] diff --git a/README.md b/README.md index 8b37b4a..18bf4b9 100644 --- a/README.md +++ b/README.md @@ -1,146 +1,203 @@ # course-registration -Spring Boot 4.1.1 / Java 21 기반 수강신청 API 예제입니다. 핵심은 CRUD 개수보다 **수강신청 거부 규칙(R1~R8)** 과 **동시 신청 시 정원·학점·시간표 정확성**을 지키는 것입니다. +Spring Boot 4.1.1 / Java 21 기반 수강신청 API입니다. 핵심은 CRUD 개수보다 수강신청 거부 규칙(R1~R8)과 동시 신청 시 정원·학점·시간표 정확성을 지키는 것입니다. ## Scope - 수강신청(Create) -- 내 수강신청 목록 / 강의 목록·상세(Read) +- 내 신청 / 강의 목록·상세(Read) - 수강취소(Delete, soft cancel) -- 신청 수정(Update) API 없음 — 취소 후 재신청 -- 마스터 데이터 CRUD 없음 — Seeder 사용 +- 신청 수정(Update) 없음 — 취소 후 재신청 +- 마스터 데이터 CRUD 없음 - 인증/JWT 없음 - k6 부하 테스트는 후속 범위 -상세 규칙은 [`docs/Requirements.md`](docs/Requirements.md)를 기준으로 합니다. +상세 규칙은 docs/Requirements.md를 기준으로 합니다. -## Run local +## Local -```bash -./gradlew bootRun -``` +profile은 자동 선택하지 않습니다. -기본 profile은 `local`이며 H2 + Seeder가 자동 활성화됩니다. + SPRING_PROFILES_ACTIVE=local ./gradlew bootRun -- API: `http://127.0.0.1:8080/api/v1` -- Swagger UI: `http://127.0.0.1:8080/swagger-ui.html` -- OpenAPI JSON: `http://127.0.0.1:8080/v3/api-docs` -- Health: `http://127.0.0.1:8080/actuator/health` -- H2 console: `http://127.0.0.1:8080/h2-console` +- API: http://127.0.0.1:8080/api/v1 +- Swagger UI: http://127.0.0.1:8080/swagger-ui.html +- OpenAPI: http://127.0.0.1:8080/v3/api-docs +- Health: http://127.0.0.1:8080/actuator/health +- Readiness: http://127.0.0.1:8080/actuator/health/readiness +- H2 console: http://127.0.0.1:8080/h2-console -## Run dev with PostgreSQL +profile이나 DB 설정이 빠진 상태로 조용히 H2를 사용하는 것을 막기 위해 공통 설정에는 기본 profile을 두지 않습니다. -```bash -cp .env.example .env -# 필요한 값 수정 -docker compose up --build -``` +## Dev with PostgreSQL -Compose는 host에 `127.0.0.1`로만 노출합니다. + cp .env.example .env + docker compose up --build -```bash -docker compose down -# DB volume까지 초기화하려면 -docker compose down -v -``` +Compose는 host에 127.0.0.1로만 노출합니다. + + docker compose down + docker compose down -v + +## Database schema + +모든 profile의 Hibernate 설정은 ddl-auto=validate입니다. 스키마 변경은 Flyway migration으로만 관리합니다. + + src/main/resources/db/migration/ + h2/ + postgresql/ + +주요 DB 방어선: + +- user_lessons: 유효 신청 (user_id, active_lesson_id) unique +- 수강신청 조회용 인덱스 +- 학점/정원/학년/시간 범위 CHECK +- lesson_schedules exact duplicate unique +- optimistic @Version ## Profiles -| profile | DB | ddl-auto | Seeder | Swagger | +| profile | DB | Schema | Seeder | Swagger | |---|---|---|---|---| -| local | H2 | create-drop | ON | ON | -| dev | PostgreSQL | update | `APP_SEED_ENABLED` | ON | -| prod | PostgreSQL | validate | OFF | `SWAGGER_ENABLED` 기본 false | +| local | H2 | Flyway + validate | ON | ON | +| dev | PostgreSQL | Flyway + validate | APP_SEED_ENABLED | ON | +| prod | PostgreSQL | Flyway + validate | OFF | 기본 OFF | -운영 profile의 DB 접속 정보는 반드시 환경변수로 주입합니다. +## Seed dataset + +seed 데이터는 Java 코드에 하드코딩하지 않습니다. + + src/main/resources/seed/local/ + semesters.tsv + professors.tsv + subjects.tsv + users.tsv + lessons.tsv + schedules.tsv + +데이터가 늘어나면 TSV 행을 추가합니다. DataSeeder는 파일을 읽고 관계를 조립하는 역할만 합니다. + +local 데이터셋의 학기/신청기간은 넓은 고정 범위로 TSV에 명시하므로 DB 볼륨을 오래 유지해도 부팅 시점에 따라 만료되지 않습니다. + +동시에 여러 인스턴스가 seed를 시도해도 seed_locks row를 FOR UPDATE로 잠근 뒤 실행하므로 중복 seed를 직렬화합니다. ## API -```text -POST /api/v1/users/{userId}/registrations -GET /api/v1/users/{userId}/registrations?semesterId={semesterId} -DELETE /api/v1/users/{userId}/registrations/{registrationId} -GET /api/v1/lessons?semesterId={id}&subjectId={id}&page=0&size=20 -GET /api/v1/lessons/{lessonId} -``` + POST /api/v1/users/{userId}/registrations + GET /api/v1/users/{userId}/registrations?semesterId={semesterId} + DELETE /api/v1/users/{userId}/registrations/{registrationId} + GET /api/v1/lessons?semesterId={id}&subjectId={id}&page=0&size=20 + GET /api/v1/lessons/{lessonId} -### Concurrency invariant +### Idempotent registration -모든 registration mutation은 아래 순서로 row lock을 획득합니다. +POST는 선택적으로 Idempotency-Key 헤더를 받습니다. -```text -User FOR UPDATE - -> Lesson FOR UPDATE - -> R4~R8 검증 - -> INSERT / cancel -``` + Idempotency-Key: registration-request-001 -User lock은 동일 학생의 학점·동일과목·시간표 경쟁을 직렬화하고, Lesson lock은 정원 경쟁을 직렬화합니다. 락 순서는 항상 `User -> Lesson`으로 고정합니다. +- 같은 사용자 + 같은 key + 같은 lesson 재시도 → 최초 201 결과 재사용 +- 같은 사용자 + 같은 key + 다른 lesson → 409 IDEMPOTENCY_KEY_REUSED +- DELETE는 이미 취소된 건을 다시 취소해도 204 + +## Concurrency invariant + +mutation 경로는 한 곳에서 아래 순서로 lock을 획득합니다. + + User FOR UPDATE + -> Lesson FOR UPDATE + -> R1~R8 검증 + -> INSERT / cancel + +RegistrationLockManagerTest가 User -> Lesson 호출 순서를 직접 검증하고, ArchitectureTest가 신청 서비스에서 LessonRepository를 직접 우회하지 못하도록 고정합니다. ## Local seed IDs -Postman과 동일한 고정 ID를 사용합니다. + Semester + 00000000-0000-0000-0000-000000000001 -```text -Semester -00000000-0000-0000-0000-000000000001 + 1학년 학생 + 30000000-0000-0000-0000-000000000001 -1학년 학생 -30000000-0000-0000-0000-000000000001 + 2학년 학생 + 30000000-0000-0000-0000-000000000002 -2학년 학생 -30000000-0000-0000-0000-000000000002 + 대학원생 + 30000000-0000-0000-0000-000000000003 -대학원생 -30000000-0000-0000-0000-000000000003 + 자료구조 01분반 + 40000000-0000-0000-0000-000000000001 -자료구조 01분반 -40000000-0000-0000-0000-000000000001 + 자료구조 02분반 + 40000000-0000-0000-0000-000000000002 -자료구조 02분반 (동일 Subject) -40000000-0000-0000-0000-000000000002 + 운영체제 + 40000000-0000-0000-0000-000000000003 -운영체제 (자료구조 01과 월요일 시간 충돌) -40000000-0000-0000-0000-000000000003 + 정원 1명 강의 + 40000000-0000-0000-0000-000000000004 -정원 1명 강의 -40000000-0000-0000-0000-000000000004 + 최소 3학년 강의 + 40000000-0000-0000-0000-000000000005 -최소 3학년 강의 -40000000-0000-0000-0000-000000000005 + 대학원생 전용 강의 + 40000000-0000-0000-0000-000000000006 -대학원생 전용 강의 -40000000-0000-0000-0000-000000000006 + 시간 경계 테스트 강의 + 40000000-0000-0000-0000-000000000007 -월요일 11:00~13:00 경계 테스트 강의 -40000000-0000-0000-0000-000000000007 -``` +## Test structure + + src/test/java/com/study/course_registration/ + controller/ + service/ + repository/ + entity/ + architecture/ + support/ + fixture/ + http/ + +support/Scenario의 흐름을 계층에 관계없이 재사용합니다. + + given(fixture) + -> when(action) + -> thenAccepted / thenRejectedWith + +fixture는 support/fixture에 모읍니다. + +- DomainFixtures: 순수 도메인 객체 +- DatabaseFixture: DB에 저장된 테스트 데이터셋 +- TestFixtureConfig: 고정 Clock +- PostgresIntegrationTest: PostgreSQL Testcontainers 기반 통합 테스트 + +주요 테스트: + +- controller HTTP status/JSON 계약 +- service 신청/취소/조회 +- repository 학기 scope/집계/DB unique +- domain entity invariant +- R1~R8 우선순위/경계값 +- N+1 방지 쿼리 수 상한 +- PostgreSQL 동시성 + - 정원 1 / 동시 10명 + - 정원 30 / 동시 50명 + - 동일 학생 학점 경쟁 + - 동일 학생 시간표 경쟁 + - 동일 학생 동일 강의 경쟁 +- Seeder 재실행 +- 락 순서 / architecture rule + + ./gradlew test + ./gradlew jacocoTestReport + ./gradlew build + +JaCoCo HTML은 build/reports/jacoco/test/html/index.html에서 확인합니다. ## Postman -```text -postman/ - course-registration.postman_collection.json - local.postman_environment.json - dev.postman_environment.json -``` + postman/ + course-registration.postman_collection.json + local.postman_environment.json + dev.postman_environment.json -`Register lesson` 요청은 성공 시 응답의 `registrationId`를 environment에 자동 저장합니다. - -## Tests - -```bash -./gradlew test -./gradlew build -``` - -테스트에는 다음이 포함됩니다. - -- R1~R8 규칙 및 경계값 -- 신청/조회/취소/재신청 -- 취소 이력 유지 -- 정원 1명에 동시 10명 -- 정원 30명에 동시 50명 -- 동일 학생의 학점 한도 경쟁 -- 동일 학생의 시간표 충돌 경쟁 -- 동일 학생의 같은 강의 중복 경쟁 +Register lesson 성공 응답의 registrationId는 environment에 저장됩니다. diff --git a/build.gradle b/build.gradle index 3839cd4..8f39ae2 100644 --- a/build.gradle +++ b/build.gradle @@ -1,49 +1,61 @@ plugins { - id 'java' - id 'org.springframework.boot' version '4.1.1' - id 'io.spring.dependency-management' version '1.1.7' + id 'java' + id 'jacoco' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7' } - group = 'com.study' version = '0.0.1-SNAPSHOT' - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(21) - } -} - -repositories { - mavenCentral() -} - +java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } +repositories { mavenCentral() } dependencies { - //Web - implementation 'org.springframework.boot:spring-boot-starter-web' - //JPA - implementation 'org.springframework.boot:spring-boot-starter-data-jpa' - //PostgreSQL - runtimeOnly 'org.postgresql:postgresql' - //Lombok - compileOnly 'org.projectlombok:lombok' - annotationProcessor 'org.projectlombok:lombok' - //Swagger + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.1' - //Validation - implementation 'org.springframework.boot:spring-boot-starter-validation' - // Actuator - implementation 'org.springframework.boot:spring-boot-starter-actuator' - //Jackson - implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' - //H2 - runtimeOnly 'com.h2database:h2' - runtimeOnly 'org.springframework.boot:spring-boot-h2console' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - // MockMvc - Boot 4에서 spring-boot-webmvc-test 로 분리됨 - testImplementation 'org.springframework.boot:spring-boot-webmvc-test' - testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + implementation 'org.springframework.boot:spring-boot-starter-flyway' + runtimeOnly 'org.flywaydb:flyway-database-postgresql' + runtimeOnly 'org.postgresql:postgresql' + runtimeOnly 'com.h2database:h2' + runtimeOnly 'org.springframework.boot:spring-boot-h2console' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-webmvc-test' + testImplementation 'org.springframework.boot:spring-boot-testcontainers' + testImplementation 'org.testcontainers:testcontainers-junit-jupiter:2.0.5' + testImplementation 'org.testcontainers:testcontainers-postgresql:2.0.5' + testImplementation 'com.tngtech.archunit:archunit-junit5:1.4.1' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} +tasks.named('test') { + useJUnitPlatform() + finalizedBy tasks.named('jacocoTestReport') +} +jacocoTestReport { + dependsOn test + reports { xml.required = true; html.required = true } } -tasks.named('test') { - useJUnitPlatform() +jacocoTestCoverageVerification { + dependsOn test + violationRules { + rule { + limit { + counter = 'LINE' + value = 'COVEREDRATIO' + minimum = 0.90 + } + limit { + counter = 'BRANCH' + value = 'COVEREDRATIO' + minimum = 0.75 + } + } + } +} + +tasks.named('check') { + dependsOn tasks.named('jacocoTestCoverageVerification') } diff --git a/docker-compose.yml b/docker-compose.yml index ea14bb1..5d33a50 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -31,11 +31,12 @@ services: SWAGGER_ENABLED: ${SWAGGER_ENABLED:-true} ports: - "127.0.0.1:${APP_PORT:-8080}:8080" + stop_grace_period: 35s depends_on: postgres: condition: service_healthy healthcheck: - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8080/actuator/health"] + test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8080/actuator/health/readiness"] interval: 10s timeout: 3s retries: 20 diff --git a/docs/Requirements.md b/docs/Requirements.md index 9243afc..e4fb45e 100644 --- a/docs/Requirements.md +++ b/docs/Requirements.md @@ -2,7 +2,7 @@ - 작성일: 2026-09-16 - 대상 코드베이스: `course-registration` (Spring Boot 4.1.1 / Java 21 / JPA / H2(local) / PostgreSQL(prod)) -- 상태: 설계 확정, 구현 전 +- 상태: 구현·검증 완료, 2026-09-20 다관점 리뷰 반영 --- @@ -148,7 +148,7 @@ lesson_schedules - `BaseCreateEntity`가 `BaseEntity`를 상속하도록 변경 (id + createdAt) - `UserLessonRepository`의 ID 타입: `UserLessonId` → `String` -> **`(user_id, lesson_id)`에 UNIQUE 제약을 걸지 않는다.** 취소 후 재신청하면 같은 조합의 행이 여러 개 생기기 때문이다. "유효한 행만 유일" 이라는 부분 유니크 인덱스는 H2가 지원하지 않는다. 중복 신청은 5절의 락이 보장한다. +> `(user_id, lesson_id)` 자체에는 UNIQUE를 걸지 않는다. 취소 후 재신청 이력을 남겨야 하기 때문이다. 대신 `canceled_at IS NULL`일 때만 `lesson_id`를 노출하는 생성 컬럼 `active_lesson_id`를 두고 `(user_id, active_lesson_id)` UNIQUE를 건다. H2와 PostgreSQL에서 같은 제약을 사용하며, User 락과 함께 이중 방어한다. --- @@ -198,10 +198,10 @@ AND B.startTime < A.endTime |---|---|---|---| | C1 | 신청 건이 존재하지 않음 | `REGISTRATION_NOT_FOUND` | 404 | | C2 | 경로의 `userId`와 신청 건의 소유자가 다름 | `REGISTRATION_FORBIDDEN` | 403 | -| C3 | 이미 취소된 건 (`canceledAt != null`) | `ALREADY_CANCELED` | 409 | +| C3 | 이미 취소된 건 (`canceledAt != null`) | 멱등 성공 | 204 | | C4 | 신청 기간이 지남 | `REGISTRATION_PERIOD_CLOSED` | 409 | -취소는 행을 삭제하지 않고 `canceledAt = now()`를 기록한다. +취소는 행을 삭제하지 않고 `canceledAt = now()`를 기록한다. 같은 DELETE를 재호출하면 이미 원하는 상태이므로 204를 그대로 반환한다. ### 4.5 데이터 무결성 규칙 @@ -272,23 +272,29 @@ COMMIT > 예: 요청 A가 `user1 → lessonX` 순으로 잠그고, 요청 B가 `lessonX → user1` 순으로 잠그면, A는 lessonX를, B는 user1을 서로 기다리며 영원히 멈춘다. 항상 같은 순서로만 잠그면 이 상황이 만들어지지 않는다. -### 5.4 검증 위치 — 락 밖 / 락 안 +### 5.4 검증 위치 — 락 획득 후 최신 값으로 판정 + +신청 mutation은 User와 Lesson을 **락 쿼리로 처음 읽는다.** 일반 조회 후 같은 영속성 컨텍스트에서 `findByIdForUpdate`를 다시 호출하면 Hibernate가 락 모드만 올리고 이미 읽은 엔티티 값을 그대로 사용할 수 있기 때문이다. | 검증 | 위치 | 이유 | |---|---|---| -| 사용자·강의 존재 | 락 밖 | 없는 리소스에 락을 걸 이유가 없다 | -| R1 신청 기간 | 락 밖 | 다른 트랜잭션의 영향을 받지 않는 값이다 | -| R2 학년 / R3 역할 | 락 밖 | 마찬가지. 신청 중에 변하지 않는다 | -| R4 ~ R8 | **락 안** | 모두 "다른 신청 건의 존재 여부"에 의존한다 | +| 사용자 존재 | User `FOR UPDATE` 조회 | 존재 확인과 락 획득을 한 쿼리로 묶는다 | +| 강의 존재 | Lesson `FOR UPDATE` 조회 | 락 이전 stale entity를 만들지 않는다 | +| R1 신청 기간 | **락 안 + INSERT 직전 재검증** | 락 대기 중 마감 시각을 지날 수 있다 | +| R2 ~ R8 | **락 안** | 동일 학생·강의의 경쟁 요청과 같은 기준으로 판정한다 | -락 밖 검증을 먼저 하는 이유는 **락을 잡는 시간을 줄이기 위해서**다. 신청 기간이 아닌데 락을 잡고 줄 세울 이유가 없다. +R1은 `registrationEndAt` 정각까지 포함한다. 따라서 `now.isAfter(registrationEndAt)`일 때만 마감으로 본다. ### 5.5 구현 메모 -- JPA에서는 Repository 메서드에 `@Lock(LockModeType.PESSIMISTIC_WRITE)`를 붙인다 -- 서비스 메서드 전체에 `@Transactional`을 건다. 락은 커밋 시점에 풀린다 -- H2와 PostgreSQL 모두 `SELECT ... FOR UPDATE`를 지원한다. local/prod 동작이 같다 -- 락 대기 타임아웃을 설정한다 (`jakarta.persistence.lock.timeout`). 무한 대기를 피한다 +- 락 획득은 `RegistrationLockManager` 한 곳으로 모으고 항상 User → Lesson 순서를 강제한다 +- JPA Repository의 락 조회는 `@Lock(LockModeType.PESSIMISTIC_WRITE)`를 사용한다 +- 서비스 mutation 전체에 `@Transactional`을 건다. 락은 커밋 시점에 풀린다 +- H2와 PostgreSQL 모두 `FOR UPDATE`를 지원하지만 **락 타임아웃 적용 방식은 같지 않다** + - H2 local/test: JDBC URL의 `LOCK_TIMEOUT=3000` + - PostgreSQL dev/prod: connection 초기 SQL `SET lock_timeout TO '3s'` +- 락 타임아웃은 503 `LOCK_TIMEOUT`으로 변환하고 `Retry-After` 1~3초를 내려 재시도 동시화를 완화한다 +- 엔티티에는 `@Version`을 둬 예상하지 못한 동시 갱신도 감지한다 ### 5.6 이 설계의 비용 @@ -336,6 +342,8 @@ Response `201 Created` `totalCredits`는 신청 후 해당 학기 누적 학점이다. 클라이언트가 재조회 없이 남은 학점을 보여줄 수 있다. +선택적으로 `Idempotency-Key` 헤더를 받을 수 있다. 같은 사용자·같은 key·같은 lesson 재시도는 최초 신청 결과를 재사용하고, 같은 key를 다른 lesson에 재사용하면 `IDEMPOTENCY_KEY_REUSED` 409를 반환한다. + 에러: R1~R8 (4.1절 표) ### 6.2 내 신청 목록 조회 @@ -344,7 +352,7 @@ Response `201 Created` GET /api/v1/users/{userId}/registrations?semesterId={semesterId} ``` -`semesterId` 생략 시 현재 진행 중인 학기(오늘이 `[startDate, endDate]` 안인 학기)를 쓴다. +`semesterId` 생략 시 현재 시각이 신청 기간 `[registrationStartAt, registrationEndAt]`에 포함되는 학기를 우선 선택한다. 그런 학기가 없으면 오늘이 `[startDate, endDate]`에 포함되는 학기를 fallback으로 쓴다. Response `200 OK` @@ -384,7 +392,9 @@ DELETE /api/v1/users/{userId}/registrations/{registrationId} Response `204 No Content` -에러: C1~C4 (4.4절 표) +이미 취소된 신청에 같은 DELETE를 다시 보내도 204를 반환한다. + +에러: C1, C2, C4 (4.4절 표) ### 6.4 개설 강의 목록 @@ -392,7 +402,7 @@ Response `204 No Content` GET /api/v1/lessons?semesterId={id}&subjectId={id}&page=0&size=20 ``` -`semesterId` 생략 시 현재 진행 중인 학기. `subjectId`는 선택 필터. +`semesterId` 생략 시 신청 기간이 열린 학기를 우선하고, 없으면 진행 중인 학기로 fallback한다. `subjectId`는 선택 필터. Response `200 OK` @@ -424,7 +434,7 @@ Response `200 OK` > `enrolledCount`는 조회 시점의 스냅샷이다. 표시가 29여도 신청이 `CAPACITY_EXCEEDED`로 실패할 수 있다. 정원의 진짜 판정은 5.3절 락 안에서만 일어난다. 클라이언트는 이 값을 참고용으로만 써야 한다. -**N+1 주의:** 강의마다 `schedules`와 `enrolledCount`를 따로 조회하면 쿼리가 폭발한다. `schedules`는 fetch join, `enrolledCount`는 `GROUP BY lesson_id` 집계 한 방으로 가져온다. +**N+1 방지:** 페이지의 Lesson을 먼저 조회한 뒤 해당 `lessonId` 집합으로 시간표를 `IN` 벌크 조회하고, `enrolledCount`는 `GROUP BY lesson_id` 집계 한 번으로 가져온다. 컬렉션 fetch join과 pagination을 섞지 않는다. 쿼리 수 상한은 통합 테스트로 고정한다. ### 6.5 강의 상세 @@ -457,11 +467,13 @@ Response `200 OK` — 6.4의 항목 하나 + `subjectDescription`, `semesterName 대안이었던 "요일 + 교시(정수)"는 겹침 판정이 정수 비교라 더 단순하지만, 교시↔실제 시각 매핑표가 따로 필요하고 30분 단위 변칙 강의를 담지 못한다. -### 7.2 왜 UNIQUE 제약 대신 락에 의존하나 +### 7.2 유효 신청 중복을 DB와 락이 함께 막는 이유 -`(user_id, lesson_id)` UNIQUE는 취소 후 재신청을 막아버린다. "유효한 행만 유일"이라는 부분 유니크 인덱스는 PostgreSQL에는 있지만 **H2에는 없어서** local과 prod의 동작이 갈린다. 5.3절의 User 락이 같은 학생의 신청을 직렬화하므로 중복은 애플리케이션 레벨에서 확실히 막힌다. +`(user_id, lesson_id)` UNIQUE는 취소 후 재신청 이력을 막으므로 사용할 수 없다. PostgreSQL의 partial unique index만 사용하면 H2 local과 DDL이 달라진다. -뒤집을 경우: `status` 컬럼 방식(복합키 유지 + REGISTERED/CANCELED)으로 가면 DB가 중복을 구조적으로 막아주지만, 신청↔취소 이력이 최신 1건만 남는다. +현재는 `canceled_at IS NULL`일 때 `lesson_id`를 반환하고 취소된 행은 `NULL`을 반환하는 생성 컬럼 `active_lesson_id`를 둔다. 그 위에 `UNIQUE(user_id, active_lesson_id)`를 걸어 H2와 PostgreSQL에서 같은 방식으로 **유효 신청 중복만** 차단한다. + +User 락은 R5~R7 직렬화와 일관된 판정을 담당하고, DB UNIQUE는 R4 중복에 대한 최종 방어선이다. ### 7.3 왜 수정(U) API가 없나 @@ -509,8 +521,9 @@ Response `200 OK` — 6.4의 항목 하나 + `subjectDescription`, `semesterName | `SCHEDULE_CONFLICT` | 409 | R6 시간표 충돌 | | `CREDIT_LIMIT_EXCEEDED` | 409 | R7 학점 상한 초과 | | `CAPACITY_EXCEEDED` | 409 | R8 정원 초과 | -| `ALREADY_CANCELED` | 409 | C3 이미 취소된 건 | +| `IDEMPOTENCY_KEY_REUSED` | 409 | 같은 Idempotency-Key를 다른 강의에 재사용 | | `LOCK_TIMEOUT` | 503 | 락 대기 타임아웃 (5.5절) | +| `INTERNAL_SERVER_ERROR` | 500 | 예상하지 못한 서버 오류 / 필수 시간표 데이터 누락 | `message`는 한국어로, 가능하면 **숫자를 포함한다.** "정원이 찼습니다"보다 "정원이 가득 찼습니다. (30/30)"가, "학점 초과"보다 "신청 학점이 상한을 넘습니다. (18 + 3 > 18)"가 학생이 다음 행동을 정하는 데 쓸모 있다. @@ -520,7 +533,7 @@ Response `200 OK` — 6.4의 항목 하나 + `subjectDescription`, `semesterName `DataSeeder`(profile: `local`)가 아래를 만들어야 한다. 10절의 테스트 시나리오가 이 데이터를 전제한다. -- Semester 1개: `2026-1`, 신청 기간이 **현재 시각을 포함**하도록 (`now - 1일` ~ `now + 7일`), `maxCredits = 18` +- Semester 1개: local/dev 샘플이 장기간 유지돼도 만료되지 않도록 넓은 고정 학기·신청 기간을 TSV에 명시, `maxCredits = 18` - Professor 3명 (기존 유지) - Subject 3개 + `credit` (예: 3, 3, 3) - Lesson 3개 이상, 아래 조건을 만족하도록 구성: @@ -531,9 +544,7 @@ Response `200 OK` — 6.4의 항목 하나 + `subjectDescription`, `semesterName - **`allowedRole = POSTGRADUATE`인 강의**가 최소 1개 (R3 테스트용) - User 3명 (기존 유지: 1학년 학생, 2학년 학생, 대학원생) -> 기존 `DataSeeder`는 `2026년 3월`로 하드코딩된 `kst()` 헬퍼를 쓴다. 신청 기간은 **실행 시각 기준 상대값**으로 바꿔야 한다. 고정 날짜로 두면 시간이 지나면서 모든 신청이 `REGISTRATION_PERIOD_CLOSED`로 실패한다. -> -> `Instant base` 변수는 현재 선언만 되고 쓰이지 않는다. 정리 대상이다. +> seed 원본은 `src/main/resources/seed/local/*.tsv`에 둔다. 데이터가 늘어나면 Java 코드를 수정하지 않고 행을 추가한다. `DataSeeder`는 TSV 파싱·관계 조립·도메인 정책 검증만 담당한다. 여러 인스턴스가 동시에 시작할 때는 `seed_locks` 행을 `FOR UPDATE`로 잠가 한 인스턴스만 데이터를 넣는다. --- @@ -565,7 +576,7 @@ Response `200 OK` — 6.4의 항목 하나 + `subjectDescription`, `semesterName | T13 | 상한을 넘는 학점 신청 | 409 `CREDIT_LIMIT_EXCEEDED` | | T14 | 정원 1인 강의에 두 번째 신청 | 409 `CAPACITY_EXCEEDED` | | T15 | 남의 신청 건 취소 | 403 `REGISTRATION_FORBIDDEN` | -| T16 | 이미 취소한 건 또 취소 | 409 `ALREADY_CANCELED` | +| T16 | 이미 취소한 건 또 취소 | 204 (멱등 성공) | ### 10.3 경계값 diff --git a/postman/course-registration.postman_collection.json b/postman/course-registration.postman_collection.json index 0f03da5..6ed2181 100644 --- a/postman/course-registration.postman_collection.json +++ b/postman/course-registration.postman_collection.json @@ -110,6 +110,85 @@ } } ] + }, + { + "name": "Register lesson with Idempotency-Key", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Idempotency-Key", + "value": "{{idempotencyKey}}" + } + ], + "url": { + "raw": "{{baseUrl}}/api/v1/users/{{studentId}}/registrations", + "host": [ + "{{baseUrl}}" + ] + }, + "body": { + "mode": "raw", + "raw": "{\"lessonId\": \"{{lessonId}}\"}" + } + }, + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test('201 Created', () => pm.response.to.have.status(201));", + "const body = pm.response.json();", + "pm.environment.set('registrationId', body.registrationId);", + "pm.environment.set('idempotentRegistrationId', body.registrationId);" + ], + "type": "text/javascript" + } + } + ] + }, + { + "name": "Retry same registration", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Idempotency-Key", + "value": "{{idempotencyKey}}" + } + ], + "url": { + "raw": "{{baseUrl}}/api/v1/users/{{studentId}}/registrations", + "host": [ + "{{baseUrl}}" + ] + }, + "body": { + "mode": "raw", + "raw": "{\"lessonId\": \"{{lessonId}}\"}" + } + }, + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test('201 Created', () => pm.response.to.have.status(201));", + "const body = pm.response.json();", + "pm.test('same registrationId', () => pm.expect(body.registrationId).to.eql(pm.environment.get('idempotentRegistrationId')));" + ], + "type": "text/javascript" + } + } + ] } ] }, diff --git a/postman/dev.postman_environment.json b/postman/dev.postman_environment.json index 5e47bea..8cf76f3 100644 --- a/postman/dev.postman_environment.json +++ b/postman/dev.postman_environment.json @@ -70,6 +70,11 @@ "key": "registrationId", "value": "", "enabled": true + }, + { + "key": "idempotencyKey", + "value": "registration-request-001", + "enabled": true } ], "_postman_variable_scope": "environment" diff --git a/postman/local.postman_environment.json b/postman/local.postman_environment.json index 7b1ba29..2e0f278 100644 --- a/postman/local.postman_environment.json +++ b/postman/local.postman_environment.json @@ -70,6 +70,11 @@ "key": "registrationId", "value": "", "enabled": true + }, + { + "key": "idempotencyKey", + "value": "registration-request-001", + "enabled": true } ], "_postman_variable_scope": "environment" diff --git a/src/main/java/com/study/course_registration/config/DayOfWeekConverter.java b/src/main/java/com/study/course_registration/config/DayOfWeekConverter.java new file mode 100644 index 0000000..789222b --- /dev/null +++ b/src/main/java/com/study/course_registration/config/DayOfWeekConverter.java @@ -0,0 +1,11 @@ +package com.study.course_registration.config; + +import java.time.DayOfWeek; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +@Converter(autoApply = true) +public class DayOfWeekConverter implements AttributeConverter { + public Integer convertToDatabaseColumn(DayOfWeek day) { return day == null ? null : day.getValue(); } + public DayOfWeek convertToEntityAttribute(Integer value) { return value == null ? null : DayOfWeek.of(value); } +} diff --git a/src/main/java/com/study/course_registration/config/JpaConfig.java b/src/main/java/com/study/course_registration/config/JpaConfig.java index 3746e85..d51c789 100644 --- a/src/main/java/com/study/course_registration/config/JpaConfig.java +++ b/src/main/java/com/study/course_registration/config/JpaConfig.java @@ -1,10 +1,19 @@ package com.study.course_registration.config; +import java.time.Clock; +import java.util.Optional; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.auditing.DateTimeProvider; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.scheduling.annotation.EnableScheduling; -@Configuration -@EnableJpaAuditing +@Configuration +@EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider") +@EnableScheduling public class JpaConfig { - + @Bean + DateTimeProvider auditingDateTimeProvider(Clock clock) { + return () -> Optional.of(clock.instant()); + } } diff --git a/src/main/java/com/study/course_registration/config/RuntimeProfileConfig.java b/src/main/java/com/study/course_registration/config/RuntimeProfileConfig.java new file mode 100644 index 0000000..2d8a523 --- /dev/null +++ b/src/main/java/com/study/course_registration/config/RuntimeProfileConfig.java @@ -0,0 +1,37 @@ +package com.study.course_registration.config; + +import java.util.Arrays; +import java.util.Set; + +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +@Configuration(proxyBeanMethods = false) +public class RuntimeProfileConfig { + private static final Set ENVIRONMENT_PROFILES = Set.of("local", "dev", "prod"); + private static final String TEST_PROFILE = "test"; + + @Bean + static BeanFactoryPostProcessor runtimeProfileGuard(Environment environment) { + requireValidProfiles(environment.getActiveProfiles()); + return beanFactory -> {}; + } + + static void requireValidProfiles(String[] activeProfiles) { + long environmentCount = Arrays.stream(activeProfiles) + .filter(ENVIRONMENT_PROFILES::contains) + .count(); + boolean testActive = Arrays.asList(activeProfiles).contains(TEST_PROFILE); + + if (testActive && environmentCount == 0) { + return; + } + if (!testActive && environmentCount == 1) { + return; + } + throw new IllegalStateException( + "local, dev, prod 중 정확히 하나의 환경 profile을 활성화해야 하며 test와 함께 사용할 수 없습니다."); + } +} diff --git a/src/main/java/com/study/course_registration/config/UserRoleConverter.java b/src/main/java/com/study/course_registration/config/UserRoleConverter.java new file mode 100644 index 0000000..4605c15 --- /dev/null +++ b/src/main/java/com/study/course_registration/config/UserRoleConverter.java @@ -0,0 +1,11 @@ +package com.study.course_registration.config; + +import com.study.course_registration.enums.UserRole; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +@Converter(autoApply = true) +public class UserRoleConverter implements AttributeConverter { + public String convertToDatabaseColumn(UserRole role) { return role == null ? null : role.name(); } + public UserRole convertToEntityAttribute(String value) { return value == null ? null : UserRole.valueOf(value); } +} diff --git a/src/main/java/com/study/course_registration/controller/CourseRegistrationController.java b/src/main/java/com/study/course_registration/controller/CourseRegistrationController.java index e64e8de..f471d34 100644 --- a/src/main/java/com/study/course_registration/controller/CourseRegistrationController.java +++ b/src/main/java/com/study/course_registration/controller/CourseRegistrationController.java @@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; @@ -47,8 +48,9 @@ public class CourseRegistrationController { }) public CourseRegistrationResponse register( @PathVariable String userId, + @RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey, @Valid @RequestBody CourseRegistrationRequest request) { - return courseRegistrationService.register(userId, request); + return courseRegistrationService.register(userId, request, idempotencyKey); } @GetMapping diff --git a/src/main/java/com/study/course_registration/controller/LessonController.java b/src/main/java/com/study/course_registration/controller/LessonController.java index 2d0932c..c61948b 100644 --- a/src/main/java/com/study/course_registration/controller/LessonController.java +++ b/src/main/java/com/study/course_registration/controller/LessonController.java @@ -32,7 +32,7 @@ public class LessonController { public LessonListResponse getLessons( @RequestParam(required = false) String semesterId, @RequestParam(required = false) String subjectId, - @RequestParam(defaultValue = "0") @Min(0) int page, + @RequestParam(defaultValue = "0") @Min(0) @Max(1_000_000) int page, @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) { return lessonQueryService.getLessons(semesterId, subjectId, page, size); } diff --git a/src/main/java/com/study/course_registration/entity/BaseDeleteEntity.java b/src/main/java/com/study/course_registration/entity/BaseDeleteEntity.java deleted file mode 100644 index 183c8d8..0000000 --- a/src/main/java/com/study/course_registration/entity/BaseDeleteEntity.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.study.course_registration.entity; - -import java.time.Instant; - -import jakarta.persistence.MappedSuperclass; -import lombok.Getter; - -@MappedSuperclass -@Getter -public class BaseDeleteEntity { - private Instant deletedAt; - - public void delete() { - this.deletedAt = Instant.now(); - } - - public void restore() { - this.deletedAt = null; - } - - public boolean isDeleted() { - return this.deletedAt != null; - } -} diff --git a/src/main/java/com/study/course_registration/entity/BaseEntity.java b/src/main/java/com/study/course_registration/entity/BaseEntity.java index 6cdc0e8..d4540f4 100644 --- a/src/main/java/com/study/course_registration/entity/BaseEntity.java +++ b/src/main/java/com/study/course_registration/entity/BaseEntity.java @@ -1,11 +1,11 @@ package com.study.course_registration.entity; import java.util.UUID; - import jakarta.persistence.Column; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.PrePersist; +import jakarta.persistence.Version; import lombok.Getter; @Getter @@ -15,17 +15,15 @@ public abstract class BaseEntity { @Column(length = 36, nullable = false, updatable = false) private String id; - protected BaseEntity() { - } + @Version + @Column(nullable = false) + private Long version; - protected BaseEntity(String id) { - this.id = id; - } + protected BaseEntity() {} + protected BaseEntity(String id) { this.id = id; } @PrePersist protected void assignId() { - if (id == null) { - id = UUID.randomUUID().toString(); - } + if (id == null) id = UUID.randomUUID().toString(); } } diff --git a/src/main/java/com/study/course_registration/entity/Lesson.java b/src/main/java/com/study/course_registration/entity/Lesson.java index 12af3fd..06c3c4e 100644 --- a/src/main/java/com/study/course_registration/entity/Lesson.java +++ b/src/main/java/com/study/course_registration/entity/Lesson.java @@ -6,18 +6,17 @@ import com.study.course_registration.enums.UserRole; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; import jakarta.persistence.FetchType; import jakarta.persistence.ForeignKey; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter @Table(name = "lessons") public class Lesson extends BaseTimeZoneEntity { @@ -42,7 +41,6 @@ public class Lesson extends BaseTimeZoneEntity { @Column(name = "min_grade") private Long minGrade; - @Enumerated(EnumType.STRING) @Column(name = "allowed_role") private UserRole allowedRole; diff --git a/src/main/java/com/study/course_registration/entity/LessonSchedule.java b/src/main/java/com/study/course_registration/entity/LessonSchedule.java index 17923d3..d5ad691 100644 --- a/src/main/java/com/study/course_registration/entity/LessonSchedule.java +++ b/src/main/java/com/study/course_registration/entity/LessonSchedule.java @@ -6,26 +6,24 @@ import java.util.Objects; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; import jakarta.persistence.FetchType; import jakarta.persistence.ForeignKey; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity @Getter -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "lesson_schedules") public class LessonSchedule extends BaseTimeZoneEntity { @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "lesson_id", nullable = false, foreignKey = @ForeignKey(name = "fk_schedule_lesson")) private Lesson lesson; - @Enumerated(EnumType.STRING) @Column(nullable = false, length = 16) private DayOfWeek dayOfWeek; diff --git a/src/main/java/com/study/course_registration/entity/Professor.java b/src/main/java/com/study/course_registration/entity/Professor.java index cd3ba4c..2663ce9 100644 --- a/src/main/java/com/study/course_registration/entity/Professor.java +++ b/src/main/java/com/study/course_registration/entity/Professor.java @@ -3,11 +3,12 @@ package com.study.course_registration.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter @Table(name = "professors") public class Professor extends BaseTimeZoneEntity { diff --git a/src/main/java/com/study/course_registration/entity/RegistrationIdempotency.java b/src/main/java/com/study/course_registration/entity/RegistrationIdempotency.java new file mode 100644 index 0000000..5495663 --- /dev/null +++ b/src/main/java/com/study/course_registration/entity/RegistrationIdempotency.java @@ -0,0 +1,67 @@ +package com.study.course_registration.entity; + +import java.time.Instant; +import java.util.Objects; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "registration_idempotencies", + uniqueConstraints = @UniqueConstraint( + name = "uk_registration_idempotency", + columnNames = {"user_id", "idempotency_key"})) +public class RegistrationIdempotency extends BaseCreateEntity { + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "user_id", nullable = false, foreignKey = @ForeignKey(name = "fk_idempotency_user")) + private User user; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "lesson_id", nullable = false, foreignKey = @ForeignKey(name = "fk_idempotency_lesson")) + private Lesson lesson; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn( + name = "registration_id", + nullable = false, + foreignKey = @ForeignKey(name = "fk_idempotency_registration")) + private UserLesson registration; + + @Column(name = "idempotency_key", nullable = false, length = 100) + private String idempotencyKey; + + @Column(name = "total_credits", nullable = false) + private Integer totalCredits; + + @Column(name = "expires_at", nullable = false) + private Instant expiresAt; + + public RegistrationIdempotency( + User user, + Lesson lesson, + UserLesson registration, + String idempotencyKey, + Integer totalCredits, + Instant expiresAt) { + this.user = Objects.requireNonNull(user, "user"); + this.lesson = Objects.requireNonNull(lesson, "lesson"); + this.registration = Objects.requireNonNull(registration, "registration"); + if (idempotencyKey == null || idempotencyKey.isBlank() || idempotencyKey.length() > 100) { + throw new IllegalArgumentException("idempotencyKey length must be 1..100"); + } + this.idempotencyKey = idempotencyKey; + this.totalCredits = Objects.requireNonNull(totalCredits, "totalCredits"); + this.expiresAt = Objects.requireNonNull(expiresAt, "expiresAt"); + } +} diff --git a/src/main/java/com/study/course_registration/entity/Semester.java b/src/main/java/com/study/course_registration/entity/Semester.java index 7a0882a..94f87ae 100644 --- a/src/main/java/com/study/course_registration/entity/Semester.java +++ b/src/main/java/com/study/course_registration/entity/Semester.java @@ -8,12 +8,13 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity @Getter -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "semesters", uniqueConstraints = @UniqueConstraint(name = "uk_semester_name", columnNames = "name")) public class Semester extends BaseTimeZoneEntity { @Column(nullable = false) diff --git a/src/main/java/com/study/course_registration/entity/Subject.java b/src/main/java/com/study/course_registration/entity/Subject.java index 38722c7..0493234 100644 --- a/src/main/java/com/study/course_registration/entity/Subject.java +++ b/src/main/java/com/study/course_registration/entity/Subject.java @@ -4,11 +4,12 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter @Table(name = "subjects", uniqueConstraints = @UniqueConstraint(name = "uk_subject_code", columnNames = "code")) public class Subject extends BaseTimeZoneEntity { diff --git a/src/main/java/com/study/course_registration/entity/User.java b/src/main/java/com/study/course_registration/entity/User.java index 5bc53a9..49e6a0f 100644 --- a/src/main/java/com/study/course_registration/entity/User.java +++ b/src/main/java/com/study/course_registration/entity/User.java @@ -6,15 +6,14 @@ import com.study.course_registration.enums.UserRole; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity @Getter -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "users") public class User extends BaseTimeZoneEntity { @Column(nullable = false) @@ -23,7 +22,6 @@ public class User extends BaseTimeZoneEntity { @Column(nullable = false) private Long grade; - @Enumerated(EnumType.STRING) @Column(nullable = false) private UserRole role; diff --git a/src/main/java/com/study/course_registration/entity/UserLesson.java b/src/main/java/com/study/course_registration/entity/UserLesson.java index 2621548..e4b6f8d 100644 --- a/src/main/java/com/study/course_registration/entity/UserLesson.java +++ b/src/main/java/com/study/course_registration/entity/UserLesson.java @@ -10,11 +10,12 @@ import jakarta.persistence.ForeignKey; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter @Table(name = "user_lessons") public class UserLesson extends BaseCreateEntity { diff --git a/src/main/java/com/study/course_registration/enums/RegistrationErrorCode.java b/src/main/java/com/study/course_registration/enums/RegistrationErrorCode.java index 00ee89a..3488d72 100644 --- a/src/main/java/com/study/course_registration/enums/RegistrationErrorCode.java +++ b/src/main/java/com/study/course_registration/enums/RegistrationErrorCode.java @@ -17,8 +17,9 @@ public enum RegistrationErrorCode { SCHEDULE_CONFLICT(HttpStatus.CONFLICT), CREDIT_LIMIT_EXCEEDED(HttpStatus.CONFLICT), CAPACITY_EXCEEDED(HttpStatus.CONFLICT), - ALREADY_CANCELED(HttpStatus.CONFLICT), - LOCK_TIMEOUT(HttpStatus.SERVICE_UNAVAILABLE); + IDEMPOTENCY_KEY_REUSED(HttpStatus.CONFLICT), + LOCK_TIMEOUT(HttpStatus.SERVICE_UNAVAILABLE), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR); private final HttpStatus status; diff --git a/src/main/java/com/study/course_registration/exception/GlobalExceptionHandler.java b/src/main/java/com/study/course_registration/exception/GlobalExceptionHandler.java index da1a11f..2367c0d 100644 --- a/src/main/java/com/study/course_registration/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/study/course_registration/exception/GlobalExceptionHandler.java @@ -1,54 +1,55 @@ package com.study.course_registration.exception; import java.time.Clock; - +import java.util.concurrent.ThreadLocalRandom; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.dao.PessimisticLockingFailureException; +import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; - import com.study.course_registration.enums.RegistrationErrorCode; - import jakarta.persistence.LockTimeoutException; import jakarta.persistence.PessimisticLockException; import jakarta.validation.ConstraintViolationException; @RestControllerAdvice public class GlobalExceptionHandler { + private static final Logger log=LoggerFactory.getLogger(GlobalExceptionHandler.class); private final Clock clock; - - public GlobalExceptionHandler(Clock clock) { - this.clock = clock; - } + public GlobalExceptionHandler(Clock clock) { this.clock=clock; } @ExceptionHandler(RegistrationException.class) - ResponseEntity handleRegistrationException(RegistrationException exception) { - return response(exception.getErrorCode(), exception.getMessage()); - } + ResponseEntity registration(RegistrationException e) { return response(e.getErrorCode(),e.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) - ResponseEntity handleValidation(MethodArgumentNotValidException exception) { - String message = exception.getBindingResult().getFieldErrors().stream() - .findFirst() - .map(error -> error.getField() + ": " + error.getDefaultMessage()) - .orElse("요청 값이 올바르지 않습니다."); - return response(RegistrationErrorCode.VALIDATION_ERROR, message); + ResponseEntity validation(MethodArgumentNotValidException e) { + String message=e.getBindingResult().getFieldErrors().stream().findFirst() + .map(x -> x.getField()+": "+x.getDefaultMessage()).orElse("요청 값이 올바르지 않습니다."); + return response(RegistrationErrorCode.VALIDATION_ERROR,message); } - @ExceptionHandler({ConstraintViolationException.class, HttpMessageNotReadableException.class}) - ResponseEntity handleBadRequest(Exception exception) { - return response(RegistrationErrorCode.VALIDATION_ERROR, "요청 값이 올바르지 않습니다."); + @ExceptionHandler({ConstraintViolationException.class,HttpMessageNotReadableException.class}) + ResponseEntity badRequest(Exception e) { return response(RegistrationErrorCode.VALIDATION_ERROR,"요청 값이 올바르지 않습니다."); } + + @ExceptionHandler({LockTimeoutException.class,PessimisticLockException.class,PessimisticLockingFailureException.class}) + ResponseEntity handleLockTimeout(Exception e) { + String retryAfter = Integer.toString(ThreadLocalRandom.current().nextInt(1, 4)); + return ResponseEntity.status(RegistrationErrorCode.LOCK_TIMEOUT.getStatus()).header(HttpHeaders.RETRY_AFTER, retryAfter) + .body(body(RegistrationErrorCode.LOCK_TIMEOUT,"다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요.")); } - @ExceptionHandler({LockTimeoutException.class, PessimisticLockException.class, PessimisticLockingFailureException.class}) - ResponseEntity handleLockTimeout(Exception exception) { - return response(RegistrationErrorCode.LOCK_TIMEOUT, "다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요."); + @ExceptionHandler(Exception.class) + ResponseEntity handleUnexpected(Exception e) { + log.error("Unhandled request failure",e); + return response(RegistrationErrorCode.INTERNAL_SERVER_ERROR,"서버 내부 오류가 발생했습니다."); } - private ResponseEntity response(RegistrationErrorCode code, String message) { - return ResponseEntity.status(code.getStatus()) - .body(new ErrorResponse(code.name(), message, clock.instant())); + private ResponseEntity response(RegistrationErrorCode code,String message) { + return ResponseEntity.status(code.getStatus()).body(body(code,message)); } + private ErrorResponse body(RegistrationErrorCode code,String message) { return new ErrorResponse(code.name(),message,clock.instant()); } } diff --git a/src/main/java/com/study/course_registration/repository/RegistrationIdempotencyRepository.java b/src/main/java/com/study/course_registration/repository/RegistrationIdempotencyRepository.java new file mode 100644 index 0000000..4b838c9 --- /dev/null +++ b/src/main/java/com/study/course_registration/repository/RegistrationIdempotencyRepository.java @@ -0,0 +1,38 @@ +package com.study.course_registration.repository; + +import java.time.Instant; +import java.util.Optional; + +import org.springframework.data.jpa.repository.EntityGraph; +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 com.study.course_registration.entity.RegistrationIdempotency; + +public interface RegistrationIdempotencyRepository extends JpaRepository { + @EntityGraph(attributePaths = { + "user", "lesson", "lesson.subject", "registration" + }) + Optional findByUser_IdAndIdempotencyKeyAndExpiresAtAfter( + String userId, + String idempotencyKey, + Instant now); + + @Modifying + @Query(""" + delete from RegistrationIdempotency value + where value.user.id = :userId + and value.idempotencyKey = :idempotencyKey + and value.expiresAt <= :now + """) + int deleteExpiredKey( + @Param("userId") String userId, + @Param("idempotencyKey") String idempotencyKey, + @Param("now") Instant now); + + @Modifying + @Query("delete from RegistrationIdempotency value where value.expiresAt <= :now") + int deleteExpired(@Param("now") Instant now); +} diff --git a/src/main/java/com/study/course_registration/repository/SemesterRepository.java b/src/main/java/com/study/course_registration/repository/SemesterRepository.java index f420144..1bc3f52 100644 --- a/src/main/java/com/study/course_registration/repository/SemesterRepository.java +++ b/src/main/java/com/study/course_registration/repository/SemesterRepository.java @@ -1,13 +1,17 @@ package com.study.course_registration.repository; +import java.time.Instant; import java.time.LocalDate; -import java.util.Optional; +import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.study.course_registration.entity.Semester; public interface SemesterRepository extends JpaRepository { - Optional findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqualOrderByStartDateDesc( + List findByStartDateLessThanEqualAndEndDateGreaterThanEqual( LocalDate startDate, LocalDate endDate); + + List findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual( + Instant startAt, Instant endAt); } diff --git a/src/main/java/com/study/course_registration/seeder/DataSeeder.java b/src/main/java/com/study/course_registration/seeder/DataSeeder.java index 28caa94..954b06e 100644 --- a/src/main/java/com/study/course_registration/seeder/DataSeeder.java +++ b/src/main/java/com/study/course_registration/seeder/DataSeeder.java @@ -1,14 +1,18 @@ package com.study.course_registration.seeder; -import java.time.Clock; import java.time.DayOfWeek; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -19,14 +23,12 @@ import com.study.course_registration.entity.Semester; import com.study.course_registration.entity.Subject; import com.study.course_registration.entity.User; import com.study.course_registration.enums.UserRole; -import com.study.course_registration.repository.LessonRepository; -import com.study.course_registration.repository.LessonScheduleRepository; -import com.study.course_registration.repository.ProfessorRepository; -import com.study.course_registration.repository.SemesterRepository; -import com.study.course_registration.repository.SubjectRepository; -import com.study.course_registration.repository.UserRepository; +import com.study.course_registration.service.policy.LessonSchedulePolicy; + +import jakarta.persistence.EntityManager; @Component +@Profile({"local", "dev"}) @ConditionalOnProperty(name = "app.seed.enabled", havingValue = "true") public class DataSeeder implements CommandLineRunner { public static final String SEMESTER_ID = "00000000-0000-0000-0000-000000000001"; @@ -41,81 +43,77 @@ public class DataSeeder implements CommandLineRunner { public static final String POSTGRADUATE_ONLY_ID = "40000000-0000-0000-0000-000000000006"; public static final String BOUNDARY_LESSON_ID = "40000000-0000-0000-0000-000000000007"; - private final Clock clock; - private final SemesterRepository semesterRepository; - private final ProfessorRepository professorRepository; - private final SubjectRepository subjectRepository; - private final LessonRepository lessonRepository; - private final LessonScheduleRepository lessonScheduleRepository; - private final UserRepository userRepository; + private final JdbcTemplate jdbcTemplate; + private final EntityManager entityManager; + private final LessonSchedulePolicy schedulePolicy; - public DataSeeder(Clock clock, - SemesterRepository semesterRepository, - ProfessorRepository professorRepository, - SubjectRepository subjectRepository, - LessonRepository lessonRepository, - LessonScheduleRepository lessonScheduleRepository, - UserRepository userRepository) { - this.clock = clock; - this.semesterRepository = semesterRepository; - this.professorRepository = professorRepository; - this.subjectRepository = subjectRepository; - this.lessonRepository = lessonRepository; - this.lessonScheduleRepository = lessonScheduleRepository; - this.userRepository = userRepository; + public DataSeeder(JdbcTemplate jdbcTemplate, EntityManager entityManager, LessonSchedulePolicy schedulePolicy) { + this.jdbcTemplate = jdbcTemplate; + this.entityManager = entityManager; + this.schedulePolicy = schedulePolicy; } @Override @Transactional public void run(String... args) { - if (semesterRepository.existsById(SEMESTER_ID)) { + jdbcTemplate.queryForObject( + "select name from seed_locks where name = ? for update", + String.class, "demo-dataset"); + if (entityManager.find(Semester.class, SEMESTER_ID) != null) { return; } - Instant now = clock.instant(); - LocalDate today = LocalDate.now(clock); - Semester semester = semesterRepository.save(new Semester( - SEMESTER_ID, "2026-1", today.minusDays(30), today.plusDays(120), - now.minusSeconds(86_400), now.plusSeconds(7 * 86_400), 18)); + Map semesters = new LinkedHashMap<>(); + for (SeedTable.Row row : SeedTable.read("seed/demo/semesters.tsv")) { + Semester semester = new Semester(row.text("id"), row.text("name"), + LocalDate.parse(row.text("startDate")), LocalDate.parse(row.text("endDate")), + Instant.parse(row.text("registrationStartAt")), Instant.parse(row.text("registrationEndAt")), + row.integer("maxCredits")); + entityManager.persist(semester); + semesters.put(semester.getId(), semester); + } - List professors = professorRepository.saveAll(List.of( - new Professor("10000000-0000-0000-0000-000000000001", "김영한"), - new Professor("10000000-0000-0000-0000-000000000002", "최태영"), - new Professor("10000000-0000-0000-0000-000000000003", "조재한"))); + Map professors = new LinkedHashMap<>(); + for (SeedTable.Row row : SeedTable.read("seed/demo/professors.tsv")) { + Professor professor = new Professor(row.text("id"), row.text("name")); + entityManager.persist(professor); + professors.put(professor.getId(), professor); + } - List subjects = subjectRepository.saveAll(List.of( - new Subject("20000000-0000-0000-0000-000000000001", "자바 프로그래밍", "CS201", "자바 프로그래밍 기초", 3), - new Subject("20000000-0000-0000-0000-000000000002", "자료구조", "CS202", "자료구조 및 알고리즘", 3), - new Subject("20000000-0000-0000-0000-000000000003", "데이터베이스", "CS203", "데이터베이스 시스템", 3), - new Subject("20000000-0000-0000-0000-000000000004", "컴퓨터 네트워크", "CS204", "네트워크 기초", 3), - new Subject("20000000-0000-0000-0000-000000000005", "운영체제", "CS301", "운영체제 핵심", 3), - new Subject("20000000-0000-0000-0000-000000000006", "대학원 세미나", "CS401", "대학원 전용 세미나", 3))); + Map subjects = new LinkedHashMap<>(); + for (SeedTable.Row row : SeedTable.read("seed/demo/subjects.tsv")) { + Subject subject = new Subject(row.text("id"), row.text("name"), row.text("code"), + row.text("description"), row.integer("credit")); + entityManager.persist(subject); + subjects.put(subject.getId(), subject); + } - Lesson data01 = new Lesson(DATA_STRUCTURES_01_ID, "자료구조 01분반", subjects.get(1), professors.get(0), semester, 30, null, null); - Lesson data02 = new Lesson(DATA_STRUCTURES_02_ID, "자료구조 02분반", subjects.get(1), professors.get(1), semester, 30, null, null); - Lesson os = new Lesson(OVERLAP_OS_ID, "운영체제", subjects.get(4), professors.get(1), semester, 30, null, null); - Lesson capacityOne = new Lesson(CAPACITY_ONE_ID, "데이터베이스 소수정예", subjects.get(2), professors.get(2), semester, 1, null, null); - Lesson minGrade = new Lesson(MIN_GRADE_ID, "고급 네트워크", subjects.get(3), professors.get(2), semester, 30, 3L, null); - Lesson postgraduate = new Lesson(POSTGRADUATE_ONLY_ID, "대학원 세미나", subjects.get(5), professors.get(0), semester, 20, null, UserRole.POSTGRADUATE); - Lesson boundary = new Lesson(BOUNDARY_LESSON_ID, "자바 프로그래밍", subjects.get(0), professors.get(0), semester, 30, null, null); - lessonRepository.saveAll(List.of(data01, data02, os, capacityOne, minGrade, postgraduate, boundary)); + for (SeedTable.Row row : SeedTable.read("seed/demo/users.tsv")) { + entityManager.persist(new User(row.text("id"), row.text("name"), row.longValue("grade"), + UserRole.valueOf(row.text("role")))); + } - lessonScheduleRepository.saveAll(List.of( - schedule("50000000-0000-0000-0000-000000000001", data01, DayOfWeek.MONDAY, 9, 11), - schedule("50000000-0000-0000-0000-000000000002", data02, DayOfWeek.TUESDAY, 9, 11), - schedule("50000000-0000-0000-0000-000000000003", os, DayOfWeek.MONDAY, 10, 12), - schedule("50000000-0000-0000-0000-000000000004", capacityOne, DayOfWeek.WEDNESDAY, 9, 11), - schedule("50000000-0000-0000-0000-000000000005", minGrade, DayOfWeek.THURSDAY, 9, 11), - schedule("50000000-0000-0000-0000-000000000006", postgraduate, DayOfWeek.FRIDAY, 9, 11), - schedule("50000000-0000-0000-0000-000000000007", boundary, DayOfWeek.MONDAY, 11, 13))); + Map lessons = new LinkedHashMap<>(); + for (SeedTable.Row row : SeedTable.read("seed/demo/lessons.tsv")) { + String minGrade = row.nullable("minGrade"); + String allowedRole = row.nullable("allowedRole"); + Lesson lesson = new Lesson(row.text("id"), row.text("name"), + subjects.get(row.text("subjectId")), professors.get(row.text("professorId")), + semesters.get(row.text("semesterId")), row.integer("capacity"), + minGrade == null ? null : Long.parseLong(minGrade), + allowedRole == null ? null : UserRole.valueOf(allowedRole)); + entityManager.persist(lesson); + lessons.put(lesson.getId(), lesson); + } - userRepository.saveAll(List.of( - new User(STUDENT_GRADE_1_ID, "학생1", 1L, UserRole.STUDENT), - new User(STUDENT_GRADE_2_ID, "학생2", 2L, UserRole.STUDENT), - new User(POSTGRADUATE_ID, "대학원생", 3L, UserRole.POSTGRADUATE))); + List schedules = new ArrayList<>(); + for (SeedTable.Row row : SeedTable.read("seed/demo/schedules.tsv")) { + schedules.add(new LessonSchedule(row.text("id"), lessons.get(row.text("lessonId")), + DayOfWeek.valueOf(row.text("dayOfWeek")), LocalTime.parse(row.text("startTime")), + LocalTime.parse(row.text("endTime")))); + } + schedulePolicy.validate(schedules); + schedules.forEach(entityManager::persist); } - private static LessonSchedule schedule(String id, Lesson lesson, DayOfWeek day, int startHour, int endHour) { - return new LessonSchedule(id, lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0)); - } } diff --git a/src/main/java/com/study/course_registration/seeder/SeedTable.java b/src/main/java/com/study/course_registration/seeder/SeedTable.java new file mode 100644 index 0000000..796e150 --- /dev/null +++ b/src/main/java/com/study/course_registration/seeder/SeedTable.java @@ -0,0 +1,47 @@ +package com.study.course_registration.seeder; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; +import java.util.stream.Collectors; + +import org.springframework.core.io.ClassPathResource; + +final class SeedTable { + private SeedTable() {} + + static List read(String resource) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader( + new ClassPathResource(resource).getInputStream(), StandardCharsets.UTF_8))) { + List lines = reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).toList(); + String[] headers = lines.getFirst().split("\t", -1); + return lines.stream().skip(1).map(line -> row(headers, line)).toList(); + } catch (IOException exception) { + throw new IllegalStateException("seed data를 읽을 수 없습니다: " + resource, exception); + } + } + + private static Row row(String[] headers, String line) { + String[] values = line.split("\t", -1); + if (headers.length != values.length) { + throw new IllegalStateException("seed column 수가 맞지 않습니다: " + line); + } + Map columns = IntStream.range(0, headers.length) + .boxed().collect(Collectors.toMap(index -> headers[index], index -> values[index])); + return new Row(columns); + } + + record Row(Map columns) { + String text(String name) { return columns.get(name); } + String nullable(String name) { + String value = text(name); + return value == null || value.isBlank() ? null : value; + } + int integer(String name) { return Integer.parseInt(text(name)); } + long longValue(String name) { return Long.parseLong(text(name)); } + } +} diff --git a/src/main/java/com/study/course_registration/service/CourseRegistrationService.java b/src/main/java/com/study/course_registration/service/CourseRegistrationService.java index 412fa46..68a9fcd 100644 --- a/src/main/java/com/study/course_registration/service/CourseRegistrationService.java +++ b/src/main/java/com/study/course_registration/service/CourseRegistrationService.java @@ -1,17 +1,17 @@ package com.study.course_registration.service; import java.time.Clock; -import java.time.LocalDate; +import java.time.Instant; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; - +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - import com.study.course_registration.dto.ScheduleResponse; import com.study.course_registration.dto.registration.CourseRegistrationRequest; import com.study.course_registration.dto.registration.CourseRegistrationResponse; @@ -19,165 +19,162 @@ import com.study.course_registration.dto.registration.RegistrationItemResponse; import com.study.course_registration.dto.registration.RegistrationListResponse; import com.study.course_registration.entity.Lesson; import com.study.course_registration.entity.LessonSchedule; +import com.study.course_registration.entity.RegistrationIdempotency; import com.study.course_registration.entity.Semester; import com.study.course_registration.entity.User; import com.study.course_registration.entity.UserLesson; import com.study.course_registration.enums.RegistrationErrorCode; import com.study.course_registration.exception.RegistrationException; -import com.study.course_registration.repository.LessonRepository; import com.study.course_registration.repository.LessonScheduleRepository; -import com.study.course_registration.repository.SemesterRepository; +import com.study.course_registration.repository.RegistrationIdempotencyRepository; import com.study.course_registration.repository.UserLessonRepository; import com.study.course_registration.repository.UserRepository; +import com.study.course_registration.service.lock.RegistrationLockManager; +import com.study.course_registration.service.lock.RegistrationLockManager.LockedRegistration; import com.study.course_registration.service.policy.RegistrationValidator; @Service public class CourseRegistrationService { private final Clock clock; private final UserRepository userRepository; - private final LessonRepository lessonRepository; - private final SemesterRepository semesterRepository; private final LessonScheduleRepository lessonScheduleRepository; private final UserLessonRepository userLessonRepository; + private final RegistrationIdempotencyRepository idempotencies; private final RegistrationValidator validator; + private final SemesterResolver semesterResolver; + private final RegistrationLockManager lockManager; + private final long idempotencyTtlSeconds; - public CourseRegistrationService(Clock clock, - UserRepository userRepository, - LessonRepository lessonRepository, - SemesterRepository semesterRepository, - LessonScheduleRepository lessonScheduleRepository, - UserLessonRepository userLessonRepository, - RegistrationValidator validator) { + public CourseRegistrationService(Clock clock, UserRepository userRepository, + LessonScheduleRepository lessonScheduleRepository, UserLessonRepository userLessonRepository, + RegistrationIdempotencyRepository idempotencies, RegistrationValidator validator, + SemesterResolver semesterResolver, RegistrationLockManager lockManager, + @Value("${app.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds) { this.clock = clock; this.userRepository = userRepository; - this.lessonRepository = lessonRepository; - this.semesterRepository = semesterRepository; this.lessonScheduleRepository = lessonScheduleRepository; this.userLessonRepository = userLessonRepository; + this.idempotencies = idempotencies; this.validator = validator; + this.semesterResolver = semesterResolver; + this.lockManager = lockManager; + this.idempotencyTtlSeconds = idempotencyTtlSeconds; } @Transactional public CourseRegistrationResponse register(String userId, CourseRegistrationRequest request) { - User user = userRepository.findById(userId) - .orElseThrow(() -> error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다.")); - Lesson lesson = lessonRepository.findById(request.lessonId()) - .orElseThrow(() -> error(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다.")); + return register(userId, request, null); + } - var now = clock.instant(); - validator.validatePreconditions(user, lesson, now); + @Transactional + public CourseRegistrationResponse register(String userId, CourseRegistrationRequest request, String idempotencyKey) { + LockedRegistration locked = lockManager.lock(userId, request.lessonId()); - // Lock order is a system invariant: User -> Lesson. - User lockedUser = userRepository.findByIdForUpdate(userId) - .orElseThrow(() -> error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다.")); - Lesson lockedLesson = lessonRepository.findByIdForUpdate(request.lessonId()) - .orElseThrow(() -> error(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다.")); + String normalizedKey = normalizeIdempotencyKey(idempotencyKey); + Instant requestTime = clock.instant(); + if (normalizedKey != null) { + idempotencies.deleteExpiredKey(userId, normalizedKey, requestTime); + Optional previous = + idempotencies.findByUser_IdAndIdempotencyKeyAndExpiresAtAfter( + userId, normalizedKey, requestTime); + if (previous.isPresent()) { + RegistrationIdempotency stored = previous.get(); + if (!stored.getLesson().getId().equals(request.lessonId())) { + throw error(RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED, + "동일한 Idempotency-Key를 다른 강의에 사용할 수 없습니다."); + } + return response(stored.getRegistration(), stored.getUser(), stored.getLesson(), stored.getTotalCredits()); + } + } - List activeRegistrations = userLessonRepository.findActiveByUserIdAndSemesterId( - lockedUser.getId(), lockedLesson.getSemester().getId()); - Map> schedules = loadSchedules(activeRegistrations, lockedLesson); - long enrolledCount = userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lockedLesson.getId()); + validator.validatePreconditions(locked.user(), locked.lesson(), requestTime); - validator.validateLocked(lockedLesson, activeRegistrations, schedules, enrolledCount); - int totalCredits = validator.totalCreditsAfter(lockedLesson, activeRegistrations); + List active = userLessonRepository.findActiveByUserIdAndSemesterId( + locked.user().getId(), locked.lesson().getSemester().getId()); + Map> schedules = loadSchedules(active, locked.lesson()); + long enrolled = userLessonRepository.countByLesson_IdAndCanceledAtIsNull(locked.lesson().getId()); - UserLesson registration = userLessonRepository.saveAndFlush(new UserLesson(lockedUser, lockedLesson)); - return new CourseRegistrationResponse( - registration.getId(), - lockedUser.getId(), - lockedLesson.getId(), - lockedLesson.getName(), - lockedLesson.getSubject().getCode(), - lockedLesson.getSubject().getCredit(), - registration.getCreatedAt(), - totalCredits); + validator.validateLocked(locked.lesson(), active, schedules, enrolled); + validator.validateRegistrationPeriod(locked.lesson(), clock.instant()); + + int totalCredits = validator.totalCreditsAfter(locked.lesson(), active); + UserLesson registration = userLessonRepository.saveAndFlush(new UserLesson(locked.user(), locked.lesson())); + if (normalizedKey != null) { + idempotencies.saveAndFlush(new RegistrationIdempotency( + locked.user(), + locked.lesson(), + registration, + normalizedKey, + totalCredits, + requestTime.plusSeconds(idempotencyTtlSeconds))); + } + return response(registration, locked.user(), locked.lesson(), totalCredits); } @Transactional(readOnly = true) public RegistrationListResponse getRegistrations(String userId, String semesterId) { - if (!userRepository.existsById(userId)) { - throw error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다."); - } - Semester semester = resolveSemester(semesterId); - List activeRegistrations = userLessonRepository.findActiveByUserIdAndSemesterId(userId, semester.getId()); - - Set lessonIds = activeRegistrations.stream() - .map(UserLesson::getLesson) - .map(Lesson::getId) + if (!userRepository.existsById(userId)) throw error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다."); + Semester semester = semesterResolver.resolve(semesterId); + List active = userLessonRepository.findActiveByUserIdAndSemesterId(userId, semester.getId()); + Set lessonIds = active.stream().map(UserLesson::getLesson).map(Lesson::getId) .collect(Collectors.toCollection(LinkedHashSet::new)); - Map> schedulesByLesson = groupSchedules( - lessonIds.isEmpty() ? List.of() : lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds)); - - List items = activeRegistrations.stream() - .map(registration -> { - Lesson lesson = registration.getLesson(); - List schedules = schedulesByLesson.getOrDefault(lesson.getId(), List.of()).stream() - .map(ScheduleResponse::from) - .toList(); - return new RegistrationItemResponse( - registration.getId(), lesson.getId(), lesson.getName(), - lesson.getSubject().getCode(), lesson.getSubject().getName(), lesson.getSubject().getCredit(), - lesson.getProfessor().getName(), schedules, registration.getCreatedAt()); - }) - .toList(); - - return new RegistrationListResponse( - userId, semester.getId(), semester.getName(), validator.currentCredits(activeRegistrations), - semester.getMaxCredits(), items); + Map> schedules = groupSchedules(lessonIds.isEmpty() ? List.of() + : lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds)); + List items = active.stream().map(registration -> { + Lesson lesson=registration.getLesson(); + return new RegistrationItemResponse(registration.getId(), lesson.getId(), lesson.getName(), + lesson.getSubject().getCode(), lesson.getSubject().getName(), lesson.getSubject().getCredit(), + lesson.getProfessor().getName(), schedules.getOrDefault(lesson.getId(),List.of()).stream() + .map(ScheduleResponse::from).toList(), registration.getCreatedAt()); + }).toList(); + return new RegistrationListResponse(userId, semester.getId(), semester.getName(), + validator.currentCredits(active), semester.getMaxCredits(), items); } @Transactional public void cancel(String userId, String registrationId) { UserLessonRepository.RegistrationTarget target = userLessonRepository.findTargetById(registrationId) .orElseThrow(() -> error(RegistrationErrorCode.REGISTRATION_NOT_FOUND, "수강신청 건을 찾을 수 없습니다.")); - if (!target.getUserId().equals(userId)) { - throw error(RegistrationErrorCode.REGISTRATION_FORBIDDEN, "다른 사용자의 수강신청은 취소할 수 없습니다."); - } - - // Mutation paths use the same fixed lock order as registration. - userRepository.findByIdForUpdate(userId) - .orElseThrow(() -> error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다.")); - Lesson lesson = lessonRepository.findByIdForUpdate(target.getLessonId()) - .orElseThrow(() -> error(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다.")); + if (!target.getUserId().equals(userId)) throw error(RegistrationErrorCode.REGISTRATION_FORBIDDEN, "다른 사용자의 수강신청은 취소할 수 없습니다."); + LockedRegistration locked = lockManager.lock(userId, target.getLessonId()); UserLesson registration = userLessonRepository.findById(registrationId) .orElseThrow(() -> error(RegistrationErrorCode.REGISTRATION_NOT_FOUND, "수강신청 건을 찾을 수 없습니다.")); - - if (registration.isCanceled()) { - throw error(RegistrationErrorCode.ALREADY_CANCELED, "이미 취소된 수강신청입니다."); - } - var now = clock.instant(); - validator.validateRegistrationPeriod(lesson, now); + if (registration.isCanceled()) return; + Instant now = clock.instant(); + validator.validateRegistrationPeriod(locked.lesson(), now); registration.cancel(now); } - private Semester resolveSemester(String semesterId) { - if (semesterId != null && !semesterId.isBlank()) { - return semesterRepository.findById(semesterId) - .orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "학기를 찾을 수 없습니다.")); + + private CourseRegistrationResponse response( + UserLesson registration, + User user, + Lesson lesson, + int totalCredits) { + return new CourseRegistrationResponse( + registration.getId(), user.getId(), lesson.getId(), lesson.getName(), + lesson.getSubject().getCode(), lesson.getSubject().getCredit(), + registration.getCreatedAt(), totalCredits); + } + + private static String normalizeIdempotencyKey(String value) { + if (value == null || value.isBlank()) return null; + String normalized = value.trim(); + if (normalized.length() > 100) { + throw error(RegistrationErrorCode.VALIDATION_ERROR, "Idempotency-Key는 100자 이하여야 합니다."); } - LocalDate today = LocalDate.now(clock); - return semesterRepository - .findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqualOrderByStartDateDesc(today, today) - .orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "현재 진행 중인 학기를 찾을 수 없습니다.")); + return normalized; } - private Map> loadSchedules(List registrations, Lesson candidate) { - Set lessonIds = registrations.stream() - .map(UserLesson::getLesson) - .map(Lesson::getId) + private Map> loadSchedules(List registrations, Lesson candidate) { + Set ids=registrations.stream().map(UserLesson::getLesson).map(Lesson::getId) .collect(Collectors.toCollection(LinkedHashSet::new)); - lessonIds.add(candidate.getId()); - return groupSchedules(lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds)); + ids.add(candidate.getId()); + return groupSchedules(lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(ids)); } - private static Map> groupSchedules(List schedules) { - return schedules.stream().collect(Collectors.groupingBy( - schedule -> schedule.getLesson().getId(), - LinkedHashMap::new, - Collectors.toList())); - } - - private static RegistrationException error(RegistrationErrorCode code, String message) { - return new RegistrationException(code, message); + private static Map> groupSchedules(List schedules) { + return schedules.stream().collect(Collectors.groupingBy(s -> s.getLesson().getId(),LinkedHashMap::new,Collectors.toList())); } + private static RegistrationException error(RegistrationErrorCode code,String message) { return new RegistrationException(code,message); } } diff --git a/src/main/java/com/study/course_registration/service/IdempotencyRetentionJob.java b/src/main/java/com/study/course_registration/service/IdempotencyRetentionJob.java new file mode 100644 index 0000000..b7b125b --- /dev/null +++ b/src/main/java/com/study/course_registration/service/IdempotencyRetentionJob.java @@ -0,0 +1,26 @@ +package com.study.course_registration.service; + +import java.time.Clock; + +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import com.study.course_registration.repository.RegistrationIdempotencyRepository; + +@Component +public class IdempotencyRetentionJob { + private final Clock clock; + private final RegistrationIdempotencyRepository repository; + + public IdempotencyRetentionJob(Clock clock, RegistrationIdempotencyRepository repository) { + this.clock = clock; + this.repository = repository; + } + + @Scheduled(fixedDelayString = "${app.idempotency.cleanup-delay-ms:3600000}") + @Transactional + public void cleanup() { + repository.deleteExpired(clock.instant()); + } +} diff --git a/src/main/java/com/study/course_registration/service/LessonQueryService.java b/src/main/java/com/study/course_registration/service/LessonQueryService.java index 3103a77..ae7686d 100644 --- a/src/main/java/com/study/course_registration/service/LessonQueryService.java +++ b/src/main/java/com/study/course_registration/service/LessonQueryService.java @@ -1,7 +1,5 @@ package com.study.course_registration.service; -import java.time.Clock; -import java.time.LocalDate; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -25,32 +23,28 @@ import com.study.course_registration.enums.RegistrationErrorCode; import com.study.course_registration.exception.RegistrationException; import com.study.course_registration.repository.LessonRepository; import com.study.course_registration.repository.LessonScheduleRepository; -import com.study.course_registration.repository.SemesterRepository; import com.study.course_registration.repository.UserLessonRepository; @Service @Transactional(readOnly = true) public class LessonQueryService { - private final Clock clock; private final LessonRepository lessonRepository; private final LessonScheduleRepository lessonScheduleRepository; private final UserLessonRepository userLessonRepository; - private final SemesterRepository semesterRepository; + private final SemesterResolver semesterResolver; - public LessonQueryService(Clock clock, - LessonRepository lessonRepository, + public LessonQueryService(LessonRepository lessonRepository, LessonScheduleRepository lessonScheduleRepository, UserLessonRepository userLessonRepository, - SemesterRepository semesterRepository) { - this.clock = clock; + SemesterResolver semesterResolver) { this.lessonRepository = lessonRepository; this.lessonScheduleRepository = lessonScheduleRepository; this.userLessonRepository = userLessonRepository; - this.semesterRepository = semesterRepository; + this.semesterResolver = semesterResolver; } public LessonListResponse getLessons(String semesterId, String subjectId, int page, int size) { - Semester semester = resolveSemester(semesterId); + Semester semester = semesterResolver.resolve(semesterId); Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Order.asc("name"), Sort.Order.asc("id"))); Page lessonPage = subjectId == null || subjectId.isBlank() ? lessonRepository.findBySemester_Id(semester.getId(), pageable) @@ -109,16 +103,6 @@ public class LessonQueryService { LinkedHashMap::new)); } - private Semester resolveSemester(String semesterId) { - if (semesterId != null && !semesterId.isBlank()) { - return semesterRepository.findById(semesterId) - .orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "학기를 찾을 수 없습니다.")); - } - LocalDate today = LocalDate.now(clock); - return semesterRepository.findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqualOrderByStartDateDesc(today, today) - .orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "현재 진행 중인 학기를 찾을 수 없습니다.")); - } - private static RegistrationException error(RegistrationErrorCode code, String message) { return new RegistrationException(code, message); } diff --git a/src/main/java/com/study/course_registration/service/SemesterResolver.java b/src/main/java/com/study/course_registration/service/SemesterResolver.java new file mode 100644 index 0000000..99dc54c --- /dev/null +++ b/src/main/java/com/study/course_registration/service/SemesterResolver.java @@ -0,0 +1,57 @@ +package com.study.course_registration.service; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDate; +import java.util.List; + +import org.springframework.stereotype.Component; + +import com.study.course_registration.entity.Semester; +import com.study.course_registration.enums.RegistrationErrorCode; +import com.study.course_registration.exception.RegistrationException; +import com.study.course_registration.repository.SemesterRepository; + +@Component +public class SemesterResolver { + private final Clock clock; + private final SemesterRepository semesterRepository; + + public SemesterResolver(Clock clock, SemesterRepository semesterRepository) { + this.clock = clock; + this.semesterRepository = semesterRepository; + } + + public Semester resolve(String semesterId) { + if (semesterId != null && !semesterId.isBlank()) { + return semesterRepository.findById(semesterId) + .orElseThrow(() -> notFound("학기를 찾을 수 없습니다.")); + } + + Instant now = clock.instant(); + List registrationSemesters = + semesterRepository.findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual( + now, now); + if (registrationSemesters.size() > 1) { + throw new IllegalStateException("동시에 두 개 이상의 수강신청 학기가 활성화되어 있습니다."); + } + if (registrationSemesters.size() == 1) { + return registrationSemesters.getFirst(); + } + + LocalDate today = LocalDate.now(clock); + List academicSemesters = + semesterRepository.findByStartDateLessThanEqualAndEndDateGreaterThanEqual(today, today); + if (academicSemesters.size() > 1) { + throw new IllegalStateException("동시에 두 개 이상의 학기가 진행 중입니다."); + } + if (academicSemesters.size() == 1) { + return academicSemesters.getFirst(); + } + throw notFound("현재 수강 가능한 학기를 찾을 수 없습니다."); + } + + private static RegistrationException notFound(String message) { + return new RegistrationException(RegistrationErrorCode.SEMESTER_NOT_FOUND, message); + } +} diff --git a/src/main/java/com/study/course_registration/service/lock/RegistrationLockManager.java b/src/main/java/com/study/course_registration/service/lock/RegistrationLockManager.java new file mode 100644 index 0000000..ad24ceb --- /dev/null +++ b/src/main/java/com/study/course_registration/service/lock/RegistrationLockManager.java @@ -0,0 +1,30 @@ +package com.study.course_registration.service.lock; + +import org.springframework.stereotype.Component; +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.User; +import com.study.course_registration.enums.RegistrationErrorCode; +import com.study.course_registration.exception.RegistrationException; +import com.study.course_registration.repository.LessonRepository; +import com.study.course_registration.repository.UserRepository; + +@Component +public class RegistrationLockManager { + private final UserRepository userRepository; + private final LessonRepository lessonRepository; + + public RegistrationLockManager(UserRepository userRepository, LessonRepository lessonRepository) { + this.userRepository = userRepository; + this.lessonRepository = lessonRepository; + } + + public LockedRegistration lock(String userId, String lessonId) { + User user = userRepository.findByIdForUpdate(userId) + .orElseThrow(() -> new RegistrationException(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다.")); + Lesson lesson = lessonRepository.findByIdForUpdate(lessonId) + .orElseThrow(() -> new RegistrationException(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다.")); + return new LockedRegistration(user, lesson); + } + + public record LockedRegistration(User user, Lesson lesson) {} +} diff --git a/src/main/java/com/study/course_registration/service/policy/LessonSchedulePolicy.java b/src/main/java/com/study/course_registration/service/policy/LessonSchedulePolicy.java new file mode 100644 index 0000000..666030e --- /dev/null +++ b/src/main/java/com/study/course_registration/service/policy/LessonSchedulePolicy.java @@ -0,0 +1,34 @@ +package com.study.course_registration.service.policy; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Component; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.LessonSchedule; + +@Component +public class LessonSchedulePolicy { + private final ScheduleConflictChecker conflictChecker; + + public LessonSchedulePolicy(ScheduleConflictChecker conflictChecker) { + this.conflictChecker = conflictChecker; + } + + public void validate(List schedules) { + Map> byLesson = schedules.stream() + .collect(Collectors.groupingBy(LessonSchedule::getLesson)); + + for (List lessonSchedules : byLesson.values()) { + for (int left = 0; left < lessonSchedules.size(); left++) { + for (int right = left + 1; right < lessonSchedules.size(); right++) { + if (conflictChecker.overlaps(lessonSchedules.get(left), lessonSchedules.get(right))) { + throw new IllegalArgumentException("같은 강의의 시간표가 겹칩니다."); + } + } + } + } + } +} diff --git a/src/main/java/com/study/course_registration/service/policy/RegistrationValidator.java b/src/main/java/com/study/course_registration/service/policy/RegistrationValidator.java index deb1726..74eee08 100644 --- a/src/main/java/com/study/course_registration/service/policy/RegistrationValidator.java +++ b/src/main/java/com/study/course_registration/service/policy/RegistrationValidator.java @@ -55,8 +55,14 @@ public class RegistrationValidator { } List candidateSchedules = schedulesByLessonId.getOrDefault(lesson.getId(), List.of()); + if (candidateSchedules.isEmpty()) { + throw error(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "강의 시간표가 없습니다."); + } for (UserLesson registration : activeRegistrations) { List existingSchedules = schedulesByLessonId.getOrDefault(registration.getLesson().getId(), List.of()); + if (existingSchedules.isEmpty()) { + throw error(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "기존 신청 강의 시간표가 없습니다."); + } for (LessonSchedule candidate : candidateSchedules) { for (LessonSchedule existing : existingSchedules) { if (scheduleConflictChecker.overlaps(candidate, existing)) { diff --git a/src/main/resources/application-dev.yaml b/src/main/resources/application-dev.yaml index 66ea8b5..bddd33b 100644 --- a/src/main/resources/application-dev.yaml +++ b/src/main/resources/application-dev.yaml @@ -1,11 +1,16 @@ +server: + address: ${SERVER_ADDRESS:0.0.0.0} + spring: datasource: url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:course_registration} username: ${DB_USERNAME:course} password: ${DB_PASSWORD:course} + hikari: + connection-init-sql: SET lock_timeout TO '3s' + flyway: + locations: classpath:db/migration/postgresql jpa: - hibernate: - ddl-auto: update show-sql: ${JPA_SHOW_SQL:false} h2: console: diff --git a/src/main/resources/application-local.yaml b/src/main/resources/application-local.yaml index 8d8b910..f52d5a1 100644 --- a/src/main/resources/application-local.yaml +++ b/src/main/resources/application-local.yaml @@ -1,12 +1,15 @@ +server: + address: 127.0.0.1 + spring: datasource: url: jdbc:h2:mem:course_db;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;LOCK_TIMEOUT=3000 driver-class-name: org.h2.Driver username: sa password: + flyway: + locations: classpath:db/migration/h2 jpa: - hibernate: - ddl-auto: create-drop show-sql: true properties: hibernate: diff --git a/src/main/resources/application-prod.yaml b/src/main/resources/application-prod.yaml index 2aa64d7..85f003e 100644 --- a/src/main/resources/application-prod.yaml +++ b/src/main/resources/application-prod.yaml @@ -1,11 +1,16 @@ +server: + address: ${SERVER_ADDRESS:0.0.0.0} + spring: datasource: url: jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME} username: ${DB_USERNAME} password: ${DB_PASSWORD} + hikari: + connection-init-sql: SET lock_timeout TO '3s' + flyway: + locations: classpath:db/migration/postgresql jpa: - hibernate: - ddl-auto: validate show-sql: false h2: console: diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index d423891..4467758 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -1,16 +1,25 @@ server: - address: ${SERVER_ADDRESS:127.0.0.1} port: ${SERVER_PORT:8080} + shutdown: graceful spring: application: name: ${APP_NAME:course-registration} - profiles: - default: local jackson: time-zone: UTC jpa: open-in-view: false + hibernate: + ddl-auto: validate + lifecycle: + timeout-per-shutdown-phase: 30s + datasource: + url: ${DB_URL} + hikari: + connection-timeout: 2000 + validation-timeout: 1000 + maximum-pool-size: ${DB_POOL_MAX_SIZE:20} + minimum-idle: ${DB_POOL_MIN_IDLE:2} springdoc: api-docs: @@ -28,3 +37,13 @@ management: health: probes: enabled: true + group: + liveness: + include: livenessState + readiness: + include: readinessState,db + +app: + idempotency: + ttl-seconds: 86400 + cleanup-delay-ms: 3600000 diff --git a/src/main/resources/db/migration/h2/V1__baseline.sql b/src/main/resources/db/migration/h2/V1__baseline.sql new file mode 100644 index 0000000..391dab4 --- /dev/null +++ b/src/main/resources/db/migration/h2/V1__baseline.sql @@ -0,0 +1,131 @@ +CREATE TABLE semesters ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + start_date DATE NOT NULL, + end_date DATE NOT NULL, + registration_start_at TIMESTAMP WITH TIME ZONE NOT NULL, + registration_end_at TIMESTAMP WITH TIME ZONE NOT NULL, + max_credits INTEGER NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT uk_semester_name UNIQUE (name), + CONSTRAINT ck_semester_dates CHECK (end_date >= start_date), + CONSTRAINT ck_semester_registration_window CHECK (registration_start_at < registration_end_at), + CONSTRAINT ck_semester_max_credits CHECK (max_credits >= 1) +); + +CREATE TABLE professors ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL +); + +CREATE TABLE subjects ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + code VARCHAR(255) NOT NULL, + description VARCHAR(1000) NOT NULL, + credit INTEGER NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT uk_subject_code UNIQUE (code), + CONSTRAINT ck_subject_credit CHECK (credit >= 1) +); + +CREATE TABLE users ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + grade BIGINT NOT NULL, + role VARCHAR(64) NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT ck_user_grade CHECK (grade >= 1) +); + +CREATE TABLE lessons ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + subject_id VARCHAR(36) NOT NULL, + professor_id VARCHAR(36) NOT NULL, + semester_id VARCHAR(36) NOT NULL, + capacity INTEGER NOT NULL, + min_grade BIGINT, + allowed_role VARCHAR(64), + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT fk_lesson_subject FOREIGN KEY (subject_id) REFERENCES subjects(id), + CONSTRAINT fk_lesson_professor FOREIGN KEY (professor_id) REFERENCES professors(id), + CONSTRAINT fk_lesson_semester FOREIGN KEY (semester_id) REFERENCES semesters(id), + CONSTRAINT ck_lesson_capacity CHECK (capacity >= 1), + CONSTRAINT ck_lesson_min_grade CHECK (min_grade IS NULL OR min_grade >= 1) +); + +CREATE TABLE lesson_schedules ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + lesson_id VARCHAR(36) NOT NULL, + day_of_week INTEGER NOT NULL, + start_time TIME NOT NULL, + end_time TIME NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT fk_schedule_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id), + CONSTRAINT ck_schedule_day CHECK (day_of_week BETWEEN 1 AND 7), + CONSTRAINT ck_schedule_time CHECK (start_time < end_time), + CONSTRAINT uk_lesson_schedule UNIQUE (lesson_id, day_of_week, start_time, end_time) +); + +CREATE TABLE user_lessons ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + user_id VARCHAR(36) NOT NULL, + lesson_id VARCHAR(36) NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + canceled_at TIMESTAMP WITH TIME ZONE, + active_lesson_id VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN canceled_at IS NULL THEN lesson_id END), + CONSTRAINT fk_user_lesson_user FOREIGN KEY (user_id) REFERENCES users(id), + CONSTRAINT fk_user_lesson_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id), + CONSTRAINT uk_user_active_lesson UNIQUE (user_id, active_lesson_id) +); + +CREATE INDEX idx_user_lessons_user_active ON user_lessons(user_id, canceled_at); +CREATE INDEX idx_user_lessons_lesson_active ON user_lessons(lesson_id, canceled_at); +CREATE INDEX idx_lessons_semester_subject ON lessons(semester_id, subject_id); +CREATE INDEX idx_schedules_lesson ON lesson_schedules(lesson_id); + + +CREATE TABLE registration_idempotencies ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + user_id VARCHAR(36) NOT NULL, + lesson_id VARCHAR(36) NOT NULL, + registration_id VARCHAR(36) NOT NULL, + idempotency_key VARCHAR(100) NOT NULL, + total_credits INTEGER NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT fk_idempotency_user FOREIGN KEY (user_id) REFERENCES users(id), + CONSTRAINT fk_idempotency_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id), + CONSTRAINT fk_idempotency_registration FOREIGN KEY (registration_id) REFERENCES user_lessons(id), + CONSTRAINT uk_registration_idempotency UNIQUE (user_id, idempotency_key), + CONSTRAINT uk_idempotency_registration UNIQUE (registration_id) +); +CREATE INDEX idx_idempotency_expires_at ON registration_idempotencies(expires_at); + +CREATE TABLE seed_locks ( + name VARCHAR(100) PRIMARY KEY +); +INSERT INTO seed_locks(name) VALUES ('demo-dataset'); diff --git a/src/main/resources/db/migration/postgresql/V1__baseline.sql b/src/main/resources/db/migration/postgresql/V1__baseline.sql new file mode 100644 index 0000000..12b8dde --- /dev/null +++ b/src/main/resources/db/migration/postgresql/V1__baseline.sql @@ -0,0 +1,124 @@ +CREATE TABLE semesters ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + start_date DATE NOT NULL, + end_date DATE NOT NULL, + registration_start_at TIMESTAMPTZ NOT NULL, + registration_end_at TIMESTAMPTZ NOT NULL, + max_credits INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uk_semester_name UNIQUE (name), + CONSTRAINT ck_semester_dates CHECK (end_date >= start_date), + CONSTRAINT ck_semester_registration_window CHECK (registration_start_at < registration_end_at), + CONSTRAINT ck_semester_max_credits CHECK (max_credits >= 1) +); + +CREATE TABLE professors ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE subjects ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + code VARCHAR(255) NOT NULL, + description VARCHAR(1000) NOT NULL, + credit INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uk_subject_code UNIQUE (code), + CONSTRAINT ck_subject_credit CHECK (credit >= 1) +); + +CREATE TABLE users ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + grade BIGINT NOT NULL, + role VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_user_grade CHECK (grade >= 1) +); + +CREATE TABLE lessons ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + name VARCHAR(255) NOT NULL, + subject_id VARCHAR(36) NOT NULL, + professor_id VARCHAR(36) NOT NULL, + semester_id VARCHAR(36) NOT NULL, + capacity INTEGER NOT NULL, + min_grade BIGINT, + allowed_role VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT fk_lesson_subject FOREIGN KEY (subject_id) REFERENCES subjects(id), + CONSTRAINT fk_lesson_professor FOREIGN KEY (professor_id) REFERENCES professors(id), + CONSTRAINT fk_lesson_semester FOREIGN KEY (semester_id) REFERENCES semesters(id), + CONSTRAINT ck_lesson_capacity CHECK (capacity >= 1), + CONSTRAINT ck_lesson_min_grade CHECK (min_grade IS NULL OR min_grade >= 1) +); + +CREATE TABLE lesson_schedules ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + lesson_id VARCHAR(36) NOT NULL, + day_of_week INTEGER NOT NULL, + start_time TIME WITHOUT TIME ZONE NOT NULL, + end_time TIME WITHOUT TIME ZONE NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT fk_schedule_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id), + CONSTRAINT ck_schedule_day CHECK (day_of_week BETWEEN 1 AND 7), + CONSTRAINT ck_schedule_time CHECK (start_time < end_time), + CONSTRAINT uk_lesson_schedule UNIQUE (lesson_id, day_of_week, start_time, end_time) +); + +CREATE TABLE user_lessons ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + user_id VARCHAR(36) NOT NULL, + lesson_id VARCHAR(36) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + canceled_at TIMESTAMPTZ, + active_lesson_id VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN canceled_at IS NULL THEN lesson_id END) STORED, + CONSTRAINT fk_user_lesson_user FOREIGN KEY (user_id) REFERENCES users(id), + CONSTRAINT fk_user_lesson_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id), + CONSTRAINT uk_user_active_lesson UNIQUE (user_id, active_lesson_id) +); + +CREATE INDEX idx_user_lessons_user_active ON user_lessons(user_id, canceled_at); +CREATE INDEX idx_user_lessons_lesson_active ON user_lessons(lesson_id, canceled_at); +CREATE INDEX idx_lessons_semester_subject ON lessons(semester_id, subject_id); +CREATE INDEX idx_schedules_lesson ON lesson_schedules(lesson_id); + + +CREATE TABLE registration_idempotencies ( + id VARCHAR(36) PRIMARY KEY, + version BIGINT NOT NULL DEFAULT 0, + user_id VARCHAR(36) NOT NULL, + lesson_id VARCHAR(36) NOT NULL, + registration_id VARCHAR(36) NOT NULL, + idempotency_key VARCHAR(100) NOT NULL, + total_credits INTEGER NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT fk_idempotency_user FOREIGN KEY (user_id) REFERENCES users(id), + CONSTRAINT fk_idempotency_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id), + CONSTRAINT fk_idempotency_registration FOREIGN KEY (registration_id) REFERENCES user_lessons(id), + CONSTRAINT uk_registration_idempotency UNIQUE (user_id, idempotency_key), + CONSTRAINT uk_idempotency_registration UNIQUE (registration_id) +); +CREATE INDEX idx_idempotency_expires_at ON registration_idempotencies(expires_at); + +CREATE TABLE seed_locks ( + name VARCHAR(100) PRIMARY KEY +); +INSERT INTO seed_locks(name) VALUES ('demo-dataset'); diff --git a/src/main/resources/seed/demo/lessons.tsv b/src/main/resources/seed/demo/lessons.tsv new file mode 100644 index 0000000..5250409 --- /dev/null +++ b/src/main/resources/seed/demo/lessons.tsv @@ -0,0 +1,8 @@ +id name subjectId professorId semesterId capacity minGrade allowedRole +40000000-0000-0000-0000-000000000001 자료구조 01분반 20000000-0000-0000-0000-000000000002 10000000-0000-0000-0000-000000000001 00000000-0000-0000-0000-000000000001 30 +40000000-0000-0000-0000-000000000002 자료구조 02분반 20000000-0000-0000-0000-000000000002 10000000-0000-0000-0000-000000000002 00000000-0000-0000-0000-000000000001 30 +40000000-0000-0000-0000-000000000003 운영체제 20000000-0000-0000-0000-000000000005 10000000-0000-0000-0000-000000000002 00000000-0000-0000-0000-000000000001 30 +40000000-0000-0000-0000-000000000004 데이터베이스 소수정예 20000000-0000-0000-0000-000000000003 10000000-0000-0000-0000-000000000003 00000000-0000-0000-0000-000000000001 1 +40000000-0000-0000-0000-000000000005 고급 네트워크 20000000-0000-0000-0000-000000000004 10000000-0000-0000-0000-000000000003 00000000-0000-0000-0000-000000000001 30 3 +40000000-0000-0000-0000-000000000006 대학원 세미나 20000000-0000-0000-0000-000000000006 10000000-0000-0000-0000-000000000001 00000000-0000-0000-0000-000000000001 20 POSTGRADUATE +40000000-0000-0000-0000-000000000007 자바 프로그래밍 20000000-0000-0000-0000-000000000001 10000000-0000-0000-0000-000000000001 00000000-0000-0000-0000-000000000001 30 diff --git a/src/main/resources/seed/demo/professors.tsv b/src/main/resources/seed/demo/professors.tsv new file mode 100644 index 0000000..cf41a90 --- /dev/null +++ b/src/main/resources/seed/demo/professors.tsv @@ -0,0 +1,4 @@ +id name +10000000-0000-0000-0000-000000000001 김영한 +10000000-0000-0000-0000-000000000002 최태영 +10000000-0000-0000-0000-000000000003 조재한 diff --git a/src/main/resources/seed/demo/schedules.tsv b/src/main/resources/seed/demo/schedules.tsv new file mode 100644 index 0000000..34260f7 --- /dev/null +++ b/src/main/resources/seed/demo/schedules.tsv @@ -0,0 +1,8 @@ +id lessonId dayOfWeek startTime endTime +50000000-0000-0000-0000-000000000001 40000000-0000-0000-0000-000000000001 MONDAY 09:00 11:00 +50000000-0000-0000-0000-000000000002 40000000-0000-0000-0000-000000000002 TUESDAY 09:00 11:00 +50000000-0000-0000-0000-000000000003 40000000-0000-0000-0000-000000000003 MONDAY 10:00 12:00 +50000000-0000-0000-0000-000000000004 40000000-0000-0000-0000-000000000004 WEDNESDAY 09:00 11:00 +50000000-0000-0000-0000-000000000005 40000000-0000-0000-0000-000000000005 THURSDAY 09:00 11:00 +50000000-0000-0000-0000-000000000006 40000000-0000-0000-0000-000000000006 FRIDAY 09:00 11:00 +50000000-0000-0000-0000-000000000007 40000000-0000-0000-0000-000000000007 MONDAY 11:00 13:00 diff --git a/src/main/resources/seed/demo/semesters.tsv b/src/main/resources/seed/demo/semesters.tsv new file mode 100644 index 0000000..83f7bb6 --- /dev/null +++ b/src/main/resources/seed/demo/semesters.tsv @@ -0,0 +1,2 @@ +id name startDate endDate registrationStartAt registrationEndAt maxCredits +00000000-0000-0000-0000-000000000001 current 2000-01-01 2099-12-31 2000-01-01T00:00:00Z 2099-12-31T23:59:59Z 18 diff --git a/src/main/resources/seed/demo/subjects.tsv b/src/main/resources/seed/demo/subjects.tsv new file mode 100644 index 0000000..5bf9013 --- /dev/null +++ b/src/main/resources/seed/demo/subjects.tsv @@ -0,0 +1,7 @@ +id name code description credit +20000000-0000-0000-0000-000000000001 자바 프로그래밍 CS201 자바 프로그래밍 기초 3 +20000000-0000-0000-0000-000000000002 자료구조 CS202 자료구조 및 알고리즘 3 +20000000-0000-0000-0000-000000000003 데이터베이스 CS203 데이터베이스 시스템 3 +20000000-0000-0000-0000-000000000004 컴퓨터 네트워크 CS204 네트워크 기초 3 +20000000-0000-0000-0000-000000000005 운영체제 CS301 운영체제 핵심 3 +20000000-0000-0000-0000-000000000006 대학원 세미나 CS401 대학원 전용 세미나 3 diff --git a/src/main/resources/seed/demo/users.tsv b/src/main/resources/seed/demo/users.tsv new file mode 100644 index 0000000..8a8a2f3 --- /dev/null +++ b/src/main/resources/seed/demo/users.tsv @@ -0,0 +1,4 @@ +id name grade role +30000000-0000-0000-0000-000000000001 학생1 1 STUDENT +30000000-0000-0000-0000-000000000002 학생2 2 STUDENT +30000000-0000-0000-0000-000000000003 대학원생 3 POSTGRADUATE diff --git a/src/test/java/com/study/course_registration/CourseRegistrationApplicationTests.java b/src/test/java/com/study/course_registration/CourseRegistrationApplicationTests.java index 491e913..a12cf4a 100644 --- a/src/test/java/com/study/course_registration/CourseRegistrationApplicationTests.java +++ b/src/test/java/com/study/course_registration/CourseRegistrationApplicationTests.java @@ -2,8 +2,10 @@ package com.study.course_registration; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; @SpringBootTest +@ActiveProfiles("test") class CourseRegistrationApplicationTests { @Test diff --git a/src/test/java/com/study/course_registration/architecture/ArchitectureTest.java b/src/test/java/com/study/course_registration/architecture/ArchitectureTest.java new file mode 100644 index 0000000..c57b1df --- /dev/null +++ b/src/test/java/com/study/course_registration/architecture/ArchitectureTest.java @@ -0,0 +1,73 @@ +package com.study.course_registration.architecture; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noFields; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; + +import java.nio.file.Path; + +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; + +class ArchitectureTest { + @Test + @DisplayName("수강신청 mutation → RegistrationLockManager 의존") + void registrationMutationUsesLockBoundary() { + JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main")); + + classes() + .that().haveSimpleName("CourseRegistrationService") + .should().dependOnClassesThat().haveSimpleName("RegistrationLockManager") + .check(classes); + + noClasses() + .that().haveSimpleName("CourseRegistrationService") + .should().dependOnClassesThat().haveSimpleName("LessonRepository") + .check(classes); + } + + @Test + @DisplayName("새 service → registration write repository 우회 금지") + void registrationWriteRepositoriesStayInsideApprovedServices() { + JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main")); + + noClasses() + .that().resideInAPackage("..service..") + .and().doNotHaveSimpleName("CourseRegistrationService") + .and().doNotHaveSimpleName("LessonQueryService") + .should().dependOnClassesThat().haveSimpleName("UserLessonRepository") + .check(classes); + + noClasses() + .that().resideInAPackage("..service..") + .and().doNotHaveSimpleName("CourseRegistrationService") + .should().dependOnClassesThat().haveSimpleName("RegistrationIdempotencyRepository") + .check(classes); + } + + @Test + @DisplayName("엔티티 연관관계 → ManyToOne만 허용") + void entityAssociationsUseManyToOneOnly() { + JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main")); + + noFields() + .that().areDeclaredInClassesThat().resideInAPackage("..entity..") + .should().beAnnotatedWith(OneToOne.class) + .check(classes); + noFields() + .that().areDeclaredInClassesThat().resideInAPackage("..entity..") + .should().beAnnotatedWith(OneToMany.class) + .check(classes); + noFields() + .that().areDeclaredInClassesThat().resideInAPackage("..entity..") + .should().beAnnotatedWith(ManyToMany.class) + .check(classes); + } +} diff --git a/src/test/java/com/study/course_registration/architecture/SourceStyleTest.java b/src/test/java/com/study/course_registration/architecture/SourceStyleTest.java new file mode 100644 index 0000000..7188ef7 --- /dev/null +++ b/src/test/java/com/study/course_registration/architecture/SourceStyleTest.java @@ -0,0 +1,65 @@ +package com.study.course_registration.architecture; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class SourceStyleTest { + private static final Pattern LOCAL_VAR = Pattern.compile("\\bvar\\s+[A-Za-z_$][A-Za-z0-9_$]*"); + private static final Pattern FQCN = Pattern.compile( + "(?:com\\.study\\.course_registration(?:\\.[a-z_][a-z0-9_]*)+|java\\.(?:util|time)(?:\\.[a-z_][a-z0-9_]*)*)\\.[A-Z][A-Za-z0-9_$]*"); + + @Test + @DisplayName("소스 스타일 → var·본문 FQCN·wildcard import 금지") + void sourceStyle() throws IOException { + List violations = new ArrayList<>(); + + for (Path sourceRoot : List.of(Path.of("src/main/java"), Path.of("src/test/java"))) { + try (Stream files = Files.walk(sourceRoot)) { + files.filter(path -> path.toString().endsWith(".java")) + .forEach(path -> inspect(path, violations)); + } + } + + assertThat(violations) + .as("명시적 타입/import 규칙 위반") + .isEmpty(); + } + + private static void inspect(Path path, List violations) { + try { + List lines = Files.readAllLines(path); + for (int index = 0; index < lines.size(); index++) { + String line = lines.get(index); + String trimmed = line.trim(); + + if (trimmed.startsWith("import ") && trimmed.contains(".*;")) { + violations.add(location(path, index, "wildcard import")); + } + if (LOCAL_VAR.matcher(line).find()) { + violations.add(location(path, index, "var")); + } + if (!trimmed.startsWith("package ") + && !trimmed.startsWith("import ") + && FQCN.matcher(line).find()) { + violations.add(location(path, index, "본문 FQCN")); + } + } + } catch (IOException exception) { + throw new IllegalStateException("소스 스타일 검사 실패: " + path, exception); + } + } + + private static String location(Path path, int zeroBasedLine, String reason) { + return path + ":" + (zeroBasedLine + 1) + " " + reason; + } +} diff --git a/src/test/java/com/study/course_registration/config/EnumConverterTest.java b/src/test/java/com/study/course_registration/config/EnumConverterTest.java new file mode 100644 index 0000000..7c1c2e5 --- /dev/null +++ b/src/test/java/com/study/course_registration/config/EnumConverterTest.java @@ -0,0 +1,44 @@ +package com.study.course_registration.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.DayOfWeek; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.study.course_registration.enums.UserRole; + +class EnumConverterTest { + @Test + @DisplayName("DayOfWeek → ISO 요일 번호") + void dayOfWeek() { + DayOfWeekConverter converter = new DayOfWeekConverter(); + + assertThat(converter.convertToDatabaseColumn(DayOfWeek.MONDAY)).isEqualTo(1); + assertThat(converter.convertToEntityAttribute(7)).isEqualTo(DayOfWeek.SUNDAY); + } + + @Test + @DisplayName("UserRole → 이름 문자열") + void userRole() { + UserRoleConverter converter = new UserRoleConverter(); + + assertThat(converter.convertToDatabaseColumn(UserRole.POSTGRADUATE)).isEqualTo("POSTGRADUATE"); + assertThat(converter.convertToEntityAttribute("STUDENT")).isEqualTo(UserRole.STUDENT); + } + + + @Test + @DisplayName("enum null → DB null") + void nullValues() { + DayOfWeekConverter day = new DayOfWeekConverter(); + UserRoleConverter role = new UserRoleConverter(); + + assertThat(day.convertToDatabaseColumn(null)).isNull(); + assertThat(day.convertToEntityAttribute(null)).isNull(); + assertThat(role.convertToDatabaseColumn(null)).isNull(); + assertThat(role.convertToEntityAttribute(null)).isNull(); + } + +} diff --git a/src/test/java/com/study/course_registration/config/RuntimeProfileConfigTest.java b/src/test/java/com/study/course_registration/config/RuntimeProfileConfigTest.java new file mode 100644 index 0000000..7951692 --- /dev/null +++ b/src/test/java/com/study/course_registration/config/RuntimeProfileConfigTest.java @@ -0,0 +1,58 @@ +package com.study.course_registration.config; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class RuntimeProfileConfigTest { + @Test + @DisplayName("환경 profile 없음 → 기동 거부") + void missingProfile() { + assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[0])) + .isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("오타 profile만 활성화 → 기동 거부") + void typoProfile() { + assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"loacl"})) + .isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("dev profile 하나 → 기동 허용") + void devProfile() { + assertThatCode(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"dev"})) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("dev + feature profile → 기동 허용") + void featureProfile() { + assertThatCode(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"dev", "metrics"})) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("local + prod → 기동 거부") + void multipleEnvironmentProfiles() { + assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"local", "prod"})) + .isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("test profile 하나 → 테스트 기동 허용") + void testProfile() { + assertThatCode(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"test"})) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("test + prod → 기동 거부") + void testAndEnvironmentProfile() { + assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"test", "prod"})) + .isInstanceOf(IllegalStateException.class); + } +} diff --git a/src/test/java/com/study/course_registration/controller/CourseRegistrationApiTest.java b/src/test/java/com/study/course_registration/controller/CourseRegistrationApiTest.java index d92b2c5..715793b 100644 --- a/src/test/java/com/study/course_registration/controller/CourseRegistrationApiTest.java +++ b/src/test/java/com/study/course_registration/controller/CourseRegistrationApiTest.java @@ -1,204 +1,263 @@ package com.study.course_registration.controller; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; import java.time.DayOfWeek; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; +import java.util.Map; 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.webmvc.test.autoconfigure.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import com.study.course_registration.entity.Lesson; -import com.study.course_registration.entity.LessonSchedule; -import com.study.course_registration.entity.Professor; -import com.study.course_registration.entity.Semester; import com.study.course_registration.entity.Subject; -import com.study.course_registration.entity.User; import com.study.course_registration.enums.RegistrationErrorCode; -import com.study.course_registration.enums.UserRole; -import com.study.course_registration.repository.LessonRepository; -import com.study.course_registration.repository.LessonScheduleRepository; -import com.study.course_registration.repository.ProfessorRepository; -import com.study.course_registration.repository.SemesterRepository; -import com.study.course_registration.repository.SubjectRepository; -import com.study.course_registration.repository.UserLessonRepository; -import com.study.course_registration.repository.UserRepository; +import com.study.course_registration.support.CourseIntegrationTest; import com.study.course_registration.support.Rejections; import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; import com.study.course_registration.support.http.ApiError; import com.study.course_registration.support.http.JsonApi; import com.study.course_registration.support.http.JsonBody; -/** - * HTTP 계층. 서비스가 올바른 예외를 던지는 것과, 그게 올바른 상태코드·바디로 나가는 것은 다른 문제다. - * 여기서만 확인할 수 있는 것이 후자다. - * - *

표현법은 단위·통합 계층과 같다. {@code Scenario.given(...).when(...).then(...)}. - * HTTP 응답을 {@link ApiError}로 번역하는 일은 {@link JsonApi}가 한다. - */ -@SpringBootTest +@CourseIntegrationTest @AutoConfigureMockMvc -@ActiveProfiles("test") -@DisplayName("수강신청 API — 에러 코드가 선언된 상태코드로 나가는가") +@DisplayName("수강신청 API") class CourseRegistrationApiTest { - /** - * HTTP 계층의 거부 판정. 코드를 꺼내면서 그 코드가 선언한 상태코드로 나갔는지도 함께 본다. - * 매핑표는 이미 {@link RegistrationErrorCode}에 있으므로, 테스트는 코드만 적으면 상태코드까지 검증된다. - */ private static final Rejections API = Rejections.of(ApiError.class, CourseRegistrationApiTest::errorCodeOf); @Autowired MockMvc mockMvc; - @Autowired UserLessonRepository userLessonRepository; - @Autowired LessonScheduleRepository lessonScheduleRepository; - @Autowired LessonRepository lessonRepository; - @Autowired SubjectRepository subjectRepository; - @Autowired ProfessorRepository professorRepository; - @Autowired SemesterRepository semesterRepository; - @Autowired UserRepository userRepository; + @Autowired DatabaseFixture fixture; private JsonApi api; - private User student; - private Lesson lesson; - private Subject subject; + private RegistrationDataset data; @BeforeEach void setUp() { - userLessonRepository.deleteAll(); - lessonScheduleRepository.deleteAll(); - lessonRepository.deleteAll(); - subjectRepository.deleteAll(); - professorRepository.deleteAll(); - semesterRepository.deleteAll(); - userRepository.deleteAll(); - - Instant now = Instant.now(); - Semester semester = semesterRepository.save(new Semester("semester", "2026-1", - LocalDate.now().minusDays(1), LocalDate.now().plusDays(100), - now.minusSeconds(3600), now.plusSeconds(3600), 18)); - Professor professor = professorRepository.save(new Professor("professor", "교수")); - subject = subjectRepository.save(new Subject("subject-a", "과목A", "A101", "A", 3)); - student = userRepository.save(new User("user", "학생", 2L, UserRole.STUDENT)); - lesson = lessonRepository.save(new Lesson("lesson-a", "강의A", subject, professor, semester, 30, null, null)); - lessonScheduleRepository.save(new LessonSchedule("schedule-a", lesson, - DayOfWeek.MONDAY, LocalTime.of(9, 0), LocalTime.of(11, 0))); - + data = fixture.registrationDataset(); api = new JsonApi(mockMvc); } @Test - @DisplayName("신청에 성공하면 201과 신청 정보를 돌려준다") - void registerReturnsCreated() { - JsonBody body = Scenario.given(api) - .when(a -> a.post(path(student.getId()), json(lesson.getId()))) - .thenAccepted(); - - assertThat(body.status()) - .as("신청 성공은 201이다") - .isEqualTo(201); - - // 응답 스키마 전체를 고정한다. 값 몇 개만 보면 필드 이름이 바뀌어도 통과한다. - assertThat(body.fieldNames()) - .as("응답 필드 이름은 클라이언트와의 계약이다") - .containsExactlyInAnyOrder( - "registrationId", "userId", "lessonId", "lessonName", - "subjectCode", "credit", "registeredAt", "totalCredits"); - - assertThat(body.at("$.userId")).isEqualTo(student.getId()); - assertThat(body.at("$.lessonId")).isEqualTo(lesson.getId()); - assertThat(body.at("$.lessonName")).isEqualTo(lesson.getName()); - assertThat(body.at("$.subjectCode")).isEqualTo(subject.getCode()); - assertThat(body.at("$.credit")).isEqualTo(3); - assertThat(body.at("$.totalCredits")).isEqualTo(3); - assertThat(body.at("$.registrationId")).isNotBlank(); - assertThat(body.at("$.registeredAt")).isNotBlank(); + @DisplayName("POST 신청 성공 → 201") + void register201() { + Scenario.given(data) + .when(current -> api.post( + path(current.student().getId()), + json(current.lesson().getId()))) + .then(body -> { + assertThat(body.status()).isEqualTo(201); + assertThat(body.fieldNames()).containsExactlyInAnyOrder( + "registrationId", + "userId", + "lessonId", + "lessonName", + "subjectCode", + "credit", + "registeredAt", + "totalCredits"); + assertThat(body.at("$.userId")).isEqualTo(data.student().getId()); + assertThat(body.at("$.lessonId")).isEqualTo(data.lesson().getId()); + assertThat(body.at("$.lessonName")).isEqualTo(data.lesson().getName()); + assertThat(body.at("$.subjectCode")).isEqualTo(data.subject().getCode()); + assertThat(body.at("$.credit")).isEqualTo(3); + assertThat(body.at("$.totalCredits")).isEqualTo(3); + assertThat(body.at("$.registrationId")).isNotBlank(); + assertThat(body.at("$.registeredAt")).isEqualTo("2026-09-21T03:00:00Z"); + }); } @Test - @DisplayName("취소에 성공하면 204와 빈 본문을 돌려준다") - void cancelReturnsNoContent() { - JsonBody created = api.post(path(student.getId()), json(lesson.getId())); - String registrationId = created.at("$.registrationId"); + @DisplayName("GET 신청 목록 → 200 + 응답 계약") + void registrations200() { + api.post(path(data.student().getId()), json(data.lesson().getId())); - JsonBody body = Scenario.given(api) - .when(a -> a.delete(path(student.getId()) + "/" + registrationId)) - .thenAccepted(); - - assertThat(body.status()) - .as("취소 성공은 204다") - .isEqualTo(204); - assertThat(body.raw()) - .as("204에는 본문이 없다") - .isEmpty(); + Scenario.given(data) + .when(current -> api.get( + path(current.student().getId()) + + "?semesterId=" + + current.semester().getId())) + .then(body -> { + assertThat(body.status()).isEqualTo(200); + assertThat(body.fieldNames()).containsExactlyInAnyOrder( + "userId", + "semesterId", + "semesterName", + "totalCredits", + "maxCredits", + "registrations"); + assertThat(body.at("$.userId")).isEqualTo(data.student().getId()); + assertThat(body.at("$.semesterId")).isEqualTo(data.semester().getId()); + assertThat(body.at("$.totalCredits")).isEqualTo(3); + Map item = body.at("$.registrations[0]"); + assertThat(item.keySet()).containsExactlyInAnyOrder( + "registrationId", + "lessonId", + "lessonName", + "subjectCode", + "subjectName", + "credit", + "professorName", + "schedules", + "registeredAt"); + }); } @Test - @DisplayName("없는 사용자로 신청하면 USER_NOT_FOUND — 404로 나간다") - void unknownUserIsNotFound() { - Scenario.given(api) - .when(a -> a.post(path("no-such-user"), json(lesson.getId()))) + @DisplayName("같은 Idempotency-Key 재시도 → 동일 201 응답") + void idempotentPost() { + JsonBody first = api.post( + path(data.student().getId()), + json(data.lesson().getId()), + "request-1"); + + Scenario.given(first) + .when(previous -> api.post( + path(data.student().getId()), + json(data.lesson().getId()), + "request-1")) + .then(second -> { + assertThat(first.status()).isEqualTo(201); + assertThat(second.status()).isEqualTo(201); + assertThat(second.at("$.registrationId")) + .isEqualTo(first.at("$.registrationId")); + assertThat(second.at("$.registeredAt")) + .isEqualTo(first.at("$.registeredAt")); + }); + } + + @Test + @DisplayName("같은 Idempotency-Key 다른 강의 → 409") + void reusedIdempotencyKey409() { + api.post(path(data.student().getId()), json(data.lesson().getId()), "request-2"); + Subject subject = fixture.subject(DomainFixtures.subject("OTHER")); + Lesson other = fixture.lesson(DomainFixtures.lesson( + subject, + data.professor(), + data.semester())); + fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.TUESDAY, 13, 15)); + + Scenario.given(other) + .when(lesson -> api.post( + path(data.student().getId()), + json(lesson.getId()), + "request-2")) + .thenRejectedWith(API, RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED); + } + + @Test + @DisplayName("DELETE 취소 성공 → 204") + void cancel204() { + String id = api.post( + path(data.student().getId()), + json(data.lesson().getId())) + .at("$.registrationId"); + + Scenario.given(id) + .when(registrationId -> api.delete( + path(data.student().getId()) + "/" + registrationId)) + .then(body -> { + assertThat(body.status()).isEqualTo(204); + assertThat(body.raw()).isEmpty(); + }); + } + + @Test + @DisplayName("DELETE 재호출 → 204") + void repeatedCancel204() { + String id = api.post( + path(data.student().getId()), + json(data.lesson().getId())) + .at("$.registrationId"); + api.delete(path(data.student().getId()) + "/" + id); + + Scenario.given(id) + .when(registrationId -> api.delete( + path(data.student().getId()) + "/" + registrationId)) + .then(body -> assertThat(body.status()).isEqualTo(204)); + } + + @Test + @DisplayName("없는 사용자 → 404 USER_NOT_FOUND") + void user404() { + Scenario.given("missing") + .when(userId -> api.post(path(userId), json(data.lesson().getId()))) .thenRejectedWith(API, RegistrationErrorCode.USER_NOT_FOUND); } @Test - @DisplayName("없는 강의로 신청하면 LESSON_NOT_FOUND — 404로 나간다") - void unknownLessonIsNotFound() { - Scenario.given(api) - .when(a -> a.post(path(student.getId()), json("no-such-lesson"))) + @DisplayName("없는 강의 → 404 LESSON_NOT_FOUND") + void lesson404() { + Scenario.given("missing") + .when(lessonId -> api.post(path(data.student().getId()), json(lessonId))) .thenRejectedWith(API, RegistrationErrorCode.LESSON_NOT_FOUND); } @Test - @DisplayName("같은 강의를 두 번 신청하면 ALREADY_REGISTERED — 409로 나간다") - void duplicateRegistrationIsConflict() { - api.post(path(student.getId()), json(lesson.getId())); + @DisplayName("중복 신청 → 409 ALREADY_REGISTERED") + void duplicate409() { + api.post(path(data.student().getId()), json(data.lesson().getId())); - Scenario.given(api) - .when(a -> a.post(path(student.getId()), json(lesson.getId()))) + Scenario.given(data) + .when(current -> api.post( + path(current.student().getId()), + json(current.lesson().getId()))) .thenRejectedWith(API, RegistrationErrorCode.ALREADY_REGISTERED); } @Test - @DisplayName("lessonId가 비면 VALIDATION_ERROR — 400으로 나간다") - void blankLessonIdIsBadRequest() { + @DisplayName("빈 lessonId → 400 VALIDATION_ERROR") + void blankLesson400() { Scenario.given(api) - .when(a -> a.post(path(student.getId()), json(""))) + .when(client -> client.post(path(data.student().getId()), json(""))) .thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR); } @Test - @DisplayName("본문이 JSON이 아니면 VALIDATION_ERROR — 400으로 나간다") - void malformedBodyIsBadRequest() { + @DisplayName("잘못된 JSON → 400 VALIDATION_ERROR") + void malformed400() { Scenario.given(api) - .when(a -> a.post(path(student.getId()), "{not json")) + .when(client -> client.post(path(data.student().getId()), "{not json")) .thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR); } @Test - @DisplayName("없는 신청 건을 취소하면 REGISTRATION_NOT_FOUND — 404로 나간다 (C1)") - void cancelingUnknownRegistrationIsNotFound() { + @DisplayName("없는 신청 취소 → 404 REGISTRATION_NOT_FOUND") + void registration404() { Scenario.given(api) - .when(a -> a.delete(path(student.getId()) + "/no-such-registration")) + .when(client -> client.delete( + path(data.student().getId()) + "/missing")) .thenRejectedWith(API, RegistrationErrorCode.REGISTRATION_NOT_FOUND); } @Test - @DisplayName("에러 응답 본문은 code·message·timestamp 세 필드를 담는다") - void errorBodyShape() { - ApiError error = org.assertj.core.api.Assertions.catchThrowableOfType(ApiError.class, - () -> api.post(path("no-such-user"), json(lesson.getId()))); + @DisplayName("시간표 없는 강의 → 500 공통 에러") + void missingSchedule500() { + Subject subject = fixture.subject(DomainFixtures.subject("BROKEN")); + Lesson broken = fixture.lesson(DomainFixtures.lesson( + subject, + data.professor(), + data.semester())); - assertThat(error.code()).isEqualTo("USER_NOT_FOUND"); - assertThat(error.detail()).isNotBlank(); - assertThat(error.status()).isEqualTo(404); + ApiError error = catchThrowableOfType( + ApiError.class, + () -> api.post( + path(data.student().getId()), + json(broken.getId()))); + + assertThat(error.status()).isEqualTo(500); + assertThat(error.code()).isEqualTo("INTERNAL_SERVER_ERROR"); + assertThat(error.fieldNames()).containsExactlyInAnyOrder( + "code", + "message", + "timestamp"); } private static String path(String userId) { @@ -206,15 +265,12 @@ class CourseRegistrationApiTest { } private static String json(String lessonId) { - return "{\"lessonId\": \"" + lessonId + "\"}"; + return "{\"lessonId\":\"" + lessonId + "\"}"; } - /** 코드를 꺼내면서 상태코드 매핑까지 확인한다. HTTP 계층에서만 볼 수 있는 값을 놓치지 않기 위해서다. */ private static RegistrationErrorCode errorCodeOf(ApiError error) { RegistrationErrorCode code = RegistrationErrorCode.valueOf(error.code()); - assertThat(error.status()) - .as("%s 는 %s 로 나가야 한다", code, code.getStatus()) - .isEqualTo(code.getStatus().value()); + assertThat(error.status()).isEqualTo(code.getStatus().value()); return code; } } diff --git a/src/test/java/com/study/course_registration/controller/LessonApiTest.java b/src/test/java/com/study/course_registration/controller/LessonApiTest.java new file mode 100644 index 0000000..4e09b0b --- /dev/null +++ b/src/test/java/com/study/course_registration/controller/LessonApiTest.java @@ -0,0 +1,108 @@ +package com.study.course_registration.controller; + +import static org.assertj.core.api.Assertions.assertThat; + +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.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.test.web.servlet.MockMvc; + +import com.study.course_registration.enums.RegistrationErrorCode; +import com.study.course_registration.support.CourseIntegrationTest; +import com.study.course_registration.support.Rejections; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.http.ApiError; +import com.study.course_registration.support.http.JsonApi; +import com.study.course_registration.support.http.JsonBody; + +@CourseIntegrationTest +@AutoConfigureMockMvc +@DisplayName("강의 API") +class LessonApiTest { + private static final Rejections API = + Rejections.of(ApiError.class, LessonApiTest::errorCodeOf); + + @Autowired MockMvc mockMvc; + @Autowired DatabaseFixture fixture; + + private JsonApi api; + private RegistrationDataset data; + + @BeforeEach + void setUp() { + data = fixture.registrationDataset(); + api = new JsonApi(mockMvc); + } + + @Test + @DisplayName("GET 목록 → 200") + void list200() { + Scenario.given(api) + .when(client -> client.get( + "/api/v1/lessons?semesterId=" + data.semester().getId())) + .then(body -> { + assertThat(body.status()).isEqualTo(200); + assertThat(body.fieldNames()).containsExactlyInAnyOrder( + "page", + "size", + "totalElements", + "lessons"); + assertThat(body.at("$.page")).isZero(); + assertThat(body.at("$.size")).isEqualTo(20); + assertThat(body.at("$.lessons.length()")).isEqualTo(1); + }); + } + + @Test + @DisplayName("GET 상세 → 200") + void detail200() { + Scenario.given(data.lesson().getId()) + .when(lessonId -> api.get("/api/v1/lessons/" + lessonId)) + .then(body -> { + assertThat(body.status()).isEqualTo(200); + assertThat(body.fieldNames()).contains( + "lessonId", + "lessonName", + "subjectCode", + "subjectName", + "subjectDescription", + "credit", + "professorName", + "semesterName", + "capacity", + "enrolledCount", + "minGrade", + "allowedRole", + "registrationStartAt", + "registrationEndAt", + "schedules"); + assertThat(body.at("$.lessonId")).isEqualTo(data.lesson().getId()); + }); + } + + @Test + @DisplayName("page 상한 초과 → 400 VALIDATION_ERROR") + void page400() { + Scenario.given(api) + .when(client -> client.get("/api/v1/lessons?page=1000001")) + .thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR); + } + + @Test + @DisplayName("없는 강의 → 404 LESSON_NOT_FOUND") + void lesson404() { + Scenario.given(api) + .when(client -> client.get("/api/v1/lessons/missing")) + .thenRejectedWith(API, RegistrationErrorCode.LESSON_NOT_FOUND); + } + + private static RegistrationErrorCode errorCodeOf(ApiError error) { + RegistrationErrorCode code = RegistrationErrorCode.valueOf(error.code()); + assertThat(error.status()).isEqualTo(code.getStatus().value()); + return code; + } +} diff --git a/src/test/java/com/study/course_registration/entity/EntityInvariantTest.java b/src/test/java/com/study/course_registration/entity/EntityInvariantTest.java new file mode 100644 index 0000000..5c0efa0 --- /dev/null +++ b/src/test/java/com/study/course_registration/entity/EntityInvariantTest.java @@ -0,0 +1,218 @@ +package com.study.course_registration.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.DayOfWeek; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.study.course_registration.enums.UserRole; +import com.study.course_registration.support.fixture.DomainFixtures; +import com.study.course_registration.support.fixture.TestData; + +class EntityInvariantTest { + @Test + @DisplayName("과목 학점 0 → 생성 거부") + void subjectCredit() { + assertThatThrownBy(() -> new Subject("과목", "CS0", "", 0)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("강의 정원 0 → 생성 거부") + void lessonCapacity() { + assertThatThrownBy(() -> new Lesson( + "강의", + DomainFixtures.subject("CS1"), + DomainFixtures.professor(), + DomainFixtures.openSemester(), + 0, + null, + null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("시간표 시작 >= 종료 → 생성 거부") + void scheduleRange() { + Lesson lesson = DomainFixtures.lesson( + DomainFixtures.subject("CS2"), + DomainFixtures.professor(), + DomainFixtures.openSemester()); + + assertThatThrownBy(() -> new LessonSchedule( + lesson, + DayOfWeek.MONDAY, + LocalTime.of(11, 0), + LocalTime.of(11, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("학기 신청 시작 >= 종료 → 생성 거부") + void semesterWindow() { + Instant now = TestData.NOW; + + assertThatThrownBy(() -> new Semester( + "학기", + TestData.TODAY, + TestData.TODAY.plusDays(1), + now, + now, + 18)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("사용자 학년 0 → 생성 거부") + void userGrade() { + assertThatThrownBy(() -> new User("학생", 0L, UserRole.STUDENT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("과목 이름 공백 → 생성 거부") + void subjectName() { + assertThatThrownBy(() -> new Subject(" ", "CS", "", 3)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("과목 코드 공백 → 생성 거부") + void subjectCode() { + assertThatThrownBy(() -> new Subject("과목", " ", "", 3)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("강의 이름 공백 → 생성 거부") + void lessonName() { + assertThatThrownBy(() -> new Lesson( + " ", + DomainFixtures.subject("CS"), + DomainFixtures.professor(), + DomainFixtures.openSemester(), + 30, + null, + null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("강의 최소 학년 0 → 생성 거부") + void minGrade() { + assertThatThrownBy(() -> new Lesson( + "강의", + DomainFixtures.subject("CS"), + DomainFixtures.professor(), + DomainFixtures.openSemester(), + 30, + 0L, + null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("학기 종료 < 시작 → 생성 거부") + void semesterDates() { + LocalDate today = TestData.TODAY; + Instant now = TestData.NOW; + + assertThatThrownBy(() -> new Semester( + "학기", + today, + today.minusDays(1), + now.minusSeconds(1), + now, + 18)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("학기 최대 학점 0 → 생성 거부") + void semesterCredits() { + LocalDate today = TestData.TODAY; + Instant now = TestData.NOW; + + assertThatThrownBy(() -> new Semester( + "학기", + today, + today.plusDays(1), + now.minusSeconds(1), + now, + 0)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("사용자 이름 공백 → 생성 거부") + void userName() { + assertThatThrownBy(() -> new User(" ", 1L, UserRole.STUDENT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("같은 신청 두 번 취소 → 도메인 거부") + void doubleCancel() { + UserLesson registration = DomainFixtures.registration( + DomainFixtures.student(2), + DomainFixtures.lesson( + DomainFixtures.subject("CS"), + DomainFixtures.professor(), + DomainFixtures.openSemester())); + registration.cancel(TestData.NOW); + + assertThatThrownBy(() -> registration.cancel(TestData.NOW)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("Idempotency-Key 공백 → 생성 거부") + void idempotencyBlank() { + User user = DomainFixtures.student(2); + Lesson lesson = DomainFixtures.lesson( + DomainFixtures.subject("CS"), + DomainFixtures.professor(), + DomainFixtures.openSemester()); + UserLesson registration = DomainFixtures.registration(user, lesson); + + assertThatThrownBy(() -> new RegistrationIdempotency(user, lesson, registration, " ", 3, TestData.NOW.plusSeconds(86400))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("과목 설명 null → 빈 문자열") + void nullSubjectDescription() { + Subject subject = new Subject("과목", "CS-N", null, 3); + + assertThat(subject.getDescription()).isEmpty(); + } + + @Test + @DisplayName("교수 이름 공백 → 생성 거부") + void professorName() { + assertThatThrownBy(() -> new Professor(" ")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("학기 이름 공백 → 생성 거부") + void semesterName() { + LocalDate today = TestData.TODAY; + Instant now = TestData.NOW; + + assertThatThrownBy(() -> new Semester( + " ", + today, + today.plusDays(1), + now.minusSeconds(1), + now, + 18)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/src/test/java/com/study/course_registration/exception/GlobalExceptionHandlerTest.java b/src/test/java/com/study/course_registration/exception/GlobalExceptionHandlerTest.java new file mode 100644 index 0000000..642326d --- /dev/null +++ b/src/test/java/com/study/course_registration/exception/GlobalExceptionHandlerTest.java @@ -0,0 +1,41 @@ +package com.study.course_registration.exception; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Clock; +import java.time.ZoneOffset; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; + +import com.study.course_registration.support.fixture.TestData; + +import jakarta.persistence.LockTimeoutException; + +class GlobalExceptionHandlerTest { + private final GlobalExceptionHandler handler = + new GlobalExceptionHandler(Clock.fixed(TestData.NOW, ZoneOffset.UTC)); + + @Test + @DisplayName("락 타임아웃 → 503 + Retry-After") + void lockTimeout() { + ResponseEntity response = handler.handleLockTimeout(new LockTimeoutException()); + + assertThat(response.getStatusCode().value()).isEqualTo(503); + assertThat(Integer.parseInt(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER))) + .isBetween(1, 3); + assertThat(response.getBody().code()).isEqualTo("LOCK_TIMEOUT"); + } + + @Test + @DisplayName("예상 못한 예외 → 500 공통 에러") + void fallback() { + ResponseEntity response = handler.handleUnexpected(new RuntimeException("boom")); + + assertThat(response.getStatusCode().value()).isEqualTo(500); + assertThat(response.getBody().code()).isEqualTo("INTERNAL_SERVER_ERROR"); + assertThat(response.getBody().timestamp()).isEqualTo(TestData.NOW); + } +} diff --git a/src/test/java/com/study/course_registration/repository/LessonRepositoryTest.java b/src/test/java/com/study/course_registration/repository/LessonRepositoryTest.java new file mode 100644 index 0000000..829992d --- /dev/null +++ b/src/test/java/com/study/course_registration/repository/LessonRepositoryTest.java @@ -0,0 +1,93 @@ +package com.study.course_registration.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.DayOfWeek; + +import org.hibernate.Hibernate; +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.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.transaction.PlatformTransactionManager; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.support.PessimisticLockProbe; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; + +class LessonRepositoryTest extends PostgresIntegrationTest { + @Autowired DatabaseFixture fixture; + @Autowired LessonRepository repository; + @Autowired PlatformTransactionManager transactionManager; + + private RegistrationDataset data; + + @BeforeEach + void setUp() { + data = fixture.registrationDataset(); + } + + @Test + @DisplayName("findByIdForUpdate → PostgreSQL lesson row lock") + void pessimisticLock() throws Exception { + PessimisticLockProbe.assertSecondTransactionBlocks( + transactionManager, + () -> repository.findByIdForUpdate(data.lesson().getId()).orElseThrow(), + () -> repository.findByIdForUpdate(data.lesson().getId()).orElseThrow()); + } + + @Test + @DisplayName("상세 조회 → subject·professor·semester graph 초기화") + void detailGraph() { + Scenario.given(data.lesson().getId()) + .when(id -> repository.findDetailedById(id).orElseThrow()) + .then(lesson -> { + assertThat(Hibernate.isInitialized(lesson.getSubject())).isTrue(); + assertThat(Hibernate.isInitialized(lesson.getProfessor())).isTrue(); + assertThat(Hibernate.isInitialized(lesson.getSemester())).isTrue(); + assertThat(lesson.getSubject().getCode()).isEqualTo(data.subject().getCode()); + assertThat(lesson.getProfessor().getId()).isEqualTo(data.professor().getId()); + assertThat(lesson.getSemester().getId()).isEqualTo(data.semester().getId()); + }); + } + + @Test + @DisplayName("학기 조회 → 이름·ID 순 정렬") + void semesterPagingAndSort() { + Subject subject = fixture.subject(DomainFixtures.subject("CS200")); + Lesson lesson = fixture.lesson(DomainFixtures.lesson( + null, "AAA 강의", subject, data.professor(), data.semester(), 30, null, null)); + fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.TUESDAY, 9, 11)); + + Scenario.given(data) + .when(current -> repository.findBySemester_Id( + current.semester().getId(), + PageRequest.of(0, 20, Sort.by("name").ascending().and(Sort.by("id").ascending())))) + .then(page -> assertThat(page.getContent()) + .extracting(Lesson::getName) + .containsExactly("AAA 강의", "CS101 강의")); + } + + @Test + @DisplayName("과목 필터 → 해당 과목 강의만 반환") + void subjectFilter() { + Subject other = fixture.subject(DomainFixtures.subject("CS300")); + Lesson lesson = fixture.lesson(DomainFixtures.lesson(other, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.FRIDAY, 9, 11)); + + Scenario.given(other.getId()) + .when(subjectId -> repository.findBySemester_IdAndSubject_Id( + data.semester().getId(), subjectId, PageRequest.of(0, 20))) + .then(page -> assertThat(page.getContent()) + .extracting(Lesson::getId) + .containsExactly(lesson.getId())); + } +} diff --git a/src/test/java/com/study/course_registration/repository/LessonScheduleRepositoryTest.java b/src/test/java/com/study/course_registration/repository/LessonScheduleRepositoryTest.java new file mode 100644 index 0000000..71043b0 --- /dev/null +++ b/src/test/java/com/study/course_registration/repository/LessonScheduleRepositoryTest.java @@ -0,0 +1,56 @@ +package com.study.course_registration.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.DayOfWeek; +import java.util.List; + +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 com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.LessonSchedule; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; + +class LessonScheduleRepositoryTest extends PostgresIntegrationTest { + @Autowired DatabaseFixture fixture; + @Autowired LessonScheduleRepository repository; + + private RegistrationDataset data; + + @BeforeEach + void setUp() { + data = fixture.registrationDataset(); + } + + @Test + @DisplayName("lesson IDs bulk 조회 → 요일·시작시각 순 정렬") + void bulkAndOrdering() { + Subject subject = fixture.subject(DomainFixtures.subject("CS200")); + Lesson other = fixture.lesson(DomainFixtures.lesson(subject, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.WEDNESDAY, 13, 15)); + fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.TUESDAY, 15, 17)); + fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.TUESDAY, 9, 11)); + + List lessonIds = List.of(data.lesson().getId(), other.getId()); + + Scenario.given(lessonIds) + .when(repository::findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc) + .then(schedules -> assertThat(schedules) + .extracting( + schedule -> schedule.getDayOfWeek().name(), + schedule -> schedule.getStartTime().toString()) + .containsExactly( + org.assertj.core.groups.Tuple.tuple("MONDAY", "09:00"), + org.assertj.core.groups.Tuple.tuple("TUESDAY", "09:00"), + org.assertj.core.groups.Tuple.tuple("TUESDAY", "15:00"), + org.assertj.core.groups.Tuple.tuple("WEDNESDAY", "13:00"))); + } +} diff --git a/src/test/java/com/study/course_registration/repository/RegistrationIdempotencyRepositoryTest.java b/src/test/java/com/study/course_registration/repository/RegistrationIdempotencyRepositoryTest.java new file mode 100644 index 0000000..41a4758 --- /dev/null +++ b/src/test/java/com/study/course_registration/repository/RegistrationIdempotencyRepositoryTest.java @@ -0,0 +1,172 @@ +package com.study.course_registration.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.DayOfWeek; +import java.time.Instant; + +import org.hibernate.Hibernate; +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.dao.DataIntegrityViolationException; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.RegistrationIdempotency; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.entity.UserLesson; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; +import com.study.course_registration.support.fixture.TestData; + +class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest { + @Autowired DatabaseFixture fixture; + @Autowired RegistrationIdempotencyRepository repository; + + private RegistrationDataset data; + private UserLesson registration; + + @BeforeEach + void setUp() { + data = fixture.registrationDataset(); + registration = fixture.registration( + DomainFixtures.registration(data.student(), data.lesson())); + } + + @Test + @DisplayName("userId + key + 유효기간 조회 → 연관 graph와 lifecycle 로드") + void lookupGraph() { + Instant expiresAt = TestData.NOW.plusSeconds(86400); + repository.saveAndFlush(idempotency("request-1", registration, data.lesson(), expiresAt)); + + Scenario.given("request-1") + .when(key -> repository + .findByUser_IdAndIdempotencyKeyAndExpiresAtAfter( + data.student().getId(), + key, + TestData.NOW) + .orElseThrow()) + .then(stored -> { + assertThat(Hibernate.isInitialized(stored.getUser())).isTrue(); + assertThat(Hibernate.isInitialized(stored.getLesson())).isTrue(); + assertThat(Hibernate.isInitialized(stored.getLesson().getSubject())).isTrue(); + assertThat(Hibernate.isInitialized(stored.getRegistration())).isTrue(); + assertThat(stored.getCreatedAt()).isNotNull(); + assertThat(stored.getExpiresAt()).isEqualTo(expiresAt); + }); + } + + @Test + @DisplayName("만료 key 삭제 → 같은 user + key 재사용 가능") + void expiredKeyCanBeRemoved() { + Instant expiredAt = TestData.NOW.minusSeconds(1); + repository.saveAndFlush(idempotency("request-expired", registration, data.lesson(), expiredAt)); + + Scenario.given("request-expired") + .when(key -> repository.deleteExpiredKey( + data.student().getId(), + key, + TestData.NOW)) + .then(deleted -> { + assertThat(deleted).isEqualTo(1); + assertThat(repository.findAll()).isEmpty(); + }); + } + + @Test + @DisplayName("만료 전체 정리 → expiresAt 지난 행만 삭제") + void deleteExpired() { + repository.saveAndFlush(idempotency( + "expired", + registration, + data.lesson(), + TestData.NOW.minusSeconds(1))); + + Subject subject = fixture.subject(DomainFixtures.subject("FRESH")); + Lesson freshLesson = fixture.lesson( + DomainFixtures.lesson(subject, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(freshLesson, DayOfWeek.TUESDAY, 13, 15)); + UserLesson freshRegistration = fixture.registration( + DomainFixtures.registration(data.student(), freshLesson)); + repository.saveAndFlush(new RegistrationIdempotency( + data.student(), + freshLesson, + freshRegistration, + "fresh", + 6, + TestData.NOW.plusSeconds(86400))); + + Scenario.given(TestData.NOW) + .when(repository::deleteExpired) + .then(deleted -> { + assertThat(deleted).isEqualTo(1); + assertThat(repository.findAll()) + .extracting(RegistrationIdempotency::getIdempotencyKey) + .containsExactly("fresh"); + }); + } + + @Test + @DisplayName("같은 user + key → DB unique 거부") + void userKeyUnique() { + repository.saveAndFlush(idempotency( + "request-1", + registration, + data.lesson(), + TestData.NOW.plusSeconds(86400))); + + Subject subject = fixture.subject(DomainFixtures.subject("OTHER")); + Lesson otherLesson = fixture.lesson( + DomainFixtures.lesson(subject, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 13, 15)); + UserLesson otherRegistration = + fixture.registration(DomainFixtures.registration(data.student(), otherLesson)); + + assertThatThrownBy(() -> repository.saveAndFlush(new RegistrationIdempotency( + data.student(), + otherLesson, + otherRegistration, + "request-1", + 6, + TestData.NOW.plusSeconds(86400)))) + .isInstanceOf(DataIntegrityViolationException.class); + } + + @Test + @DisplayName("같은 registration + 다른 key → DB unique 거부") + void registrationUnique() { + repository.saveAndFlush(idempotency( + "request-1", + registration, + data.lesson(), + TestData.NOW.plusSeconds(86400))); + + assertThatThrownBy(() -> repository.saveAndFlush(new RegistrationIdempotency( + data.student(), + data.lesson(), + registration, + "request-2", + 3, + TestData.NOW.plusSeconds(86400)))) + .isInstanceOf(DataIntegrityViolationException.class); + } + + private RegistrationIdempotency idempotency( + String key, + UserLesson target, + Lesson lesson, + Instant expiresAt) { + return new RegistrationIdempotency( + data.student(), + lesson, + target, + key, + 3, + expiresAt); + } +} diff --git a/src/test/java/com/study/course_registration/repository/SemesterRepositoryTest.java b/src/test/java/com/study/course_registration/repository/SemesterRepositoryTest.java new file mode 100644 index 0000000..73fe21a --- /dev/null +++ b/src/test/java/com/study/course_registration/repository/SemesterRepositoryTest.java @@ -0,0 +1,52 @@ +package com.study.course_registration.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +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 com.study.course_registration.entity.Semester; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DomainFixtures; +import com.study.course_registration.support.fixture.TestData; + +class SemesterRepositoryTest extends PostgresIntegrationTest { + @Autowired DatabaseFixture fixture; + @Autowired SemesterRepository repository; + + @BeforeEach + void setUp() { + fixture.reset(); + } + + @Test + @DisplayName("신청 기간 포함 조회 → 활성 학기 반환") + void findRegistrationWindow() { + Semester semester = fixture.semester(DomainFixtures.futureAcademicSemesterWithOpenRegistration()); + + Scenario.given(TestData.NOW) + .when(now -> repository + .findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual(now, now)) + .then(result -> assertThat(result) + .extracting(Semester::getId) + .containsExactly(semester.getId())); + } + + @Test + @DisplayName("학사 기간 포함 조회 → 진행 학기 반환") + void findAcademicWindow() { + Semester semester = fixture.semester(DomainFixtures.academicSemester("academic")); + + Scenario.given(TestData.TODAY) + .when(today -> repository.findByStartDateLessThanEqualAndEndDateGreaterThanEqual(today, today)) + .then(result -> assertThat(result) + .extracting(Semester::getId) + .containsExactly(semester.getId())); + } +} diff --git a/src/test/java/com/study/course_registration/repository/UserLessonRepositoryTest.java b/src/test/java/com/study/course_registration/repository/UserLessonRepositoryTest.java new file mode 100644 index 0000000..9aebe70 --- /dev/null +++ b/src/test/java/com/study/course_registration/repository/UserLessonRepositoryTest.java @@ -0,0 +1,136 @@ +package com.study.course_registration.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.DayOfWeek; +import java.util.List; + +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.dao.DataIntegrityViolationException; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.Semester; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.entity.User; +import com.study.course_registration.entity.UserLesson; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; +import com.study.course_registration.support.fixture.TestData; + +class UserLessonRepositoryTest extends PostgresIntegrationTest { + @Autowired DatabaseFixture fixture; + @Autowired UserLessonRepository repository; + + private RegistrationDataset data; + + @BeforeEach + void setUp() { + data = fixture.registrationDataset(); + } + + @Test + @DisplayName("유효 신청 조회 → 같은 학기·미취소만 반환") + void activeBySemester() { + fixture.registration(DomainFixtures.registration(data.student(), data.lesson())); + + Semester otherSemester = fixture.semester(DomainFixtures.semester( + null, + "2027-1", + TestData.TODAY.plusDays(100), + TestData.TODAY.plusDays(200), + -3600, + 3600, + 18)); + Subject otherSubject = fixture.subject(DomainFixtures.subject("OTHER")); + Lesson otherLesson = fixture.lesson( + DomainFixtures.lesson(otherSubject, data.professor(), otherSemester)); + fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 9, 11)); + fixture.registration(DomainFixtures.registration(data.student(), otherLesson)); + + Subject canceledSubject = fixture.subject(DomainFixtures.subject("CANCEL")); + Lesson canceledLesson = fixture.lesson( + DomainFixtures.lesson(canceledSubject, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(canceledLesson, DayOfWeek.WEDNESDAY, 9, 11)); + UserLesson canceled = fixture.registration( + DomainFixtures.registration(data.student(), canceledLesson)); + canceled.cancel(TestData.NOW); + repository.saveAndFlush(canceled); + + Scenario.given(data) + .when(current -> repository.findActiveByUserIdAndSemesterId( + current.student().getId(), + current.semester().getId())) + .then(result -> assertThat(result) + .extracting(registration -> registration.getLesson().getId()) + .containsExactly(data.lesson().getId())); + } + + @Test + @DisplayName("유효 신청 중복 → DB unique 거부") + void activeDuplicateIsRejected() { + fixture.registration(DomainFixtures.registration(data.student(), data.lesson())); + + assertThatThrownBy(() -> fixture.registration( + DomainFixtures.registration(data.student(), data.lesson()))) + .isInstanceOf(DataIntegrityViolationException.class); + } + + @Test + @DisplayName("취소 후 같은 강의 재신청 → 허용") + void canceledThenRegisterAgain() { + UserLesson first = fixture.registration( + DomainFixtures.registration(data.student(), data.lesson())); + first.cancel(TestData.NOW); + repository.saveAndFlush(first); + + Scenario.given(first) + .when(previous -> fixture.registration( + DomainFixtures.registration(data.student(), data.lesson()))) + .then(second -> { + assertThat(second.getId()).isNotEqualTo(first.getId()); + assertThat(repository.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId())) + .isEqualTo(1); + }); + } + + @Test + @DisplayName("강의별 신청 수 집계 → 취소 건 제외") + void aggregateCountsExcludeCanceled() { + fixture.registration(DomainFixtures.registration(data.student(), data.lesson())); + User other = fixture.user(DomainFixtures.student(3)); + UserLesson canceled = fixture.registration( + DomainFixtures.registration(other, data.lesson())); + canceled.cancel(TestData.NOW); + repository.saveAndFlush(canceled); + + Scenario.given(List.of(data.lesson().getId())) + .when(repository::countActiveByLessonIds) + .then(counts -> assertThat(counts) + .singleElement() + .satisfies(count -> { + assertThat(count.getLessonId()).isEqualTo(data.lesson().getId()); + assertThat(count.getEnrolledCount()).isEqualTo(1); + })); + } + + @Test + @DisplayName("취소 대상 projection → userId·lessonId 반환") + void targetProjection() { + UserLesson registration = fixture.registration( + DomainFixtures.registration(data.student(), data.lesson())); + + Scenario.given(registration.getId()) + .when(id -> repository.findTargetById(id).orElseThrow()) + .then(target -> { + assertThat(target.getUserId()).isEqualTo(data.student().getId()); + assertThat(target.getLessonId()).isEqualTo(data.lesson().getId()); + }); + } +} diff --git a/src/test/java/com/study/course_registration/repository/UserRepositoryTest.java b/src/test/java/com/study/course_registration/repository/UserRepositoryTest.java new file mode 100644 index 0000000..33982ea --- /dev/null +++ b/src/test/java/com/study/course_registration/repository/UserRepositoryTest.java @@ -0,0 +1,34 @@ +package com.study.course_registration.repository; + +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.transaction.PlatformTransactionManager; + +import com.study.course_registration.support.PessimisticLockProbe; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; + +class UserRepositoryTest extends PostgresIntegrationTest { + @Autowired DatabaseFixture fixture; + @Autowired UserRepository repository; + @Autowired PlatformTransactionManager transactionManager; + + private RegistrationDataset data; + + @BeforeEach + void setUp() { + data = fixture.registrationDataset(); + } + + @Test + @DisplayName("findByIdForUpdate → PostgreSQL user row lock") + void pessimisticLock() throws Exception { + PessimisticLockProbe.assertSecondTransactionBlocks( + transactionManager, + () -> repository.findByIdForUpdate(data.student().getId()).orElseThrow(), + () -> repository.findByIdForUpdate(data.student().getId()).orElseThrow()); + } +} diff --git a/src/test/java/com/study/course_registration/seeder/DataSeederTest.java b/src/test/java/com/study/course_registration/seeder/DataSeederTest.java new file mode 100644 index 0000000..8493736 --- /dev/null +++ b/src/test/java/com/study/course_registration/seeder/DataSeederTest.java @@ -0,0 +1,53 @@ +package com.study.course_registration.seeder; + +import java.time.Clock; +import static org.assertj.core.api.Assertions.assertThat; + +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.test.context.ActiveProfiles; + +import com.study.course_registration.entity.Semester; +import com.study.course_registration.repository.LessonRepository; +import com.study.course_registration.repository.SemesterRepository; +import com.study.course_registration.repository.UserRepository; + +@SpringBootTest +@ActiveProfiles("local") +class DataSeederTest { + @Autowired DataSeeder seeder; + @Autowired Clock clock; + @Autowired SemesterRepository semesters; + @Autowired LessonRepository lessons; + @Autowired UserRepository users; + + @Test + @DisplayName("local seed → 학기 1·강의 7·사용자 3") + void loadsDataset() { + assertThat(semesters.count()).isEqualTo(1); + assertThat(lessons.count()).isEqualTo(7); + assertThat(users.count()).isEqualTo(3); + } + + + @Test + @DisplayName("local seed → 신청 기간이 현재 시각 포함") + void registrationWindowContainsNow() { + Semester semester = semesters.findById(DataSeeder.SEMESTER_ID).orElseThrow(); + + assertThat(semester.getRegistrationStartAt()).isBefore(clock.instant()); + assertThat(semester.getRegistrationEndAt()).isAfter(clock.instant()); + } + + @Test + @DisplayName("seed 재실행 → 데이터 중복 없음") + void rerunIsIdempotent() throws Exception { + seeder.run(); + + assertThat(semesters.count()).isEqualTo(1); + assertThat(lessons.count()).isEqualTo(7); + assertThat(users.count()).isEqualTo(3); + } +} diff --git a/src/test/java/com/study/course_registration/seeder/SeedTableTest.java b/src/test/java/com/study/course_registration/seeder/SeedTableTest.java new file mode 100644 index 0000000..ffb2608 --- /dev/null +++ b/src/test/java/com/study/course_registration/seeder/SeedTableTest.java @@ -0,0 +1,33 @@ +package com.study.course_registration.seeder; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class SeedTableTest { + @Test + @DisplayName("TSV 읽기 → 문자열·nullable·숫자 변환") + void read() { + SeedTable.Row row = SeedTable.read("seed/test/valid.tsv").getFirst(); + + assertThat(row.text("name")).isEqualTo("alpha"); + assertThat(row.nullable("optional")).isNull(); + assertThat(row.integer("number")).isEqualTo(3); + } + + @Test + @DisplayName("컬럼 수 불일치 → 로드 실패") + void malformed() { + assertThatThrownBy(() -> SeedTable.read("seed/test/malformed.tsv")) + .isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("리소스 없음 → 로드 실패") + void missing() { + assertThatThrownBy(() -> SeedTable.read("seed/test/missing.tsv")) + .isInstanceOf(IllegalStateException.class); + } +} diff --git a/src/test/java/com/study/course_registration/service/CourseRegistrationConcurrencyIntegrationTest.java b/src/test/java/com/study/course_registration/service/CourseRegistrationConcurrencyIntegrationTest.java index 4cb9d17..d4c4045 100644 --- a/src/test/java/com/study/course_registration/service/CourseRegistrationConcurrencyIntegrationTest.java +++ b/src/test/java/com/study/course_registration/service/CourseRegistrationConcurrencyIntegrationTest.java @@ -3,9 +3,6 @@ package com.study.course_registration.service; import static org.assertj.core.api.Assertions.assertThat; import java.time.DayOfWeek; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -16,34 +13,27 @@ import java.util.concurrent.TimeUnit; 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.test.context.ActiveProfiles; import com.study.course_registration.dto.registration.CourseRegistrationRequest; import com.study.course_registration.entity.Lesson; -import com.study.course_registration.entity.LessonSchedule; import com.study.course_registration.entity.Professor; import com.study.course_registration.entity.Semester; -import com.study.course_registration.entity.Subject; import com.study.course_registration.entity.User; import com.study.course_registration.enums.RegistrationErrorCode; -import com.study.course_registration.enums.UserRole; import com.study.course_registration.exception.RegistrationException; -import com.study.course_registration.repository.*; +import com.study.course_registration.repository.UserLessonRepository; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DomainFixtures; -@SpringBootTest -@ActiveProfiles("test") -class CourseRegistrationConcurrencyIntegrationTest { +class CourseRegistrationConcurrencyIntegrationTest extends PostgresIntegrationTest { @Autowired CourseRegistrationService service; - @Autowired UserLessonRepository userLessonRepository; - @Autowired LessonScheduleRepository lessonScheduleRepository; - @Autowired LessonRepository lessonRepository; - @Autowired SubjectRepository subjectRepository; - @Autowired ProfessorRepository professorRepository; - @Autowired SemesterRepository semesterRepository; - @Autowired UserRepository userRepository; + @Autowired DatabaseFixture fixture; + @Autowired UserLessonRepository registrations; private ExecutorService executor; private Semester semester; @@ -51,11 +41,9 @@ class CourseRegistrationConcurrencyIntegrationTest { @BeforeEach void setUp() { - clearData(); - Instant now = Instant.now(); - semester = semesterRepository.save(new Semester("semester", "2026-1", LocalDate.now().minusDays(1), - LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), 18)); - professor = professorRepository.save(new Professor("professor", "교수")); + fixture.reset(); + semester = fixture.semester(DomainFixtures.openSemester()); + professor = fixture.professor(DomainFixtures.professor()); } @AfterEach @@ -67,108 +55,123 @@ class CourseRegistrationConcurrencyIntegrationTest { } @Test - void capacityOneWithTenConcurrentUsersHasExactlyOneSuccess() throws Exception { - Lesson lesson = lesson("lesson-cap1", "subject-cap1", 3, 1, DayOfWeek.MONDAY, 9, 11); - List users = users(10, "cap1-user-"); - List results = runConcurrent(users.stream() - .map(user -> () -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId()))) - .toList()); - assertThat(results.stream().filter(code -> code == null)).hasSize(1); - assertThat(results.stream().filter(code -> code == RegistrationErrorCode.CAPACITY_EXCEEDED)).hasSize(9); - assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(1); + @DisplayName("정원 1 + 동시 10명 → 성공 1") + void capacityOne() { + Lesson lesson = fixture.scheduledLesson( + semester, professor, "CAP1", 3, 1, DayOfWeek.MONDAY, 9, 11); + List users = fixture.students(10, "cap1-"); + List actions = users.stream() + .map(user -> () -> service.register( + user.getId(), + new CourseRegistrationRequest(lesson.getId()))) + .toList(); + + Scenario.given(actions) + .when(this::run) + .then(outcome -> { + assertThat(outcome.acceptedCount()).isEqualTo(1); + assertThat(outcome.rejectedCount(RegistrationErrorCode.CAPACITY_EXCEEDED)).isEqualTo(9); + assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(1); + }); } @Test - void sameStudentConcurrentLessonsCannotExceedCreditLimit() throws Exception { - replaceSemesterWithMaxCredits(3); - User user = userRepository.save(new User("credit-user", "학생", 2L, UserRole.STUDENT)); - Lesson lessonA = lesson("credit-a", "credit-subject-a", 3, 30, DayOfWeek.MONDAY, 9, 11); - Lesson lessonB = lesson("credit-b", "credit-subject-b", 3, 30, DayOfWeek.TUESDAY, 9, 11); - List results = runConcurrent(List.of( - () -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())), - () -> service.register(user.getId(), new CourseRegistrationRequest(lessonB.getId())))); - assertThat(results.stream().filter(code -> code == null)).hasSize(1); - assertThat(results.stream().filter(code -> code == RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED)).hasSize(1); + @DisplayName("정원 30 + 동시 50명 → 성공 30") + void capacityThirty() { + Lesson lesson = fixture.scheduledLesson( + semester, professor, "CAP30", 3, 30, DayOfWeek.THURSDAY, 9, 11); + List users = fixture.students(50, "cap30-"); + List actions = users.stream() + .map(user -> () -> service.register( + user.getId(), + new CourseRegistrationRequest(lesson.getId()))) + .toList(); + + Scenario.given(actions) + .when(this::run) + .then(outcome -> { + assertThat(outcome.acceptedCount()).isEqualTo(30); + assertThat(outcome.rejectedCount(RegistrationErrorCode.CAPACITY_EXCEEDED)).isEqualTo(20); + assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(30); + }); } @Test - void sameStudentConcurrentOverlappingLessonsRejectOneConflict() throws Exception { - User user = userRepository.save(new User("schedule-user", "학생", 2L, UserRole.STUDENT)); - Lesson lessonA = lesson("schedule-a", "schedule-subject-a", 3, 30, DayOfWeek.MONDAY, 9, 11); - Lesson lessonB = lesson("schedule-b", "schedule-subject-b", 3, 30, DayOfWeek.MONDAY, 10, 12); - List results = runConcurrent(List.of( - () -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())), - () -> service.register(user.getId(), new CourseRegistrationRequest(lessonB.getId())))); - assertThat(results.stream().filter(code -> code == null)).hasSize(1); - assertThat(results.stream().filter(code -> code == RegistrationErrorCode.SCHEDULE_CONFLICT)).hasSize(1); + @DisplayName("동일 학생 + 잔여 3학점 + 동시 2강의 → 성공 1") + void creditLimit() { + fixture.reset(); + semester = fixture.semester(DomainFixtures.openSemester(3)); + professor = fixture.professor(DomainFixtures.professor()); + User user = fixture.user(DomainFixtures.student(2)); + Lesson first = fixture.scheduledLesson( + semester, professor, "CR1", 3, 30, DayOfWeek.MONDAY, 9, 11); + Lesson second = fixture.scheduledLesson( + semester, professor, "CR2", 3, 30, DayOfWeek.TUESDAY, 9, 11); + + Scenario.given(List.of( + () -> service.register( + user.getId(), + new CourseRegistrationRequest(first.getId())), + () -> service.register( + user.getId(), + new CourseRegistrationRequest(second.getId())))) + .when(this::run) + .then(outcome -> { + assertThat(outcome.acceptedCount()).isEqualTo(1); + assertThat(outcome.rejectedCount(RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED)).isEqualTo(1); + }); } @Test - void sameStudentSameLessonConcurrentRequestsRejectDuplicate() throws Exception { - User user = userRepository.save(new User("duplicate-user", "학생", 2L, UserRole.STUDENT)); - Lesson lesson = lesson("duplicate-lesson", "duplicate-subject", 3, 30, DayOfWeek.WEDNESDAY, 9, 11); - List results = runConcurrent(List.of( - () -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId())), - () -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId())))); - assertThat(results.stream().filter(code -> code == null)).hasSize(1); - assertThat(results.stream().filter(code -> code == RegistrationErrorCode.ALREADY_REGISTERED)).hasSize(1); + @DisplayName("동일 학생 + 겹치는 2강의 동시 신청 → 성공 1") + void scheduleConflict() { + User user = fixture.user(DomainFixtures.student(2)); + Lesson first = fixture.scheduledLesson( + semester, professor, "SC1", 3, 30, DayOfWeek.MONDAY, 9, 11); + Lesson second = fixture.scheduledLesson( + semester, professor, "SC2", 3, 30, DayOfWeek.MONDAY, 10, 12); + + Scenario.given(List.of( + () -> service.register( + user.getId(), + new CourseRegistrationRequest(first.getId())), + () -> service.register( + user.getId(), + new CourseRegistrationRequest(second.getId())))) + .when(this::run) + .then(outcome -> { + assertThat(outcome.acceptedCount()).isEqualTo(1); + assertThat(outcome.rejectedCount(RegistrationErrorCode.SCHEDULE_CONFLICT)).isEqualTo(1); + }); } @Test - void capacityThirtyWithFiftyConcurrentUsersStopsAtThirty() throws Exception { - Lesson lesson = lesson("lesson-cap30", "subject-cap30", 3, 30, DayOfWeek.THURSDAY, 9, 11); - List users = users(50, "cap30-user-"); - List results = runConcurrent(users.stream() - .map(user -> () -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId()))) - .toList()); - assertThat(results.stream().filter(code -> code == null)).hasSize(30); - assertThat(results.stream().filter(code -> code == RegistrationErrorCode.CAPACITY_EXCEEDED)).hasSize(20); - assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(30); + @DisplayName("동일 학생 + 동일 강의 동시 신청 → 성공 1") + void duplicateLesson() { + User user = fixture.user(DomainFixtures.student(2)); + Lesson lesson = fixture.scheduledLesson( + semester, professor, "DUP", 3, 30, DayOfWeek.WEDNESDAY, 9, 11); + + Scenario.given(List.of( + () -> service.register( + user.getId(), + new CourseRegistrationRequest(lesson.getId())), + () -> service.register( + user.getId(), + new CourseRegistrationRequest(lesson.getId())))) + .when(this::run) + .then(outcome -> { + assertThat(outcome.acceptedCount()).isEqualTo(1); + assertThat(outcome.rejectedCount(RegistrationErrorCode.ALREADY_REGISTERED)).isEqualTo(1); + }); } - private void replaceSemesterWithMaxCredits(int maxCredits) { - userLessonRepository.deleteAll(); - lessonScheduleRepository.deleteAll(); - lessonRepository.deleteAll(); - semesterRepository.deleteAll(); - Instant now = Instant.now(); - semester = semesterRepository.save(new Semester("semester", "2026-1", LocalDate.now().minusDays(1), - LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), maxCredits)); - } - - private void clearData() { - userLessonRepository.deleteAll(); - lessonScheduleRepository.deleteAll(); - lessonRepository.deleteAll(); - subjectRepository.deleteAll(); - professorRepository.deleteAll(); - semesterRepository.deleteAll(); - userRepository.deleteAll(); - } - - private Lesson lesson(String lessonId, String subjectId, int credit, int capacity, - DayOfWeek day, int startHour, int endHour) { - Subject subject = subjectRepository.save(new Subject(subjectId, subjectId, subjectId, subjectId, credit)); - Lesson lesson = lessonRepository.save(new Lesson(lessonId, lessonId, subject, professor, semester, capacity, null, null)); - lessonScheduleRepository.save(new LessonSchedule("schedule-" + lessonId, lesson, day, - LocalTime.of(startHour, 0), LocalTime.of(endHour, 0))); - return lesson; - } - - private List users(int count, String prefix) { - List users = new ArrayList<>(); - for (int index = 0; index < count; index++) { - users.add(new User(prefix + index, "학생" + index, 2L, UserRole.STUDENT)); - } - return userRepository.saveAll(users); - } - - private List runConcurrent(List actions) throws Exception { + private ConcurrentOutcome run(List actions) { executor = Executors.newFixedThreadPool(actions.size()); CountDownLatch ready = new CountDownLatch(actions.size()); CountDownLatch start = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(actions.size()); - List results = Collections.synchronizedList(new ArrayList<>()); + List results = Collections.synchronizedList(new ArrayList<>()); List unexpected = Collections.synchronizedList(new ArrayList<>()); for (ThrowingAction action : actions) { @@ -177,9 +180,9 @@ class CourseRegistrationConcurrencyIntegrationTest { try { start.await(); action.run(); - results.add(null); + results.add(new Accepted()); } catch (RegistrationException exception) { - results.add(exception.getErrorCode()); + results.add(new Rejected(exception.getErrorCode())); } catch (Throwable throwable) { unexpected.add(throwable); } finally { @@ -188,11 +191,39 @@ class CourseRegistrationConcurrencyIntegrationTest { }); } - assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - assertThat(done.await(30, TimeUnit.SECONDS)).isTrue(); + try { + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(done.await(30, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("동시성 테스트가 중단되었습니다.", interrupted); + } assertThat(unexpected).isEmpty(); - return results; + return new ConcurrentOutcome(List.copyOf(results)); + } + + private sealed interface AttemptResult permits Accepted, Rejected { + } + + private record Accepted() implements AttemptResult { + } + + private record Rejected(RegistrationErrorCode code) implements AttemptResult { + } + + private record ConcurrentOutcome(List attempts) { + long acceptedCount() { + return attempts.stream().filter(Accepted.class::isInstance).count(); + } + + long rejectedCount(RegistrationErrorCode code) { + return attempts.stream() + .filter(Rejected.class::isInstance) + .map(Rejected.class::cast) + .filter(rejected -> rejected.code() == code) + .count(); + } } @FunctionalInterface diff --git a/src/test/java/com/study/course_registration/service/CourseRegistrationServiceIntegrationTest.java b/src/test/java/com/study/course_registration/service/CourseRegistrationServiceIntegrationTest.java index a973e9c..765a4b8 100644 --- a/src/test/java/com/study/course_registration/service/CourseRegistrationServiceIntegrationTest.java +++ b/src/test/java/com/study/course_registration/service/CourseRegistrationServiceIntegrationTest.java @@ -1,171 +1,281 @@ package com.study.course_registration.service; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.DayOfWeek; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; 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.test.context.ActiveProfiles; import com.study.course_registration.dto.registration.CourseRegistrationRequest; import com.study.course_registration.dto.registration.CourseRegistrationResponse; +import com.study.course_registration.dto.registration.RegistrationListResponse; import com.study.course_registration.entity.Lesson; -import com.study.course_registration.entity.LessonSchedule; import com.study.course_registration.entity.Professor; import com.study.course_registration.entity.Semester; import com.study.course_registration.entity.Subject; import com.study.course_registration.entity.User; import com.study.course_registration.enums.RegistrationErrorCode; -import com.study.course_registration.enums.UserRole; import com.study.course_registration.exception.RegistrationException; -import com.study.course_registration.repository.LessonRepository; -import com.study.course_registration.repository.LessonScheduleRepository; -import com.study.course_registration.repository.ProfessorRepository; -import com.study.course_registration.repository.SemesterRepository; -import com.study.course_registration.repository.SubjectRepository; import com.study.course_registration.repository.UserLessonRepository; -import com.study.course_registration.repository.UserRepository; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Rejections; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; +import com.study.course_registration.support.fixture.TestData; + +class CourseRegistrationServiceIntegrationTest extends PostgresIntegrationTest { + private static final Rejections REJECTIONS = + Rejections.of(RegistrationException.class, RegistrationException::getErrorCode); -@SpringBootTest -@ActiveProfiles("test") -class CourseRegistrationServiceIntegrationTest { @Autowired CourseRegistrationService service; - @Autowired UserLessonRepository userLessonRepository; - @Autowired LessonScheduleRepository lessonScheduleRepository; - @Autowired LessonRepository lessonRepository; - @Autowired SubjectRepository subjectRepository; - @Autowired ProfessorRepository professorRepository; - @Autowired SemesterRepository semesterRepository; - @Autowired UserRepository userRepository; + @Autowired DatabaseFixture fixture; + @Autowired UserLessonRepository registrations; - private Semester semester; - private User user; - private Subject subjectA; - private Subject subjectB; - private Professor professor; - private Lesson lessonA; - private Lesson lessonB; + private RegistrationDataset data; @BeforeEach void setUp() { - userLessonRepository.deleteAll(); - lessonScheduleRepository.deleteAll(); - lessonRepository.deleteAll(); - subjectRepository.deleteAll(); - professorRepository.deleteAll(); - semesterRepository.deleteAll(); - userRepository.deleteAll(); - - Instant now = Instant.now(); - semester = semesterRepository.save(new Semester("semester", "2026-1", LocalDate.now().minusDays(1), - LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), 18)); - professor = professorRepository.save(new Professor("professor", "교수")); - subjectA = subjectRepository.save(new Subject("subject-a", "과목A", "A101", "A", 3)); - subjectB = subjectRepository.save(new Subject("subject-b", "과목B", "B101", "B", 3)); - user = userRepository.save(new User("user", "학생", 2L, UserRole.STUDENT)); - lessonA = lessonRepository.save(new Lesson("lesson-a", "강의A", subjectA, professor, semester, 30, null, null)); - lessonB = lessonRepository.save(new Lesson("lesson-b", "강의B", subjectB, professor, semester, 30, null, null)); - lessonScheduleRepository.save(new LessonSchedule("schedule-a", lessonA, DayOfWeek.MONDAY, LocalTime.of(9, 0), LocalTime.of(11, 0))); - lessonScheduleRepository.save(new LessonSchedule("schedule-b", lessonB, DayOfWeek.TUESDAY, LocalTime.of(9, 0), LocalTime.of(11, 0))); + data = fixture.registrationDataset(); } @Test - void registerCreatesActiveRegistrationAndReturnsTotalCredits() { - CourseRegistrationResponse response = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - - assertThat(response.userId()).isEqualTo(user.getId()); - assertThat(response.lessonId()).isEqualTo(lessonA.getId()); - assertThat(response.totalCredits()).isEqualTo(3); - assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lessonA.getId())).isEqualTo(1); + @DisplayName("신청 성공 → 유효 신청 1건") + void register() { + Scenario.given(data) + .when(current -> service.register( + current.student().getId(), + new CourseRegistrationRequest(current.lesson().getId()))) + .then(response -> { + assertThat(response.totalCredits()).isEqualTo(3); + assertThat(response.registeredAt()).isEqualTo(TestData.NOW); + assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId())) + .isEqualTo(1); + }); } @Test - void duplicateRegistrationIsRejected() { - service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); + @DisplayName("같은 강의 재신청 → ALREADY_REGISTERED") + void duplicate() { + service.register(data.student().getId(), new CourseRegistrationRequest(data.lesson().getId())); - assertThatThrownBy(() -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()))) - .isInstanceOfSatisfying(RegistrationException.class, - ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.ALREADY_REGISTERED)); + Scenario.given(data) + .when(current -> service.register( + current.student().getId(), + new CourseRegistrationRequest(current.lesson().getId()))) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED); } @Test - void cancelThenReregisterKeepsHistoryAndOneActiveRow() { - CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - service.cancel(user.getId(), first.registrationId()); + @DisplayName("취소 후 재신청 → 이력 2건, 유효 1건") + void cancelAndRegisterAgain() { + CourseRegistrationResponse first = service.register( + data.student().getId(), + new CourseRegistrationRequest(data.lesson().getId())); + service.cancel(data.student().getId(), first.registrationId()); - CourseRegistrationResponse second = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - - assertThat(second.registrationId()).isNotEqualTo(first.registrationId()); - assertThat(userLessonRepository.findAll()).hasSize(2); - assertThat(userLessonRepository.findAll().stream().filter(it -> it.getCanceledAt() == null)).hasSize(1); + Scenario.given(data) + .when(current -> service.register( + current.student().getId(), + new CourseRegistrationRequest(current.lesson().getId()))) + .then(second -> { + assertThat(second.registrationId()).isNotEqualTo(first.registrationId()); + assertThat(registrations.findAll()).hasSize(2); + assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId())) + .isEqualTo(1); + }); } @Test - void otherUserCannotCancelRegistration() { - CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - User other = userRepository.save(new User("other-user", "다른학생", 2L, UserRole.STUDENT)); + @DisplayName("다른 사용자 취소 → REGISTRATION_FORBIDDEN") + void cannotCancelOthers() { + CourseRegistrationResponse registration = service.register( + data.student().getId(), + new CourseRegistrationRequest(data.lesson().getId())); + User other = fixture.user(DomainFixtures.studentNamed("다른학생", 2)); - assertThatThrownBy(() -> service.cancel(other.getId(), first.registrationId())) - .isInstanceOfSatisfying(RegistrationException.class, - ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.REGISTRATION_FORBIDDEN)); + Scenario.given(other) + .whenRunning(user -> service.cancel(user.getId(), registration.registrationId())) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_FORBIDDEN); } @Test - void cancelingAlreadyCanceledRegistrationIsRejected() { - CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - service.cancel(user.getId(), first.registrationId()); + @DisplayName("취소 재호출 → 멱등 성공") + void repeatedCancelIsIdempotent() { + CourseRegistrationResponse registration = service.register( + data.student().getId(), + new CourseRegistrationRequest(data.lesson().getId())); + service.cancel(data.student().getId(), registration.registrationId()); - assertThatThrownBy(() -> service.cancel(user.getId(), first.registrationId())) - .isInstanceOfSatisfying(RegistrationException.class, - ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.ALREADY_CANCELED)); + Scenario.given(data) + .whenRunning(current -> service.cancel( + current.student().getId(), + registration.registrationId())) + .then(ignored -> assertThat( + registrations.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId())) + .isZero()); } @Test - void cancelingFreesCapacityForNextRegistration() { - Lesson capacityOne = lessonRepository.save(new Lesson("capacity-one", "정원1", subjectB, professor, semester, 1, null, null)); - lessonScheduleRepository.save(new LessonSchedule("capacity-one-schedule", capacityOne, DayOfWeek.WEDNESDAY, LocalTime.of(13, 0), LocalTime.of(15, 0))); - User other = userRepository.save(new User("capacity-other", "다른학생", 2L, UserRole.STUDENT)); + @DisplayName("취소 건 → 신청 목록 제외") + void canceledRegistrationIsHidden() { + CourseRegistrationResponse registration = service.register( + data.student().getId(), + new CourseRegistrationRequest(data.lesson().getId())); + service.cancel(data.student().getId(), registration.registrationId()); - CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(capacityOne.getId())); - service.cancel(user.getId(), first.registrationId()); - CourseRegistrationResponse second = service.register(other.getId(), new CourseRegistrationRequest(capacityOne.getId())); - - assertThat(second.userId()).isEqualTo(other.getId()); - assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(capacityOne.getId())).isEqualTo(1); + Scenario.given(data) + .when(current -> service.getRegistrations( + current.student().getId(), + current.semester().getId())) + .then(result -> { + assertThat(result.totalCredits()).isZero(); + assertThat(result.registrations()).isEmpty(); + }); } @Test - void cancellationOutsideRegistrationPeriodIsRejected() { - CourseRegistrationResponse registration = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - Semester closedSemester = semesterRepository.save(new Semester("closed-semester", "closed", LocalDate.now().minusDays(100), - LocalDate.now().plusDays(100), Instant.now().minusSeconds(7200), Instant.now().minusSeconds(3600), 18)); - Lesson closedLesson = lessonRepository.save(new Lesson("closed-lesson", "마감강의", subjectB, professor, closedSemester, 30, null, null)); - lessonScheduleRepository.save(new LessonSchedule("closed-schedule", closedLesson, DayOfWeek.THURSDAY, LocalTime.of(9, 0), LocalTime.of(11, 0))); - var closedRegistration = userLessonRepository.saveAndFlush(new com.study.course_registration.entity.UserLesson(user, closedLesson)); + @DisplayName("취소 후 정원 → 다음 사용자 신청 가능") + void cancelFreesCapacity() { + Subject subject = fixture.subject(DomainFixtures.subject("CAP")); + Lesson capacityOne = fixture.lesson( + DomainFixtures.lesson(subject, data.professor(), data.semester(), 1)); + fixture.schedule(DomainFixtures.schedule(capacityOne, DayOfWeek.WEDNESDAY, 13, 15)); + User other = fixture.user(DomainFixtures.studentNamed("대기학생", 2)); - assertThatThrownBy(() -> service.cancel(user.getId(), closedRegistration.getId())) - .isInstanceOfSatisfying(RegistrationException.class, - ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED)); + CourseRegistrationResponse first = service.register( + data.student().getId(), + new CourseRegistrationRequest(capacityOne.getId())); + service.cancel(data.student().getId(), first.registrationId()); - assertThat(userLessonRepository.findById(registration.registrationId())).isPresent(); + Scenario.given(other) + .when(user -> service.register( + user.getId(), + new CourseRegistrationRequest(capacityOne.getId()))) + .thenAccepted(); } @Test - void activeRegistrationListOmitsCanceledRows() { - CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())); - service.cancel(user.getId(), first.registrationId()); - service.register(user.getId(), new CourseRegistrationRequest(lessonB.getId())); + @DisplayName("다른 학기 신청 → 현재 학기 학점 계산 제외") + void creditsAreScopedBySemester() { + Semester otherSemester = fixture.semester(DomainFixtures.semester( + null, + "2027-1", + TestData.TODAY.plusDays(120), + TestData.TODAY.plusDays(240), + -3600, + 3600, + 18)); + Subject otherSubject = fixture.subject(DomainFixtures.subject("OLD")); + Lesson otherLesson = fixture.lesson( + DomainFixtures.lesson(otherSubject, data.professor(), otherSemester)); + fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.FRIDAY, 9, 11)); + fixture.registration(DomainFixtures.registration(data.student(), otherLesson)); - var response = service.getRegistrations(user.getId(), semester.getId()); + Scenario.given(data) + .when(current -> service.register( + current.student().getId(), + new CourseRegistrationRequest(current.lesson().getId()))) + .then(response -> assertThat(response.totalCredits()).isEqualTo(3)); + } - assertThat(response.totalCredits()).isEqualTo(3); - assertThat(response.registrations()).extracting(it -> it.lessonId()).containsExactly(lessonB.getId()); + @Test + @DisplayName("신청 기간 종료 → REGISTRATION_PERIOD_CLOSED") + void closedPeriod() { + fixture.reset(); + Semester closed = fixture.semester(DomainFixtures.closedSemester()); + Professor professor = fixture.professor(DomainFixtures.professor()); + Subject subject = fixture.subject(DomainFixtures.subject("CLOSED")); + User student = fixture.user(DomainFixtures.student(2)); + Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, professor, closed)); + fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11)); + + Scenario.given(student) + .when(user -> service.register( + user.getId(), + new CourseRegistrationRequest(lesson.getId()))) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED); + } + + @Test + @DisplayName("유효 신청 조회 → DTO 전체 매핑") + void activeRegistrationList() { + service.register(data.student().getId(), new CourseRegistrationRequest(data.lesson().getId())); + + Scenario.given(data) + .when(current -> service.getRegistrations( + current.student().getId(), + current.semester().getId())) + .then(result -> { + assertThat(result.totalCredits()).isEqualTo(3); + assertThat(result.registrations()).singleElement().satisfies(item -> { + assertThat(item.lessonId()).isEqualTo(data.lesson().getId()); + assertThat(item.subjectCode()).isEqualTo(data.subject().getCode()); + assertThat(item.subjectName()).isEqualTo(data.subject().getName()); + assertThat(item.credit()).isEqualTo(3); + assertThat(item.professorName()).isEqualTo(data.professor().getName()); + assertThat(item.schedules()).hasSize(1); + assertThat(item.registeredAt()).isEqualTo(TestData.NOW); + }); + }); + } + + @Test + @DisplayName("없는 사용자 신청 조회 → USER_NOT_FOUND") + void registrationListUserNotFound() { + Scenario.given("missing") + .when(userId -> service.getRegistrations(userId, data.semester().getId())) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.USER_NOT_FOUND); + } + + @Test + @DisplayName("없는 학기 신청 조회 → SEMESTER_NOT_FOUND") + void registrationListExplicitSemesterNotFound() { + Scenario.given("missing") + .when(semesterId -> service.getRegistrations(data.student().getId(), semesterId)) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND); + } + + @Test + @DisplayName("신청 기간 없음 + 학기 진행 중 → 학기 날짜 fallback") + void registrationListAcademicFallback() { + fixture.reset(); + Semester academic = fixture.semester(DomainFixtures.academicSemester("academic")); + User student = fixture.user(DomainFixtures.student(2)); + + Scenario.given(student) + .when(user -> service.getRegistrations(user.getId(), null)) + .then(result -> { + assertThat(result.semesterId()).isEqualTo(academic.getId()); + assertThat(result.registrations()).isEmpty(); + }); + } + + @Test + @DisplayName("현재 학기 없음 → SEMESTER_NOT_FOUND") + void registrationListSemesterNotFound() { + fixture.reset(); + User student = fixture.user(DomainFixtures.student(2)); + + Scenario.given(student) + .when(user -> service.getRegistrations(user.getId(), null)) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND); + } + + @Test + @DisplayName("Idempotency-Key 101자 → VALIDATION_ERROR") + void idempotencyKeyTooLong() { + String key = "x".repeat(101); + + Scenario.given(key) + .when(value -> service.register( + data.student().getId(), + new CourseRegistrationRequest(data.lesson().getId()), + value)) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.VALIDATION_ERROR); } } diff --git a/src/test/java/com/study/course_registration/service/LessonQueryServiceIntegrationTest.java b/src/test/java/com/study/course_registration/service/LessonQueryServiceIntegrationTest.java index b23812f..b3a48c5 100644 --- a/src/test/java/com/study/course_registration/service/LessonQueryServiceIntegrationTest.java +++ b/src/test/java/com/study/course_registration/service/LessonQueryServiceIntegrationTest.java @@ -1,96 +1,200 @@ package com.study.course_registration.service; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.DayOfWeek; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; +import org.hibernate.SessionFactory; +import org.hibernate.stat.Statistics; 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.test.context.ActiveProfiles; +import com.study.course_registration.dto.lesson.LessonDetailResponse; +import com.study.course_registration.dto.lesson.LessonListResponse; import com.study.course_registration.dto.registration.CourseRegistrationRequest; import com.study.course_registration.entity.Lesson; -import com.study.course_registration.entity.LessonSchedule; import com.study.course_registration.entity.Professor; import com.study.course_registration.entity.Semester; import com.study.course_registration.entity.Subject; -import com.study.course_registration.entity.User; import com.study.course_registration.enums.RegistrationErrorCode; -import com.study.course_registration.enums.UserRole; import com.study.course_registration.exception.RegistrationException; -import com.study.course_registration.repository.*; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Rejections; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset; +import com.study.course_registration.support.fixture.DomainFixtures; -@SpringBootTest -@ActiveProfiles("test") -class LessonQueryServiceIntegrationTest { - @Autowired LessonQueryService lessonQueryService; +import jakarta.persistence.EntityManagerFactory; + +class LessonQueryServiceIntegrationTest extends PostgresIntegrationTest { + private static final Rejections REJECTIONS = + Rejections.of(RegistrationException.class, RegistrationException::getErrorCode); + + @Autowired LessonQueryService service; @Autowired CourseRegistrationService registrationService; - @Autowired UserLessonRepository userLessonRepository; - @Autowired LessonScheduleRepository lessonScheduleRepository; - @Autowired LessonRepository lessonRepository; - @Autowired SubjectRepository subjectRepository; - @Autowired ProfessorRepository professorRepository; - @Autowired SemesterRepository semesterRepository; - @Autowired UserRepository userRepository; + @Autowired DatabaseFixture fixture; + @Autowired EntityManagerFactory entityManagerFactory; - private Semester semester; - private Lesson lesson; - private User user; + private RegistrationDataset data; @BeforeEach void setUp() { - userLessonRepository.deleteAll(); - lessonScheduleRepository.deleteAll(); - lessonRepository.deleteAll(); - subjectRepository.deleteAll(); - professorRepository.deleteAll(); - semesterRepository.deleteAll(); - userRepository.deleteAll(); - - Instant now = Instant.now(); - semester = semesterRepository.save(new Semester("semester-query", "2026-1", LocalDate.now().minusDays(1), - LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), 18)); - Professor professor = professorRepository.save(new Professor("prof-query", "조회교수")); - Subject subject = subjectRepository.save(new Subject("subject-query", "자료구조", "CS202", "자료구조 설명", 3)); - lesson = lessonRepository.save(new Lesson("lesson-query", "자료구조 01", subject, professor, semester, 30, null, null)); - lessonScheduleRepository.save(new LessonSchedule("schedule-query", lesson, DayOfWeek.MONDAY, - LocalTime.of(9, 0), LocalTime.of(11, 0))); - user = userRepository.save(new User("user-query", "조회학생", 2L, UserRole.STUDENT)); - registrationService.register(user.getId(), new CourseRegistrationRequest(lesson.getId())); + data = fixture.registrationDataset(); + registrationService.register( + data.student().getId(), + new CourseRegistrationRequest(data.lesson().getId())); } @Test - void listUsesCurrentSemesterAndReturnsBulkDerivedFields() { - var response = lessonQueryService.getLessons(null, null, 0, 20); - - assertThat(response.totalElements()).isEqualTo(1); - assertThat(response.lessons()).singleElement().satisfies(item -> { - assertThat(item.lessonId()).isEqualTo(lesson.getId()); - assertThat(item.enrolledCount()).isEqualTo(1); - assertThat(item.schedules()).hasSize(1); - }); + @DisplayName("강의 목록 → 시간표·신청 수 포함") + void list() { + Scenario.given(data) + .when(current -> service.getLessons(current.semester().getId(), null, 0, 20)) + .then(response -> { + assertThat(response.totalElements()).isEqualTo(1); + assertThat(response.lessons()).singleElement().satisfies(item -> { + assertThat(item.lessonId()).isEqualTo(data.lesson().getId()); + assertThat(item.enrolledCount()).isEqualTo(1); + assertThat(item.schedules()).hasSize(1); + }); + }); } @Test - void detailContainsSubjectAndSemesterRegistrationMetadata() { - var response = lessonQueryService.getLesson(lesson.getId()); - - assertThat(response.subjectDescription()).isEqualTo("자료구조 설명"); - assertThat(response.semesterName()).isEqualTo(semester.getName()); - assertThat(response.enrolledCount()).isEqualTo(1); - assertThat(response.registrationStartAt().toEpochMilli()).isEqualTo(semester.getRegistrationStartAt().toEpochMilli()); + @DisplayName("강의 상세 → 과목·학기·신청 수 포함") + void detail() { + Scenario.given(data.lesson().getId()) + .when(service::getLesson) + .then(response -> { + assertThat(response.subjectDescription()).isEqualTo(data.subject().getDescription()); + assertThat(response.semesterName()).isEqualTo(data.semester().getName()); + assertThat(response.enrolledCount()).isEqualTo(1); + }); } @Test - void unknownSemesterIsRejected() { - assertThatThrownBy(() -> lessonQueryService.getLessons("missing", null, 0, 20)) - .isInstanceOfSatisfying(RegistrationException.class, - ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.SEMESTER_NOT_FOUND)); + @DisplayName("없는 학기 → SEMESTER_NOT_FOUND") + void unknownSemester() { + Scenario.given("missing") + .when(id -> service.getLessons(id, null, 0, 20)) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND); + } + + @Test + @DisplayName("subjectId 필터 → 해당 과목만 조회") + void subjectFilter() { + Subject other = fixture.subject(DomainFixtures.subject("CS999")); + Lesson otherLesson = fixture.lesson(DomainFixtures.lesson(other, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 9, 11)); + + Scenario.given(other.getId()) + .when(subjectId -> service.getLessons(data.semester().getId(), subjectId, 0, 20)) + .then(response -> assertThat(response.lessons()) + .extracting(item -> item.subjectCode()) + .containsExactly("CS999")); + } + + @Test + @DisplayName("페이지 크기 1 → 각 페이지 1건") + void pagination() { + Subject other = fixture.subject(DomainFixtures.subject("CS200")); + Lesson otherLesson = fixture.lesson(DomainFixtures.lesson(other, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 9, 11)); + + LessonListResponse first = service.getLessons(data.semester().getId(), null, 0, 1); + + Scenario.given(first) + .when(previous -> new PagePair( + previous, + service.getLessons(data.semester().getId(), null, 1, 1))) + .then(pair -> { + assertThat(pair.first().lessons()).hasSize(1); + assertThat(pair.second().lessons()).hasSize(1); + assertThat(pair.first().lessons().getFirst().lessonId()) + .isNotEqualTo(pair.second().lessons().getFirst().lessonId()); + }); + } + + @Test + @DisplayName("학기 시작 전 신청 기간 → 해당 학기 자동 선택") + void registrationWindowWinsOverAcademicDate() { + fixture.reset(); + Semester future = fixture.semester(DomainFixtures.futureAcademicSemesterWithOpenRegistration()); + Professor professor = fixture.professor(DomainFixtures.professor()); + Subject subject = fixture.subject(DomainFixtures.subject("FUTURE")); + Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, professor, future)); + fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11)); + + Scenario.given(lesson) + .when(ignored -> service.getLessons(null, null, 0, 20)) + .then(response -> assertThat(response.lessons()) + .extracting(item -> item.lessonId()) + .containsExactly(lesson.getId())); + } + + @Test + @DisplayName("강의 6건 조회 → SQL 6회 이하") + void bulkQueriesStayBounded() { + for (int index = 0; index < 5; index++) { + Subject subject = fixture.subject(DomainFixtures.subject("Q" + index)); + Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, data.professor(), data.semester())); + fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.of(index + 1), 13, 15)); + } + Statistics statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics(); + statistics.clear(); + + Scenario.given(data) + .when(current -> service.getLessons(current.semester().getId(), null, 0, 20)) + .then(response -> { + assertThat(response.lessons()).hasSize(6); + assertThat(statistics.getPrepareStatementCount()).isLessThanOrEqualTo(6); + }); + } + + @Test + @DisplayName("빈 학기 조회 → 빈 페이지") + void emptyPage() { + fixture.reset(); + Semester semester = fixture.semester(DomainFixtures.openSemester()); + + Scenario.given(semester.getId()) + .when(id -> service.getLessons(id, null, 0, 20)) + .then(result -> { + assertThat(result.totalElements()).isZero(); + assertThat(result.lessons()).isEmpty(); + }); + } + + @Test + @DisplayName("신청 기간 없음 + 학기 진행 중 → 학기 날짜 fallback") + void academicFallback() { + fixture.reset(); + Semester academic = fixture.semester(DomainFixtures.academicSemester("academic")); + Professor professor = fixture.professor(DomainFixtures.professor()); + Subject subject = fixture.subject(DomainFixtures.subject("ACADEMIC")); + Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, professor, academic)); + fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11)); + + Scenario.given(lesson) + .when(ignored -> service.getLessons(null, null, 0, 20)) + .then(result -> assertThat(result.lessons()) + .extracting(item -> item.lessonId()) + .containsExactly(lesson.getId())); + } + + @Test + @DisplayName("현재 학기 없음 → SEMESTER_NOT_FOUND") + void currentSemesterNotFound() { + fixture.reset(); + + Scenario.given(service) + .when(value -> value.getLessons(null, null, 0, 20)) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND); + } + + private record PagePair(LessonListResponse first, LessonListResponse second) { } } diff --git a/src/test/java/com/study/course_registration/service/SemesterResolverIntegrationTest.java b/src/test/java/com/study/course_registration/service/SemesterResolverIntegrationTest.java new file mode 100644 index 0000000..1c20d2e --- /dev/null +++ b/src/test/java/com/study/course_registration/service/SemesterResolverIntegrationTest.java @@ -0,0 +1,69 @@ +package com.study.course_registration.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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 com.study.course_registration.entity.Semester; +import com.study.course_registration.enums.RegistrationErrorCode; +import com.study.course_registration.exception.RegistrationException; +import com.study.course_registration.support.PostgresIntegrationTest; +import com.study.course_registration.support.Rejections; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DatabaseFixture; +import com.study.course_registration.support.fixture.DomainFixtures; + +class SemesterResolverIntegrationTest extends PostgresIntegrationTest { + private static final Rejections REJECTIONS = + Rejections.of(RegistrationException.class, RegistrationException::getErrorCode); + @Autowired DatabaseFixture fixture; + @Autowired SemesterResolver resolver; + + @BeforeEach + void setUp() { + fixture.reset(); + } + + @Test + @DisplayName("semesterId 명시 → 해당 학기") + void explicitSemester() { + Semester semester = fixture.semester(DomainFixtures.openSemester()); + + Scenario.given(semester.getId()) + .when(resolver::resolve) + .then(result -> assertThat(result.getId()).isEqualTo(semester.getId())); + } + + @Test + @DisplayName("신청 기간 학기 1개 → 해당 학기") + void registrationWindow() { + Semester semester = fixture.semester(DomainFixtures.futureAcademicSemesterWithOpenRegistration()); + + Scenario.given((String) null) + .when(resolver::resolve) + .then(result -> assertThat(result.getId()).isEqualTo(semester.getId())); + } + + @Test + @DisplayName("신청 기간 학기 2개 → 데이터 오류") + void overlappingRegistrationWindows() { + fixture.semester(DomainFixtures.openSemester("semester-a", "A", 18)); + fixture.semester(DomainFixtures.openSemester("semester-b", "B", 18)); + + assertThatThrownBy(() -> resolver.resolve(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("두 개 이상의 수강신청 학기"); + } + + @Test + @DisplayName("활성 학기 없음 → SEMESTER_NOT_FOUND") + void notFound() { + Scenario.given((String) null) + .when(resolver::resolve) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND); + } +} diff --git a/src/test/java/com/study/course_registration/service/lock/RegistrationLockManagerTest.java b/src/test/java/com/study/course_registration/service/lock/RegistrationLockManagerTest.java new file mode 100644 index 0000000..cbce02c --- /dev/null +++ b/src/test/java/com/study/course_registration/service/lock/RegistrationLockManagerTest.java @@ -0,0 +1,39 @@ +package com.study.course_registration.service.lock; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.User; +import com.study.course_registration.repository.LessonRepository; +import com.study.course_registration.repository.UserRepository; +import com.study.course_registration.support.fixture.DomainFixtures; + +class RegistrationLockManagerTest { + @Test + @DisplayName("락 획득 순서 → User 다음 Lesson") + void userThenLesson() { + UserRepository users = mock(UserRepository.class); + LessonRepository lessons = mock(LessonRepository.class); + User user = DomainFixtures.student(2); + Lesson lesson = DomainFixtures.lesson(DomainFixtures.subject("LOCK"), DomainFixtures.professor(), DomainFixtures.openSemester()); + when(users.findByIdForUpdate("user")).thenReturn(Optional.of(user)); + when(lessons.findByIdForUpdate("lesson")).thenReturn(Optional.of(lesson)); + + RegistrationLockManager.LockedRegistration result = new RegistrationLockManager(users, lessons).lock("user", "lesson"); + + InOrder order = inOrder(users, lessons); + order.verify(users).findByIdForUpdate("user"); + order.verify(lessons).findByIdForUpdate("lesson"); + assertThat(result.user()).isSameAs(user); + assertThat(result.lesson()).isSameAs(lesson); + } +} diff --git a/src/test/java/com/study/course_registration/service/policy/LessonSchedulePolicyTest.java b/src/test/java/com/study/course_registration/service/policy/LessonSchedulePolicyTest.java new file mode 100644 index 0000000..ce132ad --- /dev/null +++ b/src/test/java/com/study/course_registration/service/policy/LessonSchedulePolicyTest.java @@ -0,0 +1,69 @@ +package com.study.course_registration.service.policy; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.DayOfWeek; +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.LessonSchedule; +import com.study.course_registration.entity.Professor; +import com.study.course_registration.entity.Semester; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.support.Scenario; +import com.study.course_registration.support.fixture.DomainFixtures; + +@DisplayName("강의 시간표 정책") +class LessonSchedulePolicyTest { + private final LessonSchedulePolicy policy = new LessonSchedulePolicy(new ScheduleConflictChecker()); + + @Test + @DisplayName("같은 강의 시간 겹침 → 거부") + void overlap() { + Semester semester = DomainFixtures.openSemester(); + Subject subject = DomainFixtures.subject("CS101"); + Lesson lesson = DomainFixtures.lesson(subject, DomainFixtures.professor(), semester); + + List schedules = List.of( + DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11), + DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 10, 12)); + + assertThatThrownBy(() -> policy.validate(schedules)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("같은 강의 경계 접촉 → 허용") + void boundary() { + Semester semester = DomainFixtures.openSemester(); + Subject subject = DomainFixtures.subject("CS101"); + Lesson lesson = DomainFixtures.lesson(subject, DomainFixtures.professor(), semester); + + List schedules = List.of( + DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11), + DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 11, 13)); + + assertThatCode(() -> policy.validate(schedules)).doesNotThrowAnyException(); + } + + @Test + @DisplayName("서로 다른 강의 시간 겹침 → 허용") + void differentLessons() { + Semester semester = DomainFixtures.openSemester(); + Professor professor = DomainFixtures.professor(); + Lesson left = DomainFixtures.lesson(DomainFixtures.subject("CS101"), professor, semester); + Lesson right = DomainFixtures.lesson(DomainFixtures.subject("CS102"), professor, semester); + + List schedules = List.of( + DomainFixtures.schedule(left, DayOfWeek.MONDAY, 9, 11), + DomainFixtures.schedule(right, DayOfWeek.MONDAY, 9, 11)); + + Scenario.given(schedules) + .whenRunning(policy::validate) + .thenAccepted(); + } +} diff --git a/src/test/java/com/study/course_registration/service/policy/RegistrationFixture.java b/src/test/java/com/study/course_registration/service/policy/RegistrationFixture.java index 1335934..7463562 100644 --- a/src/test/java/com/study/course_registration/service/policy/RegistrationFixture.java +++ b/src/test/java/com/study/course_registration/service/policy/RegistrationFixture.java @@ -13,185 +13,106 @@ import com.study.course_registration.entity.Semester; import com.study.course_registration.entity.User; import com.study.course_registration.entity.UserLesson; import com.study.course_registration.enums.UserRole; +import com.study.course_registration.support.fixture.DomainFixtures; +import com.study.course_registration.support.fixture.TestData; -/** - * 수강신청 도메인의 given 조립 + when 행동. 도메인 지식은 전부 여기 모인다. - * - *

given/when/then의 틀은 {@link com.study.course_registration.support.Scenario}가 들고 있고, - * 이 클래스는 그 틀에 넣을 내용만 안다. 도메인이 늘어나면 이 파일이 아니라 - * 새 도메인용 Fixture가 하나 더 생긴다. - * - *

R1~R8 테스트는 전부 "어떤 학생이 / 어떤 학기에 / 이미 무엇을 신청한 상태로 / 무엇을 신청한다"는 - * 같은 뼈대를 쓴다. 규칙마다 그중 한두 칸만 달라지므로, 뼈대는 여기에 두고 테스트에는 달라지는 칸만 적는다. - * - *

when 단계는 {@link #checkEligibility()} / {@link #register()} 두 개다. - * 예외를 잡는 일은 {@code Scenario.when(...)}이 하므로 여기서는 그냥 던진다. - */ final class RegistrationFixture { private static final String CANDIDATE_LESSON_ID = "lesson-b"; private static final String EXISTING_LESSON_ID = "lesson-a"; private final RegistrationValidator validator = new RegistrationValidator(new ScheduleConflictChecker()); - - private Semester semester = TestFixtures.semester(18); + private Semester semester = DomainFixtures.openSemester("semester-1", "2026-1", 18); private final long grade; - private String candidateSubjectId = "subject-b"; private int candidateCredit = 3; private int capacity = 30; private Long minGrade; private UserRole allowedRole; - private Slot candidateSlot; - + private Slot candidateSlot = new Slot(DayOfWeek.MONDAY, 15, 16); private boolean existingIsSameLesson; private String existingSubjectId; private int existingCredit = 3; - private Slot existingSlot; - + private Slot existingSlot = new Slot(DayOfWeek.TUESDAY, 15, 16); private long enrolledCount = 1; - private RegistrationFixture(long grade) { - this.grade = grade; - } + private RegistrationFixture(long grade) { this.grade = grade; } - /** given: N학년 학부생. 모든 시나리오의 시작점이다. */ - static RegistrationFixture student(long grade) { - return new RegistrationFixture(grade); - } + static RegistrationFixture student(long grade) { return new RegistrationFixture(grade); } + RegistrationFixture semesterWithMaxCredits(int maxCredits) { semester = DomainFixtures.openSemester("semester-1", "2026-1", maxCredits); return this; } + RegistrationFixture inClosedSemester() { semester = DomainFixtures.closedSemester("semester-closed", "closed"); return this; } + RegistrationFixture applyingFor(String subjectId, int credit) { candidateSubjectId = subjectId; candidateCredit = credit; return this; } + RegistrationFixture requiringMinGrade(long value) { minGrade = value; return this; } + RegistrationFixture requiringRole(UserRole role) { allowedRole = role; return this; } + RegistrationFixture withCapacity(int value) { capacity = value; return this; } + RegistrationFixture alreadyEnrolled(long value) { enrolledCount = value; return this; } + RegistrationFixture scheduledOn(DayOfWeek day, int start, int end) { candidateSlot = new Slot(day, start, end); return this; } + RegistrationFixture withoutSchedule() { candidateSlot = null; return this; } + RegistrationFixture alreadyRegisteredSameLesson() { existingIsSameLesson = true; return this; } + RegistrationFixture alreadyRegistered(String subjectId, int credit) { existingSubjectId = subjectId; existingCredit = credit; return this; } + RegistrationFixture alreadyRegisteredOn(DayOfWeek day, int start, int end) { existingSlot = new Slot(day, start, end); return this; } + RegistrationFixture existingWithoutSchedule() { existingSlot = null; return this; } - /** given: 학점 상한이 N인 학기 (기본 18) */ - RegistrationFixture semesterWithMaxCredits(int maxCredits) { - this.semester = TestFixtures.semester(maxCredits); - return this; - } + RegistrationFixture checkEligibility() { return checkEligibilityAt(TestData.NOW); } - /** given: 신청 기간이 이미 끝난 학기 */ - RegistrationFixture inClosedSemester() { - this.semester = TestFixtures.closedSemester(); - return this; - } - - /** given: 신청하려는 강의의 과목과 학점 (기본 subject-b / 3학점) */ - RegistrationFixture applyingFor(String subjectId, int credit) { - this.candidateSubjectId = subjectId; - this.candidateCredit = credit; - return this; - } - - /** given: 신청하려는 강의에 걸린 최소 학년 제한 */ - RegistrationFixture requiringMinGrade(long minGrade) { - this.minGrade = minGrade; - return this; - } - - /** given: 신청하려는 강의에 걸린 역할 제한 */ - RegistrationFixture requiringRole(UserRole role) { - this.allowedRole = role; - return this; - } - - /** given: 신청하려는 강의의 정원 (기본 30) */ - RegistrationFixture withCapacity(int capacity) { - this.capacity = capacity; - return this; - } - - /** given: 신청하려는 강의의 현재 유효 신청 수 (기본 1) */ - RegistrationFixture alreadyEnrolled(long enrolledCount) { - this.enrolledCount = enrolledCount; - return this; - } - - /** given: 신청하려는 강의의 수업 시간 */ - RegistrationFixture scheduledOn(DayOfWeek day, int startHour, int endHour) { - this.candidateSlot = new Slot(day, startHour, endHour); - return this; - } - - /** given: 지금 신청하려는 바로 그 강의를 이미 신청해 둔 상태 (R4) */ - RegistrationFixture alreadyRegisteredSameLesson() { - this.existingIsSameLesson = true; - return this; - } - - /** given: 다른 강의를 이미 신청해 둔 상태. 과목 코드가 같으면 같은 과목의 다른 분반이 된다 (R5) */ - RegistrationFixture alreadyRegistered(String subjectId, int credit) { - this.existingSubjectId = subjectId; - this.existingCredit = credit; - return this; - } - - /** given: 이미 신청해 둔 강의의 수업 시간 */ - RegistrationFixture alreadyRegisteredOn(DayOfWeek day, int startHour, int endHour) { - this.existingSlot = new Slot(day, startHour, endHour); - return this; - } - - /** when: 신청 기간·학년·역할만 보는 사전 검사 (R1~R3). 값이 없는 행동이라 자기 자신을 돌려준다. */ - RegistrationFixture checkEligibility() { - return checkEligibilityAt(TestFixtures.NOW); - } - - /** when: 특정 시각 기준으로 사전 검사 */ RegistrationFixture checkEligibilityAt(Instant now) { Fixture fixture = assemble(); validator.validatePreconditions(fixture.user(), fixture.candidate(), now); return this; } - /** when: 락을 잡은 뒤의 본 검사 — 중복·시간표·학점·정원 (R4~R8) */ RegistrationFixture register() { Fixture fixture = assemble(); - validator.validateLocked( - fixture.candidate(), fixture.existingRegistrations(), fixture.schedules(), enrolledCount); + validator.validateLocked(fixture.candidate(), fixture.existingRegistrations(), fixture.schedules(), enrolledCount); + return this; + } + + RegistrationFixture attempt() { + checkEligibility(); + register(); return this; } - /** 신청이 성사됐을 때의 누적 학점 */ int totalCreditsAfter() { Fixture fixture = assemble(); return validator.totalCreditsAfter(fixture.candidate(), fixture.existingRegistrations()); } - Instant registrationEndAt() { - return semester.getRegistrationEndAt(); - } + Instant registrationStartAt() { return semester.getRegistrationStartAt(); } + Instant registrationEndAt() { return semester.getRegistrationEndAt(); } private Fixture assemble() { - User user = TestFixtures.student("user", grade); - Lesson candidate = TestFixtures.lesson(CANDIDATE_LESSON_ID, - TestFixtures.subject(candidateSubjectId, candidateCredit), semester, capacity, minGrade, allowedRole); - - List existingRegistrations = new ArrayList<>(); + User user = DomainFixtures.student("user", grade); + Lesson candidate = DomainFixtures.lesson(CANDIDATE_LESSON_ID, CANDIDATE_LESSON_ID, + DomainFixtures.subject(candidateSubjectId, candidateSubjectId, candidateCredit), + DomainFixtures.professor("prof-" + CANDIDATE_LESSON_ID), + semester, capacity, minGrade, allowedRole); + List existing = new ArrayList<>(); Map> schedules = new LinkedHashMap<>(); if (candidateSlot != null) { schedules.put(candidate.getId(), List.of(candidateSlot.toSchedule("schedule-b", candidate))); } - if (existingIsSameLesson) { - existingRegistrations.add(TestFixtures.registration("reg", user, candidate)); + existing.add(DomainFixtures.registration("reg", user, candidate)); } else if (existingSubjectId != null) { - Lesson existingLesson = TestFixtures.lesson(EXISTING_LESSON_ID, - TestFixtures.subject(existingSubjectId, existingCredit), semester, 30, null, null); - existingRegistrations.add(TestFixtures.registration("reg", user, existingLesson)); + Lesson existingLesson = DomainFixtures.lesson(EXISTING_LESSON_ID, EXISTING_LESSON_ID, + DomainFixtures.subject(existingSubjectId, existingSubjectId, existingCredit), + DomainFixtures.professor("prof-" + EXISTING_LESSON_ID), + semester, 30, null, null); + existing.add(DomainFixtures.registration("reg", user, existingLesson)); if (existingSlot != null) { schedules.put(existingLesson.getId(), List.of(existingSlot.toSchedule("schedule-a", existingLesson))); } } - - return new Fixture(user, candidate, existingRegistrations, schedules); + return new Fixture(user, candidate, existing, schedules); } private record Slot(DayOfWeek day, int startHour, int endHour) { LessonSchedule toSchedule(String id, Lesson lesson) { - return TestFixtures.schedule(id, lesson, day, startHour, endHour); + return DomainFixtures.schedule(id, lesson, day, startHour, endHour); } } - private record Fixture(User user, - Lesson candidate, - List existingRegistrations, - Map> schedules) { - } + private record Fixture(User user, Lesson candidate, List existingRegistrations, + Map> schedules) {} } diff --git a/src/test/java/com/study/course_registration/service/policy/RegistrationValidatorTest.java b/src/test/java/com/study/course_registration/service/policy/RegistrationValidatorTest.java index 29b3a8a..6e80221 100644 --- a/src/test/java/com/study/course_registration/service/policy/RegistrationValidatorTest.java +++ b/src/test/java/com/study/course_registration/service/policy/RegistrationValidatorTest.java @@ -16,155 +16,169 @@ import com.study.course_registration.exception.RegistrationException; import com.study.course_registration.support.Rejections; import com.study.course_registration.support.Scenario; -/** - * given → when → then 세 단계를 전부 {@link Scenario}에 맡긴다. - * - *

이 파일에서 도메인에 묶인 것은 아래 {@code REJECTIONS} 상수 한 줄과, given에 적는 조건뿐이다. - * 나머지 흐름은 어떤 도메인 테스트에서도 같은 모양이다. - */ -@DisplayName("수강신청 거부 규칙 R1~R8 (Requirements.md 4.1)") +@DisplayName("수강신청 정책") class RegistrationValidatorTest { - - /** 이 도메인이 거부하는 방식. then이 도메인을 아는 지점은 여기 한 곳뿐이다. */ private static final Rejections REJECTIONS = Rejections.of(RegistrationException.class, RegistrationException::getErrorCode); @Nested - @DisplayName("R1 신청 기간 — 기간 밖이면 REGISTRATION_PERIOD_CLOSED") - class RegistrationPeriod { + @DisplayName("R1 신청 기간") + class Period { @Test - @DisplayName("신청 종료 시각 정각에 신청하면 통과한다 (종료 시각은 기간에 포함된다)") - void endAtIsInclusive() { - RegistrationFixture fixture = RegistrationFixture.student(1); - - Scenario.given(fixture) - .when(f -> f.checkEligibilityAt(fixture.registrationEndAt())) - .thenAccepted(); + @DisplayName("시작 정각 → 허용") + void startInclusive() { + RegistrationFixture fixture = RegistrationFixture.student(2); + Scenario.given(fixture).when(f -> f.checkEligibilityAt(f.registrationStartAt())).thenAccepted(); } @Test - @DisplayName("기간이 지났으면 학년·역할 조건도 함께 어겨도 기간 오류를 먼저 반환한다") - void closedPeriodIsCheckedBeforeEligibility() { - Scenario.given(RegistrationFixture.student(1) - .inClosedSemester() - .requiringMinGrade(3) - .requiringRole(UserRole.POSTGRADUATE)) - .when(RegistrationFixture::checkEligibility) + @DisplayName("종료 정각 → 허용") + void endInclusive() { + RegistrationFixture fixture = RegistrationFixture.student(2); + Scenario.given(fixture).when(f -> f.checkEligibilityAt(f.registrationEndAt())).thenAccepted(); + } + + @Test + @DisplayName("기간 종료 + 학년 미달 → R1") + void periodBeforeGrade() { + Scenario.given(RegistrationFixture.student(1).inClosedSemester().requiringMinGrade(3)) + .when(RegistrationFixture::attempt) .thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED); } } @Nested - @DisplayName("R2 학년 제한 — 미달이면 NOT_ELIGIBLE_GRADE") - class MinGrade { + @DisplayName("R2~R5 자격·중복") + class EligibilityAndDuplicate { @Test - @DisplayName("1학년이 3학년 이상 강의를 신청하면 거부한다") - void rejectsGradeBelowMinimum() { - Scenario.given(RegistrationFixture.student(1) - .requiringMinGrade(3)) - .when(RegistrationFixture::checkEligibility) + @DisplayName("학년 미달 + 역할 불일치 → R2") + void gradeBeforeRole() { + Scenario.given(RegistrationFixture.student(1).requiringMinGrade(3).requiringRole(UserRole.POSTGRADUATE)) + .when(RegistrationFixture::attempt) .thenRejectedWith(REJECTIONS, RegistrationErrorCode.NOT_ELIGIBLE_GRADE); } - } - @Nested - @DisplayName("R3 역할 제한 — 불일치하면 NOT_ELIGIBLE_ROLE") - class AllowedRole { @Test - @DisplayName("학부생이 대학원생 전용 강의를 신청하면 거부한다") - void rejectsRoleMismatch() { - Scenario.given(RegistrationFixture.student(3) - .requiringRole(UserRole.POSTGRADUATE)) - .when(RegistrationFixture::checkEligibility) + @DisplayName("역할 불일치 + 같은 강의 → R3") + void roleBeforeDuplicate() { + Scenario.given(RegistrationFixture.student(3).requiringRole(UserRole.POSTGRADUATE).alreadyRegisteredSameLesson()) + .when(RegistrationFixture::attempt) .thenRejectedWith(REJECTIONS, RegistrationErrorCode.NOT_ELIGIBLE_ROLE); } - } - @Nested - @DisplayName("R4·R5 중복 신청 — 같은 분반이면 ALREADY_REGISTERED, 다른 분반이면 DUPLICATE_SUBJECT") - class Duplicate { @Test - @DisplayName("이미 신청한 그 강의를 다시 신청하면 과목 중복보다 강의 중복을 먼저 반환한다") - void sameLessonTakesPrecedenceOverSameSubject() { - Scenario.given(RegistrationFixture.student(2) - .alreadyRegisteredSameLesson()) - .when(RegistrationFixture::register) + @DisplayName("같은 강의 → R4") + void duplicateLesson() { + Scenario.given(RegistrationFixture.student(2).alreadyRegisteredSameLesson()) + .when(RegistrationFixture::attempt) .thenRejectedWith(REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED); } @Test - @DisplayName("같은 과목의 다른 분반을 신청하면 거부한다") - void rejectsDifferentSectionOfSameSubject() { + @DisplayName("같은 과목 다른 분반 → R5") + void duplicateSubject() { + Scenario.given(RegistrationFixture.student(2).applyingFor("subject", 3).alreadyRegistered("subject", 3)) + .when(RegistrationFixture::attempt) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.DUPLICATE_SUBJECT); + } + + @Test + @DisplayName("과목 중복 + 시간 충돌 → R5") + void duplicateSubjectBeforeSchedule() { Scenario.given(RegistrationFixture.student(2) - .applyingFor("subject", 3) - .alreadyRegistered("subject", 3)) - .when(RegistrationFixture::register) + .applyingFor("same", 3).scheduledOn(DayOfWeek.MONDAY, 10, 12) + .alreadyRegistered("same", 3).alreadyRegisteredOn(DayOfWeek.MONDAY, 9, 11)) + .when(RegistrationFixture::attempt) .thenRejectedWith(REJECTIONS, RegistrationErrorCode.DUPLICATE_SUBJECT); } } @Nested - @DisplayName("R6 시간표 충돌 — 겹치면 SCHEDULE_CONFLICT") - class ScheduleConflict { - @ParameterizedTest(name = "[{index}] {5}") + @DisplayName("R6 시간표") + class Schedule { + @ParameterizedTest(name = "{4}") @CsvSource(textBlock = """ - # 기존 수업 시작, 끝 | 신청 수업 시작, 끝 | 기대 에러(비우면 통과) | 설명 - 9, 11, 10, 12, SCHEDULE_CONFLICT, '기존 수업과 시간이 겹치면 거부한다 (월 9-11 vs 월 10-12)' - 9, 11, 11, 13, , '앞 수업이 끝나는 시각에 시작하면 신청할 수 있다 (월 9-11 vs 월 11-13)' + 9, 11, 10, 12, '겹침 → R6' + 9, 11, 11, 13, '경계 접촉 → 허용' """) - void scheduleOverlap(int existingStart, int existingEnd, int newStart, int newEnd, - RegistrationErrorCode expected, String description) { - Scenario.given(RegistrationFixture.student(2) - .alreadyRegistered("subject-a", 3) - .alreadyRegisteredOn(DayOfWeek.MONDAY, existingStart, existingEnd) - .applyingFor("subject-b", 3) - .scheduledOn(DayOfWeek.MONDAY, newStart, newEnd)) - .when(RegistrationFixture::register) - .then(REJECTIONS, expected); - } - } - - @Nested - @DisplayName("R7 학점 상한 — 초과하면 CREDIT_LIMIT_EXCEEDED") - class CreditLimit { - @ParameterizedTest(name = "[{index}] {4}") - @CsvSource(textBlock = """ - # 학기 상한 | 기존 신청 학점 | 신청 강의 학점 | 기대 에러(비우면 통과) | 설명 - 6, 3, 3, , '합계가 상한과 정확히 같으면 신청할 수 있다 (3+3=6)' - 5, 3, 3, CREDIT_LIMIT_EXCEEDED , '합계가 상한을 넘으면 거부한다 (3+3>5)' - """) - void creditLimit(int maxCredits, int existingCredit, int newCredit, - RegistrationErrorCode expected, String description) { + void overlap(int oldStart, int oldEnd, int newStart, int newEnd, String name) { RegistrationFixture fixture = RegistrationFixture.student(2) - .semesterWithMaxCredits(maxCredits) - .alreadyRegistered("subject-a", existingCredit) - .applyingFor("subject-b", newCredit); + .alreadyRegistered("old", 3).alreadyRegisteredOn(DayOfWeek.MONDAY, oldStart, oldEnd) + .applyingFor("new", 3).scheduledOn(DayOfWeek.MONDAY, newStart, newEnd); - Scenario.given(fixture) - .when(RegistrationFixture::register) - .then(REJECTIONS, expected); + if (newStart < oldEnd) { + Scenario.given(fixture).when(RegistrationFixture::attempt) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SCHEDULE_CONFLICT); + } else { + Scenario.given(fixture).when(RegistrationFixture::attempt).thenAccepted(); + } + } - assertThat(fixture.totalCreditsAfter()) - .as("신청 후 누적 학점") - .isEqualTo(existingCredit + newCredit); + @Test + @DisplayName("시간 충돌 + 학점 초과 → R6") + void scheduleBeforeCredit() { + Scenario.given(RegistrationFixture.student(2).semesterWithMaxCredits(5) + .alreadyRegistered("old", 3).alreadyRegisteredOn(DayOfWeek.MONDAY, 9, 11) + .applyingFor("new", 3).scheduledOn(DayOfWeek.MONDAY, 10, 12)) + .when(RegistrationFixture::attempt) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.SCHEDULE_CONFLICT); + } + + @Test + @DisplayName("신청 강의 시간표 없음 → 500") + void missingCandidateSchedule() { + Scenario.given(RegistrationFixture.student(2).withoutSchedule()) + .when(RegistrationFixture::attempt) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.INTERNAL_SERVER_ERROR); + } + + @Test + @DisplayName("기존 강의 시간표 없음 → 500") + void missingExistingSchedule() { + Scenario.given(RegistrationFixture.student(2).alreadyRegistered("old", 3).existingWithoutSchedule()) + .when(RegistrationFixture::attempt) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.INTERNAL_SERVER_ERROR); } } @Nested - @DisplayName("R8 정원 — 가득 차면 CAPACITY_EXCEEDED") - class Capacity { - @ParameterizedTest(name = "[{index}] {3}") + @DisplayName("R7 학점") + class Credit { + @ParameterizedTest(name = "{4}") @CsvSource(textBlock = """ - # 정원 | 현재 유효 신청 수 | 기대 에러(비우면 통과) | 설명 - 30, 29, , '마지막 한 자리는 신청할 수 있다 (29/30)' - 30, 30, CAPACITY_EXCEEDED , '정원이 가득 차면 거부한다 (30/30)' + 6, 3, 3, , '3+3=6 → 허용' + 5, 3, 3, CREDIT_LIMIT_EXCEEDED, '3+3>5 → R7' """) - void capacity(int capacity, long enrolledCount, - RegistrationErrorCode expected, String description) { - Scenario.given(RegistrationFixture.student(2) - .withCapacity(capacity) - .alreadyEnrolled(enrolledCount)) - .when(RegistrationFixture::register) + void limit(int max, int oldCredit, int newCredit, RegistrationErrorCode expected, String name) { + RegistrationFixture fixture = RegistrationFixture.student(2).semesterWithMaxCredits(max) + .alreadyRegistered("old", oldCredit).applyingFor("new", newCredit); + + Scenario.given(fixture).when(RegistrationFixture::attempt).then(REJECTIONS, expected); + assertThat(fixture.totalCreditsAfter()).isEqualTo(oldCredit + newCredit); + } + + @Test + @DisplayName("학점 초과 + 정원 초과 → R7") + void creditBeforeCapacity() { + Scenario.given(RegistrationFixture.student(2).semesterWithMaxCredits(5) + .alreadyRegistered("old", 3).applyingFor("new", 3) + .withCapacity(30).alreadyEnrolled(30)) + .when(RegistrationFixture::attempt) + .thenRejectedWith(REJECTIONS, RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED); + } + } + + @Nested + @DisplayName("R8 정원") + class Capacity { + @ParameterizedTest(name = "{3}") + @CsvSource(textBlock = """ + 30, 29, , '29/30 → 허용' + 30, 30, CAPACITY_EXCEEDED, '30/30 → R8' + """) + void capacity(int capacity, long enrolled, RegistrationErrorCode expected, String name) { + Scenario.given(RegistrationFixture.student(2).withCapacity(capacity).alreadyEnrolled(enrolled)) + .when(RegistrationFixture::attempt) .then(REJECTIONS, expected); } } diff --git a/src/test/java/com/study/course_registration/service/policy/ScheduleConflictCheckerTest.java b/src/test/java/com/study/course_registration/service/policy/ScheduleConflictCheckerTest.java index 266391a..13f901b 100644 --- a/src/test/java/com/study/course_registration/service/policy/ScheduleConflictCheckerTest.java +++ b/src/test/java/com/study/course_registration/service/policy/ScheduleConflictCheckerTest.java @@ -9,29 +9,25 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import com.study.course_registration.entity.LessonSchedule; +import com.study.course_registration.support.fixture.DomainFixtures; -@DisplayName("R6 시간 블록 겹침 판정 (Requirements.md 4.3)") +@DisplayName("시간표 겹침") class ScheduleConflictCheckerTest { private final ScheduleConflictChecker checker = new ScheduleConflictChecker(); - @DisplayName("두 시간 블록이 겹치는지 판정한다") - @ParameterizedTest(name = "[{index}] {7}") + @ParameterizedTest(name = "{7}") @CsvSource(textBlock = """ - # 블록A 요일, 시작, 끝 | 블록B 요일, 시작, 끝 | 겹치는가 | 설명 - MONDAY, 9, 11, MONDAY, 10, 12, true, '같은 요일에 시간이 겹치면 충돌이다' - MONDAY, 9, 11, MONDAY, 11, 13, false, '앞 수업이 끝나는 시각에 시작하면 충돌이 아니다' - MONDAY, 9, 11, MONDAY, 13, 15, false, '같은 요일이어도 시간이 떨어져 있으면 충돌이 아니다' - MONDAY, 9, 11, TUESDAY, 9, 11, false, '시간이 같아도 요일이 다르면 충돌이 아니다' + MONDAY, 9, 11, MONDAY, 10, 12, true, '같은 요일 겹침 → 충돌' + MONDAY, 9, 11, MONDAY, 11, 13, false, '경계 접촉 → 비충돌' + MONDAY, 9, 11, MONDAY, 13, 15, false, '같은 요일 비중첩 → 비충돌' + MONDAY, 9, 11, TUESDAY, 9, 11, false, '다른 요일 → 비충돌' """) - void overlaps(DayOfWeek dayA, int startA, int endA, - DayOfWeek dayB, int startB, int endB, - boolean expected, String description) { - // given - LessonSchedule a = TestFixtures.schedule(dayA, startA, endA); - LessonSchedule b = TestFixtures.schedule(dayB, startB, endB); + void overlaps(DayOfWeek dayA, int startA, int endA, DayOfWeek dayB, int startB, int endB, + boolean expected, String name) { + LessonSchedule a = DomainFixtures.schedule(dayA, startA, endA); + LessonSchedule b = DomainFixtures.schedule(dayB, startB, endB); - // when & then - assertThat(checker.overlaps(a, b)).as(description).isEqualTo(expected); - assertThat(checker.overlaps(b, a)).as(description + " (순서를 바꿔도 같다)").isEqualTo(expected); + assertThat(checker.overlaps(a, b)).isEqualTo(expected); + assertThat(checker.overlaps(b, a)).isEqualTo(expected); } } diff --git a/src/test/java/com/study/course_registration/service/policy/TestFixtures.java b/src/test/java/com/study/course_registration/service/policy/TestFixtures.java deleted file mode 100644 index 785b945..0000000 --- a/src/test/java/com/study/course_registration/service/policy/TestFixtures.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.study.course_registration.service.policy; - -import java.time.DayOfWeek; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; - -import com.study.course_registration.entity.Lesson; -import com.study.course_registration.entity.LessonSchedule; -import com.study.course_registration.entity.Professor; -import com.study.course_registration.entity.Semester; -import com.study.course_registration.entity.Subject; -import com.study.course_registration.entity.User; -import com.study.course_registration.entity.UserLesson; -import com.study.course_registration.enums.UserRole; - -final class TestFixtures { - static final Instant NOW = Instant.parse("2026-09-17T10:00:00Z"); - - private TestFixtures() { - } - - static Semester semester(int maxCredits) { - return new Semester("semester-1", "2026-1", LocalDate.of(2026, 9, 1), LocalDate.of(2026, 12, 31), - NOW.minusSeconds(3600), NOW.plusSeconds(3600), maxCredits); - } - - static Semester closedSemester() { - return new Semester("semester-closed", "closed", LocalDate.of(2026, 1, 1), LocalDate.of(2026, 2, 1), - NOW.minusSeconds(7200), NOW.minusSeconds(3600), 18); - } - - static User student(String id, long grade) { - return new User(id, id, grade, UserRole.STUDENT); - } - - static User postgraduate(String id) { - return new User(id, id, 3L, UserRole.POSTGRADUATE); - } - - static Lesson lesson(String id, Subject subject, Semester semester, int capacity, Long minGrade, UserRole role) { - return new Lesson(id, id, subject, new Professor("prof-" + id, "prof"), semester, capacity, minGrade, role); - } - - static Subject subject(String id, int credit) { - return new Subject(id, id, id, id, credit); - } - - static UserLesson registration(String id, User user, Lesson lesson) { - return new UserLesson(id, user, lesson); - } - - static LessonSchedule schedule(DayOfWeek day, int startHour, int endHour) { - Subject subject = subject("subject-" + day + startHour, 3); - Lesson lesson = lesson("lesson-" + day + startHour, subject, semester(18), 30, null, null); - return new LessonSchedule("schedule-" + day + startHour, lesson, day, - LocalTime.of(startHour, 0), LocalTime.of(endHour, 0)); - } - - static LessonSchedule schedule(String id, Lesson lesson, DayOfWeek day, int startHour, int endHour) { - return new LessonSchedule(id, lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0)); - } -} diff --git a/src/test/java/com/study/course_registration/support/CourseIntegrationTest.java b/src/test/java/com/study/course_registration/support/CourseIntegrationTest.java new file mode 100644 index 0000000..13dd53c --- /dev/null +++ b/src/test/java/com/study/course_registration/support/CourseIntegrationTest.java @@ -0,0 +1,22 @@ +package com.study.course_registration.support; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; + +import com.study.course_registration.support.fixture.TestFixtureConfig; + +@Inherited +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@SpringBootTest +@ActiveProfiles("test") +@Import(TestFixtureConfig.class) +public @interface CourseIntegrationTest { +} diff --git a/src/test/java/com/study/course_registration/support/Outcome.java b/src/test/java/com/study/course_registration/support/Outcome.java index 969678b..b06b8f2 100644 --- a/src/test/java/com/study/course_registration/support/Outcome.java +++ b/src/test/java/com/study/course_registration/support/Outcome.java @@ -2,13 +2,8 @@ package com.study.course_registration.support; import static org.assertj.core.api.Assertions.assertThat; -/** - * then 단계. when의 실행 결과는 값을 돌려줬거나 예외로 거부됐거나 둘 중 하나다. - * - *

도메인 타입을 모른다. 예외 타입과 코드 추출 방식은 {@link Rejections}로 받는다. - * - * @param when이 돌려준 값의 타입 - */ +import java.util.function.Consumer; + public final class Outcome { private final R result; private final RuntimeException thrown; @@ -18,38 +13,34 @@ public final class Outcome { this.thrown = thrown; } - /** then: 거부되지 않아야 한다. 돌려준 값을 그대로 넘겨주므로 이어서 내용을 확인할 수 있다. */ public R thenAccepted() { if (thrown != null) { - throw new AssertionError("통과해야 하는데 " + thrown.getClass().getSimpleName() - + " 이(가) 발생했다: " + thrown.getMessage(), thrown); + throw new AssertionError( + "성공해야 하지만 " + thrown.getClass().getSimpleName() + " 발생: " + thrown.getMessage(), + thrown); } return result; } - /** - * then: {@code expected}가 null이면 통과, 값이 있으면 그 코드로 거부되어야 한다. - * - *

표 기반 테스트에서 "기대 에러 칸이 비어 있으면 통과"를 그대로 표현하기 위한 형태다. - */ + public void then(Consumer assertions) { + assertions.accept(thenAccepted()); + } + + public void thenAccepted(Consumer assertions) { + then(assertions); + } + public void then(Rejections rejections, E expected) { if (expected == null) { thenAccepted(); - } else { - thenRejectedWith(rejections, expected); + return; } + thenRejectedWith(rejections, expected); } - /** then: 주어진 도메인의 예외로, 주어진 사유 코드로 거부되어야 한다. */ public void thenRejectedWith(Rejections rejections, E expected) { - assertThat(thrown) - .as("%s (으)로 거부되어야 하는데 통과했다", expected) - .isNotNull(); - assertThat(thrown) - .as("거부 예외 타입") - .isInstanceOf(rejections.type()); - assertThat(rejections.codeOf(thrown)) - .as("거부 사유") - .isEqualTo(expected); + assertThat(thrown).as("예외가 발생해야 한다").isNotNull(); + assertThat(thrown).isInstanceOf(rejections.type()); + assertThat(rejections.codeOf(thrown)).isEqualTo(expected); } } diff --git a/src/test/java/com/study/course_registration/support/PessimisticLockProbe.java b/src/test/java/com/study/course_registration/support/PessimisticLockProbe.java new file mode 100644 index 0000000..9a702a7 --- /dev/null +++ b/src/test/java/com/study/course_registration/support/PessimisticLockProbe.java @@ -0,0 +1,63 @@ +package com.study.course_registration.support; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +public final class PessimisticLockProbe { + private PessimisticLockProbe() {} + + public static void assertSecondTransactionBlocks( + PlatformTransactionManager transactionManager, + Supplier firstLock, + Supplier secondLock) throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch firstLocked = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + try { + Future first = executor.submit(() -> transaction.executeWithoutResult(status -> { + firstLock.get(); + firstLocked.countDown(); + await(releaseFirst); + })); + + assertThat(firstLocked.await(5, TimeUnit.SECONDS)).isTrue(); + + Future second = executor.submit(() -> transaction.executeWithoutResult(status -> secondLock.get())); + + assertThatThrownBy(() -> second.get(250, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + + releaseFirst.countDown(); + first.get(5, TimeUnit.SECONDS); + second.get(5, TimeUnit.SECONDS); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("락 테스트 release 신호를 받지 못했습니다."); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("락 테스트가 중단되었습니다.", interrupted); + } + } +} diff --git a/src/test/java/com/study/course_registration/support/PostgresIntegrationTest.java b/src/test/java/com/study/course_registration/support/PostgresIntegrationTest.java new file mode 100644 index 0000000..75a1bd3 --- /dev/null +++ b/src/test/java/com/study/course_registration/support/PostgresIntegrationTest.java @@ -0,0 +1,26 @@ +package com.study.course_registration.support; + +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +@CourseIntegrationTest +@Testcontainers +public abstract class PostgresIntegrationTest { + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer(DockerImageName.parse("postgres:16-alpine")); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void postgres(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + registry.add("spring.flyway.locations", () -> "classpath:db/migration/postgresql"); + registry.add("spring.datasource.hikari.connection-init-sql", () -> "SET lock_timeout TO '3s'"); + } +} diff --git a/src/test/java/com/study/course_registration/support/Rejections.java b/src/test/java/com/study/course_registration/support/Rejections.java index 72fbbcf..0c70d5e 100644 --- a/src/test/java/com/study/course_registration/support/Rejections.java +++ b/src/test/java/com/study/course_registration/support/Rejections.java @@ -2,20 +2,6 @@ package com.study.course_registration.support; import java.util.function.Function; -/** - * "이 도메인은 어떤 예외로 거부하고, 그 예외에서 사유 코드를 어떻게 꺼내는가"를 담은 값. - * - *

then 단계가 도메인에 묶이는 이유는 이 두 가지뿐이다. 그래서 이것만 값으로 넘기면 - * then도 제네릭이 된다. 새 도메인은 상수 한 줄만 선언하면 된다. - * - *

{@code
- * Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
- * Rejections.of(PaymentException.class, PaymentException::getCode);
- * }
- * - * @param 그 도메인이 거부할 때 던지는 예외 - * @param 거부 사유 코드 타입 (보통 enum) - */ public final class Rejections { private final Class type; private final Function codeOf; @@ -29,11 +15,6 @@ public final class Rejections { return new Rejections<>(type, codeOf); } - Class type() { - return type; - } - - E codeOf(Throwable thrown) { - return codeOf.apply(type.cast(thrown)); - } + Class type() { return type; } + E codeOf(Throwable thrown) { return codeOf.apply(type.cast(thrown)); } } diff --git a/src/test/java/com/study/course_registration/support/Scenario.java b/src/test/java/com/study/course_registration/support/Scenario.java index 74405fa..6a4de2e 100644 --- a/src/test/java/com/study/course_registration/support/Scenario.java +++ b/src/test/java/com/study/course_registration/support/Scenario.java @@ -1,24 +1,8 @@ package com.study.course_registration.support; +import java.util.function.Consumer; import java.util.function.Function; -/** - * given → when 을 표현하는 도메인 무관·계층 무관 테스트 하네스. - * - *

어떤 도메인 타입도, 어떤 계층(단위/통합/HTTP)도 여기 등장하지 않는다. - * "무언가를 준비해 두고(given) 무언가를 실행한다(when)"는 모양이 계층마다 같기 때문에 - * 이 클래스는 도메인이나 계층이 늘어나도 수정할 일이 없다. - * - *

실행 중 튀어나온 {@link RuntimeException}은 여기서 잡아 {@link Outcome}에 담는다. - * then 단계에서 "통과해야 한다 / 이 코드로 거부되어야 한다"를 판정하기 위해서다. - * - *

{@code
- * Scenario.given(fixture).when(RegistrationFixture::register).thenRejectedWith(REJECTIONS, code);
- * JsonBody body = Scenario.given(api).when(a -> a.post(path, json)).thenAccepted();
- * }
- * - * @param 계층별 fixture 타입 (메모리 빌더, 서비스, HTTP 클라이언트 …) - */ public final class Scenario { private final T fixture; @@ -26,17 +10,10 @@ public final class Scenario { this.fixture = fixture; } - /** given: 준비된 fixture를 받는다. 어떻게 조립하는지는 각 도메인·계층이 안다. */ public static Scenario given(T fixture) { return new Scenario<>(fixture); } - /** - * when: fixture에 행동을 가하고 결과를 담아 돌려준다. 예외는 여기서 잡힌다. - * - *

값을 돌려주지 않는 행동은 fixture 자신을 반환하게 두면 된다. {@code when}이 하나뿐이라 - * 계층이 달라져도 읽는 방식이 갈리지 않는다. - */ public Outcome when(Function action) { try { return new Outcome<>(action.apply(fixture), null); @@ -44,4 +21,13 @@ public final class Scenario { return new Outcome<>(null, thrown); } } + + public Outcome whenRunning(Consumer action) { + try { + action.accept(fixture); + return new Outcome<>(null, null); + } catch (RuntimeException thrown) { + return new Outcome<>(null, thrown); + } + } } diff --git a/src/test/java/com/study/course_registration/support/fixture/DatabaseFixture.java b/src/test/java/com/study/course_registration/support/fixture/DatabaseFixture.java new file mode 100644 index 0000000..4ad7bcc --- /dev/null +++ b/src/test/java/com/study/course_registration/support/fixture/DatabaseFixture.java @@ -0,0 +1,101 @@ +package com.study.course_registration.support.fixture; + +import java.time.DayOfWeek; +import java.util.ArrayList; +import java.util.List; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.LessonSchedule; +import com.study.course_registration.entity.Professor; +import com.study.course_registration.entity.Semester; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.entity.User; +import com.study.course_registration.entity.UserLesson; +import com.study.course_registration.enums.UserRole; +import com.study.course_registration.repository.LessonRepository; +import com.study.course_registration.repository.LessonScheduleRepository; +import com.study.course_registration.repository.ProfessorRepository; +import com.study.course_registration.repository.RegistrationIdempotencyRepository; +import com.study.course_registration.repository.SemesterRepository; +import com.study.course_registration.repository.SubjectRepository; +import com.study.course_registration.repository.UserLessonRepository; +import com.study.course_registration.repository.UserRepository; + +public final class DatabaseFixture { + private final RegistrationIdempotencyRepository idempotencies; + private final UserLessonRepository registrations; + private final LessonScheduleRepository schedules; + private final LessonRepository lessons; + private final SubjectRepository subjects; + private final ProfessorRepository professors; + private final SemesterRepository semesters; + private final UserRepository users; + + public DatabaseFixture(RegistrationIdempotencyRepository idempotencies, UserLessonRepository registrations, + LessonScheduleRepository schedules, LessonRepository lessons, SubjectRepository subjects, + ProfessorRepository professors, SemesterRepository semesters, UserRepository users) { + this.idempotencies = idempotencies; + this.registrations = registrations; + this.schedules = schedules; + this.lessons = lessons; + this.subjects = subjects; + this.professors = professors; + this.semesters = semesters; + this.users = users; + } + + public void reset() { + idempotencies.deleteAll(); + registrations.deleteAll(); + schedules.deleteAll(); + lessons.deleteAll(); + subjects.deleteAll(); + professors.deleteAll(); + semesters.deleteAll(); + users.deleteAll(); + } + + public RegistrationDataset registrationDataset() { + reset(); + Semester semester = semesters.save(DomainFixtures.openSemester()); + Professor professor = professors.save(DomainFixtures.professor()); + Subject subject = subjects.save(DomainFixtures.subject("CS101")); + User student = users.save(DomainFixtures.student(2)); + Lesson lesson = lessons.save(DomainFixtures.lesson(subject, professor, semester)); + schedules.save(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11)); + return new RegistrationDataset(semester, professor, subject, student, lesson); + } + + public Semester semester(Semester semester) { return semesters.save(semester); } + public Professor professor(Professor professor) { return professors.save(professor); } + public Subject subject(Subject subject) { return subjects.save(subject); } + public User user(User user) { return users.save(user); } + public Lesson lesson(Lesson lesson) { return lessons.save(lesson); } + public LessonSchedule schedule(LessonSchedule schedule) { return schedules.save(schedule); } + public UserLesson registration(UserLesson registration) { return registrations.saveAndFlush(registration); } + + + public Lesson scheduledLesson(Semester semester, Professor professor, String code, int credit, int capacity, + DayOfWeek day, int startHour, int endHour) { + Subject subject = subject(DomainFixtures.subject(code, credit)); + Lesson lesson = lesson(DomainFixtures.lesson(subject, professor, semester, capacity)); + schedule(DomainFixtures.schedule(lesson, day, startHour, endHour)); + return lesson; + } + + public List students(int count, String prefix) { + List result = new ArrayList<>(); + for (int index = 0; index < count; index++) { + result.add(users.save(new User(prefix + index, 2L, UserRole.STUDENT))); + } + return result; + } + + public record RegistrationDataset( + Semester semester, + Professor professor, + Subject subject, + User student, + Lesson lesson) { + } +} diff --git a/src/test/java/com/study/course_registration/support/fixture/DomainFixtures.java b/src/test/java/com/study/course_registration/support/fixture/DomainFixtures.java new file mode 100644 index 0000000..6af0fe3 --- /dev/null +++ b/src/test/java/com/study/course_registration/support/fixture/DomainFixtures.java @@ -0,0 +1,151 @@ +package com.study.course_registration.support.fixture; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalTime; + +import com.study.course_registration.entity.Lesson; +import com.study.course_registration.entity.LessonSchedule; +import com.study.course_registration.entity.Professor; +import com.study.course_registration.entity.Semester; +import com.study.course_registration.entity.Subject; +import com.study.course_registration.entity.User; +import com.study.course_registration.entity.UserLesson; +import com.study.course_registration.enums.UserRole; + +public final class DomainFixtures { + private DomainFixtures() {} + + public static Semester openSemester() { + return openSemester(null, "2026-2", 18); + } + + public static Semester openSemester(int maxCredits) { + return openSemester(null, "semester-" + maxCredits, maxCredits); + } + + public static Semester openSemester(String id, String name, int maxCredits) { + return new Semester(id, name, TestData.TODAY.minusDays(20), TestData.TODAY.plusDays(100), + TestData.NOW.minusSeconds(3600), TestData.NOW.plusSeconds(3600), maxCredits); + } + + public static Semester closedSemester() { + return closedSemester(null, "closed"); + } + + public static Semester closedSemester(String id, String name) { + return new Semester(id, name, TestData.TODAY.minusDays(100), TestData.TODAY.plusDays(100), + TestData.NOW.minusSeconds(7200), TestData.NOW.minusSeconds(3600), 18); + } + + public static Semester academicSemester(String name) { + return new Semester(name, TestData.TODAY.minusDays(10), TestData.TODAY.plusDays(10), + TestData.NOW.minusSeconds(7200), TestData.NOW.minusSeconds(3600), 18); + } + + public static Semester futureAcademicSemesterWithOpenRegistration() { + return new Semester("future-open", TestData.TODAY.plusDays(30), TestData.TODAY.plusDays(150), + TestData.NOW.minusSeconds(3600), TestData.NOW.plusSeconds(3600), 18); + } + + public static Semester semester( + String id, + String name, + LocalDate startDate, + LocalDate endDate, + long registrationStartOffsetSeconds, + long registrationEndOffsetSeconds, + int maxCredits) { + return new Semester(id, name, startDate, endDate, + TestData.NOW.plusSeconds(registrationStartOffsetSeconds), + TestData.NOW.plusSeconds(registrationEndOffsetSeconds), + maxCredits); + } + + public static Professor professor() { + return new Professor("교수"); + } + + public static Professor professor(String id) { + return new Professor(id, "교수-" + id); + } + + public static Subject subject(String code) { + return subject(code, 3); + } + + public static Subject subject(String code, int credit) { + return new Subject(code, code, code + " 설명", credit); + } + + public static Subject subject(String id, String code, int credit) { + return new Subject(id, code, code, code + " 설명", credit); + } + + public static User student(long grade) { + return new User("학생-" + grade, grade, UserRole.STUDENT); + } + + public static User student(String id, long grade) { + return new User(id, "학생-" + id, grade, UserRole.STUDENT); + } + + public static User studentNamed(String name, long grade) { + return new User(name, grade, UserRole.STUDENT); + } + + public static User postgraduate() { + return new User("대학원생", 3L, UserRole.POSTGRADUATE); + } + + public static Lesson lesson(Subject subject, Professor professor, Semester semester) { + return lesson(null, subject.getCode() + " 강의", subject, professor, semester, 30, null, null); + } + + public static Lesson lesson(Subject subject, Professor professor, Semester semester, int capacity) { + return lesson(null, subject.getCode() + " 강의", subject, professor, semester, capacity, null, null); + } + + public static Lesson lesson( + String id, + String name, + Subject subject, + Professor professor, + Semester semester, + int capacity, + Long minGrade, + UserRole allowedRole) { + return new Lesson(id, name, subject, professor, semester, capacity, minGrade, allowedRole); + } + + public static LessonSchedule schedule(Lesson lesson, DayOfWeek day, int startHour, int endHour) { + return new LessonSchedule(lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0)); + } + + public static LessonSchedule schedule(String id, Lesson lesson, DayOfWeek day, int startHour, int endHour) { + return new LessonSchedule(id, lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0)); + } + + public static LessonSchedule schedule(DayOfWeek day, int startHour, int endHour) { + Semester semester = openSemester("fixture-semester-" + day + startHour, "fixture-" + day + startHour, 18); + Subject subject = subject("fixture-subject-" + day + startHour, "FIX" + day.getValue() + startHour, 3); + Lesson lesson = lesson( + "fixture-lesson-" + day + startHour, + "fixture-lesson", + subject, + professor("fixture-professor-" + day + startHour), + semester, + 30, + null, + null); + return schedule("fixture-schedule-" + day + startHour, lesson, day, startHour, endHour); + } + + public static UserLesson registration(User user, Lesson lesson) { + return new UserLesson(user, lesson); + } + + public static UserLesson registration(String id, User user, Lesson lesson) { + return new UserLesson(id, user, lesson); + } +} diff --git a/src/test/java/com/study/course_registration/support/fixture/TestData.java b/src/test/java/com/study/course_registration/support/fixture/TestData.java new file mode 100644 index 0000000..b879956 --- /dev/null +++ b/src/test/java/com/study/course_registration/support/fixture/TestData.java @@ -0,0 +1,11 @@ +package com.study.course_registration.support.fixture; + +import java.time.Instant; +import java.time.LocalDate; + +public final class TestData { + public static final Instant NOW = Instant.parse("2026-09-21T03:00:00Z"); + public static final LocalDate TODAY = LocalDate.of(2026, 9, 21); + + private TestData() {} +} diff --git a/src/test/java/com/study/course_registration/support/fixture/TestFixtureConfig.java b/src/test/java/com/study/course_registration/support/fixture/TestFixtureConfig.java new file mode 100644 index 0000000..5205254 --- /dev/null +++ b/src/test/java/com/study/course_registration/support/fixture/TestFixtureConfig.java @@ -0,0 +1,34 @@ +package com.study.course_registration.support.fixture; + +import java.time.Clock; +import java.time.ZoneOffset; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +import com.study.course_registration.repository.LessonRepository; +import com.study.course_registration.repository.LessonScheduleRepository; +import com.study.course_registration.repository.ProfessorRepository; +import com.study.course_registration.repository.RegistrationIdempotencyRepository; +import com.study.course_registration.repository.SemesterRepository; +import com.study.course_registration.repository.SubjectRepository; +import com.study.course_registration.repository.UserLessonRepository; +import com.study.course_registration.repository.UserRepository; + +@TestConfiguration(proxyBeanMethods = false) +public class TestFixtureConfig { + @Bean + @Primary + Clock testClock() { + return Clock.fixed(TestData.NOW, ZoneOffset.UTC); + } + + @Bean + DatabaseFixture databaseFixture(RegistrationIdempotencyRepository idempotencies, + UserLessonRepository registrations, LessonScheduleRepository schedules, + LessonRepository lessons, SubjectRepository subjects, ProfessorRepository professors, + SemesterRepository semesters, UserRepository users) { + return new DatabaseFixture(idempotencies, registrations, schedules, lessons, subjects, professors, semesters, users); + } +} diff --git a/src/test/java/com/study/course_registration/support/http/ApiError.java b/src/test/java/com/study/course_registration/support/http/ApiError.java index 662573c..5668ade 100644 --- a/src/test/java/com/study/course_registration/support/http/ApiError.java +++ b/src/test/java/com/study/course_registration/support/http/ApiError.java @@ -1,39 +1,29 @@ package com.study.course_registration.support.http; -/** - * HTTP 응답이 4xx/5xx일 때 {@link JsonApi}가 던지는 예외. - * - *

HTTP는 예외를 던지지 않는다. 409는 던져진 게 아니라 반환된 값이다. - * 그대로 두면 단위·통합 계층과 표현법이 갈라지므로, 여기서 "거부 = 예외"로 번역해 - * {@code Scenario.given(...).when(...).then(...)} 한 가지 흐름으로 읽히게 한다. - * - *

상태코드를 잃지 않도록 {@link #status()}를 그대로 들고 있는다. HTTP 계층에서만 - * 볼 수 있는 값이 그것이기 때문이다. - */ +import java.util.Set; + +import com.jayway.jsonpath.JsonPath; + public final class ApiError extends RuntimeException { private final int status; private final String code; private final String detail; + private final String raw; - ApiError(int status, String code, String detail) { + ApiError(int status, String code, String detail, String raw) { super("HTTP " + status + " " + code + " — " + detail); this.status = status; this.code = code; this.detail = detail; + this.raw = raw; } - /** 실제로 내려온 HTTP 상태코드 */ - public int status() { - return status; - } + public int status() { return status; } + public String code() { return code; } + public String detail() { return detail; } + public String raw() { return raw; } - /** 응답 바디의 code 필드 (문자열 그대로. enum 변환은 도메인 쪽이 한다) */ - public String code() { - return code; - } - - /** 응답 바디의 message 필드 */ - public String detail() { - return detail; + public Set fieldNames() { + return JsonPath.>read(raw, "$.keys()"); } } diff --git a/src/test/java/com/study/course_registration/support/http/JsonApi.java b/src/test/java/com/study/course_registration/support/http/JsonApi.java index ad20d7f..d502692 100644 --- a/src/test/java/com/study/course_registration/support/http/JsonApi.java +++ b/src/test/java/com/study/course_registration/support/http/JsonApi.java @@ -10,14 +10,6 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.jayway.jsonpath.JsonPath; -/** - * MockMvc를 감싸 "2xx면 바디를 돌려주고, 4xx/5xx면 {@link ApiError}를 던지는" 클라이언트. - * - *

도메인을 모른다. 어떤 프로젝트의 어떤 엔드포인트에도 그대로 쓸 수 있고, - * 에러 바디가 {@code code}/{@code message} 필드를 갖는다는 것만 전제한다. - * - *

MockMvc를 여기서만 부르므로, 안쪽 API를 나중에 바꿔도 테스트는 그대로다. - */ public final class JsonApi { private final MockMvc mockMvc; @@ -26,7 +18,12 @@ public final class JsonApi { } public JsonBody post(String path, String jsonBody) { + return exchange(MockMvcRequestBuilders.post(path).contentType(MediaType.APPLICATION_JSON).content(jsonBody)); + } + + public JsonBody post(String path, String jsonBody, String idempotencyKey) { return exchange(MockMvcRequestBuilders.post(path) + .header("Idempotency-Key", idempotencyKey) .contentType(MediaType.APPLICATION_JSON) .content(jsonBody)); } @@ -43,13 +40,13 @@ public final class JsonApi { MockHttpServletResponse response; try { response = mockMvc.perform(request).andReturn().getResponse(); - } catch (Exception e) { - throw new IllegalStateException("요청을 보내지 못했다: " + request, e); + } catch (Exception exception) { + throw new IllegalStateException("요청을 보내지 못했습니다.", exception); } String body = readBody(response); if (response.getStatus() >= 400) { - throw new ApiError(response.getStatus(), readField(body, "$.code"), readField(body, "$.message")); + throw new ApiError(response.getStatus(), readField(body, "$.code"), readField(body, "$.message"), body); } return new JsonBody(response.getStatus(), body); } @@ -58,19 +55,17 @@ public final class JsonApi { try { response.setCharacterEncoding(StandardCharsets.UTF_8.name()); return response.getContentAsString(StandardCharsets.UTF_8); - } catch (Exception e) { - throw new IllegalStateException("응답 본문을 읽지 못했다", e); + } catch (Exception exception) { + throw new IllegalStateException("응답 본문을 읽지 못했습니다.", exception); } } private static String readField(String body, String path) { - if (body == null || body.isBlank()) { - return "(빈 응답 본문)"; - } + if (body == null || body.isBlank()) return "(빈 응답 본문)"; try { return String.valueOf(JsonPath.read(body, path)); - } catch (RuntimeException e) { - return "(" + path + " 없음: " + body + ")"; + } catch (RuntimeException exception) { + return "(" + path + " 없음)"; } } } diff --git a/src/test/java/com/study/course_registration/support/http/JsonBody.java b/src/test/java/com/study/course_registration/support/http/JsonBody.java index f3d2741..3e19604 100644 --- a/src/test/java/com/study/course_registration/support/http/JsonBody.java +++ b/src/test/java/com/study/course_registration/support/http/JsonBody.java @@ -2,16 +2,8 @@ package com.study.course_registration.support.http; import java.util.Set; -import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; -/** - * 2xx 응답. 상태코드와 본문을 함께 들고 있다. - * - *

상태코드를 여기 싣는 이유: {@code thenAccepted()}는 "거부되지 않았다"까지만 판정한다. - * 201과 200을 구분하는 건 그 다음 질문이고, 그 질문에 답할 값이 없으면 - * "201을 돌려준다"고 이름 붙인 테스트가 200에서도 통과한다. - */ public final class JsonBody { private final int status; private final String raw; @@ -21,28 +13,8 @@ public final class JsonBody { this.raw = raw; } - /** 실제로 내려온 HTTP 상태코드 */ - public int status() { - return status; - } - - /** 예: {@code body.at("$.totalCredits")} */ - public T at(String jsonPath) { - return JsonPath.read(raw, jsonPath); - } - - /** - * 최상위 필드 이름 전부. 응답 스키마를 통째로 고정할 때 쓴다. - * - *

값이 아니라 이름을 보는 이유: 필드 이름은 클라이언트와의 계약이다. - * 값 몇 개만 확인하면 이름이 바뀌어도 테스트가 통과한다. - */ - public Set fieldNames() { - DocumentContext ctx = JsonPath.parse(raw); - return ctx.read("$.keys()", Set.class); - } - - public String raw() { - return raw; - } + public int status() { return status; } + public T at(String jsonPath) { return JsonPath.read(raw, jsonPath); } + public Set fieldNames() { return JsonPath.read(raw, "$.keys()"); } + public String raw() { return raw; } } diff --git a/src/test/resources/application-test.yaml b/src/test/resources/application-test.yaml index b47c982..06412ff 100644 --- a/src/test/resources/application-test.yaml +++ b/src/test/resources/application-test.yaml @@ -1,19 +1,25 @@ spring: datasource: url: jdbc:h2:mem:course_test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;LOCK_TIMEOUT=3000 - driver-class-name: org.h2.Driver username: sa password: + flyway: + locations: classpath:db/migration/h2 jpa: - hibernate: - ddl-auto: create-drop open-in-view: false + hibernate: + ddl-auto: validate + properties: + hibernate: + generate_statistics: true h2: console: enabled: false + app: seed: enabled: false + springdoc: api-docs: enabled: false diff --git a/src/test/resources/seed/test/malformed.tsv b/src/test/resources/seed/test/malformed.tsv new file mode 100644 index 0000000..4749fe9 --- /dev/null +++ b/src/test/resources/seed/test/malformed.tsv @@ -0,0 +1,2 @@ +a b +1 diff --git a/src/test/resources/seed/test/valid.tsv b/src/test/resources/seed/test/valid.tsv new file mode 100644 index 0000000..5b2a587 --- /dev/null +++ b/src/test/resources/seed/test/valid.tsv @@ -0,0 +1,2 @@ +name optional number +alpha 3