Skip to content

Commit f894838

Browse files
committed
grpc-pb: Skip unknown fields
Signed-off-by: Johannes Zottele <[email protected]>
1 parent bacb8a5 commit f894838

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

grpc/grpc-core/src/commonMain/kotlin/kotlinx/rpc/grpc/pb/WireDecoder.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,17 @@ public interface WireDecoder : AutoCloseable {
8888
decoder(msg, this)
8989
popLimit(limit)
9090
}
91+
92+
public fun skipValue(writeType: WireType) {
93+
when (writeType) {
94+
WireType.VARINT -> readInt64()
95+
WireType.FIXED32 -> readFixed32()
96+
WireType.FIXED64 -> readFixed64()
97+
WireType.LENGTH_DELIMITED -> readBytes()
98+
WireType.START_GROUP -> error("Unexpected START_GROUP wire type")
99+
WireType.END_GROUP -> {} // nothing to do
100+
}
101+
}
91102
}
92103

93104
/**

grpc/grpc-core/src/commonTest/kotlin/kotlinx/rpc/grpc/pb/ProtosTest.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,24 @@ class ProtosTest {
3434
return codec.decode(source)
3535
}
3636

37+
@Test
38+
fun testUnknownFieldsDontCrash() {
39+
val buffer = Buffer()
40+
val encoder = WireEncoder(buffer)
41+
// optional sint32 sint32 = 7
42+
encoder.writeSInt32(7, 12)
43+
// optional sint64 sint64 = 8; (unknown as wrong wire-type)
44+
encoder.writeFloat(8, 2f)
45+
// optional fixed32 fixed32 = 9;
46+
encoder.writeFixed32(9, 1234u)
47+
encoder.flush()
48+
49+
val decoded = AllPrimitivesInternal.CODEC.decode(buffer)
50+
assertEquals(12, decoded.sint32)
51+
assertNull(decoded.sint64)
52+
assertEquals(1234u, decoded.fixed32)
53+
}
54+
3755
@Test
3856
fun testAllPrimitiveProto() {
3957
val msg = AllPrimitives {

protoc-gen/src/main/kotlin/kotlinx/rpc/protobuf/ModelToKotlinCommonGenerator.kt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,10 @@ class ModelToKotlinCommonGenerator(
288288
code("val tag = decoder.readTag() ?: break // EOF, we read the whole message")
289289
whenBlock {
290290
declaration.fields().forEach { (_, field) -> readMatchCase(field) }
291-
whenCase("else") { code("TODO(\"Handle unknown fields: \$tag\")") }
291+
whenCase("else") {
292+
code("// we are currently just skipping unknown fields (KRPC-191)")
293+
code("decoder.skipValue(tag.wireType)")
294+
}
292295
}
293296
}
294297
ifBranch(

0 commit comments

Comments
 (0)