Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ The default branch is `main` (not `master`). Always use `main` when comparing, d
- **Branch naming:** `JAVA-XXXX` matching the Jira ticket (e.g., `JAVA-6143`)
- **Commits:** Keep commits logical and reviewable — each commit should be a coherent unit of change
- **TODO comments:** Must reference a Jira ticket if the work belongs to a different ticket:
`// TODO JAVA-XXXX reasoning for the todo`
`// TODO-JAVA-XXXX reasoning for the todo`

## Core Rules

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1186,7 +1186,6 @@ class KotlinSerializerCodecTest {
}

@Test
@Suppress("LongMethod")
fun testDataClassWithJsonElementBsonSupport() {
val dataClassWithAllSupportedJsonTypes =
DataClassWithJsonElement(
Expand Down
2 changes: 1 addition & 1 deletion bson/src/main/org/bson/codecs/RawBsonDocumentCodec.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void encode(final BsonWriter writer, final RawBsonDocument value, final E
// abstract would be a breaking change, and adding it as a default method would force
// BsonWriter to depend on BsonBinaryReader/ByteBufferBsonInput, violating the
// interface's abstraction.
// TODO JAVA-6211 move pipe(byte[], int, int) to BsonWriter to remove this instanceof.
// TODO-JAVA-6211 move pipe(byte[], int, int) to BsonWriter to remove this instanceof.
((BsonBinaryWriter) writer).pipe(value.getBackingArray(), value.getByteOffset(), value.getByteLength());
} else {
try (BsonBinaryReader reader = new BsonBinaryReader(new ByteBufferBsonInput(value.getByteBuffer()))) {
Expand Down
2 changes: 1 addition & 1 deletion bson/src/test/unit/org/bson/vector/BinaryVectorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class BinaryVectorTest {
"FLOAT32 with padding",
// It is impossible to provide padding for INT8 in the API.
"INT8 with padding",
// TODO JAVA-5848 in 6.0.0 "Padding specified with no vector data PACKED_BIT" will throw an error (currently logs a warning).
// TODO-JAVA-5848 in 6.0.0 "Padding specified with no vector data PACKED_BIT" will throw an error (currently logs a warning).
"Padding specified with no vector data PACKED_BIT"
);

Expand Down
1 change: 1 addition & 0 deletions config/detekt/detekt.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ complexity:
LongMethod:
active: true
threshold: 60
excludes: ['**/test/**']
LongParameterList:
active: true
functionThreshold: 6
Expand Down
16 changes: 16 additions & 0 deletions config/spotbugs/exclude.xml
Original file line number Diff line number Diff line change
Expand Up @@ -327,4 +327,20 @@
<Method name="afterExecute"/>
<Bug pattern="NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION"/>
</Match>
<Match>
<!-- MongoDB status: "False Positive", SpotBugs rank: 20 -->
<!-- SpotBugs fails to recognize that `this.batchSize` invocation is unambiguous,
because bytecode does not retain the `this` qualifier. -->
<Class name="com.mongodb.client.internal.ChangeStreamIterableImpl$1"/>
<Method name="&lt;init&gt;"/>
<Bug pattern="IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD"/>
</Match>
<Match>
<!-- MongoDB status: "False Positive", SpotBugs rank: 20 -->
<!-- SpotBugs fails to recognize that `this.batchSize` invocation is unambiguous,
because bytecode does not retain the `this` qualifier. -->
<Class name="com.mongodb.reactivestreams.client.internal.ChangeStreamPublisherImpl$1"/>
<Method name="&lt;init&gt;"/>
<Bug pattern="IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD"/>
</Match>
</FindBugsFilter>
2 changes: 1 addition & 1 deletion driver-core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ dependencies {

tasks.processTestResources {
from("${rootProject.projectDir}/testing/resources")
// TODO JAVA-6283: remove this and the resources-ghsa-556f-q76p-2vxq
// TODO-JAVA-6283: remove this and the resources-ghsa-556f-q76p-2vxq
// directory once the specifications submodule includes the GridFS $eq
// tests. These files are vendored from the specifications security fork.
// Some of them replace files the submodule already provides, so this spec
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
import com.mongodb.ExplainVerbosity;
import com.mongodb.MongoNamespace;
import com.mongodb.client.cursor.TimeoutMode;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Collation;
import com.mongodb.client.model.MergeOptions;
import com.mongodb.internal.async.AsyncBatchCursor;
import com.mongodb.internal.async.SingleResultCallback;
import com.mongodb.internal.binding.AsyncReadBinding;
Expand All @@ -30,8 +32,10 @@
import org.bson.BsonDocument;
import org.bson.BsonValue;
import org.bson.codecs.Decoder;
import org.bson.conversions.Bson;

import java.util.List;
import java.util.function.Predicate;

import static com.mongodb.internal.connection.CommandHelper.applyMaxTimeMS;
import static com.mongodb.internal.operation.ExplainHelper.asExplainCommand;
Expand All @@ -43,6 +47,18 @@
* <p>This class is not part of the public API and may be removed or changed at any time</p>
*/
public class AggregateOperation<T> implements ReadOperationExplainable<T> {
/**
* {@linkplain Predicate#test(Object) Tests} if a field name is forbidden in {@link #overridingCommandOptions(BsonDocument)}.
* A forbidden field is either unconditionally required, or has client logic associated with it.
* For example, there is client logic that passes the {@code collation} field also to the {@code find} command
* when {@link Aggregates#out(Bson) $out} or {@link Aggregates#merge(MongoNamespace, MergeOptions) $merge} is used.
*
* @see ChangeStreamOperation#FORBIDDEN_COMMAND_OPTION_NAME
*/
// When changing this predicate, remember to update the documentation of the affected API.
public static final Predicate<String> FORBIDDEN_COMMAND_OPTION_NAME = ChangeStreamOperation.FORBIDDEN_COMMAND_OPTION_NAME
.or(name -> name.equals("collation"));

private final AggregateOperationImpl<T> wrapped;

public AggregateOperation(final MongoNamespace namespace, final List<BsonDocument> pipeline, final Decoder<T> decoder,
Expand Down Expand Up @@ -137,6 +153,11 @@ public AggregateOperation<T> timeoutMode(@Nullable final TimeoutMode timeoutMode
return this;
}

AggregateOperation<T> overridingCommandOptions(final BsonDocument overridingCommandOptions) {
wrapped.overridingCommandOptions(overridingCommandOptions);
return this;
}

@Override
public String getCommandName() {
return wrapped.getCommandName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ class AggregateOperationImpl<T> implements ReadOperationCursor<T> {
private BsonDocument variables;
private TimeoutMode timeoutMode;
private CursorType cursorType;
private BsonDocument overridingCommandOptions;

AggregateOperationImpl(final MongoNamespace namespace,
final List<BsonDocument> pipeline, final Decoder<T> decoder, final AggregationLevel aggregationLevel,
Expand All @@ -95,6 +96,7 @@ class AggregateOperationImpl<T> implements ReadOperationCursor<T> {
this.aggregateTarget = notNull("aggregateTarget", aggregateTarget);
this.pipelineCreator = notNull("pipelineCreator", pipelineCreator);
this.maxAdaptiveRetriesSetting = maxAdaptiveRetriesSetting;
overridingCommandOptions = new BsonDocument();
}

List<BsonDocument> getPipeline() {
Expand Down Expand Up @@ -187,6 +189,10 @@ AggregateOperationImpl<T> hint(@Nullable final BsonValue hint) {
return this;
}

void overridingCommandOptions(final BsonDocument overridingCommandOptions) {
this.overridingCommandOptions = overridingCommandOptions;
}

@Override
public String getCommandName() {
return COMMAND_NAME;
Expand Down Expand Up @@ -242,7 +248,8 @@ BsonDocument getCommand(final OperationContext operationContext, final int maxWi
if (variables != null) {
commandDocument.put("let", variables);
}

// `overridingCommandOptions` must be applied after other options
commandDocument.putAll(overridingCommandOptions);
return commandDocument;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ public class AggregateToCollectionOperation implements ReadOperationSimple<Void>
private BsonValue comment;
private BsonValue hint;
private BsonDocument variables;
private BsonDocument overridingCommandOptions;

public AggregateToCollectionOperation(final MongoNamespace namespace, final List<BsonDocument> pipeline, final ReadConcern readConcern,
final WriteConcern writeConcern) {
Expand All @@ -96,7 +97,7 @@ public AggregateToCollectionOperation(final MongoNamespace namespace, final List
this.aggregationLevel = notNull("aggregationLevel", aggregationLevel);
this.retryWrites = retryWrites;
this.maxAdaptiveRetriesSetting = maxAdaptiveRetriesSetting;

overridingCommandOptions = new BsonDocument();
isTrueArgument("pipeline is not empty", !pipeline.isEmpty());
}

Expand Down Expand Up @@ -167,6 +168,11 @@ public AggregateToCollectionOperation timeoutMode(@Nullable final TimeoutMode ti
return this;
}

AggregateToCollectionOperation overridingCommandOptions(final BsonDocument overridingCommandOptions) {
this.overridingCommandOptions = overridingCommandOptions;
return this;
}

@Override
public String getCommandName() {
return COMMAND_NAME;
Expand Down Expand Up @@ -242,6 +248,8 @@ private CommandOperationHelper.CommandCreator getCommandCreator() {
if (variables != null) {
commandDocument.put("let", variables);
}
// `overridingCommandOptions` must be applied after other options
commandDocument.putAll(overridingCommandOptions);
return commandDocument;
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,33 @@
import org.bson.codecs.RawBsonDocumentCodec;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.function.Predicate;

import static com.mongodb.assertions.Assertions.assertNotNull;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.client.cursor.TimeoutMode.CURSOR_LIFETIME;
import static java.util.Arrays.asList;

/**
* An operation that executes an {@code $changeStream} aggregation.
*
* <p>This class is not part of the public API and may be removed or changed at any time</p>
*/
public class ChangeStreamOperation<T> implements ReadOperationCursor<T> {
/**
* {@linkplain Predicate#test(Object) Tests} if a field name is forbidden in {@link #overridingCommandOptions(BsonDocument)}.
* A forbidden field is either unconditionally required, or has client logic associated with it.
* For example, there is client logic that passes the {@code comment} field also to the {@code getMore} commands.
*
* @see AggregateOperation#FORBIDDEN_COMMAND_OPTION_NAME
*/
// When changing this predicate, take into account that it affects `AggregateOperation.FORBIDDEN_COMMAND_OPTION_NAME`,
// and remember to update the documentation of the affected API.
public static final Predicate<String> FORBIDDEN_COMMAND_OPTION_NAME = new HashSet<>(asList(
"aggregate", "pipeline", "maxTimeMS", "cursor", "explain", "comment"))::contains;

private static final RawBsonDocumentCodec RAW_BSON_DOCUMENT_CODEC = new RawBsonDocumentCodec();
private final AggregateOperationImpl<RawBsonDocument> wrapped;
private final FullDocument fullDocument;
Expand Down Expand Up @@ -164,6 +179,11 @@ public ChangeStreamOperation<T> comment(final BsonValue comment) {
return this;
}

ChangeStreamOperation<T> overridingCommandOptions(final BsonDocument overridingCommandOptions) {
wrapped.overridingCommandOptions(overridingCommandOptions);
return this;
}

public boolean getShowExpandedEvents() {
return this.showExpandedEvents;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
import org.bson.BsonString;
import org.bson.BsonTimestamp;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.Decoder;
Expand Down Expand Up @@ -319,7 +320,8 @@ public <R> ReadOperationCursor<R> distinct(final String fieldName, @Nullable fin
public <R> ReadOperationExplainable<R> aggregate(final List<? extends Bson> pipeline, final Class<R> resultClass,
@Nullable final TimeoutMode timeoutMode, @Nullable final Integer batchSize,
final Collation collation, @Nullable final Bson hint, @Nullable final String hintString,
final BsonValue comment, final Bson variables, final Boolean allowDiskUse, final AggregationLevel aggregationLevel) {
final BsonValue comment, final Bson variables, final Boolean allowDiskUse, final AggregationLevel aggregationLevel,
final Document overridingCommandOptions) {
return new AggregateOperation<>(assertNotNull(namespace),
assertNotNull(toBsonDocumentList(pipeline)), codecRegistry.get(resultClass), aggregationLevel,
maxAdaptiveRetriesSetting)
Expand All @@ -330,12 +332,14 @@ public <R> ReadOperationExplainable<R> aggregate(final List<? extends Bson> pipe
.hint(hint != null ? toBsonDocument(hint) : (hintString != null ? new BsonString(hintString) : null))
.comment(comment)
.let(toBsonDocument(variables))
.timeoutMode(timeoutMode);
.timeoutMode(timeoutMode)
.overridingCommandOptions(encodeOverridingCommandOptions(overridingCommandOptions));
}

public ReadOperationSimple<Void> aggregateToCollection(final List<? extends Bson> pipeline, @Nullable final TimeoutMode timeoutMode,
final Boolean allowDiskUse, final Boolean bypassDocumentValidation, final Collation collation, @Nullable final Bson hint,
@Nullable final String hintString, final BsonValue comment, final Bson variables, final AggregationLevel aggregationLevel) {
@Nullable final String hintString, final BsonValue comment, final Bson variables, final AggregationLevel aggregationLevel,
final Document overridingCommandOptions) {
return new AggregateToCollectionOperation(assertNotNull(namespace),
assertNotNull(toBsonDocumentList(pipeline)), readConcern, writeConcern, aggregationLevel,
isRetryWrites(), maxAdaptiveRetriesSetting)
Expand All @@ -345,7 +349,8 @@ public ReadOperationSimple<Void> aggregateToCollection(final List<? extends Bso
.hint(hint != null ? toBsonDocument(hint) : (hintString != null ? new BsonString(hintString) : null))
.comment(comment)
.let(toBsonDocument(variables))
.timeoutMode(timeoutMode);
.timeoutMode(timeoutMode)
.overridingCommandOptions(encodeOverridingCommandOptions(overridingCommandOptions));
}

@SuppressWarnings("deprecation")
Expand Down Expand Up @@ -803,7 +808,8 @@ public <R> ReadOperationCursor<R> changeStream(final FullDocument fullDocument,
final FullDocumentBeforeChange fullDocumentBeforeChange, final List<? extends Bson> pipeline,
final Decoder<R> decoder, final ChangeStreamLevel changeStreamLevel, @Nullable final Integer batchSize,
final Collation collation, final BsonValue comment, final BsonDocument resumeToken,
final BsonTimestamp startAtOperationTime, final BsonDocument startAfter, final boolean showExpandedEvents) {
final BsonTimestamp startAtOperationTime, final BsonDocument startAfter, final boolean showExpandedEvents,
final Document overridingCommandOptions) {
return new ChangeStreamOperation<>(
assertNotNull(namespace),
fullDocument,
Expand All @@ -817,7 +823,8 @@ public <R> ReadOperationCursor<R> changeStream(final FullDocument fullDocument,
.startAtOperationTime(startAtOperationTime)
.startAfter(startAfter)
.showExpandedEvents(showExpandedEvents)
.retryReads(retryReads);
.retryReads(retryReads)
.overridingCommandOptions(encodeOverridingCommandOptions(overridingCommandOptions));
}

public WriteOperation<ClientBulkWriteResult> clientBulkWriteOperation(
Expand Down Expand Up @@ -866,4 +873,14 @@ private SearchIndexRequest createSearchIndexRequest(final SearchIndexModel model

return new SearchIndexRequest(definition, indexName, searchIndexType);
}

/**
* Encodes {@code overridingCommandOptions} in a way that does not require {@link #codecRegistry} to have a {@link Codec}
* for {@link Document}, if {@code overridingCommandOptions} is {@linkplain Document#isEmpty() empty}.
*/
private BsonDocument encodeOverridingCommandOptions(final Document overridingCommandOptions) {
return overridingCommandOptions.isEmpty()
? new BsonDocument()
: overridingCommandOptions.toBsonDocument(BsonDocument.class, codecRegistry);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,15 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification {
.allowDiskUse(true)
.batchSize(10)
.collation(defaultCollation)
.overridingCommandOptions(new BsonDocument('let', new BsonDocument('overriding', new BsonInt32(2))))
.let(new BsonDocument('overridden', new BsonInt32(1)))

expectedCommand = new BsonDocument('aggregate', new BsonString(helper.namespace.getCollectionName()))
.append('pipeline', new BsonArray(pipeline))
.append('allowDiskUse', new BsonBoolean(true))
.append('collation', defaultCollation.asDocument())
.append('cursor', new BsonDocument('batchSize', new BsonInt32(10)))
.append('let', new BsonDocument('overriding', new BsonInt32(2)))

then:
testOperation(operation, [3, 4, 0], expectedCommand, async, helper.cursorResult)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,26 @@ class AggregateToCollectionOperationSpecification extends OperationFunctionalSpe
operation.hint(new BsonString('x_1'))
expectedCommand.append('hint', new BsonString('x_1'))
}
if (useOverridingCommandOptions) {
operation.overridingCommandOptions(new BsonDocument('let', new BsonDocument('overriding', new BsonInt32(2))))
.let(new BsonDocument('overridden', new BsonInt32(1)))
expectedCommand.append('let', new BsonDocument('overriding', new BsonInt32(2)))
}

then:
testOperation(operation, serverVersion, expectedCommand, async, BsonDocument.parse('{ok: 1}'),
true, false, ReadPreference.primary(), false)

where:
serverVersion | includeBypassValidation | includeReadConcern | includeWriteConcern | includeCollation | async | useCursor | useHint
[3, 6, 0] | true | true | true | true | true | true | true
[3, 6, 0] | true | true | true | true | false | true | false
serverVersion << [[3, 6, 0], [3, 6, 0]]
includeBypassValidation << [true, true]
includeReadConcern << [true, true]
includeWriteConcern << [true, true]
includeCollation << [true, true]
async << [true, false]
useCursor << [true, true]
useHint << [true, false]
useOverridingCommandOptions << [true, true]
}

def 'should support collation'() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ import static com.mongodb.ClusterFixture.isStandalone
import static com.mongodb.internal.connection.ServerHelper.waitForLastRelease
import static java.util.Arrays.asList

// See https://github.com/mongodb/specifications/tree/master/source/change-streams/tests/README.md#prose-tests
/**
* See <a href="https://github.com/mongodb/specifications/tree/master/source/change-streams/tests/README.md#prose-tests">Prose Tests</a>.
* <p>
* New tests should be added to {@link com.mongodb.client.ChangeStreamProseTest}.
*/
@IgnoreIf({ isStandalone() })
class ChangeStreamOperationProseTestSpecification extends OperationFunctionalSpecification {

Expand Down
Loading