refactor: 도메인 rule로 관리하던 context 변경
This commit is contained in:
-24
@@ -1,24 +0,0 @@
|
||||
package com.study.course_registration.application.idempotency;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort;
|
||||
|
||||
@Service
|
||||
public class CleanupIdempotencyUseCase {
|
||||
private final Clock clock;
|
||||
private final IdempotencyPort idempotencies;
|
||||
|
||||
public CleanupIdempotencyUseCase(Clock clock, IdempotencyPort idempotencies) {
|
||||
this.clock = clock;
|
||||
this.idempotencies = idempotencies;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void execute() {
|
||||
idempotencies.deleteExpired(clock.instant());
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.study.course_registration.application.idempotency.port;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface IdempotencyPort {
|
||||
Optional<ReplayRecord> findActive(String userId, String key, Instant now);
|
||||
|
||||
void deleteExpiredKey(String userId, String key, Instant now);
|
||||
|
||||
void deleteExpired(Instant now);
|
||||
|
||||
void save(SaveCommand command);
|
||||
|
||||
record ReplayRecord(
|
||||
String registrationId,
|
||||
String userId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
int credit,
|
||||
Instant registeredAt,
|
||||
int totalCredits) {
|
||||
}
|
||||
|
||||
record SaveCommand(
|
||||
String userId,
|
||||
String lessonId,
|
||||
String registrationId,
|
||||
String key,
|
||||
int totalCredits,
|
||||
Instant expiresAt) {
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort.LessonDetailView;
|
||||
import com.study.course_registration.application.lesson.model.LessonDetailView;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
|
||||
@Service
|
||||
|
||||
@@ -7,8 +7,8 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.lesson.LessonListResult.LessonItemResult;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort.LessonListView;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort.LessonPage;
|
||||
import com.study.course_registration.application.lesson.model.LessonListView;
|
||||
import com.study.course_registration.application.lesson.model.LessonPage;
|
||||
import com.study.course_registration.application.semester.SemesterSelectionPolicy;
|
||||
import com.study.course_registration.application.semester.SemesterSnapshot;
|
||||
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.study.course_registration.application.lesson.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonDetailView(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
String subjectDescription,
|
||||
int credit,
|
||||
String professorName,
|
||||
String semesterName,
|
||||
int capacity,
|
||||
long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
Instant registrationStartAt,
|
||||
Instant registrationEndAt,
|
||||
List<ScheduleSlot> schedules) {
|
||||
|
||||
public LessonDetailView {
|
||||
schedules = List.copyOf(schedules);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.study.course_registration.application.lesson.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonListView(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
int credit,
|
||||
String professorName,
|
||||
int capacity,
|
||||
long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
List<ScheduleSlot> schedules) {
|
||||
|
||||
public LessonListView {
|
||||
schedules = List.copyOf(schedules);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.study.course_registration.application.lesson.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record LessonPage(
|
||||
List<LessonListView> lessons,
|
||||
long totalElements) {
|
||||
|
||||
public LessonPage {
|
||||
lessons = List.copyOf(lessons);
|
||||
}
|
||||
}
|
||||
+2
-41
@@ -1,51 +1,12 @@
|
||||
package com.study.course_registration.application.lesson.port;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
import com.study.course_registration.application.lesson.model.LessonDetailView;
|
||||
import com.study.course_registration.application.lesson.model.LessonPage;
|
||||
|
||||
public interface LessonQueryPort {
|
||||
LessonPage findPage(String semesterId, String subjectId, int page, int size);
|
||||
|
||||
Optional<LessonDetailView> findDetailed(String lessonId);
|
||||
|
||||
record LessonPage(
|
||||
List<LessonListView> lessons,
|
||||
long totalElements) {
|
||||
}
|
||||
|
||||
record LessonListView(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
int credit,
|
||||
String professorName,
|
||||
int capacity,
|
||||
long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
List<ScheduleSlot> schedules) {
|
||||
}
|
||||
|
||||
record LessonDetailView(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
String subjectDescription,
|
||||
int credit,
|
||||
String professorName,
|
||||
String semesterName,
|
||||
int capacity,
|
||||
long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
Instant registrationStartAt,
|
||||
Instant registrationEndAt,
|
||||
List<ScheduleSlot> schedules) {
|
||||
}
|
||||
}
|
||||
|
||||
+5
-2
@@ -6,6 +6,7 @@ import java.time.Instant;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.registration.model.CancellationTarget;
|
||||
import com.study.course_registration.application.registration.port.CancellationContextLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.domain.registration.CancellationContext;
|
||||
@@ -32,11 +33,13 @@ public class CancelRegistrationUseCase {
|
||||
|
||||
@Transactional
|
||||
public void execute(String userId, String registrationId) {
|
||||
CancellationContext context = contexts.load(registrationId);
|
||||
CancellationTarget target = contexts.findTarget(registrationId);
|
||||
|
||||
if (!context.ownerUserId().equals(userId)) {
|
||||
if (!target.ownerUserId().equals(userId)) {
|
||||
throw AuthorizationFailure.registrationForbidden();
|
||||
}
|
||||
|
||||
CancellationContext context = contexts.lock(target);
|
||||
if (context.canceled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.registration.RegistrationListResult.RegistrationItemResult;
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader.ActiveRegistrationView;
|
||||
import com.study.course_registration.application.registration.model.ActiveRegistrationView;
|
||||
import com.study.course_registration.application.semester.SemesterSelectionPolicy;
|
||||
import com.study.course_registration.application.semester.SemesterSnapshot;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
|
||||
+13
-11
@@ -6,14 +6,14 @@ import java.time.Instant;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.idempotency.IdempotencyCoordinator;
|
||||
import com.study.course_registration.application.idempotency.IdempotencyCoordinator.Decision;
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort.ReplayRecord;
|
||||
import com.study.course_registration.application.registration.port.RegistrationDecisionContextLoader;
|
||||
import com.study.course_registration.application.registration.idempotency.IdempotencyCoordinator;
|
||||
import com.study.course_registration.application.registration.idempotency.IdempotencyCoordinator.Decision;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencyReplay;
|
||||
import com.study.course_registration.application.registration.port.RegistrationDecisionSnapshotLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationExecutionScopeLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter.RegistrationRecord;
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.application.registration.model.RegistrationRecord;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationExecutionScope;
|
||||
import com.study.course_registration.domain.registration.RegistrationPolicy;
|
||||
import com.study.course_registration.domain.registration.RegistrationWindowGuard;
|
||||
@@ -22,7 +22,7 @@ import com.study.course_registration.domain.registration.RegistrationWindowGuard
|
||||
public class RegisterCourseUseCase {
|
||||
private final Clock clock;
|
||||
private final RegistrationExecutionScopeLoader executionScopes;
|
||||
private final RegistrationDecisionContextLoader decisionContexts;
|
||||
private final RegistrationDecisionSnapshotLoader decisionSnapshots;
|
||||
private final RegistrationWriter registrations;
|
||||
private final RegistrationPolicy registrationPolicy;
|
||||
private final RegistrationWindowGuard registrationWindowGuard;
|
||||
@@ -31,14 +31,14 @@ public class RegisterCourseUseCase {
|
||||
public RegisterCourseUseCase(
|
||||
Clock clock,
|
||||
RegistrationExecutionScopeLoader executionScopes,
|
||||
RegistrationDecisionContextLoader decisionContexts,
|
||||
RegistrationDecisionSnapshotLoader decisionSnapshots,
|
||||
RegistrationWriter registrations,
|
||||
RegistrationPolicy registrationPolicy,
|
||||
RegistrationWindowGuard registrationWindowGuard,
|
||||
IdempotencyCoordinator idempotency) {
|
||||
this.clock = clock;
|
||||
this.executionScopes = executionScopes;
|
||||
this.decisionContexts = decisionContexts;
|
||||
this.decisionSnapshots = decisionSnapshots;
|
||||
this.registrations = registrations;
|
||||
this.registrationPolicy = registrationPolicy;
|
||||
this.registrationWindowGuard = registrationWindowGuard;
|
||||
@@ -62,7 +62,9 @@ public class RegisterCourseUseCase {
|
||||
return replay(decision.replay().orElseThrow());
|
||||
}
|
||||
|
||||
RegistrationContext context = decisionContexts.load(scope, requestTime);
|
||||
executionScopes.lockLesson(scope);
|
||||
|
||||
RegistrationDecisionSnapshot context = decisionSnapshots.load(scope, requestTime);
|
||||
registrationPolicy.validate(context);
|
||||
|
||||
registrationWindowGuard.verify(context.lesson(), clock.instant());
|
||||
@@ -89,7 +91,7 @@ public class RegisterCourseUseCase {
|
||||
totalCredits);
|
||||
}
|
||||
|
||||
private static RegistrationResult replay(ReplayRecord stored) {
|
||||
private static RegistrationResult replay(IdempotencyReplay stored) {
|
||||
return new RegistrationResult(
|
||||
stored.registrationId(),
|
||||
stored.userId(),
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.study.course_registration.application.registration.idempotency;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.registration.idempotency.port.IdempotencyPort;
|
||||
|
||||
@Service
|
||||
public class CleanupIdempotencyUseCase {
|
||||
private final Clock clock;
|
||||
private final IdempotencyPort idempotencies;
|
||||
private final int batchSize;
|
||||
|
||||
public CleanupIdempotencyUseCase(
|
||||
Clock clock,
|
||||
IdempotencyPort idempotencies,
|
||||
@Value("${app.idempotency.cleanup-batch-size:500}") int batchSize) {
|
||||
this.clock = clock;
|
||||
this.idempotencies = idempotencies;
|
||||
this.batchSize = batchSize;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public int execute() {
|
||||
return idempotencies.deleteExpiredBatch(clock.instant(), batchSize);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.study.course_registration.application.registration.idempotency;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.failure.ApplicationFailure;
|
||||
|
||||
public final class IdempotencyConflict extends ApplicationFailure {
|
||||
private IdempotencyConflict(String message) {
|
||||
super(RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED, message);
|
||||
}
|
||||
|
||||
public static IdempotencyConflict reusedForDifferentLesson() {
|
||||
return new IdempotencyConflict(
|
||||
"동일한 Idempotency-Key를 다른 강의에 사용할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
+20
-17
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.application.idempotency;
|
||||
package com.study.course_registration.application.registration.idempotency;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
@@ -6,12 +6,11 @@ import java.util.Optional;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort.ReplayRecord;
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort.SaveCommand;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter.RegistrationRecord;
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencyReplay;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencySaveCommand;
|
||||
import com.study.course_registration.application.registration.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.application.registration.model.RegistrationRecord;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.failure.RequestValidationFailure;
|
||||
|
||||
@Component
|
||||
@@ -21,7 +20,7 @@ public class IdempotencyCoordinator {
|
||||
|
||||
public IdempotencyCoordinator(
|
||||
IdempotencyPort idempotencies,
|
||||
@Value("$" + "{app.idempotency.ttl-seconds:86400}") long ttlSeconds) {
|
||||
@Value("${app.idempotency.ttl-seconds:86400}") long ttlSeconds) {
|
||||
this.idempotencies = idempotencies;
|
||||
this.ttlSeconds = ttlSeconds;
|
||||
}
|
||||
@@ -33,21 +32,21 @@ public class IdempotencyCoordinator {
|
||||
}
|
||||
|
||||
idempotencies.deleteExpiredKey(userId, key, now);
|
||||
Optional<ReplayRecord> previous = idempotencies.findActive(userId, key, now);
|
||||
Optional<IdempotencyReplay> previous = idempotencies.findActive(userId, key, now);
|
||||
if (previous.isEmpty()) {
|
||||
return Decision.newRequest(key);
|
||||
}
|
||||
|
||||
ReplayRecord stored = previous.get();
|
||||
IdempotencyReplay stored = previous.get();
|
||||
if (!stored.lessonId().equals(lessonId)) {
|
||||
throw BusinessRejection.idempotencyKeyReused();
|
||||
throw IdempotencyConflict.reusedForDifferentLesson();
|
||||
}
|
||||
return Decision.replay(key, stored);
|
||||
}
|
||||
|
||||
public void record(
|
||||
Decision decision,
|
||||
RegistrationContext context,
|
||||
RegistrationDecisionSnapshot snapshot,
|
||||
RegistrationRecord registration,
|
||||
int totalCredits,
|
||||
Instant now) {
|
||||
@@ -55,11 +54,15 @@ public class IdempotencyCoordinator {
|
||||
return;
|
||||
}
|
||||
|
||||
idempotencies.save(new SaveCommand(
|
||||
context.user().id(),
|
||||
context.lesson().id(),
|
||||
idempotencies.save(new IdempotencySaveCommand(
|
||||
snapshot.user().id(),
|
||||
snapshot.lesson().id(),
|
||||
registration.registrationId(),
|
||||
decision.key(),
|
||||
snapshot.lesson().name(),
|
||||
snapshot.lesson().subjectCode(),
|
||||
snapshot.lesson().subjectCredit(),
|
||||
registration.registeredAt(),
|
||||
totalCredits,
|
||||
now.plusSeconds(ttlSeconds)));
|
||||
}
|
||||
@@ -77,7 +80,7 @@ public class IdempotencyCoordinator {
|
||||
|
||||
public record Decision(
|
||||
String key,
|
||||
Optional<ReplayRecord> replay) {
|
||||
Optional<IdempotencyReplay> replay) {
|
||||
|
||||
static Decision withoutKey() {
|
||||
return new Decision(null, Optional.empty());
|
||||
@@ -87,7 +90,7 @@ public class IdempotencyCoordinator {
|
||||
return new Decision(key, Optional.empty());
|
||||
}
|
||||
|
||||
static Decision replay(String key, ReplayRecord stored) {
|
||||
static Decision replay(String key, IdempotencyReplay stored) {
|
||||
return new Decision(key, Optional.of(stored));
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.study.course_registration.application.registration.idempotency.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record IdempotencyReplay(
|
||||
String registrationId,
|
||||
String userId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
int credit,
|
||||
Instant registeredAt,
|
||||
int totalCredits) {
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.study.course_registration.application.registration.idempotency.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record IdempotencySaveCommand(
|
||||
String userId,
|
||||
String lessonId,
|
||||
String registrationId,
|
||||
String key,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
int credit,
|
||||
Instant registeredAt,
|
||||
int totalCredits,
|
||||
Instant expiresAt) {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.study.course_registration.application.registration.idempotency.port;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencyReplay;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencySaveCommand;
|
||||
|
||||
public interface IdempotencyPort {
|
||||
Optional<IdempotencyReplay> findActive(String userId, String key, Instant now);
|
||||
|
||||
void deleteExpiredKey(String userId, String key, Instant now);
|
||||
|
||||
int deleteExpiredBatch(Instant now, int batchSize);
|
||||
|
||||
void save(IdempotencySaveCommand command);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.study.course_registration.application.registration.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
|
||||
public record ActiveRegistrationView(
|
||||
String registrationId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
int credit,
|
||||
String professorName,
|
||||
List<ScheduleSlot> schedules,
|
||||
Instant registeredAt) {
|
||||
|
||||
public ActiveRegistrationView {
|
||||
schedules = List.copyOf(schedules);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.study.course_registration.application.registration.model;
|
||||
|
||||
public record CancellationTarget(
|
||||
String registrationId,
|
||||
String ownerUserId,
|
||||
String lessonId) {
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.study.course_registration.application.registration.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record RegistrationRecord(
|
||||
String registrationId,
|
||||
Instant registeredAt) {
|
||||
}
|
||||
+4
-1
@@ -1,7 +1,10 @@
|
||||
package com.study.course_registration.application.registration.port;
|
||||
|
||||
import com.study.course_registration.application.registration.model.CancellationTarget;
|
||||
import com.study.course_registration.domain.registration.CancellationContext;
|
||||
|
||||
public interface CancellationContextLoader {
|
||||
CancellationContext load(String registrationId);
|
||||
CancellationTarget findTarget(String registrationId);
|
||||
|
||||
CancellationContext lock(CancellationTarget target);
|
||||
}
|
||||
|
||||
+3
-3
@@ -2,9 +2,9 @@ package com.study.course_registration.application.registration.port;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationExecutionScope;
|
||||
|
||||
public interface RegistrationDecisionContextLoader {
|
||||
RegistrationContext load(RegistrationExecutionScope scope, Instant now);
|
||||
public interface RegistrationDecisionSnapshotLoader {
|
||||
RegistrationDecisionSnapshot load(RegistrationExecutionScope scope, Instant now);
|
||||
}
|
||||
+2
@@ -4,4 +4,6 @@ import com.study.course_registration.domain.registration.RegistrationExecutionSc
|
||||
|
||||
public interface RegistrationExecutionScopeLoader {
|
||||
RegistrationExecutionScope open(String userId, String lessonId);
|
||||
|
||||
void lockLesson(RegistrationExecutionScope scope);
|
||||
}
|
||||
|
||||
+1
-14
@@ -1,24 +1,11 @@
|
||||
package com.study.course_registration.application.registration.port;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
import com.study.course_registration.application.registration.model.ActiveRegistrationView;
|
||||
|
||||
public interface RegistrationReader {
|
||||
boolean userExists(String userId);
|
||||
|
||||
List<ActiveRegistrationView> findActive(String userId, String semesterId);
|
||||
|
||||
record ActiveRegistrationView(
|
||||
String registrationId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
int credit,
|
||||
String professorName,
|
||||
List<ScheduleSlot> schedules,
|
||||
Instant registeredAt) {
|
||||
}
|
||||
}
|
||||
|
||||
+2
-5
@@ -2,13 +2,10 @@ package com.study.course_registration.application.registration.port;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import com.study.course_registration.application.registration.model.RegistrationRecord;
|
||||
|
||||
public interface RegistrationWriter {
|
||||
RegistrationRecord create(String userId, String lessonId);
|
||||
|
||||
void cancel(String registrationId, Instant canceledAt);
|
||||
|
||||
record RegistrationRecord(
|
||||
String registrationId,
|
||||
Instant registeredAt) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,6 @@ import com.study.course_registration.domain.registration.rule.AlreadyRegisteredR
|
||||
import com.study.course_registration.domain.registration.rule.CapacityRule;
|
||||
import com.study.course_registration.domain.registration.rule.CreditLimitRule;
|
||||
import com.study.course_registration.domain.registration.rule.DuplicateSubjectRule;
|
||||
import com.study.course_registration.domain.registration.rule.GradeEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.RegistrationPeriodRule;
|
||||
import com.study.course_registration.domain.registration.rule.RoleEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleAvailabilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleConflictRule;
|
||||
import com.study.course_registration.domain.schedule.LessonSchedulePolicy;
|
||||
@@ -37,9 +34,6 @@ public class DomainPolicyConfig {
|
||||
@Bean
|
||||
RegistrationPolicy registrationPolicy(ScheduleConflictChecker checker) {
|
||||
return new RegistrationPolicy(
|
||||
new RegistrationPeriodRule(),
|
||||
new GradeEligibilityRule(),
|
||||
new RoleEligibilityRule(),
|
||||
new AlreadyRegisteredRule(),
|
||||
new DuplicateSubjectRule(),
|
||||
new ScheduleAvailabilityRule(),
|
||||
|
||||
-1
@@ -1,7 +1,6 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
public record CancellationContext(
|
||||
String ownerUserId,
|
||||
String registrationId,
|
||||
LessonPolicySnapshot lesson,
|
||||
boolean canceled) {
|
||||
|
||||
+43
@@ -1,6 +1,7 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
@@ -17,4 +18,46 @@ public record LessonPolicySnapshot(
|
||||
int capacity,
|
||||
Long minGrade,
|
||||
UserRole allowedRole) {
|
||||
|
||||
public LessonPolicySnapshot {
|
||||
Objects.requireNonNull(id, "id");
|
||||
Objects.requireNonNull(name, "name");
|
||||
Objects.requireNonNull(subjectId, "subjectId");
|
||||
Objects.requireNonNull(subjectCode, "subjectCode");
|
||||
Objects.requireNonNull(semesterId, "semesterId");
|
||||
Objects.requireNonNull(registrationStartAt, "registrationStartAt");
|
||||
Objects.requireNonNull(registrationEndAt, "registrationEndAt");
|
||||
if (subjectCredit < 1) {
|
||||
throw new IllegalArgumentException("subjectCredit must be at least 1");
|
||||
}
|
||||
if (maxCredits < 1) {
|
||||
throw new IllegalArgumentException("maxCredits must be at least 1");
|
||||
}
|
||||
if (capacity < 1) {
|
||||
throw new IllegalArgumentException("capacity must be at least 1");
|
||||
}
|
||||
if (minGrade != null && minGrade < 1) {
|
||||
throw new IllegalArgumentException("minGrade must be at least 1");
|
||||
}
|
||||
if (!registrationStartAt.isBefore(registrationEndAt)) {
|
||||
throw new IllegalArgumentException("registrationStartAt must be before registrationEndAt");
|
||||
}
|
||||
}
|
||||
|
||||
public void verifyRegistrationWindow(Instant now) {
|
||||
Objects.requireNonNull(now, "now");
|
||||
if (now.isBefore(registrationStartAt) || now.isAfter(registrationEndAt)) {
|
||||
throw RegistrationRejection.registrationPeriodClosed();
|
||||
}
|
||||
}
|
||||
|
||||
public void verifyStudentEligibility(UserProfile user) {
|
||||
Objects.requireNonNull(user, "user");
|
||||
if (minGrade != null && user.grade() < minGrade) {
|
||||
throw RegistrationRejection.notEligibleGrade(user.grade(), minGrade);
|
||||
}
|
||||
if (allowedRole != null && user.role() != allowedRole) {
|
||||
throw RegistrationRejection.notEligibleRole(allowedRole);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
|
||||
public record RegistrationContext(
|
||||
UserProfile user,
|
||||
LessonPolicySnapshot lesson,
|
||||
List<ActiveRegistrationSnapshot> activeRegistrations,
|
||||
Map<String, List<ScheduleSlot>> schedulesByLessonId,
|
||||
long enrolledCount,
|
||||
Instant now) {
|
||||
|
||||
public List<ScheduleSlot> candidateSchedules() {
|
||||
return schedulesByLessonId.getOrDefault(lesson.id(), List.of());
|
||||
}
|
||||
|
||||
public List<ScheduleSlot> schedulesOf(ActiveRegistrationSnapshot registration) {
|
||||
return schedulesByLessonId.getOrDefault(registration.lessonId(), List.of());
|
||||
}
|
||||
|
||||
public int currentCredits() {
|
||||
return activeRegistrations.stream()
|
||||
.mapToInt(ActiveRegistrationSnapshot::credit)
|
||||
.sum();
|
||||
}
|
||||
|
||||
public int totalCreditsAfter() {
|
||||
return currentCredits() + lesson.subjectCredit();
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
|
||||
public record RegistrationDecisionSnapshot(
|
||||
UserProfile user,
|
||||
LessonPolicySnapshot lesson,
|
||||
List<ActiveRegistrationSnapshot> activeRegistrations,
|
||||
Map<String, List<ScheduleSlot>> schedulesByLessonId,
|
||||
long enrolledCount,
|
||||
Instant now) {
|
||||
|
||||
public RegistrationDecisionSnapshot {
|
||||
Objects.requireNonNull(user, "user");
|
||||
Objects.requireNonNull(lesson, "lesson");
|
||||
Objects.requireNonNull(activeRegistrations, "activeRegistrations");
|
||||
Objects.requireNonNull(schedulesByLessonId, "schedulesByLessonId");
|
||||
Objects.requireNonNull(now, "now");
|
||||
if (enrolledCount < 0) {
|
||||
throw RegistrationInvariantViolation.negativeEnrolledCount();
|
||||
}
|
||||
|
||||
activeRegistrations = List.copyOf(activeRegistrations);
|
||||
Map<String, List<ScheduleSlot>> copiedSchedules = new LinkedHashMap<>();
|
||||
schedulesByLessonId.forEach((lessonId, slots) -> copiedSchedules.put(
|
||||
Objects.requireNonNull(lessonId, "schedule lessonId"),
|
||||
List.copyOf(Objects.requireNonNull(slots, "schedule slots"))));
|
||||
schedulesByLessonId = Collections.unmodifiableMap(copiedSchedules);
|
||||
}
|
||||
|
||||
public List<ScheduleSlot> candidateSchedules() {
|
||||
return schedulesByLessonId.getOrDefault(lesson.id(), List.of());
|
||||
}
|
||||
|
||||
public List<ScheduleSlot> schedulesOf(ActiveRegistrationSnapshot registration) {
|
||||
return schedulesByLessonId.getOrDefault(registration.lessonId(), List.of());
|
||||
}
|
||||
|
||||
public int currentCredits() {
|
||||
return activeRegistrations.stream()
|
||||
.mapToInt(ActiveRegistrationSnapshot::credit)
|
||||
.sum();
|
||||
}
|
||||
|
||||
public int totalCreditsAfter() {
|
||||
return currentCredits() + lesson.subjectCredit();
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
public enum RegistrationInvariant {
|
||||
NEGATIVE_ENROLLED_COUNT,
|
||||
MISSING_CANDIDATE_LESSON_SCHEDULE,
|
||||
MISSING_EXISTING_LESSON_SCHEDULE
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
public final class RegistrationInvariantViolation extends RuntimeException {
|
||||
private final RegistrationInvariant invariant;
|
||||
|
||||
private RegistrationInvariantViolation(RegistrationInvariant invariant, String message) {
|
||||
super(message);
|
||||
this.invariant = invariant;
|
||||
}
|
||||
|
||||
public static RegistrationInvariantViolation negativeEnrolledCount() {
|
||||
return new RegistrationInvariantViolation(
|
||||
RegistrationInvariant.NEGATIVE_ENROLLED_COUNT,
|
||||
"수강 인원 수는 음수일 수 없습니다.");
|
||||
}
|
||||
|
||||
public static RegistrationInvariantViolation missingCandidateSchedule() {
|
||||
return new RegistrationInvariantViolation(
|
||||
RegistrationInvariant.MISSING_CANDIDATE_LESSON_SCHEDULE,
|
||||
"신청 가능한 강의에 시간표가 없습니다.");
|
||||
}
|
||||
|
||||
public static RegistrationInvariantViolation missingExistingSchedule() {
|
||||
return new RegistrationInvariantViolation(
|
||||
RegistrationInvariant.MISSING_EXISTING_LESSON_SCHEDULE,
|
||||
"기존 신청 강의에 시간표가 없습니다.");
|
||||
}
|
||||
|
||||
public RegistrationInvariant invariant() {
|
||||
return invariant;
|
||||
}
|
||||
}
|
||||
+28
-27
@@ -1,43 +1,44 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.domain.registration.rule.AlreadyRegisteredRule;
|
||||
import com.study.course_registration.domain.registration.rule.CapacityRule;
|
||||
import com.study.course_registration.domain.registration.rule.CreditLimitRule;
|
||||
import com.study.course_registration.domain.registration.rule.DuplicateSubjectRule;
|
||||
import com.study.course_registration.domain.registration.rule.GradeEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.RegistrationPeriodRule;
|
||||
import com.study.course_registration.domain.registration.rule.RoleEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleAvailabilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleConflictRule;
|
||||
|
||||
public final class RegistrationPolicy {
|
||||
private final List<RegistrationRule> orderedRules;
|
||||
private final AlreadyRegisteredRule alreadyRegistered;
|
||||
private final DuplicateSubjectRule duplicateSubject;
|
||||
private final ScheduleAvailabilityRule scheduleAvailability;
|
||||
private final ScheduleConflictRule scheduleConflict;
|
||||
private final CreditLimitRule creditLimit;
|
||||
private final CapacityRule capacity;
|
||||
|
||||
public RegistrationPolicy(
|
||||
RegistrationPeriodRule registrationPeriodRule,
|
||||
GradeEligibilityRule gradeEligibilityRule,
|
||||
RoleEligibilityRule roleEligibilityRule,
|
||||
AlreadyRegisteredRule alreadyRegisteredRule,
|
||||
DuplicateSubjectRule duplicateSubjectRule,
|
||||
ScheduleAvailabilityRule scheduleAvailabilityRule,
|
||||
ScheduleConflictRule scheduleConflictRule,
|
||||
CreditLimitRule creditLimitRule,
|
||||
CapacityRule capacityRule) {
|
||||
this.orderedRules = List.of(
|
||||
registrationPeriodRule,
|
||||
gradeEligibilityRule,
|
||||
roleEligibilityRule,
|
||||
alreadyRegisteredRule,
|
||||
duplicateSubjectRule,
|
||||
scheduleAvailabilityRule,
|
||||
scheduleConflictRule,
|
||||
creditLimitRule,
|
||||
capacityRule);
|
||||
AlreadyRegisteredRule alreadyRegistered,
|
||||
DuplicateSubjectRule duplicateSubject,
|
||||
ScheduleAvailabilityRule scheduleAvailability,
|
||||
ScheduleConflictRule scheduleConflict,
|
||||
CreditLimitRule creditLimit,
|
||||
CapacityRule capacity) {
|
||||
this.alreadyRegistered = alreadyRegistered;
|
||||
this.duplicateSubject = duplicateSubject;
|
||||
this.scheduleAvailability = scheduleAvailability;
|
||||
this.scheduleConflict = scheduleConflict;
|
||||
this.creditLimit = creditLimit;
|
||||
this.capacity = capacity;
|
||||
}
|
||||
|
||||
public void validate(RegistrationContext context) {
|
||||
orderedRules.forEach(rule -> rule.validate(context));
|
||||
public void validate(RegistrationDecisionSnapshot snapshot) {
|
||||
snapshot.lesson().verifyRegistrationWindow(snapshot.now());
|
||||
snapshot.lesson().verifyStudentEligibility(snapshot.user());
|
||||
|
||||
alreadyRegistered.verify(snapshot);
|
||||
duplicateSubject.verify(snapshot);
|
||||
scheduleAvailability.verify(snapshot);
|
||||
scheduleConflict.verify(snapshot);
|
||||
creditLimit.verify(snapshot);
|
||||
capacity.verify(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public final class RegistrationRejection extends RuntimeException {
|
||||
private final RegistrationRejectionCode code;
|
||||
|
||||
private RegistrationRejection(RegistrationRejectionCode code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public static RegistrationRejection registrationPeriodClosed() {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.REGISTRATION_PERIOD_CLOSED,
|
||||
"수강신청 기간이 아닙니다.");
|
||||
}
|
||||
|
||||
public static RegistrationRejection notEligibleGrade(long currentGrade, long minGrade) {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.NOT_ELIGIBLE_GRADE,
|
||||
"수강 가능한 학년이 아닙니다. (현재 " + currentGrade + "학년, 최소 " + minGrade + "학년)");
|
||||
}
|
||||
|
||||
public static RegistrationRejection notEligibleRole(UserRole requiredRole) {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.NOT_ELIGIBLE_ROLE,
|
||||
"수강 가능한 역할이 아닙니다. (필요 역할: " + requiredRole + ")");
|
||||
}
|
||||
|
||||
public static RegistrationRejection alreadyRegistered() {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.ALREADY_REGISTERED,
|
||||
"이미 신청한 강의입니다.");
|
||||
}
|
||||
|
||||
public static RegistrationRejection duplicateSubject() {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.DUPLICATE_SUBJECT,
|
||||
"같은 과목의 다른 분반을 이미 신청했습니다.");
|
||||
}
|
||||
|
||||
public static RegistrationRejection scheduleConflict(
|
||||
DayOfWeek dayOfWeek,
|
||||
LocalTime startTime,
|
||||
LocalTime endTime) {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.SCHEDULE_CONFLICT,
|
||||
"기존 수업과 시간이 겹칩니다. (" + dayOfWeek + " " + startTime + "-" + endTime + ")");
|
||||
}
|
||||
|
||||
public static RegistrationRejection creditLimitExceeded(int current, int requested, int max) {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.CREDIT_LIMIT_EXCEEDED,
|
||||
"신청 학점이 상한을 넘습니다. (" + current + " + " + requested + " > " + max + ")");
|
||||
}
|
||||
|
||||
public static RegistrationRejection capacityExceeded(long enrolled, int capacity) {
|
||||
return new RegistrationRejection(
|
||||
RegistrationRejectionCode.CAPACITY_EXCEEDED,
|
||||
"정원이 가득 찼습니다. (" + enrolled + "/" + capacity + ")");
|
||||
}
|
||||
|
||||
public RegistrationRejectionCode code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
public enum RegistrationRejectionCode {
|
||||
REGISTRATION_PERIOD_CLOSED,
|
||||
NOT_ELIGIBLE_GRADE,
|
||||
NOT_ELIGIBLE_ROLE,
|
||||
ALREADY_REGISTERED,
|
||||
DUPLICATE_SUBJECT,
|
||||
SCHEDULE_CONFLICT,
|
||||
CREDIT_LIMIT_EXCEEDED,
|
||||
CAPACITY_EXCEEDED
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
public interface RegistrationRule {
|
||||
void validate(RegistrationContext context);
|
||||
}
|
||||
+1
-6
@@ -2,13 +2,8 @@ package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
public final class RegistrationWindowGuard {
|
||||
public void verify(LessonPolicySnapshot lesson, Instant now) {
|
||||
if (now.isBefore(lesson.registrationStartAt())
|
||||
|| now.isAfter(lesson.registrationEndAt())) {
|
||||
throw BusinessRejection.registrationPeriodClosed();
|
||||
}
|
||||
lesson.verifyRegistrationWindow(now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record UserProfile(
|
||||
String id,
|
||||
long grade,
|
||||
UserRole role) {
|
||||
|
||||
public UserProfile {
|
||||
Objects.requireNonNull(id, "id");
|
||||
Objects.requireNonNull(role, "role");
|
||||
if (grade < 1) {
|
||||
throw new IllegalArgumentException("grade must be at least 1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-9
@@ -1,16 +1,14 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
|
||||
public final class AlreadyRegisteredRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
boolean duplicate = context.activeRegistrations().stream()
|
||||
.anyMatch(registration -> registration.lessonId().equals(context.lesson().id()));
|
||||
public final class AlreadyRegisteredRule {
|
||||
public void verify(RegistrationDecisionSnapshot snapshot) {
|
||||
boolean duplicate = snapshot.activeRegistrations().stream()
|
||||
.anyMatch(registration -> registration.lessonId().equals(snapshot.lesson().id()));
|
||||
if (duplicate) {
|
||||
throw BusinessRejection.alreadyRegistered();
|
||||
throw RegistrationRejection.alreadyRegistered();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-10
@@ -1,16 +1,14 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
|
||||
public final class CapacityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.enrolledCount() >= context.lesson().capacity()) {
|
||||
throw BusinessRejection.capacityExceeded(
|
||||
context.enrolledCount(),
|
||||
context.lesson().capacity());
|
||||
public final class CapacityRule {
|
||||
public void verify(RegistrationDecisionSnapshot snapshot) {
|
||||
if (snapshot.enrolledCount() >= snapshot.lesson().capacity()) {
|
||||
throw RegistrationRejection.capacityExceeded(
|
||||
snapshot.enrolledCount(),
|
||||
snapshot.lesson().capacity());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-10
@@ -1,17 +1,15 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
|
||||
public final class CreditLimitRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
int current = context.currentCredits();
|
||||
int requested = context.lesson().subjectCredit();
|
||||
int max = context.lesson().maxCredits();
|
||||
public final class CreditLimitRule {
|
||||
public void verify(RegistrationDecisionSnapshot snapshot) {
|
||||
int current = snapshot.currentCredits();
|
||||
int requested = snapshot.lesson().subjectCredit();
|
||||
int max = snapshot.lesson().maxCredits();
|
||||
if (current + requested > max) {
|
||||
throw BusinessRejection.creditLimitExceeded(current, requested, max);
|
||||
throw RegistrationRejection.creditLimitExceeded(current, requested, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-9
@@ -1,16 +1,14 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
|
||||
public final class DuplicateSubjectRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
boolean duplicate = context.activeRegistrations().stream()
|
||||
.anyMatch(registration -> registration.subjectId().equals(context.lesson().subjectId()));
|
||||
public final class DuplicateSubjectRule {
|
||||
public void verify(RegistrationDecisionSnapshot snapshot) {
|
||||
boolean duplicate = snapshot.activeRegistrations().stream()
|
||||
.anyMatch(registration -> registration.subjectId().equals(snapshot.lesson().subjectId()));
|
||||
if (duplicate) {
|
||||
throw BusinessRejection.duplicateSubject();
|
||||
throw RegistrationRejection.duplicateSubject();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
public final class GradeEligibilityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
Long minGrade = context.lesson().minGrade();
|
||||
if (minGrade != null && context.user().grade() < minGrade) {
|
||||
throw BusinessRejection.notEligibleGrade(context.user().grade(), minGrade);
|
||||
}
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
public final class RegistrationPeriodRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.now().isBefore(context.lesson().registrationStartAt())
|
||||
|| context.now().isAfter(context.lesson().registrationEndAt())) {
|
||||
throw BusinessRejection.registrationPeriodClosed();
|
||||
}
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
public final class RoleEligibilityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.lesson().allowedRole() != null
|
||||
&& context.user().role() != context.lesson().allowedRole()) {
|
||||
throw BusinessRejection.notEligibleRole(context.lesson().allowedRole());
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-11
@@ -1,18 +1,16 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationInvariantViolation;
|
||||
|
||||
public final class ScheduleAvailabilityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.candidateSchedules().isEmpty()) {
|
||||
throw SystemInvariantViolation.missingCandidateSchedule();
|
||||
public final class ScheduleAvailabilityRule {
|
||||
public void verify(RegistrationDecisionSnapshot snapshot) {
|
||||
if (snapshot.candidateSchedules().isEmpty()) {
|
||||
throw RegistrationInvariantViolation.missingCandidateSchedule();
|
||||
}
|
||||
context.activeRegistrations().forEach(registration -> {
|
||||
if (context.schedulesOf(registration).isEmpty()) {
|
||||
throw SystemInvariantViolation.missingExistingSchedule();
|
||||
snapshot.activeRegistrations().forEach(registration -> {
|
||||
if (snapshot.schedulesOf(registration).isEmpty()) {
|
||||
throw RegistrationInvariantViolation.missingExistingSchedule();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+8
-10
@@ -1,26 +1,24 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import com.study.course_registration.domain.registration.ActiveRegistrationSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
import com.study.course_registration.domain.schedule.ScheduleConflictChecker;
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
public final class ScheduleConflictRule implements RegistrationRule {
|
||||
public final class ScheduleConflictRule {
|
||||
private final ScheduleConflictChecker conflictChecker;
|
||||
|
||||
public ScheduleConflictRule(ScheduleConflictChecker conflictChecker) {
|
||||
this.conflictChecker = conflictChecker;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
for (ActiveRegistrationSnapshot registration : context.activeRegistrations()) {
|
||||
for (ScheduleSlot candidate : context.candidateSchedules()) {
|
||||
for (ScheduleSlot existing : context.schedulesOf(registration)) {
|
||||
public void verify(RegistrationDecisionSnapshot snapshot) {
|
||||
for (ActiveRegistrationSnapshot registration : snapshot.activeRegistrations()) {
|
||||
for (ScheduleSlot candidate : snapshot.candidateSchedules()) {
|
||||
for (ScheduleSlot existing : snapshot.schedulesOf(registration)) {
|
||||
if (conflictChecker.overlaps(candidate, existing)) {
|
||||
throw BusinessRejection.scheduleConflict(
|
||||
throw RegistrationRejection.scheduleConflict(
|
||||
candidate.dayOfWeek(),
|
||||
candidate.startTime(),
|
||||
candidate.endTime());
|
||||
|
||||
@@ -41,10 +41,9 @@ public class UserLesson extends BaseCreateEntity {
|
||||
}
|
||||
|
||||
public void cancel(Instant canceledAt) {
|
||||
if (this.canceledAt != null) {
|
||||
throw new IllegalStateException("registration is already canceled");
|
||||
if (this.canceledAt == null) {
|
||||
this.canceledAt = Objects.requireNonNull(canceledAt, "canceledAt");
|
||||
}
|
||||
this.canceledAt = Objects.requireNonNull(canceledAt, "canceledAt");
|
||||
}
|
||||
|
||||
public boolean isCanceled() {
|
||||
|
||||
@@ -17,5 +17,7 @@ public enum RegistrationErrorCode {
|
||||
CAPACITY_EXCEEDED,
|
||||
IDEMPOTENCY_KEY_REUSED,
|
||||
LOCK_TIMEOUT,
|
||||
DB_POOL_EXHAUSTED,
|
||||
DB_UNAVAILABLE,
|
||||
INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public final class BusinessRejection extends ApplicationFailure {
|
||||
private BusinessRejection(RegistrationErrorCode code, String message) {
|
||||
super(code, message);
|
||||
}
|
||||
|
||||
public static BusinessRejection registrationPeriodClosed() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED,
|
||||
"수강신청 기간이 아닙니다.");
|
||||
}
|
||||
|
||||
public static BusinessRejection notEligibleGrade(long currentGrade, long minGrade) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.NOT_ELIGIBLE_GRADE,
|
||||
"수강 가능한 학년이 아닙니다. (현재 " + currentGrade + "학년, 최소 " + minGrade + "학년)");
|
||||
}
|
||||
|
||||
public static BusinessRejection notEligibleRole(UserRole requiredRole) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.NOT_ELIGIBLE_ROLE,
|
||||
"수강 가능한 역할이 아닙니다. (필요 역할: " + requiredRole + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection alreadyRegistered() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.ALREADY_REGISTERED,
|
||||
"이미 신청한 강의입니다.");
|
||||
}
|
||||
|
||||
public static BusinessRejection duplicateSubject() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.DUPLICATE_SUBJECT,
|
||||
"같은 과목의 다른 분반을 이미 신청했습니다.");
|
||||
}
|
||||
|
||||
public static BusinessRejection scheduleConflict(
|
||||
DayOfWeek dayOfWeek,
|
||||
LocalTime startTime,
|
||||
LocalTime endTime) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.SCHEDULE_CONFLICT,
|
||||
"기존 수업과 시간이 겹칩니다. (" + dayOfWeek + " " + startTime + "-" + endTime + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection creditLimitExceeded(int current, int requested, int max) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED,
|
||||
"신청 학점이 상한을 넘습니다. (" + current + " + " + requested + " > " + max + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection capacityExceeded(long enrolled, int capacity) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.CAPACITY_EXCEEDED,
|
||||
"정원이 가득 찼습니다. (" + enrolled + "/" + capacity + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection idempotencyKeyReused() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED,
|
||||
"동일한 Idempotency-Key를 다른 강의에 사용할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
public enum InfrastructureFailureReason {
|
||||
LOCK_CONTENTION,
|
||||
DB_POOL_EXHAUSTED,
|
||||
DB_UNAVAILABLE
|
||||
}
|
||||
+31
-2
@@ -3,13 +3,42 @@ package com.study.course_registration.failure;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public final class RetryableInfrastructureFailure extends KnownFailure {
|
||||
private RetryableInfrastructureFailure(String message, Throwable cause) {
|
||||
super(RegistrationErrorCode.LOCK_TIMEOUT, message, cause);
|
||||
private final InfrastructureFailureReason reason;
|
||||
|
||||
private RetryableInfrastructureFailure(
|
||||
RegistrationErrorCode errorCode,
|
||||
InfrastructureFailureReason reason,
|
||||
String message,
|
||||
Throwable cause) {
|
||||
super(errorCode, message, cause);
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
public static RetryableInfrastructureFailure lockTimeout(Throwable cause) {
|
||||
return new RetryableInfrastructureFailure(
|
||||
RegistrationErrorCode.LOCK_TIMEOUT,
|
||||
InfrastructureFailureReason.LOCK_CONTENTION,
|
||||
"다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요.",
|
||||
cause);
|
||||
}
|
||||
|
||||
public static RetryableInfrastructureFailure dbPoolExhausted(Throwable cause) {
|
||||
return new RetryableInfrastructureFailure(
|
||||
RegistrationErrorCode.DB_POOL_EXHAUSTED,
|
||||
InfrastructureFailureReason.DB_POOL_EXHAUSTED,
|
||||
"데이터베이스 연결이 혼잡합니다. 잠시 후 다시 시도해 주세요.",
|
||||
cause);
|
||||
}
|
||||
|
||||
public static RetryableInfrastructureFailure dbUnavailable(Throwable cause) {
|
||||
return new RetryableInfrastructureFailure(
|
||||
RegistrationErrorCode.DB_UNAVAILABLE,
|
||||
InfrastructureFailureReason.DB_UNAVAILABLE,
|
||||
"데이터베이스에 일시적으로 연결할 수 없습니다. 잠시 후 다시 시도해 주세요.",
|
||||
cause);
|
||||
}
|
||||
|
||||
public InfrastructureFailureReason reason() {
|
||||
return reason;
|
||||
}
|
||||
}
|
||||
|
||||
+9
-5
@@ -3,6 +3,7 @@ package com.study.course_registration.infrastructure.persistence;
|
||||
import org.springframework.dao.PessimisticLockingFailureException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.registration.model.CancellationTarget;
|
||||
import com.study.course_registration.application.registration.port.CancellationContextLoader;
|
||||
import com.study.course_registration.domain.registration.CancellationContext;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
@@ -32,20 +33,23 @@ public class JpaCancellationContextLoader implements CancellationContextLoader {
|
||||
}
|
||||
|
||||
@Override
|
||||
public CancellationContext load(String registrationId) {
|
||||
public CancellationTarget findTarget(String registrationId) {
|
||||
UserLessonRepository.RegistrationTarget target =
|
||||
registrations.findTargetById(registrationId)
|
||||
.orElseThrow(ResourceNotFound::registration);
|
||||
return new CancellationTarget(registrationId, target.getUserId(), target.getLessonId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CancellationContext lock(CancellationTarget target) {
|
||||
try {
|
||||
users.findByIdForUpdate(target.getUserId()).orElseThrow(ResourceNotFound::user);
|
||||
Lesson lesson = lessons.findByIdForUpdate(target.getLessonId())
|
||||
users.findByIdForUpdate(target.ownerUserId()).orElseThrow(ResourceNotFound::user);
|
||||
Lesson lesson = lessons.findByIdForUpdate(target.lessonId())
|
||||
.orElseThrow(ResourceNotFound::lesson);
|
||||
UserLesson registration = registrations.findById(registrationId)
|
||||
UserLesson registration = registrations.findById(target.registrationId())
|
||||
.orElseThrow(ResourceNotFound::registration);
|
||||
|
||||
return new CancellationContext(
|
||||
target.getUserId(),
|
||||
registration.getId(),
|
||||
JpaSnapshotMapper.lessonPolicy(lesson),
|
||||
registration.isCanceled());
|
||||
|
||||
+25
-12
@@ -1,16 +1,20 @@
|
||||
package com.study.course_registration.infrastructure.persistence;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencyReplay;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencySaveCommand;
|
||||
import com.study.course_registration.application.registration.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
import com.study.course_registration.infrastructure.persistence.idempotency.RegistrationIdempotencyEntity;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.RegistrationIdempotencyRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserLessonRepository;
|
||||
@@ -35,16 +39,16 @@ public class JpaIdempotencyAdapter implements IdempotencyPort {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ReplayRecord> findActive(String userId, String key, Instant now) {
|
||||
public Optional<IdempotencyReplay> findActive(String userId, String key, Instant now) {
|
||||
return repository.findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(userId, key, now)
|
||||
.map(stored -> new ReplayRecord(
|
||||
.map(stored -> new IdempotencyReplay(
|
||||
stored.getRegistration().getId(),
|
||||
stored.getUser().getId(),
|
||||
stored.getLesson().getId(),
|
||||
stored.getLesson().getName(),
|
||||
stored.getLesson().getSubject().getCode(),
|
||||
stored.getLesson().getSubject().getCredit(),
|
||||
stored.getRegistration().getCreatedAt(),
|
||||
stored.getLessonName(),
|
||||
stored.getSubjectCode(),
|
||||
stored.getCredit(),
|
||||
stored.getRegisteredAt(),
|
||||
stored.getTotalCredits()));
|
||||
}
|
||||
|
||||
@@ -54,22 +58,31 @@ public class JpaIdempotencyAdapter implements IdempotencyPort {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteExpired(Instant now) {
|
||||
repository.deleteExpired(now);
|
||||
public int deleteExpiredBatch(Instant now, int batchSize) {
|
||||
List<String> ids = repository.findExpiredIds(now, PageRequest.of(0, batchSize));
|
||||
if (ids.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
repository.deleteAllByIdInBatch(ids);
|
||||
return ids.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SaveCommand command) {
|
||||
public void save(IdempotencySaveCommand command) {
|
||||
User user = users.findById(command.userId()).orElseThrow(ResourceNotFound::user);
|
||||
Lesson lesson = lessons.findById(command.lessonId()).orElseThrow(ResourceNotFound::lesson);
|
||||
UserLesson registration = registrations.findById(command.registrationId())
|
||||
.orElseThrow(ResourceNotFound::registration);
|
||||
|
||||
repository.saveAndFlush(new RegistrationIdempotency(
|
||||
repository.saveAndFlush(new RegistrationIdempotencyEntity(
|
||||
user,
|
||||
lesson,
|
||||
registration,
|
||||
command.key(),
|
||||
command.lessonName(),
|
||||
command.subjectCode(),
|
||||
command.credit(),
|
||||
command.registeredAt(),
|
||||
command.totalCredits(),
|
||||
command.expiresAt()));
|
||||
}
|
||||
|
||||
+3
@@ -12,6 +12,9 @@ import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.lesson.model.LessonDetailView;
|
||||
import com.study.course_registration.application.lesson.model.LessonListView;
|
||||
import com.study.course_registration.application.lesson.model.LessonPage;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort;
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
|
||||
+6
-6
@@ -10,10 +10,10 @@ import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.registration.port.RegistrationDecisionContextLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationDecisionSnapshotLoader;
|
||||
import com.study.course_registration.domain.registration.ActiveRegistrationSnapshot;
|
||||
import com.study.course_registration.domain.registration.LessonPolicySnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationDecisionSnapshot;
|
||||
import com.study.course_registration.domain.registration.RegistrationExecutionScope;
|
||||
import com.study.course_registration.domain.registration.UserProfile;
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
@@ -27,13 +27,13 @@ import com.study.course_registration.infrastructure.persistence.repository.UserL
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserRepository;
|
||||
|
||||
@Component
|
||||
public class JpaRegistrationDecisionContextLoader implements RegistrationDecisionContextLoader {
|
||||
public class JpaRegistrationDecisionSnapshotLoader implements RegistrationDecisionSnapshotLoader {
|
||||
private final UserRepository users;
|
||||
private final LessonRepository lessons;
|
||||
private final UserLessonRepository registrations;
|
||||
private final LessonScheduleRepository schedules;
|
||||
|
||||
public JpaRegistrationDecisionContextLoader(
|
||||
public JpaRegistrationDecisionSnapshotLoader(
|
||||
UserRepository users,
|
||||
LessonRepository lessons,
|
||||
UserLessonRepository registrations,
|
||||
@@ -45,7 +45,7 @@ public class JpaRegistrationDecisionContextLoader implements RegistrationDecisio
|
||||
}
|
||||
|
||||
@Override
|
||||
public RegistrationContext load(RegistrationExecutionScope scope, Instant now) {
|
||||
public RegistrationDecisionSnapshot load(RegistrationExecutionScope scope, Instant now) {
|
||||
User userEntity = users.findById(scope.userId()).orElseThrow(ResourceNotFound::user);
|
||||
Lesson lessonEntity = lessons.findDetailedById(scope.lessonId()).orElseThrow(ResourceNotFound::lesson);
|
||||
|
||||
@@ -73,7 +73,7 @@ public class JpaRegistrationDecisionContextLoader implements RegistrationDecisio
|
||||
|
||||
long enrolled = registrations.countByLesson_IdAndCanceledAtIsNull(lesson.id());
|
||||
|
||||
return new RegistrationContext(
|
||||
return new RegistrationDecisionSnapshot(
|
||||
user,
|
||||
lesson,
|
||||
active,
|
||||
+9
-1
@@ -29,10 +29,18 @@ public class JpaRegistrationExecutionScopeLoader implements RegistrationExecutio
|
||||
public RegistrationExecutionScope open(String userId, String lessonId) {
|
||||
try {
|
||||
users.findByIdForUpdate(userId).orElseThrow(ResourceNotFound::user);
|
||||
lessons.findByIdForUpdate(lessonId).orElseThrow(ResourceNotFound::lesson);
|
||||
return new RegistrationExecutionScope(userId, lessonId);
|
||||
} catch (PessimisticLockingFailureException | LockTimeoutException | PessimisticLockException exception) {
|
||||
throw RetryableInfrastructureFailure.lockTimeout(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void lockLesson(RegistrationExecutionScope scope) {
|
||||
try {
|
||||
lessons.findByIdForUpdate(scope.lessonId()).orElseThrow(ResourceNotFound::lesson);
|
||||
} catch (PessimisticLockingFailureException | LockTimeoutException | PessimisticLockException exception) {
|
||||
throw RetryableInfrastructureFailure.lockTimeout(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -8,6 +8,8 @@ import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.registration.model.ActiveRegistrationView;
|
||||
import com.study.course_registration.application.registration.model.RegistrationRecord;
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.domain.schedule.ScheduleSlot;
|
||||
@@ -91,9 +93,7 @@ public class JpaRegistrationPersistenceAdapter implements RegistrationReader, Re
|
||||
public void cancel(String registrationId, Instant canceledAt) {
|
||||
UserLesson registration = registrations.findById(registrationId)
|
||||
.orElseThrow(ResourceNotFound::registration);
|
||||
if (!registration.isCanceled()) {
|
||||
registration.cancel(canceledAt);
|
||||
registrations.saveAndFlush(registration);
|
||||
}
|
||||
registration.cancel(canceledAt);
|
||||
registrations.saveAndFlush(registration);
|
||||
}
|
||||
}
|
||||
|
||||
+42
-4
@@ -1,8 +1,13 @@
|
||||
package com.study.course_registration.entity;
|
||||
package com.study.course_registration.infrastructure.persistence.idempotency;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.study.course_registration.entity.BaseCreateEntity;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
@@ -22,7 +27,7 @@ import lombok.NoArgsConstructor;
|
||||
uniqueConstraints = @UniqueConstraint(
|
||||
name = "uk_registration_idempotency",
|
||||
columnNames = {"user_id", "idempotency_key"}))
|
||||
public class RegistrationIdempotency extends BaseCreateEntity {
|
||||
public class RegistrationIdempotencyEntity extends BaseCreateEntity {
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id", nullable = false, foreignKey = @ForeignKey(name = "fk_idempotency_user"))
|
||||
private User user;
|
||||
@@ -41,17 +46,33 @@ public class RegistrationIdempotency extends BaseCreateEntity {
|
||||
@Column(name = "idempotency_key", nullable = false, length = 100)
|
||||
private String idempotencyKey;
|
||||
|
||||
@Column(name = "lesson_name", nullable = false)
|
||||
private String lessonName;
|
||||
|
||||
@Column(name = "subject_code", nullable = false)
|
||||
private String subjectCode;
|
||||
|
||||
@Column(name = "credit", nullable = false)
|
||||
private Integer credit;
|
||||
|
||||
@Column(name = "registered_at", nullable = false)
|
||||
private Instant registeredAt;
|
||||
|
||||
@Column(name = "total_credits", nullable = false)
|
||||
private Integer totalCredits;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
public RegistrationIdempotency(
|
||||
public RegistrationIdempotencyEntity(
|
||||
User user,
|
||||
Lesson lesson,
|
||||
UserLesson registration,
|
||||
String idempotencyKey,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
Integer credit,
|
||||
Instant registeredAt,
|
||||
Integer totalCredits,
|
||||
Instant expiresAt) {
|
||||
this.user = Objects.requireNonNull(user, "user");
|
||||
@@ -61,7 +82,24 @@ public class RegistrationIdempotency extends BaseCreateEntity {
|
||||
throw new IllegalArgumentException("idempotencyKey length must be 1..100");
|
||||
}
|
||||
this.idempotencyKey = idempotencyKey;
|
||||
this.totalCredits = Objects.requireNonNull(totalCredits, "totalCredits");
|
||||
this.lessonName = requireText(lessonName, "lessonName");
|
||||
this.subjectCode = requireText(subjectCode, "subjectCode");
|
||||
if (credit == null || credit < 1) {
|
||||
throw new IllegalArgumentException("credit must be at least 1");
|
||||
}
|
||||
this.credit = credit;
|
||||
this.registeredAt = Objects.requireNonNull(registeredAt, "registeredAt");
|
||||
if (totalCredits == null || totalCredits < 1) {
|
||||
throw new IllegalArgumentException("totalCredits must be at least 1");
|
||||
}
|
||||
this.totalCredits = totalCredits;
|
||||
this.expiresAt = Objects.requireNonNull(expiresAt, "expiresAt");
|
||||
}
|
||||
|
||||
private static String requireText(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException(field + " must not be blank");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+9
-16
@@ -1,8 +1,10 @@
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
@@ -10,32 +12,23 @@ import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.infrastructure.persistence.idempotency.RegistrationIdempotencyEntity;
|
||||
|
||||
public interface RegistrationIdempotencyRepository extends JpaRepository<RegistrationIdempotency, String> {
|
||||
@EntityGraph(attributePaths = {
|
||||
"user", "lesson", "lesson.subject", "registration"
|
||||
})
|
||||
Optional<RegistrationIdempotency> findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(
|
||||
public interface RegistrationIdempotencyRepository extends JpaRepository<RegistrationIdempotencyEntity, String> {
|
||||
@EntityGraph(attributePaths = {"user", "lesson", "registration"})
|
||||
Optional<RegistrationIdempotencyEntity> findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(
|
||||
String userId,
|
||||
String idempotencyKey,
|
||||
Instant now);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("""
|
||||
delete from RegistrationIdempotency value
|
||||
where value.user.id = :userId
|
||||
and value.idempotencyKey = :idempotencyKey
|
||||
and value.expiresAt <= :now
|
||||
""")
|
||||
@Query("delete from RegistrationIdempotencyEntity 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
|
||||
@Transactional
|
||||
@Query("delete from RegistrationIdempotency value where value.expiresAt <= :now")
|
||||
int deleteExpired(@Param("now") Instant now);
|
||||
@Query("select value.id from RegistrationIdempotencyEntity value where value.expiresAt <= :now order by value.expiresAt asc, value.id asc")
|
||||
List<String> findExpiredIds(@Param("now") Instant now, Pageable pageable);
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.study.course_registration.infrastructure.scheduling;
|
||||
|
||||
import java.util.OptionalInt;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
import org.springframework.dao.TransientDataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
@Component
|
||||
public class DatabaseJobLock {
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
|
||||
public DatabaseJobLock(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.transactionTemplate = transactionTemplate;
|
||||
}
|
||||
|
||||
public OptionalInt callWithLock(String name, IntSupplier task) {
|
||||
Integer result = transactionTemplate.execute(status -> {
|
||||
try {
|
||||
jdbcTemplate.queryForObject(
|
||||
"select name from maintenance_locks where name = ? for update nowait",
|
||||
String.class,
|
||||
name);
|
||||
} catch (TransientDataAccessException exception) {
|
||||
status.setRollbackOnly();
|
||||
return null;
|
||||
}
|
||||
return task.getAsInt();
|
||||
});
|
||||
return result == null ? OptionalInt.empty() : OptionalInt.of(result);
|
||||
}
|
||||
}
|
||||
+23
-4
@@ -1,20 +1,39 @@
|
||||
package com.study.course_registration.infrastructure.scheduling;
|
||||
|
||||
import java.util.OptionalInt;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.idempotency.CleanupIdempotencyUseCase;
|
||||
import com.study.course_registration.application.registration.idempotency.CleanupIdempotencyUseCase;
|
||||
|
||||
@Component
|
||||
public class IdempotencyRetentionJob {
|
||||
private final CleanupIdempotencyUseCase cleanupIdempotencyUseCase;
|
||||
static final String LOCK_NAME = "idempotency-cleanup";
|
||||
|
||||
public IdempotencyRetentionJob(CleanupIdempotencyUseCase cleanupIdempotencyUseCase) {
|
||||
private final CleanupIdempotencyUseCase cleanupIdempotencyUseCase;
|
||||
private final DatabaseJobLock jobLock;
|
||||
private final int maxBatchesPerRun;
|
||||
|
||||
public IdempotencyRetentionJob(
|
||||
CleanupIdempotencyUseCase cleanupIdempotencyUseCase,
|
||||
DatabaseJobLock jobLock,
|
||||
@Value("${app.idempotency.cleanup-max-batches-per-run:20}") int maxBatchesPerRun) {
|
||||
this.cleanupIdempotencyUseCase = cleanupIdempotencyUseCase;
|
||||
this.jobLock = jobLock;
|
||||
this.maxBatchesPerRun = maxBatchesPerRun;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${app.idempotency.cleanup-delay-ms:3600000}")
|
||||
public void cleanup() {
|
||||
cleanupIdempotencyUseCase.execute();
|
||||
for (int index = 0; index < maxBatchesPerRun; index++) {
|
||||
OptionalInt deleted = jobLock.callWithLock(
|
||||
LOCK_NAME,
|
||||
cleanupIdempotencyUseCase::execute);
|
||||
if (deleted.isEmpty() || deleted.getAsInt() == 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
package com.study.course_registration.web.error;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLTransientConnectionException;
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.PessimisticLockingFailureException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationInvariantViolation;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.failure.ApplicationFailure;
|
||||
import com.study.course_registration.failure.RetryableInfrastructureFailure;
|
||||
@@ -40,8 +50,8 @@ public class ApiExceptionHandler {
|
||||
@ExceptionHandler(RetryableInfrastructureFailure.class)
|
||||
ResponseEntity<ApiErrorResponse> retryable(RetryableInfrastructureFailure failure) {
|
||||
metrics.record(failure);
|
||||
log.warn("Retryable infrastructure failure: {}", failure.getMessage());
|
||||
return lockTimeoutResponse(failure.getMessage());
|
||||
log.warn("Retryable infrastructure failure [{}]: {}", failure.reason(), failure.getMessage());
|
||||
return retryableResponse(failure.getErrorCode(), failure.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ApplicationFailure.class)
|
||||
@@ -65,6 +75,41 @@ public class ApiExceptionHandler {
|
||||
return badRequest("요청 값이 올바르지 않습니다.");
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentTypeMismatchException.class, MissingServletRequestParameterException.class})
|
||||
ResponseEntity<ApiErrorResponse> requestBinding(Exception exception) {
|
||||
return badRequest("요청 값이 올바르지 않습니다.");
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
ResponseEntity<ApiErrorResponse> notFound(NoResourceFoundException exception) {
|
||||
return response(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 API를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
ResponseEntity<ApiErrorResponse> methodNotAllowed(HttpRequestMethodNotSupportedException exception) {
|
||||
return response(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", "지원하지 않는 HTTP 메서드입니다.");
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
ResponseEntity<ApiErrorResponse> unsupportedMediaType(HttpMediaTypeNotSupportedException exception) {
|
||||
return response(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", "지원하지 않는 Content-Type입니다.");
|
||||
}
|
||||
|
||||
@ExceptionHandler(RegistrationRejection.class)
|
||||
ResponseEntity<ApiErrorResponse> registrationRejected(RegistrationRejection rejection) {
|
||||
metrics.record(rejection);
|
||||
return ResponseEntity.status(httpMapper.map(rejection.code()))
|
||||
.body(new ApiErrorResponse(rejection.code().name(), rejection.getMessage(), clock.instant()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(RegistrationInvariantViolation.class)
|
||||
ResponseEntity<ApiErrorResponse> registrationInvariant(RegistrationInvariantViolation failure) {
|
||||
metrics.record(failure);
|
||||
log.error("Registration invariant violation [{}]", failure.invariant(), failure);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(body(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "서버 내부 오류가 발생했습니다."));
|
||||
}
|
||||
|
||||
@ExceptionHandler(SystemInvariantViolation.class)
|
||||
ResponseEntity<ApiErrorResponse> invariant(SystemInvariantViolation failure) {
|
||||
metrics.record(failure);
|
||||
@@ -75,8 +120,21 @@ public class ApiExceptionHandler {
|
||||
|
||||
@ExceptionHandler({LockTimeoutException.class, PessimisticLockException.class, PessimisticLockingFailureException.class})
|
||||
ResponseEntity<ApiErrorResponse> rawLockTimeout(Exception exception) {
|
||||
log.warn("Persistence lock timeout: {}", exception.getMessage());
|
||||
return lockTimeoutResponse("다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요.");
|
||||
return retryable(RetryableInfrastructureFailure.lockTimeout(exception));
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataAccessResourceFailureException.class)
|
||||
ResponseEntity<ApiErrorResponse> databaseResourceFailure(DataAccessResourceFailureException exception) {
|
||||
SQLException sqlException = findSqlException(exception);
|
||||
if (sqlException != null
|
||||
&& sqlException.getSQLState() != null
|
||||
&& sqlException.getSQLState().startsWith("08")) {
|
||||
return retryable(RetryableInfrastructureFailure.dbUnavailable(exception));
|
||||
}
|
||||
if (hasTransientConnectionCause(exception)) {
|
||||
return retryable(RetryableInfrastructureFailure.dbPoolExhausted(exception));
|
||||
}
|
||||
return retryable(RetryableInfrastructureFailure.dbUnavailable(exception));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
@@ -91,11 +149,40 @@ public class ApiExceptionHandler {
|
||||
.body(body(RegistrationErrorCode.VALIDATION_ERROR, message));
|
||||
}
|
||||
|
||||
private ResponseEntity<ApiErrorResponse> lockTimeoutResponse(String message) {
|
||||
private ResponseEntity<ApiErrorResponse> response(HttpStatus status, String code, String message) {
|
||||
return ResponseEntity.status(status)
|
||||
.body(new ApiErrorResponse(code, message, clock.instant()));
|
||||
}
|
||||
|
||||
private ResponseEntity<ApiErrorResponse> retryableResponse(
|
||||
RegistrationErrorCode code,
|
||||
String message) {
|
||||
String retryAfter = Integer.toString(ThreadLocalRandom.current().nextInt(1, 4));
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.header(HttpHeaders.RETRY_AFTER, retryAfter)
|
||||
.body(body(RegistrationErrorCode.LOCK_TIMEOUT, message));
|
||||
.body(body(code, message));
|
||||
}
|
||||
|
||||
private static SQLException findSqlException(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
if (current instanceof SQLException sqlException) {
|
||||
return sqlException;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean hasTransientConnectionCause(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
if (current instanceof SQLTransientConnectionException) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private ApiErrorResponse body(RegistrationErrorCode code, String message) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.study.course_registration.web.error;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationRejectionCode;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
@Component
|
||||
@@ -17,8 +18,16 @@ public class FailureHttpMapper {
|
||||
case REGISTRATION_PERIOD_CLOSED, ALREADY_REGISTERED, DUPLICATE_SUBJECT,
|
||||
SCHEDULE_CONFLICT, CREDIT_LIMIT_EXCEEDED, CAPACITY_EXCEEDED,
|
||||
IDEMPOTENCY_KEY_REUSED -> HttpStatus.CONFLICT;
|
||||
case LOCK_TIMEOUT -> HttpStatus.SERVICE_UNAVAILABLE;
|
||||
case LOCK_TIMEOUT, DB_POOL_EXHAUSTED, DB_UNAVAILABLE -> HttpStatus.SERVICE_UNAVAILABLE;
|
||||
case INTERNAL_SERVER_ERROR -> HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
};
|
||||
}
|
||||
|
||||
public HttpStatus map(RegistrationRejectionCode code) {
|
||||
return switch (code) {
|
||||
case NOT_ELIGIBLE_GRADE, NOT_ELIGIBLE_ROLE -> HttpStatus.FORBIDDEN;
|
||||
case REGISTRATION_PERIOD_CLOSED, ALREADY_REGISTERED, DUPLICATE_SUBJECT,
|
||||
SCHEDULE_CONFLICT, CREDIT_LIMIT_EXCEEDED, CAPACITY_EXCEEDED -> HttpStatus.CONFLICT;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ package com.study.course_registration.web.error;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationInvariantViolation;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
import com.study.course_registration.failure.ApplicationFailure;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.failure.KnownFailure;
|
||||
import com.study.course_registration.failure.RetryableInfrastructureFailure;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
@@ -19,17 +20,26 @@ public class FailureMetrics {
|
||||
}
|
||||
|
||||
public void record(KnownFailure failure) {
|
||||
String category = failure instanceof BusinessRejection
|
||||
? "business_rejection"
|
||||
: failure instanceof RetryableInfrastructureFailure
|
||||
? "retryable_infrastructure"
|
||||
: failure instanceof ApplicationFailure
|
||||
? "application_failure"
|
||||
: "known_failure";
|
||||
String category = failure instanceof RetryableInfrastructureFailure
|
||||
? "retryable_infrastructure"
|
||||
: failure instanceof ApplicationFailure
|
||||
? "application_failure"
|
||||
: "known_failure";
|
||||
String reason = failure instanceof RetryableInfrastructureFailure retryable
|
||||
? retryable.reason().name().toLowerCase()
|
||||
: failure.getErrorCode().name().toLowerCase();
|
||||
registry.counter(
|
||||
"application_failure_total",
|
||||
"category", category,
|
||||
"reason", failure.getErrorCode().name().toLowerCase())
|
||||
"reason", reason)
|
||||
.increment();
|
||||
}
|
||||
|
||||
public void record(RegistrationRejection rejection) {
|
||||
registry.counter(
|
||||
"application_failure_total",
|
||||
"category", "business_rejection",
|
||||
"reason", rejection.code().name().toLowerCase())
|
||||
.increment();
|
||||
}
|
||||
|
||||
@@ -39,4 +49,11 @@ public class FailureMetrics {
|
||||
"reason", failure.getInvariantCode().name().toLowerCase())
|
||||
.increment();
|
||||
}
|
||||
|
||||
public void record(RegistrationInvariantViolation failure) {
|
||||
registry.counter(
|
||||
"system_invariant_violation_total",
|
||||
"reason", failure.invariant().name().toLowerCase())
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ spring:
|
||||
datasource:
|
||||
url: ${DB_URL}
|
||||
hikari:
|
||||
connection-timeout: 2000
|
||||
connection-timeout: ${DB_CONNECTION_TIMEOUT_MS:5000}
|
||||
validation-timeout: 1000
|
||||
maximum-pool-size: ${DB_POOL_MAX_SIZE:20}
|
||||
minimum-idle: ${DB_POOL_MIN_IDLE:2}
|
||||
@@ -47,3 +47,5 @@ app:
|
||||
idempotency:
|
||||
ttl-seconds: 86400
|
||||
cleanup-delay-ms: 3600000
|
||||
cleanup-batch-size: 500
|
||||
cleanup-max-batches-per-run: 20
|
||||
|
||||
@@ -107,6 +107,10 @@ CREATE TABLE registration_idempotencies (
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
registration_id VARCHAR(36) NOT NULL,
|
||||
idempotency_key VARCHAR(100) NOT NULL,
|
||||
lesson_name VARCHAR(255) NOT NULL,
|
||||
subject_code VARCHAR(255) NOT NULL,
|
||||
credit INTEGER NOT NULL,
|
||||
registered_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
total_credits INTEGER NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
@@ -122,3 +126,8 @@ CREATE TABLE seed_locks (
|
||||
name VARCHAR(100) PRIMARY KEY
|
||||
);
|
||||
INSERT INTO seed_locks(name) VALUES ('demo-dataset');
|
||||
|
||||
CREATE TABLE maintenance_locks (
|
||||
name VARCHAR(100) PRIMARY KEY
|
||||
);
|
||||
INSERT INTO maintenance_locks(name) VALUES ('idempotency-cleanup');
|
||||
|
||||
@@ -107,6 +107,10 @@ CREATE TABLE registration_idempotencies (
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
registration_id VARCHAR(36) NOT NULL,
|
||||
idempotency_key VARCHAR(100) NOT NULL,
|
||||
lesson_name VARCHAR(255) NOT NULL,
|
||||
subject_code VARCHAR(255) NOT NULL,
|
||||
credit INTEGER NOT NULL,
|
||||
registered_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
total_credits INTEGER NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
@@ -122,3 +126,8 @@ CREATE TABLE seed_locks (
|
||||
name VARCHAR(100) PRIMARY KEY
|
||||
);
|
||||
INSERT INTO seed_locks(name) VALUES ('demo-dataset');
|
||||
|
||||
CREATE TABLE maintenance_locks (
|
||||
name VARCHAR(100) PRIMARY KEY
|
||||
);
|
||||
INSERT INTO maintenance_locks(name) VALUES ('idempotency-cleanup');
|
||||
|
||||
+4
@@ -19,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import com.study.course_registration.application.registration.RegisterCourseCommand;
|
||||
import com.study.course_registration.application.registration.RegisterCourseUseCase;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.Professor;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
@@ -170,6 +171,9 @@ class CourseRegistrationConcurrencyIntegrationTest extends PostgresIntegrationTe
|
||||
start.await();
|
||||
action.run();
|
||||
results.add(new Accepted());
|
||||
} catch (RegistrationRejection rejection) {
|
||||
results.add(new Rejected(
|
||||
RegistrationErrorCode.valueOf(rejection.code().name())));
|
||||
} catch (ApplicationFailure exception) {
|
||||
results.add(new Rejected(exception.getErrorCode()));
|
||||
} catch (Throwable throwable) {
|
||||
|
||||
+6
-6
@@ -14,10 +14,10 @@ import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import com.study.course_registration.application.idempotency.IdempotencyCoordinator;
|
||||
import com.study.course_registration.application.idempotency.IdempotencyCoordinator.Decision;
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort.ReplayRecord;
|
||||
import com.study.course_registration.application.registration.port.RegistrationDecisionContextLoader;
|
||||
import com.study.course_registration.application.registration.idempotency.IdempotencyCoordinator;
|
||||
import com.study.course_registration.application.registration.idempotency.IdempotencyCoordinator.Decision;
|
||||
import com.study.course_registration.application.registration.idempotency.model.IdempotencyReplay;
|
||||
import com.study.course_registration.application.registration.port.RegistrationDecisionSnapshotLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationExecutionScopeLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.domain.registration.RegistrationExecutionScope;
|
||||
@@ -30,7 +30,7 @@ class RegisterCourseUseCaseTest {
|
||||
@DisplayName("idempotency replay → decision context 조회와 write 없이 즉시 반환")
|
||||
void replaySkipsDecisionContextLoading() {
|
||||
RegistrationExecutionScopeLoader scopes = mock(RegistrationExecutionScopeLoader.class);
|
||||
RegistrationDecisionContextLoader contexts = mock(RegistrationDecisionContextLoader.class);
|
||||
RegistrationDecisionSnapshotLoader contexts = mock(RegistrationDecisionSnapshotLoader.class);
|
||||
RegistrationWriter registrations = mock(RegistrationWriter.class);
|
||||
RegistrationPolicy policy = mock(RegistrationPolicy.class);
|
||||
RegistrationWindowGuard windowGuard = mock(RegistrationWindowGuard.class);
|
||||
@@ -38,7 +38,7 @@ class RegisterCourseUseCaseTest {
|
||||
|
||||
RegistrationExecutionScope scope =
|
||||
new RegistrationExecutionScope("user", "lesson");
|
||||
ReplayRecord replay = new ReplayRecord(
|
||||
IdempotencyReplay replay = new IdempotencyReplay(
|
||||
"registration",
|
||||
"user",
|
||||
"lesson",
|
||||
|
||||
+13
-8
@@ -15,6 +15,7 @@ import com.study.course_registration.application.registration.RegisterCourseComm
|
||||
import com.study.course_registration.application.registration.RegisterCourseUseCase;
|
||||
import com.study.course_registration.application.registration.RegistrationListResult;
|
||||
import com.study.course_registration.application.registration.RegistrationResult;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.Professor;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
@@ -32,7 +33,11 @@ import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
private static final Rejections<ApplicationFailure, RegistrationErrorCode> REJECTIONS =
|
||||
private static final Rejections<RegistrationRejection, RegistrationErrorCode> REGISTRATION_REJECTIONS =
|
||||
Rejections.of(
|
||||
RegistrationRejection.class,
|
||||
rejection -> RegistrationErrorCode.valueOf(rejection.code().name()));
|
||||
private static final Rejections<ApplicationFailure, RegistrationErrorCode> APPLICATION_FAILURES =
|
||||
Rejections.of(ApplicationFailure.class, ApplicationFailure::getErrorCode);
|
||||
|
||||
@Autowired RegisterCourseUseCase registerCourse;
|
||||
@@ -72,7 +77,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
.when(current -> register(
|
||||
current.student().getId(),
|
||||
current.lesson().getId()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED);
|
||||
.thenRejectedWith(REGISTRATION_REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,7 +106,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
|
||||
Scenario.given(other)
|
||||
.whenRunning(user -> cancelRegistration.execute(user.getId(), registration.registrationId()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_FORBIDDEN);
|
||||
.thenRejectedWith(APPLICATION_FAILURES, RegistrationErrorCode.REGISTRATION_FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -237,7 +242,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
|
||||
Scenario.given(student)
|
||||
.when(user -> register(user.getId(), lesson.getId()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED);
|
||||
.thenRejectedWith(REGISTRATION_REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -268,7 +273,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
void registrationListUserNotFound() {
|
||||
Scenario.given("missing")
|
||||
.when(userId -> getRegistrations.execute(userId, data.semester().getId()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.USER_NOT_FOUND);
|
||||
.thenRejectedWith(APPLICATION_FAILURES, RegistrationErrorCode.USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -276,7 +281,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
void registrationListExplicitSemesterNotFound() {
|
||||
Scenario.given("missing")
|
||||
.when(semesterId -> getRegistrations.execute(data.student().getId(), semesterId))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
.thenRejectedWith(APPLICATION_FAILURES, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -302,7 +307,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
|
||||
Scenario.given(student)
|
||||
.when(user -> getRegistrations.execute(user.getId(), null))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
.thenRejectedWith(APPLICATION_FAILURES, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -315,7 +320,7 @@ class RegistrationUseCaseIntegrationTest extends PostgresIntegrationTest {
|
||||
data.student().getId(),
|
||||
data.lesson().getId(),
|
||||
value))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.VALIDATION_ERROR);
|
||||
.thenRejectedWith(APPLICATION_FAILURES, RegistrationErrorCode.VALIDATION_ERROR);
|
||||
}
|
||||
|
||||
private RegistrationResult register(String userId, String lessonId) {
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.study.course_registration.application.registration.idempotency;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.study.course_registration.application.registration.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.support.MutableClock;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class CleanupIdempotencyUseCaseTest {
|
||||
@Test
|
||||
@DisplayName("cleanup → 현재 시각 기준으로 설정된 batch 크기만 삭제")
|
||||
void deletesSingleBatchAtCurrentTime() {
|
||||
MutableClock clock = new MutableClock(TestData.NOW, ZoneOffset.UTC);
|
||||
IdempotencyPort idempotencies = mock(IdempotencyPort.class);
|
||||
CleanupIdempotencyUseCase useCase =
|
||||
new CleanupIdempotencyUseCase(clock, idempotencies, 500);
|
||||
when(idempotencies.deleteExpiredBatch(TestData.NOW, 500)).thenReturn(23);
|
||||
|
||||
int deleted = useCase.execute();
|
||||
|
||||
assertThat(deleted).isEqualTo(23);
|
||||
verify(idempotencies).deleteExpiredBatch(TestData.NOW, 500);
|
||||
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
when(idempotencies.deleteExpiredBatch(TestData.NOW.plusSeconds(1), 500)).thenReturn(0);
|
||||
|
||||
assertThat(useCase.execute()).isZero();
|
||||
verify(idempotencies).deleteExpiredBatch(TestData.NOW.plusSeconds(1), 500);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ class ArchitectureTest {
|
||||
classes()
|
||||
.that().haveSimpleName("RegisterCourseUseCase")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationExecutionScopeLoader")
|
||||
.andShould().dependOnClassesThat().haveSimpleName("RegistrationDecisionContextLoader")
|
||||
.andShould().dependOnClassesThat().haveSimpleName("RegistrationDecisionSnapshotLoader")
|
||||
.check(classes);
|
||||
|
||||
classes()
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
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.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DatabaseSchemaParityTest {
|
||||
private static final Pattern CREATE_TABLE = Pattern.compile(
|
||||
"CREATE\\s+TABLE\\s+([A-Za-z0-9_]+)\\s*\\((.*?)\\);",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
|
||||
@Test
|
||||
@DisplayName("H2/PostgreSQL baseline → table·column 구조 동등")
|
||||
void baselineSchemasHaveSameTablesAndColumns() throws IOException {
|
||||
Map<String, Set<String>> postgres = tables(Path.of(
|
||||
"src/main/resources/db/migration/postgresql/V1__baseline.sql"));
|
||||
Map<String, Set<String>> h2 = tables(Path.of(
|
||||
"src/main/resources/db/migration/h2/V1__baseline.sql"));
|
||||
|
||||
assertThat(h2).isEqualTo(postgres);
|
||||
}
|
||||
|
||||
private static Map<String, Set<String>> tables(Path path) throws IOException {
|
||||
String sql = Files.readString(path);
|
||||
Matcher matcher = CREATE_TABLE.matcher(sql);
|
||||
Map<String, Set<String>> tables = new LinkedHashMap<>();
|
||||
while (matcher.find()) {
|
||||
tables.put(matcher.group(1).toLowerCase(), columns(matcher.group(2)));
|
||||
}
|
||||
return tables;
|
||||
}
|
||||
|
||||
private static Set<String> columns(String body) {
|
||||
Set<String> columns = new LinkedHashSet<>();
|
||||
for (String rawLine : body.split("\\R")) {
|
||||
String line = rawLine.trim();
|
||||
if (line.isEmpty()
|
||||
|| line.toUpperCase().startsWith("CONSTRAINT ")
|
||||
|| line.toUpperCase().startsWith("PRIMARY KEY")
|
||||
|| line.toUpperCase().startsWith("UNIQUE ")
|
||||
|| line.toUpperCase().startsWith("FOREIGN KEY")) {
|
||||
continue;
|
||||
}
|
||||
String token = line.split("\\s+", 2)[0].replace(",", "");
|
||||
columns.add(token.toLowerCase());
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ScenarioUsageTest {
|
||||
private static final String SCENARIO_GIVEN = "Scenario" + ".given(";
|
||||
|
||||
@Test
|
||||
@DisplayName("Scenario GWT → when 뒤 terminal assertion 필수")
|
||||
void scenarioChainsMustEndWithAssertion() throws IOException {
|
||||
List<String> violations = new ArrayList<>();
|
||||
|
||||
try (Stream<Path> files = Files.walk(Path.of("src/test/java"))) {
|
||||
files.filter(path -> path.toString().endsWith(".java"))
|
||||
.filter(path -> !path.endsWith("ScenarioUsageTest.java"))
|
||||
.forEach(path -> inspect(path, violations));
|
||||
}
|
||||
|
||||
assertThat(violations)
|
||||
.as("Scenario.given(...).when(...) 체인은 then 계열 assertion으로 종료해야 합니다.")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
private static void inspect(Path path, List<String> violations) {
|
||||
try {
|
||||
String source = Files.readString(path);
|
||||
int cursor = 0;
|
||||
while (true) {
|
||||
int start = source.indexOf(SCENARIO_GIVEN, cursor);
|
||||
if (start < 0) {
|
||||
return;
|
||||
}
|
||||
int end = statementEnd(source, start);
|
||||
if (end < 0) {
|
||||
violations.add(path + " Scenario statement terminator not found");
|
||||
return;
|
||||
}
|
||||
String statement = source.substring(start, end + 1);
|
||||
if (statement.contains(".when") && !statement.contains(".then")) {
|
||||
int line = source.substring(0, start).split("\\R", -1).length;
|
||||
violations.add(path + ":" + line + " missing terminal assertion");
|
||||
}
|
||||
cursor = end + 1;
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("Scenario usage 검사 실패: " + path, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static int statementEnd(String source, int start) {
|
||||
int parentheses = 0;
|
||||
int braces = 0;
|
||||
int brackets = 0;
|
||||
boolean inString = false;
|
||||
boolean inChar = false;
|
||||
boolean escaped = false;
|
||||
|
||||
for (int index = start; index < source.length(); index++) {
|
||||
char current = source.charAt(index);
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
if ((inString || inChar) && current == '\\') {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if (!inChar && current == '"') {
|
||||
inString = !inString;
|
||||
continue;
|
||||
}
|
||||
if (!inString && current == '\'') {
|
||||
inChar = !inChar;
|
||||
continue;
|
||||
}
|
||||
if (inString || inChar) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current == '(') {
|
||||
parentheses++;
|
||||
} else if (current == ')') {
|
||||
parentheses--;
|
||||
} else if (current == '{') {
|
||||
braces++;
|
||||
} else if (current == '}') {
|
||||
braces--;
|
||||
} else if (current == '[') {
|
||||
brackets++;
|
||||
} else if (current == ']') {
|
||||
brackets--;
|
||||
} else if (current == ';' && parentheses == 0 && braces == 0 && brackets == 0) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
+2
-8
@@ -12,9 +12,6 @@ import com.study.course_registration.domain.registration.rule.AlreadyRegisteredR
|
||||
import com.study.course_registration.domain.registration.rule.CapacityRule;
|
||||
import com.study.course_registration.domain.registration.rule.CreditLimitRule;
|
||||
import com.study.course_registration.domain.registration.rule.DuplicateSubjectRule;
|
||||
import com.study.course_registration.domain.registration.rule.GradeEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.RegistrationPeriodRule;
|
||||
import com.study.course_registration.domain.registration.rule.RoleEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleAvailabilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleConflictRule;
|
||||
import com.study.course_registration.domain.schedule.ScheduleConflictChecker;
|
||||
@@ -146,7 +143,7 @@ final class RegistrationFixture {
|
||||
return registrationEndAt;
|
||||
}
|
||||
|
||||
private RegistrationContext context(Instant now) {
|
||||
private RegistrationDecisionSnapshot context(Instant now) {
|
||||
UserProfile user = new UserProfile("user", grade, UserRole.STUDENT);
|
||||
LessonPolicySnapshot candidate = candidate();
|
||||
|
||||
@@ -176,7 +173,7 @@ final class RegistrationFixture {
|
||||
}
|
||||
}
|
||||
|
||||
return new RegistrationContext(
|
||||
return new RegistrationDecisionSnapshot(
|
||||
user,
|
||||
candidate,
|
||||
active,
|
||||
@@ -204,9 +201,6 @@ final class RegistrationFixture {
|
||||
private static RegistrationPolicy policy() {
|
||||
ScheduleConflictChecker checker = new ScheduleConflictChecker();
|
||||
return new RegistrationPolicy(
|
||||
new RegistrationPeriodRule(),
|
||||
new GradeEligibilityRule(),
|
||||
new RoleEligibilityRule(),
|
||||
new AlreadyRegisteredRule(),
|
||||
new DuplicateSubjectRule(),
|
||||
new ScheduleAvailabilityRule(),
|
||||
|
||||
+28
-9
@@ -3,6 +3,8 @@ package com.study.course_registration.domain.registration;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
@@ -12,18 +14,18 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
import com.study.course_registration.failure.ApplicationFailure;
|
||||
import com.study.course_registration.failure.InvariantCode;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
import com.study.course_registration.support.MutableClock;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
|
||||
@DisplayName("수강신청 정책")
|
||||
class RegistrationPolicyTest {
|
||||
private static final Rejections<ApplicationFailure, RegistrationErrorCode> REJECTIONS =
|
||||
Rejections.of(ApplicationFailure.class, ApplicationFailure::getErrorCode);
|
||||
private static final Rejections<SystemInvariantViolation, InvariantCode> INVARIANTS =
|
||||
Rejections.of(SystemInvariantViolation.class, SystemInvariantViolation::getInvariantCode);
|
||||
private static final Rejections<RegistrationRejection, RegistrationErrorCode> REJECTIONS =
|
||||
Rejections.of(
|
||||
RegistrationRejection.class,
|
||||
rejection -> RegistrationErrorCode.valueOf(rejection.code().name()));
|
||||
private static final Rejections<RegistrationInvariantViolation, RegistrationInvariant> INVARIANTS =
|
||||
Rejections.of(RegistrationInvariantViolation.class, RegistrationInvariantViolation::invariant);
|
||||
|
||||
@Nested
|
||||
@DisplayName("R1 신청 기간")
|
||||
@@ -42,6 +44,23 @@ class RegistrationPolicyTest {
|
||||
Scenario.given(fixture).when(f -> f.checkEligibilityAt(f.registrationEndAt())).thenAccepted();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("종료 정각 허용 → 1ns 이후 기간 종료 거부")
|
||||
void endBoundaryWithMovingClock() {
|
||||
RegistrationFixture fixture = RegistrationFixture.student(2);
|
||||
MutableClock clock = new MutableClock(fixture.registrationEndAt(), ZoneOffset.UTC);
|
||||
|
||||
Scenario.given(fixture)
|
||||
.when(current -> current.checkEligibilityAt(clock.instant()))
|
||||
.thenAccepted();
|
||||
|
||||
clock.advance(Duration.ofNanos(1));
|
||||
|
||||
Scenario.given(fixture)
|
||||
.when(current -> current.checkEligibilityAt(clock.instant()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기간 종료 + 학년 미달 → R1")
|
||||
void periodBeforeGrade() {
|
||||
@@ -133,7 +152,7 @@ class RegistrationPolicyTest {
|
||||
void missingCandidateSchedule() {
|
||||
Scenario.given(RegistrationFixture.student(2).withoutSchedule())
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(INVARIANTS, InvariantCode.MISSING_CANDIDATE_LESSON_SCHEDULE);
|
||||
.thenRejectedWith(INVARIANTS, RegistrationInvariant.MISSING_CANDIDATE_LESSON_SCHEDULE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -141,7 +160,7 @@ class RegistrationPolicyTest {
|
||||
void missingExistingSchedule() {
|
||||
Scenario.given(RegistrationFixture.student(2).alreadyRegistered("old", 3).existingWithoutSchedule())
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(INVARIANTS, InvariantCode.MISSING_EXISTING_LESSON_SCHEDULE);
|
||||
.thenRejectedWith(INVARIANTS, RegistrationInvariant.MISSING_EXISTING_LESSON_SCHEDULE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -157,8 +157,8 @@ class EntityInvariantTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 신청 두 번 취소 → 도메인 거부")
|
||||
void doubleCancel() {
|
||||
@DisplayName("같은 신청 두 번 취소 → 최초 취소 시각을 유지")
|
||||
void doubleCancelIsIdempotent() {
|
||||
UserLesson registration = DomainFixtures.registration(
|
||||
DomainFixtures.student(2),
|
||||
DomainFixtures.lesson(
|
||||
@@ -166,23 +166,9 @@ class EntityInvariantTest {
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester()));
|
||||
registration.cancel(TestData.NOW);
|
||||
registration.cancel(TestData.NOW.plusSeconds(10));
|
||||
|
||||
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);
|
||||
assertThat(registration.getCanceledAt()).isEqualTo(TestData.NOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+8
-3
@@ -3,6 +3,7 @@ package com.study.course_registration.infrastructure.persistence;
|
||||
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.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
@@ -20,7 +21,7 @@ import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
class JpaRegistrationExecutionScopeLoaderTest {
|
||||
@Test
|
||||
@DisplayName("execution scope 확보 → User 다음 Lesson 순서로 직렬화")
|
||||
@DisplayName("execution scope → User 직렬화 후 필요할 때 Lesson 직렬화")
|
||||
void userThenLesson() {
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
LessonRepository lessons = mock(LessonRepository.class);
|
||||
@@ -38,10 +39,14 @@ class JpaRegistrationExecutionScopeLoaderTest {
|
||||
|
||||
RegistrationExecutionScope scope = loader.open("user", "lesson");
|
||||
|
||||
assertThat(scope.userId()).isEqualTo("user");
|
||||
assertThat(scope.lessonId()).isEqualTo("lesson");
|
||||
verifyNoInteractions(lessons);
|
||||
|
||||
loader.lockLesson(scope);
|
||||
|
||||
InOrder order = inOrder(users, lessons);
|
||||
order.verify(users).findByIdForUpdate("user");
|
||||
order.verify(lessons).findByIdForUpdate("lesson");
|
||||
assertThat(scope.userId()).isEqualTo("user");
|
||||
assertThat(scope.lessonId()).isEqualTo("lesson");
|
||||
}
|
||||
}
|
||||
|
||||
+39
-32
@@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -12,11 +13,12 @@ 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 org.springframework.data.domain.PageRequest;
|
||||
|
||||
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.infrastructure.persistence.idempotency.RegistrationIdempotencyEntity;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
@@ -39,10 +41,10 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("userId + key + 유효기간 조회 → 연관 graph와 lifecycle 로드")
|
||||
@DisplayName("userId + key + 유효기간 조회 → replay snapshot과 필수 연관만 로드")
|
||||
void lookupGraph() {
|
||||
Instant expiresAt = TestData.NOW.plusSeconds(86400);
|
||||
repository.saveAndFlush(idempotency("request-1", registration, data.lesson(), expiresAt));
|
||||
repository.saveAndFlush(idempotency("request-1", registration, data.lesson(), 3, expiresAt));
|
||||
|
||||
Scenario.given("request-1")
|
||||
.when(key -> repository
|
||||
@@ -54,9 +56,12 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
.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.getLessonName()).isEqualTo(data.lesson().getName());
|
||||
assertThat(stored.getSubjectCode()).isEqualTo(data.subject().getCode());
|
||||
assertThat(stored.getCredit()).isEqualTo(data.subject().getCredit());
|
||||
assertThat(stored.getRegisteredAt()).isEqualTo(registration.getCreatedAt());
|
||||
assertThat(stored.getTotalCredits()).isEqualTo(3);
|
||||
assertThat(stored.getExpiresAt()).isEqualTo(expiresAt);
|
||||
});
|
||||
}
|
||||
@@ -65,7 +70,7 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
@DisplayName("만료 key 삭제 → 같은 user + key 재사용 가능")
|
||||
void expiredKeyCanBeRemoved() {
|
||||
Instant expiredAt = TestData.NOW.minusSeconds(1);
|
||||
repository.saveAndFlush(idempotency("request-expired", registration, data.lesson(), expiredAt));
|
||||
repository.saveAndFlush(idempotency("request-expired", registration, data.lesson(), 3, expiredAt));
|
||||
|
||||
Scenario.given("request-expired")
|
||||
.when(key -> repository.deleteExpiredKey(
|
||||
@@ -79,12 +84,13 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("만료 전체 정리 → expiresAt 지난 행만 삭제")
|
||||
void deleteExpired() {
|
||||
repository.saveAndFlush(idempotency(
|
||||
@DisplayName("만료 정리 조회 → batch 크기만큼 오래된 id만 반환")
|
||||
void findExpiredIdsIsBounded() {
|
||||
RegistrationIdempotencyEntity expired = repository.saveAndFlush(idempotency(
|
||||
"expired",
|
||||
registration,
|
||||
data.lesson(),
|
||||
3,
|
||||
TestData.NOW.minusSeconds(1)));
|
||||
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("FRESH"));
|
||||
@@ -93,22 +99,18 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
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,
|
||||
repository.saveAndFlush(idempotency(
|
||||
"fresh",
|
||||
freshRegistration,
|
||||
freshLesson,
|
||||
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");
|
||||
});
|
||||
List<String> expiredIds = repository.findExpiredIds(
|
||||
TestData.NOW,
|
||||
PageRequest.of(0, 1));
|
||||
|
||||
assertThat(expiredIds).containsExactly(expired.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,6 +120,7 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
"request-1",
|
||||
registration,
|
||||
data.lesson(),
|
||||
3,
|
||||
TestData.NOW.plusSeconds(86400)));
|
||||
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("OTHER"));
|
||||
@@ -127,11 +130,10 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
UserLesson otherRegistration =
|
||||
fixture.registration(DomainFixtures.registration(data.student(), otherLesson));
|
||||
|
||||
assertThatThrownBy(() -> repository.saveAndFlush(new RegistrationIdempotency(
|
||||
data.student(),
|
||||
otherLesson,
|
||||
otherRegistration,
|
||||
assertThatThrownBy(() -> repository.saveAndFlush(idempotency(
|
||||
"request-1",
|
||||
otherRegistration,
|
||||
otherLesson,
|
||||
6,
|
||||
TestData.NOW.plusSeconds(86400))))
|
||||
.isInstanceOf(DataIntegrityViolationException.class);
|
||||
@@ -144,29 +146,34 @@ class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
"request-1",
|
||||
registration,
|
||||
data.lesson(),
|
||||
3,
|
||||
TestData.NOW.plusSeconds(86400)));
|
||||
|
||||
assertThatThrownBy(() -> repository.saveAndFlush(new RegistrationIdempotency(
|
||||
data.student(),
|
||||
data.lesson(),
|
||||
registration,
|
||||
assertThatThrownBy(() -> repository.saveAndFlush(idempotency(
|
||||
"request-2",
|
||||
registration,
|
||||
data.lesson(),
|
||||
3,
|
||||
TestData.NOW.plusSeconds(86400))))
|
||||
.isInstanceOf(DataIntegrityViolationException.class);
|
||||
}
|
||||
|
||||
private RegistrationIdempotency idempotency(
|
||||
private RegistrationIdempotencyEntity idempotency(
|
||||
String key,
|
||||
UserLesson target,
|
||||
Lesson lesson,
|
||||
int totalCredits,
|
||||
Instant expiresAt) {
|
||||
return new RegistrationIdempotency(
|
||||
return new RegistrationIdempotencyEntity(
|
||||
data.student(),
|
||||
lesson,
|
||||
target,
|
||||
key,
|
||||
3,
|
||||
lesson.getName(),
|
||||
lesson.getSubject().getCode(),
|
||||
lesson.getSubject().getCredit(),
|
||||
target.getCreatedAt(),
|
||||
totalCredits,
|
||||
expiresAt);
|
||||
}
|
||||
}
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.study.course_registration.infrastructure.scheduling;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.OptionalInt;
|
||||
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 org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.study.course_registration.support.CourseIntegrationTest;
|
||||
|
||||
@CourseIntegrationTest
|
||||
class DatabaseJobLockTest {
|
||||
private static final String TEST_LOCK = "database-job-lock-test";
|
||||
|
||||
@Autowired DatabaseJobLock jobLock;
|
||||
@Autowired JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 maintenance lock 동시 획득 → 한 실행만 진입")
|
||||
void onlyOneConcurrentOwner() throws Exception {
|
||||
jdbcTemplate.update("delete from maintenance_locks where name = ?", TEST_LOCK);
|
||||
jdbcTemplate.update("insert into maintenance_locks(name) values (?)", TEST_LOCK);
|
||||
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
|
||||
try {
|
||||
Future<OptionalInt> first = executor.submit(() -> jobLock.callWithLock(
|
||||
TEST_LOCK,
|
||||
() -> {
|
||||
entered.countDown();
|
||||
await(release);
|
||||
return 1;
|
||||
}));
|
||||
|
||||
assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
OptionalInt second = jobLock.callWithLock(
|
||||
TEST_LOCK,
|
||||
() -> {
|
||||
throw new AssertionError("second owner must not execute");
|
||||
});
|
||||
|
||||
assertThat(second.isEmpty()).isTrue();
|
||||
release.countDown();
|
||||
|
||||
OptionalInt firstResult = first.get(5, TimeUnit.SECONDS);
|
||||
assertThat(firstResult.isPresent()).isTrue();
|
||||
assertThat(firstResult.getAsInt()).isEqualTo(1);
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
jdbcTemplate.update("delete from maintenance_locks where name = ?", TEST_LOCK);
|
||||
}
|
||||
}
|
||||
|
||||
private static void await(CountDownLatch latch) {
|
||||
try {
|
||||
if (!latch.await(5, TimeUnit.SECONDS)) {
|
||||
throw new IllegalStateException("lock test latch timeout");
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("lock test interrupted", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
-6
@@ -1,23 +1,45 @@
|
||||
package com.study.course_registration.infrastructure.scheduling;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.OptionalInt;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.study.course_registration.application.idempotency.CleanupIdempotencyUseCase;
|
||||
import com.study.course_registration.infrastructure.scheduling.IdempotencyRetentionJob;
|
||||
import com.study.course_registration.application.registration.idempotency.CleanupIdempotencyUseCase;
|
||||
|
||||
class IdempotencyRetentionJobTest {
|
||||
@Test
|
||||
@DisplayName("cleanup → CleanupIdempotencyUseCase 실행")
|
||||
void cleanup() {
|
||||
@DisplayName("cleanup batch 완료 후 빈 batch → 반복 종료")
|
||||
void cleanupStopsOnEmptyBatch() {
|
||||
CleanupIdempotencyUseCase cleanup = mock(CleanupIdempotencyUseCase.class);
|
||||
IdempotencyRetentionJob job = new IdempotencyRetentionJob(cleanup);
|
||||
DatabaseJobLock jobLock = mock(DatabaseJobLock.class);
|
||||
when(jobLock.callWithLock(eq(IdempotencyRetentionJob.LOCK_NAME), any(IntSupplier.class)))
|
||||
.thenAnswer(invocation -> OptionalInt.of(invocation.<IntSupplier>getArgument(1).getAsInt()));
|
||||
when(cleanup.execute()).thenReturn(500, 3, 0);
|
||||
|
||||
IdempotencyRetentionJob job = new IdempotencyRetentionJob(cleanup, jobLock, 20);
|
||||
job.cleanup();
|
||||
|
||||
verify(cleanup).execute();
|
||||
verify(cleanup, org.mockito.Mockito.times(3)).execute();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("cleanup lock 미획득 → 삭제 실행 안 함")
|
||||
void cleanupSkipsWhenLockIsOwnedByAnotherInstance() {
|
||||
CleanupIdempotencyUseCase cleanup = mock(CleanupIdempotencyUseCase.class);
|
||||
DatabaseJobLock jobLock = mock(DatabaseJobLock.class);
|
||||
when(jobLock.callWithLock(eq(IdempotencyRetentionJob.LOCK_NAME), any(IntSupplier.class)))
|
||||
.thenReturn(OptionalInt.empty());
|
||||
|
||||
new IdempotencyRetentionJob(cleanup, jobLock, 20).cleanup();
|
||||
|
||||
verify(cleanup, org.mockito.Mockito.never()).execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.study.course_registration.support;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class MutableClock extends Clock {
|
||||
private final AtomicReference<Instant> current;
|
||||
private final ZoneId zone;
|
||||
|
||||
public MutableClock(Instant initialInstant, ZoneId zone) {
|
||||
this(new AtomicReference<>(Objects.requireNonNull(initialInstant, "initialInstant")),
|
||||
Objects.requireNonNull(zone, "zone"));
|
||||
}
|
||||
|
||||
private MutableClock(AtomicReference<Instant> current, ZoneId zone) {
|
||||
this.current = current;
|
||||
this.zone = zone;
|
||||
}
|
||||
|
||||
public void set(Instant instant) {
|
||||
current.set(Objects.requireNonNull(instant, "instant"));
|
||||
}
|
||||
|
||||
public void advance(Duration duration) {
|
||||
Objects.requireNonNull(duration, "duration");
|
||||
current.updateAndGet(instant -> instant.plus(duration));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return zone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId targetZone) {
|
||||
return new MutableClock(current, Objects.requireNonNull(targetZone, "targetZone"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return current.get();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.study.course_registration.support.fixture;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
@@ -15,13 +14,14 @@ import com.study.course_registration.infrastructure.persistence.repository.Semes
|
||||
import com.study.course_registration.infrastructure.persistence.repository.SubjectRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserLessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserRepository;
|
||||
import com.study.course_registration.support.MutableClock;
|
||||
|
||||
@TestConfiguration(proxyBeanMethods = false)
|
||||
public class TestFixtureConfig {
|
||||
@Bean
|
||||
@Primary
|
||||
Clock testClock() {
|
||||
return Clock.fixed(TestData.NOW, ZoneOffset.UTC);
|
||||
MutableClock testClock() {
|
||||
return new MutableClock(TestData.NOW, ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -2,15 +2,19 @@ package com.study.course_registration.web.error;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLTransientConnectionException;
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.domain.registration.RegistrationRejection;
|
||||
import com.study.course_registration.failure.RetryableInfrastructureFailure;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
@@ -29,7 +33,7 @@ class ApiExceptionHandlerTest {
|
||||
@DisplayName("business rejection → HTTP mapper 결과 + stacktrace 없는 정상 실패")
|
||||
void businessRejection() {
|
||||
ResponseEntity<ApiErrorResponse> response =
|
||||
handler.application(BusinessRejection.capacityExceeded(30, 30));
|
||||
handler.registrationRejected(RegistrationRejection.capacityExceeded(30, 30));
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(409);
|
||||
assertThat(response.getBody().code()).isEqualTo("CAPACITY_EXCEEDED");
|
||||
@@ -48,6 +52,36 @@ class ApiExceptionHandlerTest {
|
||||
assertThat(response.getBody().code()).isEqualTo("LOCK_TIMEOUT");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("DB pool 고갈 → 503 DB_POOL_EXHAUSTED")
|
||||
void dbPoolExhausted() {
|
||||
ResponseEntity<ApiErrorResponse> response = handler.retryable(
|
||||
RetryableInfrastructureFailure.dbPoolExhausted(
|
||||
new SQLTransientConnectionException("pool exhausted")));
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(503);
|
||||
assertThat(response.getBody().code()).isEqualTo("DB_POOL_EXHAUSTED");
|
||||
assertThat(registry.get("application_failure_total")
|
||||
.tag("reason", "db_pool_exhausted")
|
||||
.counter()
|
||||
.count())
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("DB 연결 SQLState 08 → 503 DB_UNAVAILABLE")
|
||||
void dbUnavailable() {
|
||||
DataAccessResourceFailureException failure =
|
||||
new DataAccessResourceFailureException(
|
||||
"database down",
|
||||
new SQLException("connection refused", "08006"));
|
||||
|
||||
ResponseEntity<ApiErrorResponse> response = handler.databaseResourceFailure(failure);
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(503);
|
||||
assertThat(response.getBody().code()).isEqualTo("DB_UNAVAILABLE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("system invariant → 500 + invariant metric")
|
||||
void invariant() {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.study.course_registration.web.error;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
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.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.study.course_registration.support.CourseIntegrationTest;
|
||||
|
||||
@CourseIntegrationTest
|
||||
@AutoConfigureMockMvc
|
||||
@DisplayName("Spring MVC 표준 오류 계약")
|
||||
class SpringMvcErrorContractTest {
|
||||
@Autowired MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 API → 404 NOT_FOUND")
|
||||
void unknownRoute404() throws Exception {
|
||||
mockMvc.perform(get("/api/v1/not-found"))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$.code").value("NOT_FOUND"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("지원하지 않는 메서드 → 405 METHOD_NOT_ALLOWED")
|
||||
void unsupportedMethod405() throws Exception {
|
||||
mockMvc.perform(put("/api/v1/lessons"))
|
||||
.andExpect(status().isMethodNotAllowed())
|
||||
.andExpect(jsonPath("$.code").value("METHOD_NOT_ALLOWED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("지원하지 않는 Content-Type → 415 UNSUPPORTED_MEDIA_TYPE")
|
||||
void unsupportedMediaType415() throws Exception {
|
||||
mockMvc.perform(post("/api/v1/users/user/registrations")
|
||||
.contentType(MediaType.TEXT_PLAIN)
|
||||
.content("{\"lessonId\":\"lesson\"}"))
|
||||
.andExpect(status().isUnsupportedMediaType())
|
||||
.andExpect(jsonPath("$.code").value("UNSUPPORTED_MEDIA_TYPE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("요청 파라미터 타입 불일치 → 400 VALIDATION_ERROR")
|
||||
void typeMismatch400() throws Exception {
|
||||
mockMvc.perform(get("/api/v1/lessons?page=abc"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value("VALIDATION_ERROR"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user