# course-registration Spring Boot 4.1.1 / Java 21 기반 수강신청 API입니다. 핵심은 CRUD 개수보다 수강신청 거부 규칙(R1~R8)과 동시 신청 시 정원·학점·시간표 정확성을 지키는 것입니다. ## Scope - 수강신청(Create) - 내 신청 / 강의 목록·상세(Read) - 수강취소(Delete, soft cancel) - 신청 수정(Update) 없음 — 취소 후 재신청 - 마스터 데이터 CRUD 없음 - 인증/JWT 없음 - k6 부하 테스트는 후속 범위 상세 규칙은 docs/Requirements.md를 기준으로 합니다. ## Local profile은 자동 선택하지 않습니다. 런타임에서는 `local/dev/prod` 중 정확히 하나만 허용하고, 테스트에서는 `test` profile만 사용합니다. 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: 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 profile이나 DB 설정이 빠진 상태로 조용히 H2를 사용하는 것을 막기 위해 공통 설정에는 기본 profile을 두지 않습니다. ## Dev with PostgreSQL cp .env.example .env docker compose up --build 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 | Schema | Seeder | Swagger | |---|---|---|---|---| | local | H2 | Flyway + validate | ON | ON | | dev | PostgreSQL | Flyway + validate | APP_SEED_ENABLED | ON | | prod | PostgreSQL | Flyway + validate | OFF | 기본 OFF | ## Seed dataset seed 데이터는 Java 코드에 하드코딩하지 않습니다. src/main/resources/seed/demo/ semesters.tsv professors.tsv subjects.tsv users.tsv lessons.tsv schedules.tsv 데이터가 늘어나면 TSV 행을 추가합니다. DataSeeder는 파일을 읽고 관계를 조립하는 역할만 합니다. demo 데이터셋의 학기/신청기간은 넓은 고정 범위로 TSV에 명시하므로 DB 볼륨을 오래 유지해도 부팅 시점에 따라 만료되지 않습니다. 동시에 여러 인스턴스가 seed를 시도해도 seed_locks row를 FOR UPDATE로 잠근 뒤 실행하므로 중복 seed를 직렬화합니다. ## API 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} ### Idempotent registration POST는 선택적으로 Idempotency-Key 헤더를 받습니다. Idempotency-Key: registration-request-001 - 보존 기간은 24시간이다. - TTL 안에서 같은 사용자 + 같은 key + 같은 lesson 재시도 → 최초 201 결과 재사용 - 최초 신청을 이후 취소했더라도 TTL 안의 같은 key 재시도는 **새 신청을 만들지 않고 최초 POST 결과를 replay** - TTL 안에서 같은 사용자 + 같은 key + 다른 lesson → 409 `IDEMPOTENCY_KEY_REUSED` - 만료 행은 주기적으로 정리하고, 만료된 key는 새 요청에서 다시 사용할 수 있다. - DELETE는 이미 취소된 건을 다시 취소해도 204 ## Architecture 런타임 경계는 다음 방향으로만 의존합니다. Web Controller / DTO / FailureHttpMapper -> Application UseCase / Query -> Domain Policy / ordered RegistrationRule -> Application Port -> Infrastructure JPA Adapter -> Spring Data Repository application action은 `RegisterCourseUseCase`, `CancelRegistrationUseCase`, `GetRegistrationsQuery`, `GetLessonsQuery`, `GetLessonQuery`, `CleanupIdempotencyUseCase`로 분리합니다. 수강신청 정책은 `RegistrationContext`를 입력으로 받고 `RegistrationPolicy`가 R1~R8의 관측 가능한 우선순서를 명시적인 ordered rule list로 유지합니다. 이 프로젝트는 **strict boundary**를 선택합니다. - Domain은 Spring/JPA에 의존하지 않는 plain Java다. - Application Port는 JPA Entity를 반환하지 않고 snapshot/read model만 반환한다. - Spring Data Repository와 JPA Entity mapping은 infrastructure 안에서 끝낸다. - Application은 `@Lock`, `Page`, projection, `EntityManager` 같은 persistence mechanism을 알지 않는다. - `ArchitectureTest`가 `application/domain -> entity`, `domain -> Spring`, `application -> Spring Data/JPA` 의존을 금지한다. 실패도 의미에 따라 분리합니다. - `KnownFailure` - `ApplicationFailure`: resource not found / business rejection / authorization / request validation - `RetryableInfrastructureFailure`: lock timeout처럼 재시도 가능한 infrastructure failure - `SystemInvariantViolation`: 중복 활성 학기, 필수 시간표 누락 등 사용자 재시도로 해결되지 않는 invariant 위반 - HTTP status는 `RegistrationErrorCode`가 아니라 Web의 `FailureHttpMapper`가 결정 - business rejection은 ERROR stacktrace를 남기지 않고 metric으로 집계 - retryable failure는 WARN, system invariant와 unexpected failure는 ERROR ## Concurrency invariant 신청 mutation은 다음 순서를 유지합니다. RegistrationExecutionScope 확보 -> Infrastructure에서 User FOR UPDATE -> Infrastructure에서 Lesson FOR UPDATE -> Idempotency 판정 -> replay면 즉시 반환 -> 신규 요청이면 RegistrationContext 조회 -> active registrations -> schedules -> capacity count -> R1~R8 검증 -> RegistrationWindowGuard 재검증 -> INSERT `RegistrationExecutionScopeLoader.open()`은 업무 용어만 노출하고 실제 `FOR UPDATE`는 `JpaRegistrationExecutionScopeLoader` 내부에 숨깁니다. replay 요청은 User/Lesson 직렬화와 idempotency lookup 뒤에 바로 끝나며 active/schedule/count query를 수행하지 않습니다. 취소도 Application에서는 `CancellationContextLoader.load()`만 호출하고, User → Lesson lock 순서는 `JpaCancellationContextLoader` 내부 책임입니다. ## Master data policy 현재 API에는 Semester/Subject/Professor/Lesson/User를 수정하는 마스터 CRUD가 없습니다. 신청 transaction은 User → Lesson을 락 쿼리로 **처음 읽는 것**을 전제로 합니다. 운영 규칙은 **수강신청 기간 동안 판정에 사용되는 master policy data를 수정하지 않는다**입니다. 대상은 최소한 `Subject.credit`, `Semester.maxCredits`, `Semester.registrationStartAt/registrationEndAt`, `Lesson.capacity/minGrade/allowedRole`, `LessonSchedule`입니다. 향후 관리자 수정 기능을 추가할 때는 이 freeze 규칙과 일관된 snapshot 보장 방식을 함께 재설계해야 합니다. ID는 현재 Java에서 `String UUID`, DB에서 `VARCHAR(36)`을 유지합니다. PostgreSQL native `uuid` 전환은 API/JPA 타입과 H2/PostgreSQL migration을 함께 바꾸는 별도 스키마 변경으로 분리합니다. ## Local seed IDs Semester 00000000-0000-0000-0000-000000000001 1학년 학생 30000000-0000-0000-0000-000000000001 2학년 학생 30000000-0000-0000-0000-000000000002 대학원생 30000000-0000-0000-0000-000000000003 자료구조 01분반 40000000-0000-0000-0000-000000000001 자료구조 02분반 40000000-0000-0000-0000-000000000002 운영체제 40000000-0000-0000-0000-000000000003 정원 1명 강의 40000000-0000-0000-0000-000000000004 최소 3학년 강의 40000000-0000-0000-0000-000000000005 대학원생 전용 강의 40000000-0000-0000-0000-000000000006 시간 경계 테스트 강의 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) / whenRunning(action) -> then(assertions) / thenRejectedWith fixture는 support/fixture에 모읍니다. - DomainFixtures: 순수 도메인 객체 - DatabaseFixture: DB에 저장된 테스트 데이터셋 - TestFixtureConfig: 고정 Clock - PostgresIntegrationTest: PostgreSQL Testcontainers 기반 통합 테스트 주요 테스트: - controller HTTP status/JSON 계약 - application UseCase/Query 신청·취소·조회 - repository 학기 scope/집계/DB unique - domain entity invariant - R1~R8 우선순위/경계값 - N+1 방지 쿼리 수 상한 - PostgreSQL 동시성 - 정원 1 / 동시 10명 - 정원 30 / 동시 50명 - 동일 학생 학점 경쟁 - 동일 학생 시간표 경쟁 - 동일 학생 동일 강의 경쟁 - Seeder 재실행 - execution scope loader의 User → Lesson 직렬화 순서 / strict architecture rule ./gradlew test ./gradlew jacocoTestReport ./gradlew build JaCoCo HTML은 build/reports/jacoco/test/html/index.html에서 확인합니다. ## Postman postman/ course-registration.postman_collection.json local.postman_environment.json dev.postman_environment.json Register lesson 성공 응답의 registrationId는 environment에 저장됩니다.