fix(network): compress packets as a persistent sync-flush deflate stream

This commit is contained in:
Fiereu committed 2026-07-19 22:35:04 +02:00
1 parent b6cfbbb2b0
commit 9732c9373c
3 files changed
+80 -18

No files matched your search

@@ -5,9 +5,13 @@ import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
import java.util.zip.Inflater
// Mirror of the encoder: one persistent raw inflater per connection, never reset, so the deflate
// window carries across packets. Each compressed segment is inflated after re-appending the
// 00 00 FF FF sync marker that the sender stripped.
class CompressionDecoder : ByteToMessageDecoder() {
private val inflater = Inflater(true)
private val chunk = ByteArray(0x4000)
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
if (buffer.readableBytes() < 2) return
@@ -21,19 +25,18 @@ class CompressionDecoder : ByteToMessageDecoder() {
output.writeBytes(buffer, buffer.readerIndex(), payloadLen)
buffer.skipBytes(payloadLen)
} else {
val input = ByteArray(payloadLen)
buffer.readBytes(input)
inflater.reset()
val input = ByteArray(payloadLen + 4)
buffer.readBytes(input, 0, payloadLen)
input[payloadLen] = 0
input[payloadLen + 1] = 0
input[payloadLen + 2] = 0xFF.toByte()
input[payloadLen + 3] = 0xFF.toByte()
inflater.setInput(input)
val chunk = ByteArray(0x4000)
while (!inflater.finished() && !inflater.needsInput()) {
while (!inflater.needsInput()) {
val written = inflater.inflate(chunk)
if (written == 0) break
output.writeBytes(chunk, 0, written)
}
if (output.readableBytes() >= 2) {
output.writerIndex(output.writerIndex() - 2)
}
}
out += output.retain()
} finally {
@@ -3,11 +3,16 @@ package de.fiereu.network.handlers
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
// One continuous raw deflate stream per connection: the deflater is never reset, so its sliding
// window carries across packets. Each compressed packet is a Z_SYNC_FLUSH segment ending in
// 00 00 FF FF, which the client re-appends, so those four bytes are dropped here.
class CompressionEncoder(private val threshold: Int = 256) : MessageToByteEncoder<ByteBuf>() {
private val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
private val chunk = ByteArray(0x4000)
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
if (msg.readableBytes() < 1) return
@@ -20,23 +25,27 @@ class CompressionEncoder(private val threshold: Int = 256) : MessageToByteEncode
msg.skipBytes(payloadLen)
return
}
val input = ByteArray(payloadLen + 2)
val input = ByteArray(payloadLen)
msg.getBytes(msg.readerIndex(), input, 0, payloadLen)
input[payloadLen] = 0xFF.toByte()
input[payloadLen + 1] = 0xFF.toByte()
msg.skipBytes(payloadLen)
out.writeByte(1)
deflater.reset()
deflater.setInput(input)
val chunk = ByteArray(0x4000)
while (true) {
val written = deflater.deflate(chunk, 0, chunk.size, Deflater.SYNC_FLUSH)
if (written == 0) break
out.writeBytes(chunk, 0, written)
}
val buffer = ByteArrayOutputStream(payloadLen)
var written: Int
do {
written = deflater.deflate(chunk, 0, chunk.size, Deflater.SYNC_FLUSH)
buffer.write(chunk, 0, written)
} while (written == chunk.size)
val deflated = buffer.toByteArray()
val bodyLen = (deflated.size - SYNC_MARKER).coerceAtLeast(0)
out.writeBytes(deflated, 0, bodyLen)
}
override fun handlerRemoved(ctx: ChannelHandlerContext) {
deflater.end()
}
private companion object {
const val SYNC_MARKER = 4
}
}
@@ -0,0 +1,50 @@
package de.fiereu.network
import de.fiereu.network.handlers.CompressionDecoder
import de.fiereu.network.handlers.CompressionEncoder
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
private fun frame(opcode: Int, payload: ByteArray): ByteBuf =
Unpooled.buffer().apply {
writeByte(opcode)
writeBytes(payload)
}
private fun body(buf: ByteBuf): ByteArray {
val bytes = ByteArray(buf.readableBytes())
buf.readBytes(bytes)
return bytes.copyOfRange(1, bytes.size)
}
class CompressionRoundtripTest :
FunSpec({
test("compressed payload above threshold round-trips byte for byte") {
val payload = ByteArray(300) { (it * 7).toByte() }
val enc = EmbeddedChannel(CompressionEncoder(threshold = 256))
val dec = EmbeddedChannel(CompressionDecoder())
enc.writeOutbound(frame(0x13, payload))
dec.writeInbound(enc.readOutbound<ByteBuf>())
body(dec.readInbound()) shouldBe payload
}
test("two compressed packets share one continuous deflate stream") {
val first = ByteArray(300) { (it * 3).toByte() }
val second = ByteArray(300) { (it * 11 + 5).toByte() }
val enc = EmbeddedChannel(CompressionEncoder(threshold = 256))
val dec = EmbeddedChannel(CompressionDecoder())
enc.writeOutbound(frame(0x13, first))
enc.writeOutbound(frame(0x13, second))
dec.writeInbound(enc.readOutbound<ByteBuf>())
dec.writeInbound(enc.readOutbound<ByteBuf>())
body(dec.readInbound()) shouldBe first
body(dec.readInbound()) shouldBe second
}
})