There doesn't seem to be a way to provide a new Co...
# ktor
c
There doesn't seem to be a way to provide a new CoroutineContext for a Call, i.e. this doesn't work:
Copy code
//fun Application.installContextCaching() {
//    intercept(ApplicationCallPipeline.Plugins) {
//        withContextCache {
//            proceedWith(subject)
//        }
//    }
//}
Seems the pipelining don't wrap interceptors which is what is normally expected.?
m
creating a plugin works
Copy code
val yourPlugin = createRouteScopedPlugin(
    name = "Plugin",
    createConfiguration = { Config() }) {
    on(RequestContextRouteHook) { call, proceed ->
        withContext(...) { proceed() }
    }
}
c
Mmmm, I'll try the "createRouteScopedPLugin" then, the intercept didn't work unfortunatly
Yeah same issue
I did install to the application not that route tho, guessing thats the only difference can try that quickly
Yeah no bueno, it looks like it used to work in 2.x but not 3.x
m
I am pretty sure it works because I am using it extensively to pass the calling user, your problem must be somewhere else
c
Do you have a full example you can share?
a
The following code doesn't work as expected with both Ktor 2.3.13 and 3.2.1:
Copy code
fun main() {
    embeddedServer(Netty, port = 3333) {
        routing {
            withRequestContextCache {
                get {
                    println(coroutineContext[MyContextElement])
                    call.respondText { "OK" }
                }
            }
        }
    }.start(wait = true)
}

fun Route.withRequestContextCache(
    build: Route.() -> Unit
): Route {
    val route = this
    route.install(ContextCache)
    route.build()
    return route
}

val ContextCache = createRouteScopedPlugin(
    name = "ContextCache",
    createConfiguration = {}) {
    on(RequestContextCacheRouteHook) { call, proceed ->
        withContext(MyContextElement()) {
            proceed()
        }
    }
}
internal object RequestContextCacheRouteHook : Hook<suspend (ApplicationCall, suspend () -> Unit) -> Unit> {
    internal val RequestContextCachePhase: PipelinePhase = PipelinePhase("RequestContextCachePhase")
    override fun install(
        pipeline: ApplicationCallPipeline,
        handler: suspend (ApplicationCall, suspend () -> Unit) -> Unit,
    ) {
        pipeline.insertPhaseAfter(ApplicationCallPipeline.Plugins, RequestContextCachePhase)
        pipeline.intercept(RequestContextCachePhase) {
            handler(call, ::proceed)
        }
    }
}

class MyContextElement() : CoroutineContext.Element {
    override val key: CoroutineContext.Key<*>
        get() = MyContextElement

    companion object : CoroutineContext.Key<MyContextElement>
}
c
I have what @Aleksei Tirman [JB] has, so @minivac interest to see what you have that works...?
m
copy pasting directly from my code
Copy code
/**
 * This plugin makes the [PrincipalHolder] available globally for the duration of the request.
 *
 */
val principalHolderPlugin = createRouteScopedPlugin(
    name = "AppPrincipalPlugin",
    createConfiguration = { Config() }) {
    on(RequestContextRouteHook) { call, proceed ->
        PrincipalHolder.withCall(call) {
            val principal = call.authentication.principal<BasePrincipal>()
            if (principal != null) {
                PrincipalHolder.withPrincipal(
                    principal = principal,
                    block = proceed
                )
            } else {
                Errors.Common.Unauthorized.`throw`(
                    "Authentication missing from request when calling ${call.request.path()}",
                )
            }
        }
    }
}
and the holder
Copy code
/**
 * Facade to get the current call from the request.
 *
 * Be careful when accessing this class from an executor thread, as it will
 * most likely not have right value.
 */
object PrincipalHolder {

    /**
     * Do not read or modify. Internal use only.
     */
    @PublishedApi
    internal val principalTL = ThreadLocal<BasePrincipal>()

    suspend fun principal(): BasePrincipal {
        principalTL.ensurePresent()
        return principalTL.get()
            ?: Errors.Security.MissingPrincipal.`throw`(
                "Tried to read PrincipalHolder.principal()" +
                    " without a principal in context"
            )
    }

    suspend fun call(): ApplicationCall {
        callTL.ensurePresent()
        return callTL.get()
    }

    suspend inline fun <T> withPrincipal(
        principal: BasePrincipal,
        crossinline block: suspend () -> T,
    ): T {
        return withContext(principalTL.asContextElement(principal)) {
            block()
        }
    }

    suspend fun principalContext(): CoroutineContext {
        return principalTL.asContextElement(principal())
    }
}
it's basically how the the mdc plugin works too in ktor-logging, I used it as a reference for my implementation, instead of a correlation id I have a principal, but identical idea
c
But you wrap every call with
withPrincipal
right?
m
I do it once at the root of my routes
Copy code
route {
        authenticate(
            configurations = arrayOf(
                // ... auth configuration
            ),
            strategy = AuthenticationStrategy.FirstSuccessful
        ) {
            install(principalHolderPlugin)  // <- set it once at the root
            userRoutes()
            projectRoutes()
            projectMemberRoutes()
            // other stuff
        }
    }
c
interesting
I'll try again, but I'm pretty sure already did something like that