Skip to content

Commit 5476cd6

Browse files
committed
only create a mutable copy of the BsonDocument when needed
1 parent 0a2897b commit 5476cd6

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

dd-java-agent/instrumentation/mongo/common/src/main/java/datadog/trace/instrumentation/mongo/MongoCommentInjector.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@ public static BsonDocument injectComment(String dbmComment, BsonDocument origina
2828
return originalBsonDocument;
2929
}
3030

31-
// Create a mutable copy by constructing a new BsonDocument and copying all entries
32-
// This handles both regular BsonDocument and immutable RawBsonDocument/ByteBufBsonDocument
33-
BsonDocument command = new BsonDocument();
34-
command.putAll(originalBsonDocument);
31+
BsonDocument command = originalBsonDocument;
32+
if (!originalBsonDocument.getClass().equals(BsonDocument.class)) {
33+
// Create a mutable copy by constructing a new BsonDocument and copying all entries
34+
// This handles both regular BsonDocument and immutable RawBsonDocument/ByteBufBsonDocument
35+
command = new BsonDocument();
36+
command.putAll(originalBsonDocument);
37+
}
3538

3639
try {
3740
for (String commentKey : new String[] {"comment", "$comment"}) {

dd-java-agent/instrumentation/mongo/common/src/test/groovy/MongoCommentInjectorTest.groovy

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import datadog.trace.instrumentation.mongo.MongoCommentInjector
55
import org.bson.BsonDocument
66
import org.bson.BsonString
77
import org.bson.RawBsonDocument
8+
import org.bson.codecs.BsonDocumentCodec
89

910
abstract class BaseMongoCommentInjectorTest extends InstrumentationSpecification {
1011
@Override
@@ -113,7 +114,7 @@ class MongoCommentInjectorServiceModeForkedTest extends BaseMongoCommentInjector
113114
114115
// Create a RawBsonDocument (immutable) by encoding a regular BsonDocument
115116
def mutableDoc = new BsonDocument("find", new BsonString("collection"))
116-
def rawDoc = new RawBsonDocument(mutableDoc, new org.bson.codecs.BsonDocumentCodec())
117+
def rawDoc = new RawBsonDocument(mutableDoc, new BsonDocumentCodec())
117118
def dbmComment = "dddbs='test-service',dde='test'"
118119
119120
// Verify RawBsonDocument.clone() returns immutable document
@@ -151,6 +152,6 @@ class MongoCommentInjectorServiceModeForkedTest extends BaseMongoCommentInjector
151152
result != null
152153
result.containsKey("comment")
153154
result.get("comment").asString().getValue() == dbmComment
154-
!result.is(originalCommand)
155+
result.is(originalCommand)
155156
}
156157
}

0 commit comments

Comments
 (0)