Kotlin / kotlinx-rpc

Add asynchronous RPC services to your multiplatform applications.
https://kotlin.github.io/kotlinx-rpc/
Apache License 2.0
756 stars 17 forks source link

RPC Server Service loses transport coroutine context #226

Open yakivy opened 2 weeks ago

yakivy commented 2 weeks ago

Describe the bug I have CallID Ktor plugin installed, it sets correct MDC for SLF4J, but it is lost during actual service logic (that probably means that it is called in different than transport coroutine context)

To Reproduce Kotlin version - 2.0.10 Gradle version - 8.8 OS (Or at least KMP platform) - mac os sonoma Kotlin RPC version - 0.2.4 Steps to reproduce the behavior:

class FileParsingInternalService( override val coroutineContext: CoroutineContext, ): FileParsingService { override suspend fun parse(): Unit = println("MDC: " + MDC.getCopyOfContextMap()) }

registerService { FileParsingInternalService(it) }


- call our RPC server

**Actual behavior**
You see `MDC: null` in console

**Expected behavior**
You see `MDC: {callId=test}` in console

**Additional context**
Link to a small slack discussion: https://kotlinlang.slack.com/archives/C072YJ3Q91V/p1730721325535899

> Probably the main cause of the problem is here:
https://github.com/Kotlin/kotlinx-rpc/blob/main/krpc/krpc-server/src/jvmMain/kotlin/kotlinx/rpc/krpc/server/internal/RPCServerService.kt#L175
Actual RPC service logic is called in the RPC service coroutine context (Child Supervisor Job) instead of transport coroutine context (that has MDCContext). My naive approach would be to make the method suspended and launch service call on kotlin.coroutines.coroutineContext, but probably it will break control flow.