Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 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
73 changes: 45 additions & 28 deletions api/src/main/kotlin/filter/ErrorWebFilter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.wafflestudio.snu4t.filter

import com.fasterxml.jackson.databind.ObjectMapper
import com.wafflestudio.snu4t.common.exception.ErrorType
import com.wafflestudio.snu4t.common.exception.ProxyException
import com.wafflestudio.snu4t.common.exception.Snu4tException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
Expand All @@ -26,36 +27,52 @@ class ErrorWebFilter(
): Mono<Void> {
return chain.filter(exchange)
.onErrorResume { throwable ->
val errorBody: ErrorBody
val httpStatusCode: HttpStatusCode
when (throwable) {
is Snu4tException -> {
httpStatusCode = throwable.error.httpStatus
errorBody = makeErrorBody(throwable)
}
is ResponseStatusException -> {
httpStatusCode = throwable.statusCode
errorBody =
makeErrorBody(
Snu4tException(errorMessage = throwable.body.title ?: ErrorType.DEFAULT_ERROR.errorMessage),
)
}
else -> {
log.error(throwable.message, throwable)
httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR
errorBody = makeErrorBody(Snu4tException())
if (throwable is ProxyException) {
exchange.response.statusCode = throwable.statusCode
exchange.response.headers.contentType = MediaType.APPLICATION_JSON
exchange.response.writeWith(
Mono.just(
exchange.response
.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(throwable.errorBody)),
),
)
} else {
val errorBody: ErrorBody
val httpStatusCode: HttpStatusCode
when (throwable) {
is Snu4tException -> {
httpStatusCode = throwable.error.httpStatus
errorBody = makeErrorBody(throwable)
}

is ResponseStatusException -> {
httpStatusCode = throwable.statusCode
errorBody =
makeErrorBody(
Snu4tException(
errorMessage = throwable.body.title ?: ErrorType.DEFAULT_ERROR.errorMessage,
),
)
}

else -> {
log.error(throwable.message, throwable)
httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR
errorBody = makeErrorBody(Snu4tException())
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

기존 when 이 있는데 depth가 더 들어가서 한눈에 안들어오네요

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (throwable is ProxyException) {
exchange.response.statusCode = throwable.statusCode
exchange.response.headers.contentType = MediaType.APPLICATION_JSON
exchange.response.writeWith(
Mono.just(
exchange.response
.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(throwable.errorBody)),
),
)
} else {
val errorBody: ErrorBody
val httpStatusCode: HttpStatusCode
when (throwable) {
is Snu4tException -> {
httpStatusCode = throwable.error.httpStatus
errorBody = makeErrorBody(throwable)
}
is ResponseStatusException -> {
httpStatusCode = throwable.statusCode
errorBody =
makeErrorBody(
Snu4tException(
errorMessage = throwable.body.title ?: ErrorType.DEFAULT_ERROR.errorMessage,
),
)
}
else -> {
log.error(throwable.message, throwable)
httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR
errorBody = makeErrorBody(Snu4tException())
}
}
val errorBody: Any
val httpStatusCode: HttpStatusCode
when (throwable) {
is ProxyException -> {
httpStatusCode = throwable.statusCode
errorBody = throwable.errorBody
}
is Snu4tException -> {
httpStatusCode = throwable.error.httpStatus
errorBody = makeErrorBody(throwable)
}
is ResponseStatusException -> {
httpStatusCode = throwable.statusCode
errorBody =
makeErrorBody(
Snu4tException(errorMessage = throwable.body.title ?: ErrorType.DEFAULT_ERROR.errorMessage),
)
}
else -> {
log.error(throwable.message, throwable)
httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR
errorBody = makeErrorBody(Snu4tException())
}
}

그냥 이렇게 하면 안되나요

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

errorBody가 Any 타입으로만 바뀝니다.

}

exchange.response.statusCode = httpStatusCode
exchange.response.headers.contentType = MediaType.APPLICATION_JSON
exchange.response.writeWith(
Mono.just(
exchange.response
.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(errorBody)),
),
)
exchange.response.statusCode = httpStatusCode
exchange.response.headers.contentType = MediaType.APPLICATION_JSON
exchange.response.writeWith(
Mono.just(
exchange.response
.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(errorBody)),
),
)
}
}
}

