Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Kotlin value class in annotated services #5449

Merged
merged 1 commit into from
Apr 3, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

package com.linecorp.armeria.internal.common.kotlin

import com.google.common.base.Preconditions.checkState
import com.google.common.base.Predicate
import com.linecorp.armeria.common.ContextAwareExecutor
import com.linecorp.armeria.common.kotlin.CoroutineContexts
import com.linecorp.armeria.common.kotlin.asCoroutineContext
Expand All @@ -32,12 +34,18 @@ import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.future.future
import org.reactivestreams.Publisher
import org.reflections.ReflectionUtils
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutorService
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.reflect.full.callSuspend
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.full.callSuspendBy
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.kotlinFunction

/**
Expand All @@ -46,17 +54,21 @@ import kotlin.reflect.jvm.kotlinFunction
@OptIn(DelicateCoroutinesApi::class)
internal fun callKotlinSuspendingMethod(
method: Method,
obj: Any,
args: Array<Any>,
target: Any,
args: Array<Any?>,
executorService: ExecutorService,
ctx: ServiceRequestContext,
): CompletableFuture<Any?> {
val kFunction = checkNotNull(method.kotlinFunction) { "method is not a kotlin function" }
if (!kFunction.isAccessible) {
kFunction.isAccessible = true
}
val future =
GlobalScope.future(newCoroutineCtx(executorService, ctx)) {
val argsMap = toArgMap(kFunction, target, args)
val response =
kFunction
.callSuspend(obj, *args)
.callSuspendBy(argsMap)
.let { if (it == Unit) null else it }

if (response != null && ctx.isCancelled) {
Expand All @@ -76,6 +88,53 @@ internal fun callKotlinSuspendingMethod(
return future
}

/**
* Forked from https://github.com/spring-projects/spring-framework/blob/91b9a7537138d7de478c3229069acfe946adcb3a/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java#L309
* to support value classes.
*/
private fun toArgMap(
kFunction: KFunction<*>,
target: Any,
args: Array<Any?>,
): Map<KParameter, Any> {
val argMap = HashMap<KParameter, Any>(args.size + 1)
var index = 0
for (parameter in kFunction.parameters) {
when (parameter.kind) {
KParameter.Kind.INSTANCE -> argMap[parameter] = target
KParameter.Kind.VALUE -> {
if (!parameter.isOptional) {
args[index]?.let { arg ->
val classifier = parameter.type.classifier
if (classifier is KClass<*> && classifier.isValue) {
val methods =
ReflectionUtils.getAllMethods(
classifier.java,
Predicate {
it.isSynthetic && Modifier.isStatic(it.modifiers) && it.name == "box-impl"
},
)
checkState(
methods.size == 1,
"Unable to find a single box-impl synthetic static method in %s",
classifier.java.name,
)
// Convert value class to its boxed type.
argMap[parameter] = methods.first().invoke(null, arg)
} else {
argMap[parameter] = arg
}
}
}
index++
}
KParameter.Kind.EXTENSION_RECEIVER ->
throw IllegalStateException("Unsupported parameter kind: ${parameter.kind}")
}
}
return argMap
}

/**
* Converts [Flow] into [Publisher].
* @see FlowCollectingPublisher
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright 2024 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.linecorp.armeria.server.kotlin

import com.linecorp.armeria.common.HttpStatus
import com.linecorp.armeria.common.MediaType
import com.linecorp.armeria.server.ServerBuilder
import com.linecorp.armeria.server.annotation.Post
import com.linecorp.armeria.server.annotation.ProducesJson
import com.linecorp.armeria.testing.junit5.server.ServerExtension
import net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension

class ValueClassTest {
@Test
fun shouldBindValueClass() {
val client = server.blockingWebClient()
val input =
"""
{
"hello": "world!",
"hi": 123
}
""".trimIndent()
val res =
client.prepare()
.post("/value-class")
.content(
MediaType.JSON,
input,
).execute()
assertThat(res.status()).isEqualTo(HttpStatus.OK)
assertThatJson(res.contentUtf8()).isEqualTo(input)
}

companion object {
@RegisterExtension
val server: ServerExtension =
object : ServerExtension() {
override fun configure(sb: ServerBuilder) {
sb.annotatedService(MyAnnotatedService())
}
}

data class Inner(val hello: String, val hi: Int)

@JvmInline
value class MyValueClass(val inner: Inner)

private class MyAnnotatedService {
@Post("/value-class")
@ProducesJson
suspend fun foo(input: MyValueClass): MyValueClass {
return input
}
}
}
}