kmongo icon indicating copy to clipboard operation
kmongo copied to clipboard

Serialization for a Mongo type using kotlinx-serialization and ktor

Open manideepl-dev opened this issue 6 years ago • 10 comments

I'm trying to implement a custom serializer for the Point class from Mongo. I'm seeing this error: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT


import com.mongodb.client.model.geojson.Point
import com.mongodb.client.model.geojson.Position
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

object PointSerializer : KSerializer<Point> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Point", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Point) {
        val values = value.coordinates.values
        var source = ""
            values.forEach {
             source += it.toString() + "\n"
        }
        print("source point: $source")
        encoder.encodeString(source)
    }

    override fun deserialize(decoder: Decoder): Point {
        val string = decoder.decodeString()
        val values = string.split("\n")
        val doubleValues = mutableListOf<Double>()
        for (value in values) {
             doubleValues.add(value.toDouble())
        }
        println("doubles: $doubleValues")
        return Point(Position(doubleValues))
    }
}

The usage is this:

import com.manla.PointSerializer
import com.mongodb.client.model.geojson.Point
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable

@Serializable
data class Address(
    val line1 : String,
    val line2 : String,
    val city : String,
    val state : String,
    val country : String,
    @Serializable(with = PointSerializer::class)
    @Contextual
    val location : Point
)

What am I doing wrong? :(

manideepl-dev avatar Oct 19 '20 08:10 manideepl-dev

Can you post the full error stack?

Moortu avatar Oct 19 '20 09:10 Moortu

Now I see a different error strangely:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.manla.models.Reader. at org.bson.internal.CodecCache.getOrThrow(CodecCache.java:57) at org.bson.internal.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:64) at org.bson.internal.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:39) at com.mongodb.internal.operation.Operations.aggregate(Operations.java:177) at com.mongodb.internal.operation.AsyncOperations.aggregate(AsyncOperations.java:125) at com.mongodb.internal.async.client.AsyncAggregateIterableImpl.asAsyncReadOperation(AsyncAggregateIterableImpl.java:165) at com.mongodb.internal.async.client.AsyncMongoIterableImpl.batchCursor(AsyncMongoIterableImpl.java:167) at com.mongodb.reactivestreams.client.internal.MongoIterableSubscription.requestInitialData(MongoIterableSubscription.java:45) at com.mongodb.reactivestreams.client.internal.AbstractSubscription.tryRequestInitialData(AbstractSubscription.java:177) at com.mongodb.reactivestreams.client.internal.AbstractSubscription.request(AbstractSubscription.java:100) at kotlinx.coroutines.reactive.SubscriptionChannel.onSubscribe(Channel.kt:103) at com.mongodb.reactivestreams.client.internal.MongoIterableSubscription.<init>(MongoIterableSubscription.java:39) at com.mongodb.reactivestreams.client.internal.Publishers.lambda$publish$0(Publishers.java:43) at com.mongodb.reactivestreams.client.internal.AggregatePublisherImpl.subscribe(AggregatePublisherImpl.java:100) at kotlinx.coroutines.reactive.ChannelKt.openSubscription(Channel.kt:32) at kotlinx.coroutines.reactive.ChannelKt.openSubscription$default(Channel.kt:30) at org.litote.kmongo.coroutine.CoroutinePublisherKt.toList(CoroutinePublisher.kt:63) at org.litote.kmongo.coroutine.CoroutinePublisher.toList(CoroutinePublisher.kt:48) at com.manla.DBRepo.getReaders(DBRepo.kt:39) at com.manla.ApplicationKt$module$2$1.invokeSuspend(Application.kt:27) at com.manla.ApplicationKt$module$2$1.invoke(Application.kt) at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243) at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113) at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133) at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77) at io.ktor.routing.Routing.executeResult(Routing.kt:148) at io.ktor.routing.Routing.interceptor(Routing.kt:35) at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:100) at io.ktor.routing.Routing$Feature$install$1.invoke(Routing.kt) at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243) at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113) at io.ktor.features.ContentNegotiation$Feature$install$1.invokeSuspend(ContentNegotiation.kt:113) at io.ktor.features.ContentNegotiation$Feature$install$1.invoke(ContentNegotiation.kt) at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243) at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113) at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133) at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77) at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invokeSuspend(DefaultEnginePipeline.kt:121) at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invoke(DefaultEnginePipeline.kt) at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243) at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113) at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133) at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77) at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invokeSuspend(NettyApplicationCallHandler.kt:54) at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt) at kotlinx.coroutines.intrinsics.UndispatchedKt.startCoroutineUndispatched(Undispatched.kt:55) at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:111) at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56) at kotlinx.coroutines.BuildersKt.launch(Unknown Source) at io.ktor.server.netty.NettyApplicationCallHandler.handleRequest(NettyApplicationCallHandler.kt:37) at io.ktor.server.netty.NettyApplicationCallHandler.channelRead(NettyApplicationCallHandler.kt:29) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61) at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:834)

