Provide a way to propagate a custom context to CoroutineContext
See original GitHub issueCurrently, CoroutineContext could be customized with AbstractCoroutineServerImpl
constructor.
https://github.com/grpc/grpc-kotlin/blob/2f3d86b661894d2047c98ca8082932dffc8378d1/stub/src/main/java/io/grpc/kotlin/AbstractCoroutineServerImpl.kt#L29
And it is combined with GrpcContextElement
that captures a context from the current thread and propagates it.
https://github.com/grpc/grpc-kotlin/blob/2f3d86b661894d2047c98ca8082932dffc8378d1/stub/src/main/java/io/grpc/kotlin/ServerCalls.kt#L199
However, a CoroutinContext
injected by users could not propagate any context from the current thread, because it was instantiated when the Coroutine stub is created.
We can use a hack that was suggested by @anuraaga, https://github.com/line/armeria/pull/2669#issuecomment-615269862
internal object ArmeriaContext: CoroutineContext {
override fun <R> fold(initial: R, operation: (R, CoroutineContext.Element) -> R): R =
EmptyCoroutineContext.fold(initial, operation)
override fun <E : CoroutineContext.Element> get(key: CoroutineContext.Key<E>): E? =
EmptyCoroutineContext.get(key)
override fun minusKey(key: CoroutineContext.Key<*>): CoroutineContext =
EmptyCoroutineContext.minusKey(key)
override fun plus(context: CoroutineContext): CoroutineContext {
val requestCtx: RequestContext = RequestContext.current()
return requestCtx.contextAwareExecutor().asCoroutineDispatcher() + context
}
}
We don’t think this is a nice approach. If AbstractCoroutineServerImpl
get CoroutineContext
from a method then constructor parameter, gRPC-Kotlin users can easily propagate their context to CoroutineContext.
abstract class AbstractCoroutineServerImpl(
val defaultContext: CoroutineContext = EmptyCoroutineContext
) : BindableService {
open fun context(): CoroutineContext = defaultContext
}
class UserService: XXXCoroutineImplBase() {
override fun context(): CoroutineContext {
return ServiceRequestContext.current().contextAwareExecutor().asCoroutineDispatcher()
}
}
Do you think this change makes sense, I could make a PR. 😀
/cc @anuraaga
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:15 (3 by maintainers)
Top GitHub Comments
Merged a mechanism to introduce
CoroutineContext
elements via an interceptor – which can also be easily installed on multiple servers, which seem applicable to many of these use cases.I’m moving forward on a design for an interceptor-based solution, where interceptors can inject
CoroutineContext
elements. There’s no ambiguity about how they work, what information they have access to, or other thread-local information.