Hey. Quick question from me surrounding “best-prac...
# graphql-kotlin
a
Hey. Quick question from me surrounding “best-practices”. I have a spring boot application, and I want to add a sessionId onto each request (for simplicity let’s say i want to a unique id for each query) - what’s the intended way of doing this with contexts/directives, etc? Especially if we’re adding this unique Id onto MDC, where would you thing it natural to put the MDC.put(“session”) and MDC.remove(“session”)?
d
It is a pretty common use case (especially with something like tracing). Underlying problem is how to store it so it is available for the whole session. With Spring MVC apps you could use something like
ThreadLocals
to store it (which MDC relies on). With WebFlux (which we use in
graphql-kotlin-spring-server
) you have reactor subscriber context (and coroutine context through interop).
Unfortunately though is that since we rely on
graphql-java
execution logic we jump between reactor/coroutines and
CompletableFuture
which don't have any contextual information. One way to solve it is to create your custom
GraphQLServer
(https://github.com/ExpediaGroup/graphql-kotlin/blob/master/servers/graphql-kotlin-[…]tlin/com/expediagroup/graphql/server/execution/GraphQLServer.kt) which populates MDC (and other contextual data) and then wraps the execution in your coroutine context. You then would also need to create custom
DataFetcher
(I'd extend https://github.com/ExpediaGroup/graphql-kotlin/blob/master/generator/graphql-kotli[…]expediagroup/graphql/generator/execution/FunctionDataFetcher.kt) that propagates the coroutine context when invoking suspendable functions.
Thats actually what we do internally in our servers.
Personally I'd also store that ID in the GraphQL context object which is bound to the whole GraphQL request and can be retrieved easily from environment (e.g. so you could use it from instrumentations etc)
a
I see 🤔 Ye, I was curious since it seems like a (very) common use case, but it makes sense when you explain it like that! Thanks for the pointers! I’ll look into doing something like that 🙂
👍 1
d
🤞 one day will have time to rewrite that execution logic to coroutines and drop the completable future dependency
a
That would indeed be amazing 🙏
r