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

Support discriminators not being the first field when decoding #1324

Merged
merged 5 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
90 changes: 64 additions & 26 deletions bson-kotlinx/src/main/kotlin/org/bson/codecs/kotlinx/BsonDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -120,28 +120,14 @@ internal open class DefaultBsonDecoder(

@Suppress("ReturnCount")
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
when (descriptor.kind) {
is StructureKind.LIST -> {
reader.readStartArray()
return BsonArrayDecoder(reader, serializersModule, configuration)
}
is PolymorphicKind -> {
return PolymorphicDecoder(reader, serializersModule, configuration)
}
return when (descriptor.kind) {
is StructureKind.LIST -> BsonArrayDecoder(descriptor, reader, serializersModule, configuration)
is PolymorphicKind -> PolymorphicDecoder(descriptor, reader, serializersModule, configuration)
is StructureKind.CLASS,
StructureKind.OBJECT -> {
val current = reader.currentBsonType
if (current == null || current == BsonType.DOCUMENT) {
reader.readStartDocument()
}
}
is StructureKind.MAP -> {
reader.readStartDocument()
return BsonDocumentDecoder(reader, serializersModule, configuration)
}
StructureKind.OBJECT -> BsonDocumentDecoder(descriptor, reader, serializersModule, configuration)
is StructureKind.MAP -> MapDecoder(descriptor, reader, serializersModule, configuration)
else -> throw SerializationException("Primitives are not supported at top-level")
}
return DefaultBsonDecoder(reader, serializersModule, configuration)
}

override fun endStructure(descriptor: SerialDescriptor) {
Expand Down Expand Up @@ -194,10 +180,23 @@ internal open class DefaultBsonDecoder(

@OptIn(ExperimentalSerializationApi::class)
private class BsonArrayDecoder(
descriptor: SerialDescriptor,
reader: AbstractBsonReader,
serializersModule: SerializersModule,
configuration: BsonConfiguration
) : DefaultBsonDecoder(reader, serializersModule, configuration) {

init {
reader.currentBsonType?.let {
if (it != BsonType.ARRAY) {
throw SerializationException(
"Invalid data for `${descriptor.kind}` expected a bson array found: " + "${reader.currentBsonType}")
}
}

reader.readStartArray()
}

private var index = 0
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
val nextType = reader.readBsonType()
Expand All @@ -208,12 +207,25 @@ private class BsonArrayDecoder(

@OptIn(ExperimentalSerializationApi::class)
private class PolymorphicDecoder(
descriptor: SerialDescriptor,
reader: AbstractBsonReader,
serializersModule: SerializersModule,
configuration: BsonConfiguration
) : DefaultBsonDecoder(reader, serializersModule, configuration) {
private var index = 0
private var mark: BsonReaderMark? = reader.mark
private var mark: BsonReaderMark?

init {
mark = reader.mark
reader.currentBsonType?.let {
if (it != BsonType.DOCUMENT) {
throw SerializationException(
"Invalid data for `${descriptor.serialName}` expected a bson document found: " +
"${reader.currentBsonType}")
}
}
reader.readStartDocument()
}

override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T {
mark?.let {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clears the mark on the first decoding of values.

Expand All @@ -227,15 +239,12 @@ private class PolymorphicDecoder(
var found = false
return when (index) {
0 -> {
reader.readStartDocument()
reader.readBsonType()
while (reader.state != AbstractBsonReader.State.END_OF_DOCUMENT) {
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
if (reader.readName() == configuration.classDiscriminator) {
found = true
break
}
reader.skipValue()
reader.readBsonType()
}
if (!found) {
throw SerializationException(
Expand All @@ -252,6 +261,26 @@ private class PolymorphicDecoder(

@OptIn(ExperimentalSerializationApi::class)
private class BsonDocumentDecoder(
descriptor: SerialDescriptor,
reader: AbstractBsonReader,
serializersModule: SerializersModule,
configuration: BsonConfiguration
) : DefaultBsonDecoder(reader, serializersModule, configuration) {
init {
reader.currentBsonType?.let {
if (it != BsonType.DOCUMENT) {
throw SerializationException(
"Invalid data for `${descriptor.serialName}` expected a bson document found: " +
"${reader.currentBsonType}")
}
}
reader.readStartDocument()
}
}

@OptIn(ExperimentalSerializationApi::class)
private class MapDecoder(
descriptor: SerialDescriptor,
reader: AbstractBsonReader,
serializersModule: SerializersModule,
configuration: BsonConfiguration
Expand All @@ -260,6 +289,17 @@ private class BsonDocumentDecoder(
private var index = 0
private var isKey = false

init {
reader.currentBsonType?.let {
jyemin marked this conversation as resolved.
Show resolved Hide resolved
if (it != BsonType.DOCUMENT) {
throw SerializationException(
"Invalid data for `${descriptor.kind}` expected a bson document found: " +
"${reader.currentBsonType}")
}
}
reader.readStartDocument()
}

override fun decodeString(): String {
return if (isKey) {
reader.readName()
Expand All @@ -275,8 +315,6 @@ private class BsonDocumentDecoder(
"Invalid key type for ${descriptor.serialName}. Expected STRING or ENUM but found: `${keyKind}`")
}

System.err.println(descriptor.serialName)

if (!isKey) {
isKey = true
val nextType = reader.readBsonType()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

@OptIn(ExperimentalSerializationApi::class)
@Suppress("LargeClass")
class KotlinSerializerCodecTest {
private val numberLong = "\$numberLong"
private val oid = "\$oid"
Expand Down Expand Up @@ -670,19 +671,40 @@ class KotlinSerializerCodecTest {
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}

assertThrows<MissingFieldException>("Invalid complex types") {
val data = BsonDocument.parse("""{"_id": "myId", "embedded": 123}""")
val codec = KotlinSerializerCodec.create<DataClassWithEmbedded>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}

assertThrows<IllegalArgumentException>("Failing init") {
val data = BsonDocument.parse("""{"id": "myId"}""")
val codec = KotlinSerializerCodec.create<DataClassWithFailingInit>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}

val exception =
var exception =
assertThrows<SerializationException>("Invalid complex types - document") {
val data = BsonDocument.parse("""{"_id": "myId", "embedded": 123}""")
val codec = KotlinSerializerCodec.create<DataClassWithEmbedded>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals(
"Invalid data for `org.bson.codecs.kotlinx.samples.DataClassEmbedded` " +
"expected a bson document found: INT32",
exception.message)

exception =
assertThrows<SerializationException>("Invalid complex types - list") {
val data = BsonDocument.parse("""{"_id": "myId", "nested": 123}""")
val codec = KotlinSerializerCodec.create<DataClassListOfDataClasses>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals("Invalid data for `LIST` expected a bson array found: INT32", exception.message)

exception =
assertThrows<SerializationException>("Invalid complex types - map") {
val data = BsonDocument.parse("""{"_id": "myId", "nested": 123}""")
val codec = KotlinSerializerCodec.create<DataClassMapOfDataClasses>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals("Invalid data for `MAP` expected a bson document found: INT32", exception.message)

exception =
assertThrows<SerializationException>("Missing discriminator") {
val data = BsonDocument.parse("""{"_id": {"$oid": "111111111111111111111111"}, "name": "string"}""")
val codec = KotlinSerializerCodec.create<SealedInterface>()
Expand Down