Expand Down
44 changes: 44 additions & 0 deletions api/src/main/kotlin/handler/EvServiceHandler.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.wafflestudio.snu4t.handler

import com.wafflestudio.snu4t.evaluation.service.EvService
import com.wafflestudio.snu4t.middleware.SnuttRestApiDefaultMiddleware
import kotlinx.coroutines.reactor.awaitSingleOrNull
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.bodyToMono

@Component
class EvServiceHandler(
private val evService: EvService,
snuttRestApiDefaultMiddleware: SnuttRestApiDefaultMiddleware,
) : ServiceHandler(snuttRestApiDefaultMiddleware) {
suspend fun handleGet(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.GET)
}

suspend fun handlePost(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.POST)
}

suspend fun handleDelete(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.DELETE)
}

suspend fun handlePatch(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.PATCH)
}

suspend fun getMyLatestLectures(req: ServerRequest) =
handle(req) {
evService.getMyLatestLectures(req.userId, req.queryParams())
}
}
12 changes: 12 additions & 0 deletions api/src/main/kotlin/router/MainRouter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.wafflestudio.snu4t.handler.ConfigHandler
import com.wafflestudio.snu4t.handler.CoursebookHandler
import com.wafflestudio.snu4t.handler.DeviceHandler
import com.wafflestudio.snu4t.handler.EvHandler
import com.wafflestudio.snu4t.handler.EvServiceHandler
import com.wafflestudio.snu4t.handler.FeedbackHandler
import com.wafflestudio.snu4t.handler.FriendHandler
import com.wafflestudio.snu4t.handler.FriendTableHandler
Expand Down Expand Up @@ -68,6 +69,7 @@ class MainRouter(
private val tagHandler: TagHandler,
private val feedbackHandler: FeedbackHandler,
private val staticPageHandler: StaticPageHandler,
private val evServiceHandler: EvServiceHandler,
) {
@Bean
fun healthCheck() =
Expand Down Expand Up @@ -295,6 +297,16 @@ class MainRouter(
GET("/ev/lectures/{lectureId}/summary", evHandler::getLectureEvaluationSummary)
}

@Bean
fun evServiceRouter() =
v1CoRouter {
GET("/ev-service/v1/users/me/lectures/latest", evServiceHandler::getMyLatestLectures)
GET("/ev-service/{*requestPath}", evServiceHandler::handleGet)
POST("/ev-service/{*requestPath}", evServiceHandler::handlePost)
DELETE("/ev-service/{*requestPath}", evServiceHandler::handleDelete)
PATCH("/ev-service/{*requestPath}", evServiceHandler::handlePatch)
}

@Bean
@CoursebookDocs
fun coursebookRouter() =
Expand Down
2 changes: 2 additions & 0 deletions api/src/test/kotlin/timetable/TimetableIntegTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.wafflestudio.snu4t.timetable
import BaseIntegTest
import com.ninjasquad.springmockk.MockkBean
import com.wafflestudio.snu4t.evaluation.repository.SnuttEvRepository
import com.wafflestudio.snu4t.evaluation.service.EvService
import com.wafflestudio.snu4t.fixture.TimetableFixture
import com.wafflestudio.snu4t.fixture.UserFixture
import com.wafflestudio.snu4t.handler.RequestContext
Expand All @@ -25,6 +26,7 @@ import timetables.dto.TimetableBriefDto
class TimetableIntegTest(
@MockkBean private val mockMiddleware: SnuttRestApiDefaultMiddleware,
@MockkBean private val mockSnuttEvRepository: SnuttEvRepository,
@MockkBean private val evService: EvService,
val mainRouter: MainRouter,
val timetableFixture: TimetableFixture,
val userFixture: UserFixture,
Expand Down
9 changes: 9 additions & 0 deletions core/src/main/kotlin/common/exception/ProxyException.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.wafflestudio.snu4t.common.exception

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.http.HttpStatusCode

class ProxyException(
val statusCode: HttpStatusCode,
val errorBody: Map<String, Any?>,
) : RuntimeException(ObjectMapper().writeValueAsString(errorBody))
Copy link
Member

@Hank-Choi Hank-Choi Jan 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exception 파일인데 ObjectMapper를 가져오는게 조금 어색해요

그냥 message 빼도 될 것 같은데요
어차피 Throwable.message 쓰는 경우 없을테니..

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그리고 이거 ev 서비스란 것도 명시해주세요
아마 이런식으로 프록시하는건 이게 마지막일거라서..

Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ interface CoursebookRepository : CoroutineCrudRepository<Coursebook, String> {
suspend fun findFirstByOrderByYearDescSemesterDesc(): Coursebook

suspend fun findAllByOrderByYearDescSemesterDesc(): List<Coursebook>

suspend fun findTop3ByOrderByYearDescSemesterDesc(): List<Coursebook>
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ interface CoursebookService {
suspend fun getLatestCoursebook(): Coursebook

suspend fun getCoursebooks(): List<Coursebook>

suspend fun getLastTwoCourseBooksBeforeCurrent(): List<Coursebook>
}

@Service
class CoursebookServiceImpl(private val coursebookRepository: CoursebookRepository) : CoursebookService {
override suspend fun getLatestCoursebook(): Coursebook = coursebookRepository.findFirstByOrderByYearDescSemesterDesc()

override suspend fun getCoursebooks(): List<Coursebook> = coursebookRepository.findAllByOrderByYearDescSemesterDesc()

override suspend fun getLastTwoCourseBooksBeforeCurrent(): List<Coursebook> =
coursebookRepository.findTop3ByOrderByYearDescSemesterDesc().slice(
1..2,
)
}
25 changes: 25 additions & 0 deletions core/src/main/kotlin/evaluation/dto/EvLectureInfoDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.wafflestudio.snu4t.evaluation.dto

import com.fasterxml.jackson.annotation.JsonProperty
import com.wafflestudio.snu4t.common.enum.Semester
import com.wafflestudio.snu4t.timetables.data.TimetableLecture

data class EvLectureInfoDto(
val year: Int,
val semester: Int,
val instructor: String?,
@JsonProperty("course_number")
val courseNumber: String?,
)

fun EvLectureInfoDto(
timetableLecture: TimetableLecture,
year: Int,
semester: Semester,
): EvLectureInfoDto =
EvLectureInfoDto(
year = year,
semester = semester.value,
instructor = timetableLecture.instructor,
courseNumber = timetableLecture.courseNumber,
)
16 changes: 16 additions & 0 deletions core/src/main/kotlin/evaluation/dto/EvUserDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.wafflestudio.snu4t.evaluation.dto

import com.wafflestudio.snu4t.users.data.User

data class EvUserDto(
val id: String?,
val email: String?,
val local_id: String?,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네이밍 통일하시죠 JsonProperty로 json에만 스네이크케이스면 좋겠습니다.

)

fun EvUserDto(user: User) =
EvUserDto(
id = user.id,
email = user.email,
local_id = user.credential.localId,
)
128 changes: 128 additions & 0 deletions core/src/main/kotlin/evaluation/service/EvService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package com.wafflestudio.snu4t.evaluation.service

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.PropertyNamingStrategies
import com.wafflestudio.snu4t.common.exception.ProxyException
import com.wafflestudio.snu4t.common.util.buildMultiValueMap
import com.wafflestudio.snu4t.config.SnuttEvWebClient
import com.wafflestudio.snu4t.coursebook.service.CoursebookService
import com.wafflestudio.snu4t.evaluation.dto.EvLectureInfoDto
import com.wafflestudio.snu4t.evaluation.dto.EvUserDto
import com.wafflestudio.snu4t.timetables.service.TimetableService
import com.wafflestudio.snu4t.users.service.UserService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.withContext
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.util.MultiValueMap
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.bodyToMono
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Mono
import java.net.URLEncoder

@Service
class EvService(
private val snuttEvWebClient: SnuttEvWebClient,
private val timetableService: TimetableService,
private val coursebookService: CoursebookService,
private val userService: UserService,
) {
suspend fun handleRouting(
userId: String,
requestPath: String,
requestQueryParams: MultiValueMap<String, String> = buildMultiValueMap(mapOf()),
originalBody: String,
method: HttpMethod,
): Map<String, Any?> {
val result: MutableMap<String, Any?> =
snuttEvWebClient.method(method)
.uri { builder -> builder.path(requestPath).queryParams(requestQueryParams).build() }
.header("Snutt-User-Id", userId)
.header(HttpHeaders.CONTENT_ENCODING, "UTF-8")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(BodyInserters.fromValue(originalBody))
.retrieve()
.onStatus(HttpStatusCode::isError) { response ->
response.bodyToMono<Map<String, Any?>>()
.flatMap { errorBody ->
Mono.error(ProxyException(response.statusCode(), errorBody))
}
}
.bodyToMono<MutableMap<String, Any?>>()
.awaitSingle()
return updateUserInfo(result)
}

suspend fun getMyLatestLectures(
userId: String,
requestQueryParams: MultiValueMap<String, String>? = null,
): Map<String, Any?> {
val recentLectures: List<EvLectureInfoDto> =
coursebookService.getLastTwoCourseBooksBeforeCurrent().flatMap { coursebook ->
timetableService.getTimetablesBySemester(userId, coursebook.year, coursebook.semester)
.toList()
.flatMap { timetable ->
timetable.lectures.map { lecture ->
EvLectureInfoDto(
lecture,
coursebook.year,
coursebook.semester,
)
}
}
}

val encodedJson =
withContext(Dispatchers.IO) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분에 왜 withContext를 썼는지, 그리고 왜 Dispatchers.IO를 썼는지 궁금하네

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

비슷하게 해보니까
URLEncoder.encode 에서 블라킹이 발생할 수 있다고 하는데
그렇다고 IO Dispatcher에서 돌리는 것도 좀 이상하다고 생각합니다.

URLEncoder.encode(
ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE).writeValueAsString(recentLectures),
"UTF-8",
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

objectMapper는 dependency injection해서 써도 될 듯

}

return snuttEvWebClient.get()
.uri { builder ->
UriComponentsBuilder.fromUri(builder.build())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 라인은 왜 있는 거에요?

.path("/v1/users/me/lectures/latest")
.queryParam("snutt_lecture_info", encodedJson)
.queryParams(requestQueryParams)
.build(true).toUri()
}
Copy link
Member

@Hank-Choi Hank-Choi Jan 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

webclient uri 빌더 문법 저도 싫어하는데
Encoder 가 dispatcher에 쌓여있는게 좀 더 싫어서 아래 코드가 나아보입니다.

Suggested change
val encodedJson =
withContext(Dispatchers.IO) {
URLEncoder.encode(
ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE).writeValueAsString(recentLectures),
"UTF-8",
)
}
return snuttEvWebClient.get()
.uri { builder ->
UriComponentsBuilder.fromUri(builder.build())
.path("/v1/users/me/lectures/latest")
.queryParam("snutt_lecture_info", encodedJson)
.queryParams(requestQueryParams)
.build(true).toUri()
}
val lectureInfoParam = ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE).writeValueAsString(recentLectures)
return snuttEvWebClient.get()
.uri { builder ->
builder
.path("/v1/users/me/lectures/latest")
.queryParam("snutt_lecture_info", "{lectureInfoParam}")
.queryParams(requestQueryParams)
.build(lectureInfoParam)
}

.header("Snutt-User-Id", userId)
.header(HttpHeaders.CONTENT_ENCODING, "UTF-8")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.retrieve()
.onStatus(HttpStatusCode::isError) { response ->
response.bodyToMono<Map<String, Any?>>()
.flatMap { errorBody ->
Mono.error(ProxyException(response.statusCode(), errorBody))
}
}
.bodyToMono<MutableMap<String, Any?>>()
.awaitSingle()
}

@Suppress("UNCHECKED_CAST")
private suspend fun updateUserInfo(data: MutableMap<String, Any?>): MutableMap<String, Any?> {
val updatedMap: MutableMap<String, Any?> = mutableMapOf()
for ((k, v) in data.entries) {
if (k == "user_id") {
val userDto = runCatching { EvUserDto(userService.getUser(v as String)) }.getOrNull()
updatedMap["user"] = userDto
} else {
when (v) {
is List<*> -> updatedMap[k] = v.map { updateUserInfo(it as MutableMap<String, Any?>) }
is MutableMap<*, *> -> updatedMap[k] = updateUserInfo(v as MutableMap<String, Any?>)
else -> updatedMap[k] = v
}
}
}
return updatedMap
}
}
Loading