Add clear error message when timing out expecting a message

This commit is contained in:
2026-11-08 22:30:20 +00:00
parent 7e7361799a
commit 00a4fd3a93
@@ -6,6 +6,7 @@ import com.shr4pnel.ferretirc.net.messages.ServerMessage.Numeric
import io.github.oshai.kotlinlogging.KotlinLogging import io.github.oshai.kotlinlogging.KotlinLogging
import io.github.oshai.kotlinlogging.slf4j.logger import io.github.oshai.kotlinlogging.slf4j.logger
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharedFlow
@@ -114,20 +115,20 @@ class Server(
* @param T The type of ServerMessage to fetch * @param T The type of ServerMessage to fetch
* @return A set of messages of type T in the buffer that arrive before untilMessage appears * @return A set of messages of type T in the buffer that arrive before untilMessage appears
*/ */
suspend inline fun <reified T : ServerMessage, reified U : ServerMessage> fetchMessagesOfType( // suspend inline fun <reified T : ServerMessage, reified U : ServerMessage> fetchMessagesOfType(
timeoutMillis: Long = 5000, // timeoutMillis: Long = 5000,
noinline subscriptionMessage: suspend () -> Unit = {}, // noinline subscriptionMessage: suspend () -> Unit = {},
): List<T> { // ): List<T> {
val buffer = mutableListOf<T>() // val buffer = mutableListOf<T>()
withTimeoutOrNull(timeoutMillis) { // withTimeoutOrNull(timeoutMillis) {
msgBuffer // msgBuffer
.onSubscription { subscriptionMessage() } // .onSubscription { subscriptionMessage() }
.takeWhile { it !is U } // .takeWhile { it !is U }
.filterIsInstance<T>() // .filterIsInstance<T>()
.collect { buffer.add(it) } // .collect { buffer.add(it) }
} ?: logger.error { "Timed out while waiting to receive ${U::class}" } // } ?: logger.error { "Timed out while waiting to receive ${U::class}" }
return buffer.toList() // return buffer.toList()
} // }
fun fetchFeatures() { fun fetchFeatures() {
} }
@@ -137,12 +138,18 @@ class Server(
predicate: (T) -> Boolean = { true }, predicate: (T) -> Boolean = { true },
timeoutMillis: Long = 5000, timeoutMillis: Long = 5000,
onSubscribedLambda: suspend () -> Unit = {}, onSubscribedLambda: suspend () -> Unit = {},
): T = ): T {
withTimeout(timeoutMillis) { try {
msgBuffer return withTimeout(timeoutMillis) {
.onSubscription { onSubscribedLambda() } msgBuffer
.filter { kClass.isInstance(it) } .onSubscription { onSubscribedLambda() }
.map { kClass.cast(it) } .filter { kClass.isInstance(it) }
.first(predicate) .map { kClass.cast(it) }
.first(predicate)
}
} catch (e: TimeoutCancellationException) {
logger.error {"Timed out while waiting to receive ${kClass.simpleName} message"}
throw e
} }
}
} }