How I'm initializing the db.

private val connectionString = ConnectionString("mongodb+srv://<username>:<password>@cluster0.rtcig.mongodb.net/<dbname>?retryWrites=true&w=majority")

    private val client = MongoClients.create(connectionString).coroutine
    private val database = client.getDatabase(<dbname>)
    private val readersCollection = database.getCollection<Reader>("readers")

The Reader class:

@Serializable
data class Reader(
        @Contextual
        val _id: Id<Reader>,
        val name: String,
        val mobile: String,
        val email: String,
        val books : List<String>?,
        val address : Address
)

The dependencies:

implementation("org.litote.kmongo:kmongo-id:$kmongo_version")
implementation("org.litote.kmongo:kmongo-coroutine-serialization:$kmongo_version")
implementation("org.litote.kmongo:kmongo-id-serialization:$kmongo_version")

manideepl-dev avatar Oct 19 '20 12:10 manideepl-dev

I think you need to use KMongo.createClient(connectionString).coroutine instead of MongoClients.create(connectionString).coroutine

the MongoClients is the direct Mongo Driver, whereas Kmongo is the wrapper

the Mongo driver will not have the Serializer registered, that's why you get the error. The KMongo wrapper will have it.

Moortu avatar Oct 19 '20 13:10 Moortu

Oh yes I changed it now, thank you.

Now here is the stacktrace for the original error:

org.bson.BsonInvalidOperationException: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT. at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:690) at org.bson.AbstractBsonReader.checkPreconditions(AbstractBsonReader.java:722) at org.bson.AbstractBsonReader.readString(AbstractBsonReader.java:457) at com.github.jershell.kbson.FlexibleDecoder.decodeString(BsonFlexibleDecoder.kt:114) at com.github.jershell.kbson.BsonFlexibleDecoder.decodeString(BsonFlexibleDecoder.kt:226) at com.manla.PointSerializer.deserialize(PointSerializer.kt:26) at com.manla.PointSerializer.deserialize(PointSerializer.kt:12) at kotlinx.serialization.encoding.Decoder$DefaultImpls.decodeSerializableValue(Decoding.kt:234) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:17) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:41) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableElement(AbstractDecoder.kt:63) at com.manla.models.Address$$serializer.deserialize(Address.kt) at com.manla.models.Address$$serializer.deserialize(Address.kt:9) at kotlinx.serialization.encoding.Decoder$DefaultImpls.decodeSerializableValue(Decoding.kt:234) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:17) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:41) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableElement(AbstractDecoder.kt:63) at com.manla.models.Reader$$serializer.deserialize(Reader.kt) at com.manla.models.Reader$$serializer.deserialize(Reader.kt:11) at kotlinx.serialization.encoding.Decoder$DefaultImpls.decodeSerializableValue(Decoding.kt:234) at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:17) at org.litote.kmongo.serialization.SerializationCodec.decode(SerializationCodec.kt:69) at com.mongodb.internal.operation.CommandResultArrayCodec.decode(CommandResultArrayCodec.java:52) at com.mongodb.internal.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:60) at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:87) at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:42) at org.bson.internal.LazyCodec.decode(LazyCodec.java:48) at org.bson.codecs.BsonDocumentCodec.readValue(BsonDocumentCodec.java:104) at com.mongodb.internal.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:63) at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:87) at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:42) at com.mongodb.internal.connection.ReplyMessage.<init>(ReplyMessage.java:51) at com.mongodb.internal.connection.InternalStreamConnection.getCommandResult(InternalStreamConnection.java:477) at com.mongodb.internal.connection.InternalStreamConnection.access$1000(InternalStreamConnection.java:78) at com.mongodb.internal.connection.InternalStreamConnection$2$1.onResult(InternalStreamConnection.java:462) at com.mongodb.internal.connection.InternalStreamConnection$2$1.onResult(InternalStreamConnection.java:440) at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback$MessageCallback.onResult(InternalStreamConnection.java:745) at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback$MessageCallback.onResult(InternalStreamConnection.java:712) at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:582) at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:579) at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.completed(AsynchronousChannelStream.java:250) at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.completed(AsynchronousChannelStream.java:233) at com.mongodb.internal.connection.tlschannel.async.AsynchronousTlsChannel.lambda$read$4(AsynchronousTlsChannel.java:122) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834)

