TA 역할 Spring 경계 smoke #3
9 changed files with 478 additions and 0 deletions
|
|
@ -0,0 +1,3 @@
|
|||
# role-ta-live-1522-001-attempt-1-run-6e84b72613b1
|
||||
|
||||
Forge 이슈 작업 브랜치 `forge/role-ta-live-1522-001-attempt-1-run-6e84b72613b1`.
|
||||
84
docs/adr/ADR-001-spring-architecture-boundaries.md
Normal file
84
docs/adr/ADR-001-spring-architecture-boundaries.md
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
# ADR-001: Spring MVC 아키텍처 경계 및 계약 정의
|
||||
|
||||
## Context
|
||||
|
||||
runtime-role-matrix-live 프로젝트는 Spring Boot 기반 REST API 서버로 역할 기반 접근 제어(RBAC)를 구현한다. 레이어 간 책임 분담, 오류 처리 계약, 트랜잭션 범위가 명시적으로 정의되어 있지 않아 일관성 없는 구현이 발생할 위험이 있다.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. 레이어 경계 정의
|
||||
|
||||
| 레이어 | 책임 |
|
||||
|-------|------|
|
||||
| **Controller** | HTTP 요청/응답, 입력 검증, DTO 변환, HTTP 상태 코드 결정. 트랜잭션 경계 없음 |
|
||||
| **Service** | 비즈니스 로직, 도메인 객체 조작, @Transactional 선언적 트랜잭션, BusinessException 발생 |
|
||||
| **Repository** | 데이터 접근(JPA), 쿼리 실행, Entity 변환. 순수 데이터 조작만 수행 |
|
||||
|
||||
### 2. 오류 계약 (RFC 7807 Problem Details)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "https://api.runtimematrix.com/errors/role-not-found",
|
||||
"title": "역할을 찾을 수 없습니다",
|
||||
"status": 404,
|
||||
"detail": "ID가 'admin'인 역할이 존재하지 않습니다.",
|
||||
"instance": "/api/v1/roles/admin",
|
||||
"timestamp": "2026-07-14T15:22:00Z",
|
||||
"traceId": "abc123def456"
|
||||
}
|
||||
```
|
||||
|
||||
**예외 계층**: `RuntimeException → BusinessException(추상) → RoleNotFoundException, RoleAlreadyExistsException`
|
||||
|
||||
**HTTP 상태 매핑**:
|
||||
|
||||
| 예외 | 상태 |
|
||||
|-----|------|
|
||||
| ValidationException | 400 |
|
||||
| BusinessException | 400/409 |
|
||||
| RoleNotFoundException | 404 |
|
||||
| PermissionDeniedException | 403 |
|
||||
| InternalServerException | 500 |
|
||||
|
||||
### 3. 트랜잭션 경계
|
||||
|
||||
| 규칙 | 설명 |
|
||||
|-----|------|
|
||||
| 시작점 | Service Layer public 메서드 |
|
||||
| 전파 | REQUIRED (기본값) |
|
||||
| 읽기 전용 | SELECT-only 메서드에 `readOnly=true` |
|
||||
| 격리 수준 | READ_COMMITTED |
|
||||
| 롤백 | RuntimeException, BusinessException → Yes |
|
||||
|
||||
### 4. 의존성 규칙
|
||||
|
||||
| From → To | 허용 |
|
||||
|-----------|------|
|
||||
| Controller → Service | ✅ |
|
||||
| Controller → Repository | ❌ |
|
||||
| Service → Repository | ✅ |
|
||||
| Service → Domain | ✅ |
|
||||
| Repository → Service | ❌ |
|
||||
|
||||
### 5. 패키지 구조
|
||||
|
||||
```
|
||||
com.runtimematrix
|
||||
├── controller/dto # Request/Response DTO
|
||||
├── service/command # Command 객체
|
||||
├── repository # JPA Repository
|
||||
├── domain/model # 도메인 객체
|
||||
├── domain/exception # 도메인 예외
|
||||
└── config # Spring Configuration
|
||||
```
|
||||
|
||||
## Consequences
|
||||
|
||||
**긍정**: 레이어별 책임 명확, 일관된 오류 응답, 데이터 일관성 보장, 테스트 용이성 향상
|
||||
|
||||
**부정**: 기존 코드 수정 필요, 추가 DTO/Command 클래스 필요
|
||||
|
||||
## References
|
||||
|
||||
- [Spring Transaction Management](https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction)
|
||||
- [RFC 7807 Problem Details](https://tools.ietf.org/html/rfc7807)
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
package com.runtimematrix.config;
|
||||
|
||||
import com.runtimematrix.controller.dto.ErrorResponse;
|
||||
import com.runtimematrix.domain.exception.BusinessException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** 전역 예외 처리기 - RFC 7807 Problem Details 형식으로 변환 */
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex, HttpServletRequest request) {
|
||||
String traceId = getOrGenerateTraceId();
|
||||
MDC.put("traceId", traceId);
|
||||
log.warn("[{}] {} - {}", traceId, ex.getErrorCode(), ex.getMessage());
|
||||
|
||||
return ResponseEntity.status(ex.getHttpStatus())
|
||||
.body(ErrorResponse.of(ex.getType(), ex.getErrorCode(), ex.getMessage(),
|
||||
ex.getHttpStatus(), request.getRequestURI(), traceId));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidationException(MethodArgumentNotValidException ex, HttpServletRequest request) {
|
||||
String traceId = getOrGenerateTraceId();
|
||||
String detail = ex.getBindingResult().getFieldErrors().stream()
|
||||
.map(FieldError::getDefaultMessage).collect(Collectors.joining("; "));
|
||||
log.warn("[{}] Validation failed: {}", traceId, detail);
|
||||
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ErrorResponse.of("https://api.runtimematrix.com/errors/validation-failed",
|
||||
"validation-failed", "입력 검증에 실패했습니다: " + detail,
|
||||
HttpStatus.BAD_REQUEST.value(), request.getRequestURI(), traceId));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex, HttpServletRequest request) {
|
||||
String traceId = getOrGenerateTraceId();
|
||||
log.error("[{}] Unexpected error", traceId, ex);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(ErrorResponse.of("https://api.runtimematrix.com/errors/internal-server-error",
|
||||
"internal-server-error", "예상치 못한 오류가 발생했습니다.",
|
||||
HttpStatus.INTERNAL_SERVER_ERROR.value(), request.getRequestURI(), traceId));
|
||||
}
|
||||
|
||||
private String getOrGenerateTraceId() {
|
||||
String existing = MDC.get("traceId");
|
||||
return existing != null ? existing : UUID.randomUUID().toString().substring(0, 12);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
package com.runtimematrix.controller;
|
||||
|
||||
import com.runtimematrix.controller.dto.RoleResponse;
|
||||
import com.runtimematrix.domain.model.Role;
|
||||
import com.runtimematrix.service.RoleService;
|
||||
import com.runtimematrix.service.command.CreateRoleCommand;
|
||||
import com.runtimematrix.service.command.UpdateRoleCommand;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 역할 관리 REST 컨트롤러.
|
||||
* ADR-001 Controller 경계: HTTP 처리, 검증, DTO 변환만 수행. 비즈니스 로직 없음.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/roles")
|
||||
public class RoleController {
|
||||
|
||||
private final RoleService roleService;
|
||||
|
||||
public RoleController(RoleService roleService) {
|
||||
this.roleService = roleService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<RoleResponse> createRole(@Valid @RequestBody CreateRoleRequest request) {
|
||||
CreateRoleCommand command = new CreateRoleCommand(request.name(), request.description());
|
||||
Role created = roleService.createRole(command);
|
||||
return ResponseEntity.created(URI.create("/api/v1/roles/" + created.getId()))
|
||||
.body(RoleResponse.from(created));
|
||||
}
|
||||
|
||||
@GetMapping("/{roleId}")
|
||||
public ResponseEntity<RoleResponse> getRole(@PathVariable String roleId) {
|
||||
return ResponseEntity.ok(RoleResponse.from(roleService.getRole(roleId)));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<RoleResponse>> getAllRoles() {
|
||||
return ResponseEntity.ok(roleService.getAllRoles().stream()
|
||||
.map(RoleResponse::from).toList());
|
||||
}
|
||||
|
||||
@PutMapping("/{roleId}")
|
||||
public ResponseEntity<RoleResponse> updateRole(
|
||||
@PathVariable String roleId,
|
||||
@Valid @RequestBody UpdateRoleRequest request) {
|
||||
UpdateRoleCommand command = new UpdateRoleCommand(request.name(), request.description());
|
||||
return ResponseEntity.ok(RoleResponse.from(roleService.updateRole(roleId, command)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{roleId}")
|
||||
public ResponseEntity<Void> deleteRole(@PathVariable String roleId) {
|
||||
roleService.deleteRole(roleId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package com.runtimematrix.controller.dto;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** RFC 7807 Problem Details 형식의 오류 응답 DTO */
|
||||
public record ErrorResponse(
|
||||
String type, String title, int status, String detail,
|
||||
String instance, String timestamp, String traceId
|
||||
) {
|
||||
public static ErrorResponse of(String type, String title, String detail,
|
||||
int status, String instance, String traceId) {
|
||||
return new ErrorResponse(type, title, status, detail, instance, Instant.now().toString(), traceId);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
package com.runtimematrix.domain.exception;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
|
||||
/**
|
||||
* 비즈니스 로직 수행 중 발생하는 예외의 기본 클래스.
|
||||
* 모든 도메인 예외는 이 클래스를 상속한다.
|
||||
*/
|
||||
public abstract class BusinessException extends RuntimeException {
|
||||
|
||||
private final String errorCode;
|
||||
private final String resourceId;
|
||||
|
||||
protected BusinessException(String errorCode, String message, String resourceId) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
this.resourceId = resourceId;
|
||||
}
|
||||
|
||||
public String getErrorCode() { return errorCode; }
|
||||
public String getResourceId() { return resourceId; }
|
||||
public abstract int getHttpStatus();
|
||||
public String getType() { return "https://api.runtimematrix.com/errors/" + errorCode; }
|
||||
|
||||
/** 역할 미존재 예외 */
|
||||
public static class RoleNotFoundException extends BusinessException {
|
||||
private static final String CODE = "role-not-found";
|
||||
public RoleNotFoundException(String roleId) {
|
||||
super(CODE, MessageFormat.format("ID가 ''{0}''인 역할을 찾을 수 없습니다.", roleId), roleId);
|
||||
}
|
||||
@Override public int getHttpStatus() { return 404; }
|
||||
}
|
||||
|
||||
/** 역할 중복 예외 */
|
||||
public static class RoleAlreadyExistsException extends BusinessException {
|
||||
private static final String CODE = "role-already-exists";
|
||||
public RoleAlreadyExistsException(String roleName) {
|
||||
super(CODE, MessageFormat.format("이름이 ''{0}''인 역할이 이미 존재합니다.", roleName), roleName);
|
||||
}
|
||||
@Override public int getHttpStatus() { return 409; }
|
||||
}
|
||||
}
|
||||
85
src/main/java/com/runtimematrix/service/RoleService.java
Normal file
85
src/main/java/com/runtimematrix/service/RoleService.java
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
package com.runtimematrix.service;
|
||||
|
||||
import com.runtimematrix.domain.exception.BusinessException;
|
||||
import com.runtimematrix.domain.model.Role;
|
||||
import com.runtimematrix.repository.RoleRepository;
|
||||
import com.runtimematrix.service.command.CreateRoleCommand;
|
||||
import com.runtimematrix.service.command.UpdateRoleCommand;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 역할 관리 서비스.
|
||||
* ADR-001 트랜잭션 경계: Service Layer public 메서드에서 시작
|
||||
*/
|
||||
@Service
|
||||
public class RoleService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RoleService.class);
|
||||
private final RoleRepository roleRepository;
|
||||
|
||||
public RoleService(RoleRepository roleRepository) {
|
||||
this.roleRepository = roleRepository;
|
||||
}
|
||||
|
||||
/** 쓰기 트랜잭션 */
|
||||
@Transactional
|
||||
public Role createRole(CreateRoleCommand command) {
|
||||
log.debug("Creating role: {}", command.name());
|
||||
if (roleRepository.existsByName(command.name())) {
|
||||
throw new BusinessException.RoleAlreadyExistsException(command.name());
|
||||
}
|
||||
Role role = Role.create(command.name(), command.description());
|
||||
log.info("Role created: id={}, name={}", role.getId(), role.getName());
|
||||
return roleRepository.save(role);
|
||||
}
|
||||
|
||||
/** 읽기 전용 트랜잭션 */
|
||||
@Transactional(readOnly = true)
|
||||
public Role getRole(String roleId) {
|
||||
log.debug("Fetching role: {}", roleId);
|
||||
return roleRepository.findById(roleId)
|
||||
.orElseThrow(() -> new BusinessException.RoleNotFoundException(roleId));
|
||||
}
|
||||
|
||||
/** 읽기 전용 트랜잭션 */
|
||||
@Transactional(readOnly = true)
|
||||
public List<Role> getAllRoles() {
|
||||
return roleRepository.findAll();
|
||||
}
|
||||
|
||||
/** 쓰기 트랜잭션 */
|
||||
@Transactional
|
||||
public Role updateRole(String roleId, UpdateRoleCommand command) {
|
||||
log.debug("Updating role: {}", roleId);
|
||||
Role role = roleRepository.findById(roleId)
|
||||
.orElseThrow(() -> new BusinessException.RoleNotFoundException(roleId));
|
||||
|
||||
if (command.name() != null && !command.name().equals(role.getName())) {
|
||||
if (roleRepository.existsByName(command.name())) {
|
||||
throw new BusinessException.RoleAlreadyExistsException(command.name());
|
||||
}
|
||||
role.updateName(command.name());
|
||||
}
|
||||
if (command.description() != null) {
|
||||
role.updateDescription(command.description());
|
||||
}
|
||||
log.info("Role updated: id={}", roleId);
|
||||
return role;
|
||||
}
|
||||
|
||||
/** 쓰기 트랜잭션 */
|
||||
@Transactional
|
||||
public void deleteRole(String roleId) {
|
||||
log.debug("Deleting role: {}", roleId);
|
||||
if (!roleRepository.existsById(roleId)) {
|
||||
throw new BusinessException.RoleNotFoundException(roleId);
|
||||
}
|
||||
roleRepository.deleteById(roleId);
|
||||
log.info("Role deleted: id={}", roleId);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package com.runtimematrix.architecture;
|
||||
|
||||
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
import com.tngtech.archunit.library.Architectures.layeredArchitecture;
|
||||
import com.tngtech.archunit.library.dependencies.SlicesRuleDefinition;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_DEPEND_ON_UPPER_LAYERS;
|
||||
|
||||
/** ADR-001 레이어 경계 Arquillian 테스트 */
|
||||
@DisplayName("아키텍처 경계 검증")
|
||||
class LayerBoundaryTest {
|
||||
|
||||
private JavaClasses classes;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
classes = new ClassFileImporter().importPackages("com.runtimematrix");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Controller는 Service에만 접근 가능")
|
||||
void controller_should_only_access_service() {
|
||||
ArchRule rule = layeredArchitecture()
|
||||
.layer("Controller").definedBy("..controller..")
|
||||
.layer("Service").definedBy("..service..")
|
||||
.layer("Repository").definedBy("..repository..")
|
||||
.layer("Domain").definedBy("..domain..")
|
||||
.whereLayer("Controller").mayOnlyAccessLayers("Service", "Domain");
|
||||
rule.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Service는 Repository와 Domain에만 접근 가능")
|
||||
void service_should_only_access_repository_and_domain() {
|
||||
ArchRule rule = layeredArchitecture()
|
||||
.layer("Controller").definedBy("..controller..")
|
||||
.layer("Service").definedBy("..service..")
|
||||
.layer("Repository").definedBy("..repository..")
|
||||
.layer("Domain").definedBy("..domain..")
|
||||
.whereLayer("Service").mayOnlyAccessLayers("Repository", "Domain");
|
||||
rule.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("하위 레이어는 상위 레이어에 의존하지 않음")
|
||||
void no_upward_dependencies() {
|
||||
NO_CLASSES_DEPEND_ON_UPPER_LAYERS.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("패키지 간 순환 의존성 없음")
|
||||
void no_cyclic_dependencies() {
|
||||
ArchRule rule = SlicesRuleDefinition.slices()
|
||||
.matching("com.runtimematrix.(*)..").should().beFreeOfCycles();
|
||||
rule.check(classes);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package com.runtimematrix.controller;
|
||||
|
||||
import com.runtimematrix.config.GlobalExceptionHandler;
|
||||
import com.runtimematrix.domain.exception.BusinessException;
|
||||
import com.runtimematrix.service.RoleService;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/** ADR-001 RFC 7807 오류 응답 계약 테스트 */
|
||||
@WebMvcTest(RoleController.class)
|
||||
@Import(GlobalExceptionHandler.class)
|
||||
@DisplayName("오류 응답 계약 테스트")
|
||||
class ErrorResponseContractTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private RoleService roleService;
|
||||
|
||||
@Test
|
||||
@DisplayName("역할 미존재 시 404와 RFC 7807 형식 응답 반환")
|
||||
void role_not_found_returns_404_with_problem_details() throws Exception {
|
||||
String roleId = "non-existent";
|
||||
when(roleService.getRole(roleId)).thenThrow(new BusinessException.RoleNotFoundException(roleId));
|
||||
|
||||
mockMvc.perform(get("/api/v1/roles/{roleId}", roleId))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.type", startsWith("https://api.runtimematrix.com/errors/")))
|
||||
.andExpect(jsonPath("$.title", is("역할을 찾을 수 없습니다")))
|
||||
.andExpect(jsonPath("$.status", is(404)))
|
||||
.andExpect(jsonPath("$.detail", containsString(roleId)))
|
||||
.andExpect(jsonPath("$.instance", containsString("/api/v1/roles/")))
|
||||
.andExpect(jsonPath("$.timestamp", notNullValue()))
|
||||
.andExpect(jsonPath("$.traceId", notNullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("오류 응답에 모든 필수 필드 포함")
|
||||
void error_response_contains_all_required_fields() throws Exception {
|
||||
when(roleService.getRole("test")).thenThrow(new BusinessException.RoleNotFoundException("test"));
|
||||
|
||||
mockMvc.perform(get("/api/v1/roles/{roleId}", "test"))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$", hasKey("type")))
|
||||
.andExpect(jsonPath("$", hasKey("title")))
|
||||
.andExpect(jsonPath("$", hasKey("status")))
|
||||
.andExpect(jsonPath("$", hasKey("detail")))
|
||||
.andExpect(jsonPath("$", hasKey("instance")))
|
||||
.andExpect(jsonPath("$", hasKey("timestamp")))
|
||||
.andExpect(jsonPath("$", hasKey("traceId")));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue