kmongo icon indicating copy to clipboard operation
kmongo copied to clipboard

Request: Add explicit error message when incorrectly registering codecs to prevent OutOfMemoryError

Open korri123 opened this issue 2 years ago • 0 comments

So I just spend a few hours debugging a strange issue that was due to this kind of code:

    @Test
    fun `verify circular reference in kmongo, codec and jackson causes out of memory error`() {
        data class Chunk (
            val name: String
        )

        val mongoClient = KMongo.createClient(
            MongoClientSettings.builder()
                .applyConnectionString(ConnectionString("mongodb://localhost:27017"))
                .codecRegistry(fromCodecs(
                    // doesn't need to be anything here but I had a custom codec
                ))
                .build()
        )
        // boom, out of memory
        mongoClient.getDatabase("test").getCollection<Chunk>()
            .insertOne(
                Chunk(
                    name = "test"
                )
            )
    }

Now this was resolved by adding MongoClientSettings.getDefaultCodecRegistry() to the codecRegistry call after the custom codecs which in hindsight is a pretty dumb mistake on my part.

The issue was basically a circular reference between LazyCodec.java's wrapped == JacksonCodec and JacksonCodec.kt's rawBsonDocumentCodec == LazyCodec so the eaches encode functions kept calling each other recursively until a java.lang.OutOfMemoryError happened.

Would it be possible to have an error message that detects if the circular references are there?

korri123 avatar May 30 '23 16:05 korri123