Issue
Recently I was trying to implement simple web-socket application with Kotlin and ktor library. My server just has single web-socket handler which I implement like the following:
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
install(WebSockets)
routing {
webSocket("/handle") {
// ... more domain specific logic which uses coroutines ...
launch {
for (message in incoming) {
// process message
}
}
}
}
}
Original code contains more logic which include starting a bunch of another coroutines - so launch
-ing the incoming
queue processing in separate coroutine doesn't look weird for me.
Unfortunally, the ktor
closes the underlying web-socket connection as soon, as inner block function finished. This was unexpected behaviour for me, because I though that webSocket
function will behave similar to coroutineScope
standard function, which waits for all attached coroutines to finish before continue execution.
This bug was very hard to spot for me, so I want to understand the design of webSocket
function more deeply. So, I have the following questions:
- Why
webSocket
function don't wait for attached coroutines? Is it a bug or a intentional decision? - What is the conventions about functions that deal with
coroutineScope
-s? Should I always guard my coroutines with known standard library functions (likecoroutineScope
)? Or should library writers follow some guidelines - for example, always wait for all attached coroutines in scope to finish?
Solution
- This behavior was implemented long ago without structured concurrency in mind. I'd say it's a problem that can be fixed on the Ktor side so I've created this issue to address it. A fix will make it easier to write Websocket handlers and will improve readability.
- It depends on whether library maintainers consider supporting structured concurrency or not for a particular case.
Answered By - Aleksei Tirman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.