Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Kotlin, Spring Boot, Spring Data JPA, Spring Security, JWT, PostgreSQL, Redis, G

`user`, `market`, `challenge`, `trading`, `portfolio`, `recommendation` (reaction logging), `learning`

Packages are organized by **domain, not by layer**. Before adding new code, decide which domain it belongs to and place it in that package.
Follow [ARCHITECTURE.md](ARCHITECTURE.md) for the required `domain` and `global` package layout. Before adding code, decide whether it belongs to a domain layer or a global concern and place it there.

## Boundary with the FastAPI AI Service (important)

Expand Down
55 changes: 55 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Architecture

## Package Layout

```text
team.cklob.arena
├── domain
│ └── {domainName}
│ ├── presentation
│ │ ├── request
│ │ ├── response
│ │ └── controller
│ ├── application
│ │ └── impl
│ ├── domain
│ │ ├── entity
│ │ ├── type
│ │ └── repository
│ └── infrastructure
└── global
├── common
├── config
├── security
├── exception
├── response
├── annotation
├── util
└── property
```

`{domainName}` is one of `user`, `market`, `challenge`, `trading`, `portfolio`, `recommendation`, or `learning`.

Do not create an empty package. Add a package only when it contains production code.

## Domain Layers

- `presentation`: HTTP controllers and request/response DTOs. Controllers validate input and delegate only to application services.
- `application`: use cases, orchestration, and transaction boundaries. Place concrete service implementations in `application.impl`.
- `domain`: entities, domain types, and repository interfaces. Keep domain business rules here when they do not require orchestration or external I/O.
- `infrastructure`: external API clients, persistence adapters, and other technology-specific implementations.

Use the package form `team.cklob.arena.domain.{domainName}.{layer}`. A domain may depend on `global`, but one domain must not reach into another domain's `presentation` or `application` package.

## Global Packages

- `common`: cross-cutting types that do not belong to another global concern.
- `config`: Spring configuration and framework integration setup.
- `security`: JWT, authentication, authorization, and Spring Security components.
- `exception`: shared exception contracts, error-code contracts, and global exception handlers.
- `response`: shared API response envelopes and response advice.
- `annotation`: reusable annotations and their supporting code.
- `util`: stateless helpers with no domain ownership.
- `property`: `@ConfigurationProperties` classes.

`global` must not contain domain business logic, domain entities, or domain repositories.
3 changes: 1 addition & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ Main backend for an AI mock investment battle platform. Users compete against AI

`user` · `market` · `challenge` · `trading` · `portfolio` · `recommendation` (reaction logging) · `learning`

- Follow **domain-based package structure**. Avoid layer-first structure (splitting into controller/service/repository at the top level).
- Package convention: `team.cklob.arena.{domain}.{layer}`
Follow [ARCHITECTURE.md](ARCHITECTURE.md) for the required `domain` and `global` package layout.

## Boundary with the FastAPI AI Service

Expand Down
2 changes: 2 additions & 0 deletions src/main/kotlin/team/cklob/arena/ArenaApplication.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package team.cklob.arena

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication

@SpringBootApplication
@ConfigurationPropertiesScan
class ArenaApplication