manideepl-dev avatar Oct 19 '20 14:10 manideepl-dev

@manideepl I think your serializer / deserializer isn't correct. Try debugging that

Moortu avatar Oct 19 '20 17:10 Moortu

I couldn't :( I used a simple model to map the BSON with this class:

@Serializable data class GeoPoint( val type : String, val coordinates : Array<Double> )

manideepl-dev avatar Oct 20 '20 18:10 manideepl-dev

@manideepl look at this unit test https://github.com/Litote/kmongo/commit/1b7e813f8bfa72ad0305abeb1ab5fb55c2683d32#diff-26118dfd6605f99f98000400bb4c25773fe1d03fffb6a6d71dc6ec4924b8d470R30 : it does not fail ;)

zigzago avatar Oct 21 '20 20:10 zigzago

What? How come you're only handling the type attribute and not the coordinates attribute?

manideepl-dev avatar Oct 22 '20 08:10 manideepl-dev

in your sample @manideepl you serialize in a string and deserialize from a string - just change the serializer implementation to build the string to serialize - and of course for deserialization parse the string to rebuild the type & coordinate attributes. Note that it would be better to serialize both attributes separately (using encoder.beginStructure and encoder.endStructure) - but direct string serialization is also supported - this is the purpose of the unit test ;)

zigzago avatar Oct 26 '20 14:10 zigzago

For anyone still looking to create a Point serializer, this one is working for me:

object PointSerializer : KSerializer<Point> {
    override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Point") {
        element("type", PrimitiveSerialDescriptor("GeoJsonObjectType", PrimitiveKind.STRING))
        element("coordinates", PositionSerializer::descriptor.get())
    }

    override fun serialize(encoder: Encoder, value: Point) {
        encoder.encodeStructure(descriptor) {
            encodeStringElement(descriptor, 0, "Point")
            encodeSerializableElement(descriptor, 1, PositionSerializer, value.coordinates)
        }
    }

    override fun deserialize(decoder: Decoder): Point =
        decoder.decodeStructure(descriptor) {
            var coordinates: Position? = null
            while (true) {
                when (val index = decodeElementIndex(descriptor)) {
                    0 -> decodeStringElement(descriptor, 0)
                    1 -> coordinates = decodeSerializableElement(descriptor, 1, PositionSerializer)
                    CompositeDecoder.DECODE_DONE -> break
                    else -> error("Unexpected index: $index")
                }
            }
            Point(coordinates!!)
        }
}

object PositionSerializer : KSerializer<Position> {
    private val delegateSerializer = DoubleArraySerializer()
    override val descriptor = SerialDescriptor("Position", delegateSerializer.descriptor)

    override fun serialize(encoder: Encoder, value: Position) {
        encoder.encodeSerializableValue(delegateSerializer, value.values.toDoubleArray())
    }

    override fun deserialize(decoder: Decoder): Position =
        Position(decoder.decodeSerializableValue(delegateSerializer).toList())
}

Source: https://kotlinlang.slack.com/archives/CQ5JC5T0F/p1645087200935369?thread_ts=1645066822.224609&cid=CQ5JC5T0F

brahyam avatar Sep 18 '22 12:09 brahyam