Make EventBus coroutine-compatible
This commit is contained in:
parent
321e73ca80
commit
81a39c2e96
12 changed files with 117 additions and 51 deletions
|
@ -18,6 +18,7 @@ dependencies {
|
|||
implementation("io.netty:netty-all:4.1.50.Final")
|
||||
implementation("org.slf4j:slf4j-api:1.7.30")
|
||||
implementation("ch.qos.logback:logback-classic:1.2.3")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.8")
|
||||
testImplementation(kotlin("test-junit5"))
|
||||
}
|
||||
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package space.blokk
|
||||
|
||||
import kotlinx.coroutines.CoroutineName
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import space.blokk.events.EventBus
|
||||
import space.blokk.net.BlokkSocketServer
|
||||
import space.blokk.server.Server
|
||||
|
@ -9,7 +11,8 @@ import space.blokk.utils.Logger
|
|||
class BlokkServer internal constructor(): Server {
|
||||
init { i = this }
|
||||
|
||||
override val eventBus = EventBus(ServerEvent::class)
|
||||
override val scope = CoroutineScope(CoroutineName("BlokkServer"))
|
||||
override val eventBus = EventBus(ServerEvent::class, scope)
|
||||
val logger = Logger("BlokkServer")
|
||||
var blokkSocketServer = BlokkSocketServer(this); private set
|
||||
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
package space.blokk.net
|
||||
|
||||
import io.netty.channel.Channel
|
||||
import kotlinx.coroutines.*
|
||||
import space.blokk.BlokkServer
|
||||
import space.blokk.events.*
|
||||
import space.blokk.net.events.SessionEvent
|
||||
import space.blokk.net.events.SessionPacketReceivedEvent
|
||||
|
@ -8,13 +10,16 @@ import space.blokk.net.events.SessionPacketSendEvent
|
|||
import space.blokk.net.protocols.OutgoingPacket
|
||||
import space.blokk.net.protocols.Protocol
|
||||
import space.blokk.net.protocols.handshaking.HandshakingProtocol
|
||||
import space.blokk.server.events.SessionInitializedEvent
|
||||
import space.blokk.utils.Logger
|
||||
import space.blokk.utils.awaitSuspending
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
|
||||
class BlokkSession(private val channel: Channel) : Session {
|
||||
override val address: InetAddress = (channel.remoteAddress() as InetSocketAddress).address
|
||||
val logger = Logger("BlokkSession(${address.hostAddress})")
|
||||
private val identifier = "BlokkSession(${address.hostAddress})"
|
||||
val logger = Logger(identifier)
|
||||
|
||||
override var currentProtocol: Protocol = HandshakingProtocol
|
||||
set(value) {
|
||||
|
@ -22,30 +27,41 @@ class BlokkSession(private val channel: Channel) : Session {
|
|||
field = value
|
||||
}
|
||||
|
||||
override val eventBus = EventBus(SessionEvent::class)
|
||||
override val scope = CoroutineScope(Dispatchers.Unconfined + CoroutineName(identifier))
|
||||
override val eventBus = EventBus(SessionEvent::class, scope)
|
||||
|
||||
var active: Boolean = true
|
||||
|
||||
init {
|
||||
eventBus.register(object : Listener {
|
||||
@EventHandler(priority = EventPriority.INTERNAL)
|
||||
fun onSessionPacketReceived(event: SessionPacketReceivedEvent<*>) {
|
||||
event.ifNotCancelled { SessionPacketReceivedEventHandler.handle(event.session as BlokkSession, event.packet) }
|
||||
suspend fun onSessionPacketReceived(event: SessionPacketReceivedEvent<*>) {
|
||||
SessionPacketReceivedEventHandler.handle(event.session as BlokkSession, event.packet)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
override fun send(packet: OutgoingPacket) {
|
||||
fun onConnect() = scope.launch {
|
||||
if (BlokkServer.i.eventBus.emit(SessionInitializedEvent(this@BlokkSession)).isCancelled) channel.close()
|
||||
else BlokkServer.i.blokkSocketServer.allSessionsGroup.add(this@BlokkSession)
|
||||
}
|
||||
|
||||
fun onDisconnect() {
|
||||
active = false
|
||||
scope.cancel("Disconnected")
|
||||
BlokkServer.i.blokkSocketServer.allSessionsGroup.remove(this)
|
||||
}
|
||||
|
||||
override suspend fun send(packet: OutgoingPacket) {
|
||||
if (!active) throw IllegalStateException("The session is not active anymore")
|
||||
|
||||
logger debug { "Sending packet: $packet" }
|
||||
val event = eventBus.emit(SessionPacketSendEvent(this, packet))
|
||||
if (event.isCancelled) return
|
||||
|
||||
val cf = channel.writeAndFlush(PacketMessage(this, event.packet))
|
||||
cf.addListener { future ->
|
||||
if (!future.isSuccess) {
|
||||
logger error { "Packet send failed: ${future.cause()}" }
|
||||
val event = eventBus.emit(SessionPacketSendEvent(this@BlokkSession, packet))
|
||||
event.ifNotCancelled {
|
||||
try {
|
||||
channel.writeAndFlush(PacketMessage(this@BlokkSession, event.packet)).awaitSuspending()
|
||||
} catch (e: Throwable) {
|
||||
logger error { "Packet send failed: $e" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@ import space.blokk.net.protocols.status.StatusProtocolHandler
|
|||
open class ProtocolPacketReceivedEventHandler(handlers: Map<out IncomingPacketCompanion<*>, PacketReceivedEventHandler<out IncomingPacket>>) {
|
||||
private val handlers = handlers.mapKeys { it.key.packetType }
|
||||
|
||||
fun handle(session: BlokkSession, packet: IncomingPacket) {
|
||||
suspend fun handle(session: BlokkSession, packet: IncomingPacket) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val handler = handlers[packet::class] as PacketReceivedEventHandler<IncomingPacket>?
|
||||
handler?.handle(session, packet)
|
||||
|
@ -18,18 +18,18 @@ open class ProtocolPacketReceivedEventHandler(handlers: Map<out IncomingPacketCo
|
|||
}
|
||||
|
||||
abstract class PacketReceivedEventHandler<T: IncomingPacket> {
|
||||
abstract fun handle(session: BlokkSession, packet: T)
|
||||
abstract suspend fun handle(session: BlokkSession, packet: T)
|
||||
|
||||
companion object {
|
||||
fun <T: IncomingPacket> of(fn: (session: BlokkSession, packet: T) -> Unit) =
|
||||
fun <T: IncomingPacket> of(fn: suspend (session: BlokkSession, packet: T) -> Unit) =
|
||||
object : PacketReceivedEventHandler<T>() {
|
||||
override fun handle(session: BlokkSession, packet: T) = fn(session, packet)
|
||||
override suspend fun handle(session: BlokkSession, packet: T) = fn(session, packet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object SessionPacketReceivedEventHandler {
|
||||
fun handle(session: BlokkSession, packet: IncomingPacket) {
|
||||
suspend fun handle(session: BlokkSession, packet: IncomingPacket) {
|
||||
val handler = when(session.currentProtocol) {
|
||||
HandshakingProtocol -> HandshakingProtocolHandler
|
||||
StatusProtocol -> StatusProtocolHandler
|
||||
|
|
|
@ -5,22 +5,14 @@ import io.netty.channel.ChannelHandlerContext
|
|||
import io.netty.handler.codec.MessageToMessageCodec
|
||||
import space.blokk.BlokkServer
|
||||
import space.blokk.net.protocols.OutgoingPacket
|
||||
import space.blokk.server.events.SessionInitializedEvent
|
||||
import java.io.IOException
|
||||
|
||||
class PacketCodec(private val session: BlokkSession): MessageToMessageCodec<ByteBuf, PacketMessage<*>>() {
|
||||
override fun channelActive(ctx: ChannelHandlerContext) {
|
||||
if (BlokkServer.i.eventBus.emit(SessionInitializedEvent(session)).isCancelled) ctx.channel().close()
|
||||
else BlokkServer.i.blokkSocketServer.allSessionsGroup.add(session)
|
||||
}
|
||||
|
||||
override fun channelInactive(ctx: ChannelHandlerContext) {
|
||||
session.active = false
|
||||
BlokkServer.i.blokkSocketServer.allSessionsGroup.remove(session)
|
||||
}
|
||||
override fun channelActive(ctx: ChannelHandlerContext) { session.onConnect() }
|
||||
override fun channelInactive(ctx: ChannelHandlerContext) { session.onDisconnect() }
|
||||
|
||||
override fun encode(ctx: ChannelHandlerContext, msg: PacketMessage<*>, out: MutableList<Any>) {
|
||||
if (msg.packet !is OutgoingPacket) throw Error("Only clientbound packets can be sent")
|
||||
if (msg.packet !is OutgoingPacket) throw Error("Only clientbound packets are allowed. This should never happen.")
|
||||
val buffer = ctx.alloc().buffer()
|
||||
with(MinecraftDataTypes) { buffer.writeVarInt(msg.packetCompanion.id) }
|
||||
msg.packet.encode(buffer)
|
||||
|
@ -42,5 +34,6 @@ class PacketCodec(private val session: BlokkSession): MessageToMessageCodec<Byte
|
|||
|
||||
// You can usually ignore connection errors as they are caused by modified clients such as hack clients
|
||||
if (BlokkServer.i.silentConnectionErrors) session.logger.debug(message) else session.logger.error(message)
|
||||
cause.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,14 +2,17 @@ package space.blokk.net
|
|||
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.channel.SimpleChannelInboundHandler
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import space.blokk.net.events.SessionPacketReceivedEvent
|
||||
import space.blokk.net.protocols.IncomingPacket
|
||||
|
||||
class PacketMessageHandler(private val session: BlokkSession): SimpleChannelInboundHandler<PacketMessage<*>>() {
|
||||
override fun channelRead0(ctx: ChannelHandlerContext, msg: PacketMessage<*>) {
|
||||
if (msg.packet !is IncomingPacket) throw Error("Only serverbound packets are allowed. This should never happen.")
|
||||
msg.session.logger.debug { "Packet received: ${msg.packet}" }
|
||||
msg.session.eventBus.emit(SessionPacketReceivedEvent(msg.session, msg.packet))
|
||||
session.logger.debug { "Packet received: ${msg.packet}" }
|
||||
runBlocking {
|
||||
session.eventBus.emitAndAwait(SessionPacketReceivedEvent(session, msg.packet))
|
||||
}
|
||||
|
||||
// TODO: Disconnect when invalid data is received
|
||||
}
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package space.blokk.utils
|
||||
|
||||
import io.netty.channel.ChannelFuture
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlin.coroutines.Continuation
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
|
||||
suspend fun ChannelFuture.awaitSuspending() {
|
||||
fun listen(c: Continuation<Unit>) {
|
||||
addListener { c.resumeWith(if (it.isSuccess) Result.success(Unit) else Result.failure(it.cause())) }
|
||||
}
|
||||
|
||||
if (isCancellable) {
|
||||
suspendCancellableCoroutine<Unit> { c ->
|
||||
if (isCancelled) c.cancel()
|
||||
else {
|
||||
c.invokeOnCancellation { cancel(false) }
|
||||
listen(c)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
suspendCoroutine<Unit> { c -> listen(c) }
|
||||
}
|
||||
}
|
Reference in a new issue