fun main(args: Array<String>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package team.cklob.arena.challenge
package team.cklob.arena.domain.challenge

import jakarta.persistence.Column
import jakarta.persistence.Entity
Expand All @@ -15,8 +15,8 @@ import jakarta.persistence.OneToOne
import jakarta.persistence.Table
import jakarta.persistence.UniqueConstraint
import org.springframework.data.jpa.repository.JpaRepository
import team.cklob.arena.market.MarketType
import team.cklob.arena.user.User
import team.cklob.arena.domain.market.MarketType
import team.cklob.arena.domain.user.User
import java.math.BigDecimal
import java.time.LocalDateTime

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package team.cklob.arena.domain.challenge

import org.springframework.http.HttpStatus
import team.cklob.arena.global.exception.ErrorCode

enum class ChallengeErrorCode(
override val status: HttpStatus,
override val message: String,
) : ErrorCode {
CHALLENGE_ALREADY_ENDED(HttpStatus.CONFLICT, "이미 종료된 챌린지입니다."),
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package team.cklob.arena.market
package team.cklob.arena.domain.market

import jakarta.persistence.Column
import jakarta.persistence.Entity
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package team.cklob.arena.recommendation
package team.cklob.arena.domain.recommendation

import jakarta.persistence.Column
import jakarta.persistence.Entity
Expand All @@ -14,8 +14,8 @@ import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
import org.hibernate.annotations.CreationTimestamp
import org.springframework.data.jpa.repository.JpaRepository
import team.cklob.arena.challenge.Challenge
import team.cklob.arena.market.Symbol
import team.cklob.arena.domain.challenge.Challenge
import team.cklob.arena.domain.market.Symbol
import java.math.BigDecimal
import java.time.LocalDateTime

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package team.cklob.arena.domain.recommendation

import org.springframework.http.HttpStatus
import team.cklob.arena.global.exception.ErrorCode

enum class RecommendationErrorCode(
override val status: HttpStatus,
override val message: String,
) : ErrorCode {
RECOMMENDATION_ALREADY_REACTED(HttpStatus.CONFLICT, "이미 반응한 추천입니다."),
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package team.cklob.arena.trading
package team.cklob.arena.domain.trading

import jakarta.persistence.Column
import jakarta.persistence.Entity
Expand All @@ -16,7 +16,7 @@ import jakarta.persistence.Table
import jakarta.persistence.UniqueConstraint
import org.hibernate.annotations.CreationTimestamp
import org.springframework.data.jpa.repository.JpaRepository
import team.cklob.arena.challenge.ChallengeParticipant
import team.cklob.arena.domain.challenge.ChallengeParticipant
import java.math.BigDecimal
import java.time.LocalDateTime

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package team.cklob.arena.domain.trading

import org.springframework.http.HttpStatus
import team.cklob.arena.global.exception.ErrorCode

enum class TradingErrorCode(
override val status: HttpStatus,
override val message: String,
) : ErrorCode {
INSUFFICIENT_BALANCE(HttpStatus.CONFLICT, "잔액이 부족합니다."),
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package team.cklob.arena.user
package team.cklob.arena.domain.user

import jakarta.persistence.Column
import jakarta.persistence.Entity
Expand Down
32 changes: 32 additions & 0 deletions src/main/kotlin/team/cklob/arena/global/config/OpenApiConfig.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package team.cklob.arena.global.config

import io.swagger.v3.oas.models.Components
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.media.ObjectSchema
import io.swagger.v3.oas.models.media.StringSchema
import io.swagger.v3.oas.models.security.SecurityScheme
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import team.cklob.arena.global.exception.CommonErrorCode

@Configuration
class OpenApiConfig {
@Bean
fun openApi(): OpenAPI =
OpenAPI().components(
Components()
.addSecuritySchemes(
"bearerAuth",
SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT"),
).addSchemas(
"CommonErrorResponse",
ObjectSchema()
.addProperty("code", StringSchema().example(CommonErrorCode.INVALID_REQUEST.code))
.addProperty("message", StringSchema().example(CommonErrorCode.INVALID_REQUEST.message))
.addProperty("data", ObjectSchema().nullable(true)),
),
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package team.cklob.arena.global.exception

import org.springframework.http.HttpStatus

enum class CommonErrorCode(
override val status: HttpStatus,
override val message: String,
) : ErrorCode {
INVALID_REQUEST(HttpStatus.BAD_REQUEST, "잘못된 요청입니다."),
MALFORMED_JSON(HttpStatus.BAD_REQUEST, "요청 본문 형식이 올바르지 않습니다."),
INVALID_TYPE_VALUE(HttpStatus.BAD_REQUEST, "요청 값의 형식이 올바르지 않습니다."),
METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, "지원하지 않는 HTTP 메서드입니다."),
RESOURCE_NOT_FOUND(HttpStatus.NOT_FOUND, "요청한 리소스를 찾을 수 없습니다."),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 오류가 발생했습니다."),
}
10 changes: 10 additions & 0 deletions src/main/kotlin/team/cklob/arena/global/exception/ErrorCode.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package team.cklob.arena.global.exception

import org.springframework.http.HttpStatus

interface ErrorCode {
val status: HttpStatus
val message: String
val code: String
get() = (this as Enum<*>).name
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package team.cklob.arena.global.exception

class ExpectedException(
val errorCode: ErrorCode,
messageOverride: String? = null,
) : RuntimeException(messageOverride ?: errorCode.message)
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package team.cklob.arena.global.exception

import com.fasterxml.jackson.databind.exc.InvalidFormatException
import jakarta.validation.ConstraintViolationException
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.validation.BindException
import org.springframework.web.HttpRequestMethodNotSupportedException
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.NoHandlerFoundException
import org.springframework.web.servlet.resource.NoResourceFoundException
import team.cklob.arena.global.response.CommonApiResponse
import team.cklob.arena.global.response.FieldErrorDetail
import team.cklob.arena.global.response.ValidationErrorData

@RestControllerAdvice
class GlobalExceptionHandler {
private val log = LoggerFactory.getLogger(javaClass)

@ExceptionHandler(ExpectedException::class)
fun handleExpectedException(exception: ExpectedException): ResponseEntity<CommonApiResponse<Any>> =
response(exception.errorCode, exception.message ?: exception.errorCode.message)

@ExceptionHandler(MethodArgumentNotValidException::class, BindException::class)
fun handleValidationException(exception: BindException): ResponseEntity<CommonApiResponse<Any>> {
val fieldErrors =
exception.bindingResult.fieldErrors.map {
FieldErrorDetail(field = it.field, reason = it.defaultMessage ?: "유효하지 않은 값입니다.")
}

return response(
errorCode = CommonErrorCode.INVALID_REQUEST,
data = ValidationErrorData(fieldErrors),
)
}
Comment thread
cfcromn marked this conversation as resolved.
Resolved

@ExceptionHandler(ConstraintViolationException::class)
fun handleConstraintViolation(exception: ConstraintViolationException): ResponseEntity<CommonApiResponse<Any>> =
response(
errorCode = CommonErrorCode.INVALID_REQUEST,
data =
ValidationErrorData(
exception.constraintViolations.map {
FieldErrorDetail(field = it.propertyPath.toString(), reason = it.message)
},
),
)

@ExceptionHandler(HttpMessageNotReadableException::class)
fun handleUnreadableMessage(exception: HttpMessageNotReadableException): ResponseEntity<CommonApiResponse<Any>> =
response(
if (exception.cause is InvalidFormatException) {
CommonErrorCode.INVALID_TYPE_VALUE
} else {
CommonErrorCode.MALFORMED_JSON
},
)

@ExceptionHandler(MethodArgumentTypeMismatchException::class)
fun handleTypeMismatch(exception: MethodArgumentTypeMismatchException): ResponseEntity<CommonApiResponse<Any>> =
response(CommonErrorCode.INVALID_TYPE_VALUE)

@ExceptionHandler(HttpRequestMethodNotSupportedException::class)
fun handleMethodNotSupported(exception: HttpRequestMethodNotSupportedException): ResponseEntity<CommonApiResponse<Any>> =
response(CommonErrorCode.METHOD_NOT_ALLOWED)

@ExceptionHandler(NoHandlerFoundException::class, NoResourceFoundException::class)
fun handleNotFound(exception: Exception): ResponseEntity<CommonApiResponse<Any>> {
return response(CommonErrorCode.RESOURCE_NOT_FOUND)
}

@ExceptionHandler(Exception::class)
fun handleUnexpectedException(exception: Exception): ResponseEntity<CommonApiResponse<Any>> {
log.error("Unhandled exception", exception)
return response(CommonErrorCode.INTERNAL_SERVER_ERROR)
}

private fun response(
errorCode: ErrorCode,
message: String = errorCode.message,
data: Any? = null,
): ResponseEntity<CommonApiResponse<Any>> =
ResponseEntity
.status(errorCode.status)
.body(CommonApiResponse.error(errorCode, message, data))
}
38 changes: 38 additions & 0 deletions src/main/kotlin/team/cklob/arena/global/response/ApiResponse.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package team.cklob.arena.global.response

import team.cklob.arena.global.exception.ErrorCode

data class CommonApiResponse<T>(
val code: String,
val message: String,
val data: T? = null,
) {
companion object {
fun <T> success(data: T): CommonApiResponse<T> =
CommonApiResponse(
code = "SUCCESS",
message = "성공했습니다.",
data = data,
)

fun error(
errorCode: ErrorCode,
message: String = errorCode.message,
data: Any? = null,
): CommonApiResponse<Any> =
CommonApiResponse(
code = errorCode.code,
message = message,
data = data,
)
}
}

data class FieldErrorDetail(
val field: String,
val reason: String,
)

data class ValidationErrorData(
val fieldErrors: List<FieldErrorDetail>,
)
Loading
Loading