Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix yamux remote open #292

Merged
merged 6 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions libp2p/src/main/kotlin/io/libp2p/mux/yamux/YamuxHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ open class YamuxHandler(
when (msg.flags) {
YamuxFlags.SYN -> {
// ACK the new stream
onRemoteOpen(msg.id)
onRemoteYamuxOpen(msg.id)
ctx.writeAndFlush(YamuxFrame(msg.id, YamuxType.WINDOW_UPDATE, YamuxFlags.ACK, 0))
}
YamuxFlags.FIN -> onRemoteDisconnect(msg.id)
Expand Down Expand Up @@ -107,9 +107,12 @@ open class YamuxHandler(
fun handleWindowUpdate(msg: YamuxFrame) {
handleFlags(msg)
val size = msg.lenData.toInt()
if (size == 0)
return
val sendWindow = sendWindows.get(msg.id)
if (sendWindow == null)
throw Libp2pException("No send window for " + msg.id)
if (sendWindow == null) {
return
}
sendWindow.addAndGet(size)
val buffer = sendBuffers.get(msg.id)
if (buffer != null) {
Expand All @@ -122,8 +125,9 @@ open class YamuxHandler(
val ctx = getChannelHandlerContext()

val sendWindow = sendWindows.get(child.id)
if (sendWindow == null)
if (sendWindow == null) {
throw Libp2pException("No send window for " + child.id)
}
if (sendWindow.get() <= 0) {
// wait until the window is increased to send more data
val buffer = sendBuffers.getOrPut(child.id, { SendBuffer(ctx) })
Expand All @@ -147,17 +151,18 @@ open class YamuxHandler(
}

override fun onLocalOpen(child: MuxChannel<ByteBuf>) {
onStreamCreate(child)
onStreamCreate(child.id)
getChannelHandlerContext().writeAndFlush(YamuxFrame(child.id, YamuxType.DATA, YamuxFlags.SYN, 0))
}

override fun onRemoteCreated(child: MuxChannel<ByteBuf>) {
onStreamCreate(child)
private fun onRemoteYamuxOpen(id: MuxId) {
onStreamCreate(id)
onRemoteOpen(id)
}

private fun onStreamCreate(child: MuxChannel<ByteBuf>) {
receiveWindows.put(child.id, AtomicInteger(INITIAL_WINDOW_SIZE))
sendWindows.put(child.id, AtomicInteger(INITIAL_WINDOW_SIZE))
private fun onStreamCreate(childId: MuxId) {
receiveWindows.putIfAbsent(childId, AtomicInteger(INITIAL_WINDOW_SIZE))
sendWindows.putIfAbsent(childId, AtomicInteger(INITIAL_WINDOW_SIZE))
}

override fun onLocalDisconnect(child: MuxChannel<ByteBuf>) {
Expand Down
44 changes: 31 additions & 13 deletions libp2p/src/test/kotlin/io/libp2p/mux/MuxHandlerAbstractTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ abstract class MuxHandlerAbstractTest {
val parentChannelId get() = ech.id()

val allocatedBufs = mutableListOf<ByteBuf>()
val activeEventHandlers = mutableListOf<TestEventHandler>()

abstract val maxFrameDataLength: Int
abstract fun createMuxHandler(streamHandler: StreamHandler<*>): MuxHandler
Expand Down Expand Up @@ -75,6 +76,9 @@ abstract class MuxHandlerAbstractTest {

@AfterEach
open fun cleanUpAndCheck() {
childHandlers.forEach {
assertThat(it.exceptions).isEmpty()
}
childHandlers.clear()

allocatedBufs.forEach {
Expand Down Expand Up @@ -113,6 +117,8 @@ abstract class MuxHandlerAbstractTest {
return buf
}

protected fun allocateMessage(hexBytes: String) = hexBytes.fromHex().toByteBuf(allocateBuf())

fun assertHandlerCount(count: Int) = assertEquals(count, childHandlers.size)
fun assertLastMessage(handler: Int, msgCount: Int, msg: String) {
val messages = childHandlers[handler].inboundMessages
Expand Down Expand Up @@ -142,7 +148,6 @@ abstract class MuxHandlerAbstractTest {
assertEquals("66", childHandlers[0].inboundMessages.last())

assertFalse(childHandlers[0].isInactivated)
assertTrue(childHandlers[0].exceptions.isEmpty())
}

@Test
Expand Down Expand Up @@ -205,9 +210,7 @@ abstract class MuxHandlerAbstractTest {
assertLastMessage(1, 2, "34")

assertFalse(childHandlers[0].isInactivated)
assertTrue(childHandlers[0].exceptions.isEmpty())
assertFalse(childHandlers[1].isInactivated)
assertTrue(childHandlers[1].exceptions.isEmpty())
}

@Test
Expand All @@ -233,7 +236,6 @@ abstract class MuxHandlerAbstractTest {
assertFalse(childHandlers[0].isInactivated)
resetStream(12)
assertTrue(childHandlers[0].isHandlerRemoved)
assertTrue(childHandlers[0].exceptions.isEmpty())

openStream(22)
writeStream(22, "33")
Expand All @@ -247,7 +249,6 @@ abstract class MuxHandlerAbstractTest {
assertFalse(childHandlers[1].isInactivated)
resetStream(22)
assertTrue(childHandlers[1].isHandlerRemoved)
assertTrue(childHandlers[1].exceptions.isEmpty())
}

@Test
Expand All @@ -270,7 +271,6 @@ abstract class MuxHandlerAbstractTest {

assertTrue(childHandlers[0].ctx.channel().closeFuture().isDone)
assertTrue(childHandlers[0].isHandlerRemoved)
assertTrue(childHandlers[0].exceptions.isEmpty())
}

@Test
Expand Down Expand Up @@ -326,7 +326,7 @@ abstract class MuxHandlerAbstractTest {
@Test
fun `local create and after local disconnect should still read`() {
val handler = openStreamByLocal()
handler.ctx.writeAndFlush("1984".fromHex().toByteBuf(allocateBuf()))
handler.ctx.writeAndFlush(allocateMessage("1984"))
handler.ctx.disconnect().sync()

val openFrame = readFrameOrThrow()
Expand Down Expand Up @@ -362,7 +362,7 @@ abstract class MuxHandlerAbstractTest {
assertThat(handler.isUnregistered).isFalse()
assertThat(handler.userEvents).containsExactly(RemoteWriteClosed)

handler.ctx.writeAndFlush("1984".fromHex().toByteBuf(allocateBuf()))
handler.ctx.writeAndFlush(allocateMessage("1984"))

val readFrame = readFrameOrThrow()
assertThat(readFrame.flag).isEqualTo(Data)
Expand Down Expand Up @@ -393,7 +393,7 @@ abstract class MuxHandlerAbstractTest {
readFrameOrThrow()

val largeMessage = "42".repeat(maxFrameDataLength - 1) + "4344"
handler.ctx.writeAndFlush(largeMessage.fromHex().toByteBuf(allocateBuf()))
handler.ctx.writeAndFlush(allocateMessage(largeMessage))

val dataFrame1 = readFrameOrThrow()
assertThat(dataFrame1.data.fromHex())
Expand All @@ -416,7 +416,7 @@ abstract class MuxHandlerAbstractTest {
handler.ctx.disconnect()

assertThrows(Exception::class.java) {
handler.ctx.writeAndFlush("42".fromHex().toByteBuf(allocateBuf())).sync()
handler.ctx.writeAndFlush(allocateMessage("42")).sync()
}
}

Expand All @@ -426,7 +426,7 @@ abstract class MuxHandlerAbstractTest {
handler.ctx.close()

assertThrows(Exception::class.java) {
handler.ctx.writeAndFlush("42".fromHex().toByteBuf(allocateBuf())).sync()
handler.ctx.writeAndFlush(allocateMessage("42")).sync()
}
}

Expand All @@ -436,11 +436,28 @@ abstract class MuxHandlerAbstractTest {
ech.close().sync()

assertThrows(Exception::class.java) {
handler.ctx.writeAndFlush("42".fromHex().toByteBuf(allocateBuf())).sync()
handler.ctx.writeAndFlush(allocateMessage("42")).sync()
}
}

@Test
fun `test writing to remotely open stream upon activation`() {
activeEventHandlers += TestEventHandler {
val writePromise = it.ctx.writeAndFlush(allocateMessage("42"))
writePromise.sync()
}
openStream(33)

val dataFrame = readFrameOrThrow()
assertThat(dataFrame.streamId).isEqualTo(33)
assertThat(dataFrame.data).isEqualTo("42")
}

fun interface TestEventHandler {
fun handle(testHandler: TestHandler)
}

class TestHandler : ChannelInboundHandlerAdapter() {
inner class TestHandler : ChannelInboundHandlerAdapter() {
val inboundMessages = mutableListOf<String>()
lateinit var ctx: ChannelHandlerContext
var readCompleteEventCount = 0
Expand Down Expand Up @@ -477,6 +494,7 @@ abstract class MuxHandlerAbstractTest {
assertFalse(isActivated)
isActivated = true
println("MultiplexHandlerTest.channelActive")
activeEventHandlers.forEach { it.handle(this) }
}

override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
Expand Down
28 changes: 18 additions & 10 deletions libp2p/src/test/kotlin/io/libp2p/mux/yamux/YamuxHandlerTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import io.netty.channel.ChannelHandlerContext
class YamuxHandlerTest : MuxHandlerAbstractTest() {

override val maxFrameDataLength = 256
private val readFrameQueue = ArrayDeque<AbstractTestMuxFrame>()

override fun createMuxHandler(streamHandler: StreamHandler<*>): MuxHandler =
object : YamuxHandler(
Expand Down Expand Up @@ -44,17 +45,24 @@ class YamuxHandlerTest : MuxHandlerAbstractTest() {
}

override fun readFrame(): AbstractTestMuxFrame? {
val maybeYamuxFrame = ech.readOutbound<YamuxFrame>()
return maybeYamuxFrame?.let { yamuxFrame ->
val flag = when {
yamuxFrame.flags == YamuxFlags.SYN -> Open
yamuxFrame.flags == YamuxFlags.FIN -> Close
yamuxFrame.flags == YamuxFlags.RST -> Reset
yamuxFrame.type == YamuxType.DATA -> Data
else -> throw AssertionError("Unsupported yamux frame: $yamuxFrame")
val yamuxFrame = ech.readOutbound<YamuxFrame>()
if (yamuxFrame != null) {
when (yamuxFrame.flags) {
YamuxFlags.SYN -> readFrameQueue += AbstractTestMuxFrame(yamuxFrame.id.id, Open)
}

val data = yamuxFrame.data?.readAllBytesAndRelease()?.toHex() ?: ""
when {
yamuxFrame.type == YamuxType.DATA && data.isNotEmpty() ->
readFrameQueue += AbstractTestMuxFrame(yamuxFrame.id.id, Data, data)
}

when (yamuxFrame.flags) {
YamuxFlags.FIN -> readFrameQueue += AbstractTestMuxFrame(yamuxFrame.id.id, Close)
YamuxFlags.RST -> readFrameQueue += AbstractTestMuxFrame(yamuxFrame.id.id, Reset)
}
val sData = yamuxFrame.data?.readAllBytesAndRelease()?.toHex() ?: ""
AbstractTestMuxFrame(yamuxFrame.id.id, flag, sData)
}

return readFrameQueue.removeFirstOrNull()
}
}