From 785eedee9e8b9f279ccf32d265971c615a57d805 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sun, 15 Nov 2026 15:37:42 +0100 Subject: [PATCH 1/5] Annotate serialVersionUID fields with @Serial --- .../de/bwaldvogel/mongo/backend/AbstractMongoCollection.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java | 2 ++ .../src/main/java/de/bwaldvogel/mongo/backend/LimitedList.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/backend/Missing.java | 3 +++ .../main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java | 2 ++ .../de/bwaldvogel/mongo/backend/aggregation/Aggregation.java | 2 ++ .../mongo/backend/aggregation/stage/ProjectStage.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java | 2 ++ .../src/main/java/de/bwaldvogel/mongo/bson/BsonJavaScript.java | 2 ++ .../java/de/bwaldvogel/mongo/bson/BsonRegularExpression.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/bson/BsonTimestamp.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/bson/Decimal128.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/bson/Document.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/bson/LegacyUUID.java | 2 ++ core/src/main/java/de/bwaldvogel/mongo/bson/MaxKey.java | 3 +++ core/src/main/java/de/bwaldvogel/mongo/bson/MinKey.java | 3 +++ core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java | 2 ++ .../java/de/bwaldvogel/mongo/exception/BadValueException.java | 3 +++ .../mongo/exception/CannotIndexParallelArraysError.java | 2 ++ .../mongo/exception/CannotTraverseElementException.java | 3 +++ .../mongo/exception/ConflictingUpdateOperatorsException.java | 3 +++ .../bwaldvogel/mongo/exception/ConversionFailureException.java | 3 +++ .../de/bwaldvogel/mongo/exception/CursorNotFoundException.java | 3 +++ .../mongo/exception/DollarPrefixedFieldNameException.java | 3 +++ .../java/de/bwaldvogel/mongo/exception/DuplicateKeyError.java | 2 ++ .../mongo/exception/FailedToOptimizePipelineError.java | 3 +++ .../de/bwaldvogel/mongo/exception/FailedToParseException.java | 3 +++ .../bwaldvogel/mongo/exception/IllegalOperationException.java | 3 +++ .../de/bwaldvogel/mongo/exception/ImmutableFieldException.java | 3 +++ .../bwaldvogel/mongo/exception/IndexBuildFailedException.java | 2 ++ .../mongo/exception/IndexKeySpecsConflictException.java | 3 +++ .../de/bwaldvogel/mongo/exception/IndexNotFoundException.java | 3 +++ .../de/bwaldvogel/mongo/exception/InvalidIdFieldError.java | 3 +++ .../de/bwaldvogel/mongo/exception/InvalidNamespaceError.java | 3 +++ .../de/bwaldvogel/mongo/exception/InvalidOptionsException.java | 3 +++ .../java/de/bwaldvogel/mongo/exception/KeyConstraintError.java | 3 +++ .../mongo/exception/MergeStageNoMatchingDocumentException.java | 3 +++ .../java/de/bwaldvogel/mongo/exception/MongoServerError.java | 2 ++ .../de/bwaldvogel/mongo/exception/MongoServerException.java | 3 +++ .../mongo/exception/MongoServerNotYetImplementedException.java | 3 +++ .../bwaldvogel/mongo/exception/MongoSilentServerException.java | 3 +++ .../bwaldvogel/mongo/exception/NamespaceExistsException.java | 3 +++ .../mongo/exception/NoReplicationEnabledException.java | 3 +++ .../de/bwaldvogel/mongo/exception/NoSuchCommandException.java | 3 +++ .../de/bwaldvogel/mongo/exception/PathNotViableException.java | 3 +++ .../de/bwaldvogel/mongo/exception/TypeMismatchException.java | 3 +++ .../bwaldvogel/mongo/exception/UnsupportedConversionError.java | 3 +++ .../de/bwaldvogel/mongo/wire/MongoExceptionHandlerTest.java | 3 +++ 48 files changed, 126 insertions(+) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java index 043d67eed..e623f1c82 100755 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java @@ -2,6 +2,7 @@ import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD; +import java.io.Serial; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -462,6 +463,7 @@ public Document findAndModify(Document query) { public static class FindAndModifyPlanExecutorError extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; private static final String PREFIX = "Plan executor error during findAndModify :: caused by :: "; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java index da7bb6375..bb197b455 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java @@ -1,5 +1,6 @@ package de.bwaldvogel.mongo.backend; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; @@ -14,6 +15,7 @@ public final class KeyValue implements Serializable, Iterable { + @Serial private static final long serialVersionUID = 1L; // Every constructor stores a serializable ArrayList here. diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/LimitedList.java b/core/src/main/java/de/bwaldvogel/mongo/backend/LimitedList.java index bf14d4c02..5675919d7 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/LimitedList.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/LimitedList.java @@ -1,9 +1,11 @@ package de.bwaldvogel.mongo.backend; +import java.io.Serial; import java.util.ArrayList; public class LimitedList extends ArrayList { + @Serial private static final long serialVersionUID = -4265811949513159615L; private final int limit; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Missing.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Missing.java index b3e1bed3d..d8a710c84 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Missing.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Missing.java @@ -1,9 +1,12 @@ package de.bwaldvogel.mongo.backend; +import java.io.Serial; + import de.bwaldvogel.mongo.bson.Bson; public class Missing implements Bson { + @Serial private static final long serialVersionUID = 1L; private static final Missing INSTANCE = new Missing(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java b/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java index 0166de770..462ac473f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java @@ -12,6 +12,7 @@ import static de.bwaldvogel.mongo.backend.Command.LIST_DATABASES; import static de.bwaldvogel.mongo.backend.Command.SERVER_STATUS; +import java.io.Serial; import java.time.Clock; import java.util.Collection; import java.util.List; @@ -52,6 +53,7 @@ public ReadOnlyProxy(MongoBackend backend) { public static class ReadOnlyException extends MongoServerException { + @Serial private static final long serialVersionUID = 1L; ReadOnlyException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java index 206341f14..d91009a34 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java @@ -2,6 +2,7 @@ import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD; +import java.io.Serial; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -280,6 +281,7 @@ public boolean isModifying() { private static class PlanExecutorError extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; private static final String MESSAGE_PREFIX = "PlanExecutor error during aggregation :: caused by :: "; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ProjectStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ProjectStage.java index e752ef489..933b87e99 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ProjectStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ProjectStage.java @@ -2,6 +2,7 @@ import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD; +import java.io.Serial; import java.util.List; import java.util.Map.Entry; import java.util.stream.Collectors; @@ -98,6 +99,7 @@ Document projectDocument(Document document) { public static class InvalidProjectException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; private static final String MESSAGE_PREFIX = "Invalid $project :: caused by :: "; diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java b/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java index a0a574e9c..79b9e23a8 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java @@ -1,10 +1,12 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; import java.util.Arrays; import java.util.Objects; public final class BinData implements Comparable, Bson { + @Serial private static final long serialVersionUID = 1L; private final byte[] data; diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/BsonJavaScript.java b/core/src/main/java/de/bwaldvogel/mongo/bson/BsonJavaScript.java index ad48afa52..445f08151 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/BsonJavaScript.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/BsonJavaScript.java @@ -1,9 +1,11 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; import java.util.Objects; public final class BsonJavaScript implements Bson { + @Serial private static final long serialVersionUID = 1L; private final String code; diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/BsonRegularExpression.java b/core/src/main/java/de/bwaldvogel/mongo/bson/BsonRegularExpression.java index 09797d8fa..05434880f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/BsonRegularExpression.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/BsonRegularExpression.java @@ -1,5 +1,6 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -8,6 +9,7 @@ public class BsonRegularExpression implements Bson { + @Serial private static final long serialVersionUID = 1L; private static final String REGEX = "$regex"; diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/BsonTimestamp.java b/core/src/main/java/de/bwaldvogel/mongo/bson/BsonTimestamp.java index 61b3342b0..66afc3662 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/BsonTimestamp.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/BsonTimestamp.java @@ -1,10 +1,12 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; import java.time.Instant; import java.util.Objects; public final class BsonTimestamp implements Bson, Comparable { + @Serial private static final long serialVersionUID = 1L; private final long value; diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/Decimal128.java b/core/src/main/java/de/bwaldvogel/mongo/bson/Decimal128.java index b2e5175f2..38b6549a1 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/Decimal128.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/Decimal128.java @@ -2,6 +2,7 @@ import static java.math.MathContext.DECIMAL128; +import java.io.Serial; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; @@ -11,6 +12,7 @@ public final class Decimal128 extends Number implements Serializable, Comparable { + @Serial private static final long serialVersionUID = 1L; public static final Decimal128 ONE = new Decimal128(1, 3476778912330022912L); diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java b/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java index 985e8a384..a5a632d6b 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java @@ -1,5 +1,6 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; @@ -13,6 +14,7 @@ public final class Document implements Map, Bson { + @Serial private static final long serialVersionUID = 1L; private final LinkedHashMap documentAsMap = new LinkedHashMap<>(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/LegacyUUID.java b/core/src/main/java/de/bwaldvogel/mongo/bson/LegacyUUID.java index be538e178..61d760113 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/LegacyUUID.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/LegacyUUID.java @@ -1,10 +1,12 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; import java.util.Objects; import java.util.UUID; public final class LegacyUUID implements Comparable, Bson { + @Serial private static final long serialVersionUID = 1L; private final UUID uuid; diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/MaxKey.java b/core/src/main/java/de/bwaldvogel/mongo/bson/MaxKey.java index 039cb4f23..2f031f627 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/MaxKey.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/MaxKey.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; + public class MaxKey implements Bson { + @Serial private static final long serialVersionUID = 1L; private static final MaxKey INSTANCE = new MaxKey(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/MinKey.java b/core/src/main/java/de/bwaldvogel/mongo/bson/MinKey.java index 2e853b9c0..8fae83119 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/MinKey.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/MinKey.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.bson; +import java.io.Serial; + public class MinKey implements Bson { + @Serial private static final long serialVersionUID = 1L; private static final MinKey INSTANCE = new MinKey(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java b/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java index 1e8c1c4a2..1bbc28cea 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java @@ -2,6 +2,7 @@ import static de.bwaldvogel.mongo.wire.BsonConstants.LENGTH_OBJECTID; +import java.io.Serial; import java.security.SecureRandom; import java.util.Arrays; import java.util.HexFormat; @@ -11,6 +12,7 @@ public class ObjectId implements Bson, Comparable { + @Serial private static final long serialVersionUID = 1L; private static final Pattern PATTERN = Pattern.compile("^[a-f0-9]{24}$"); diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/BadValueException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/BadValueException.java index f6d0f0dd8..615d168bf 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/BadValueException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/BadValueException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class BadValueException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; private final boolean shouldPrefixCommandContext; diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/CannotIndexParallelArraysError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/CannotIndexParallelArraysError.java index 29ff757f3..009cb666d 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/CannotIndexParallelArraysError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/CannotIndexParallelArraysError.java @@ -1,5 +1,6 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -7,6 +8,7 @@ public class CannotIndexParallelArraysError extends KeyConstraintError { + @Serial private static final long serialVersionUID = 1L; public CannotIndexParallelArraysError(Collection paths) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/CannotTraverseElementException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/CannotTraverseElementException.java index b3370e69d..9d351c90f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/CannotTraverseElementException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/CannotTraverseElementException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class CannotTraverseElementException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public CannotTraverseElementException() { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/ConflictingUpdateOperatorsException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/ConflictingUpdateOperatorsException.java index e19285745..a45a16985 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/ConflictingUpdateOperatorsException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/ConflictingUpdateOperatorsException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class ConflictingUpdateOperatorsException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public ConflictingUpdateOperatorsException(String updatePath, String conflictingPath) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/ConversionFailureException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/ConversionFailureException.java index e737f157f..8b7164b08 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/ConversionFailureException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/ConversionFailureException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class ConversionFailureException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public ConversionFailureException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/CursorNotFoundException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/CursorNotFoundException.java index 4bd5819fe..9a4649914 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/CursorNotFoundException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/CursorNotFoundException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class CursorNotFoundException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public CursorNotFoundException(long cursorId) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/DollarPrefixedFieldNameException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/DollarPrefixedFieldNameException.java index 8876d940e..1e5e6127f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/DollarPrefixedFieldNameException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/DollarPrefixedFieldNameException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class DollarPrefixedFieldNameException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public DollarPrefixedFieldNameException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/DuplicateKeyError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/DuplicateKeyError.java index 87562fb3f..f866acb0e 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/DuplicateKeyError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/DuplicateKeyError.java @@ -1,5 +1,6 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -12,6 +13,7 @@ public class DuplicateKeyError extends KeyConstraintError { + @Serial private static final long serialVersionUID = 1L; public DuplicateKeyError(Index index, MongoCollection collection, List keys, KeyValue keyValue) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToOptimizePipelineError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToOptimizePipelineError.java index 4989b3ae0..447dde34b 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToOptimizePipelineError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToOptimizePipelineError.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class FailedToOptimizePipelineError extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; private static final String FAILED_TO_OPTIMIZE_MESSAGE = "Failed to optimize pipeline :: caused by :: "; diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToParseException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToParseException.java index d55a2548b..e8593908c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToParseException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToParseException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class FailedToParseException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public FailedToParseException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/IllegalOperationException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/IllegalOperationException.java index 394c749d2..fa30f15d2 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/IllegalOperationException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/IllegalOperationException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class IllegalOperationException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public IllegalOperationException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/ImmutableFieldException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/ImmutableFieldException.java index 57b23b549..734c7d8cd 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/ImmutableFieldException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/ImmutableFieldException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class ImmutableFieldException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public ImmutableFieldException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/IndexBuildFailedException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/IndexBuildFailedException.java index 3374e6fc3..2b006a9da 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/IndexBuildFailedException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/IndexBuildFailedException.java @@ -1,10 +1,12 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; import java.util.UUID; import de.bwaldvogel.mongo.MongoCollection; public class IndexBuildFailedException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public IndexBuildFailedException(MongoServerError e, MongoCollection collection) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/IndexKeySpecsConflictException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/IndexKeySpecsConflictException.java index 0adccd267..3c04b982f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/IndexKeySpecsConflictException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/IndexKeySpecsConflictException.java @@ -1,10 +1,13 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + import de.bwaldvogel.mongo.backend.Index; import de.bwaldvogel.mongo.bson.Json; public class IndexKeySpecsConflictException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public IndexKeySpecsConflictException(Index requestedIndex, Index existingIndex) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/IndexNotFoundException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/IndexNotFoundException.java index fea6fdeb7..2df45a2fc 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/IndexNotFoundException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/IndexNotFoundException.java @@ -1,9 +1,12 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + import de.bwaldvogel.mongo.bson.Document; public class IndexNotFoundException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public IndexNotFoundException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidIdFieldError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidIdFieldError.java index 26c54a411..a60d9117b 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidIdFieldError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidIdFieldError.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class InvalidIdFieldError extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public InvalidIdFieldError(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidNamespaceError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidNamespaceError.java index f5aac76d5..4866b62b6 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidNamespaceError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidNamespaceError.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class InvalidNamespaceError extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public InvalidNamespaceError(String namespace) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidOptionsException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidOptionsException.java index 5969b8603..0493c3164 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidOptionsException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidOptionsException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class InvalidOptionsException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public InvalidOptionsException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/KeyConstraintError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/KeyConstraintError.java index 5f4436284..baa7ee6ae 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/KeyConstraintError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/KeyConstraintError.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class KeyConstraintError extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; KeyConstraintError(ErrorCode errorCode, String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/MergeStageNoMatchingDocumentException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MergeStageNoMatchingDocumentException.java index 7b45329e8..8e298e7a7 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/MergeStageNoMatchingDocumentException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/MergeStageNoMatchingDocumentException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class MergeStageNoMatchingDocumentException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public MergeStageNoMatchingDocumentException() { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java index 49acce7f8..57022891f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java @@ -1,9 +1,11 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; import java.util.Arrays; public class MongoServerError extends MongoServerException { + @Serial private static final long serialVersionUID = 1L; private final String message; diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerException.java index d98074fdd..5515edba2 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerException.java @@ -1,9 +1,12 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + import de.bwaldvogel.mongo.backend.Assert; public class MongoServerException extends RuntimeException { + @Serial private static final long serialVersionUID = 1L; private boolean logError = true; diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerNotYetImplementedException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerNotYetImplementedException.java index 894ff945c..840e1bd97 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerNotYetImplementedException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerNotYetImplementedException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class MongoServerNotYetImplementedException extends MongoServerException { + @Serial private static final long serialVersionUID = 1L; private static final String ISSUES_URL = "https://github.com/bwaldvogel/mongo-java-server/issues/"; diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoSilentServerException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoSilentServerException.java index 16833deb7..fb19cef28 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoSilentServerException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoSilentServerException.java @@ -1,10 +1,13 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + /** * similar to {@link MongoServerException} but will not be logged as error with stacktrace */ public class MongoSilentServerException extends MongoServerException { + @Serial private static final long serialVersionUID = 1L; public MongoSilentServerException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/NamespaceExistsException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/NamespaceExistsException.java index adf6ebf10..8869c0d7e 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/NamespaceExistsException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/NamespaceExistsException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class NamespaceExistsException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public NamespaceExistsException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/NoReplicationEnabledException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/NoReplicationEnabledException.java index c7f9f3bbc..d422cf685 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/NoReplicationEnabledException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/NoReplicationEnabledException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class NoReplicationEnabledException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public NoReplicationEnabledException() { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/NoSuchCommandException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/NoSuchCommandException.java index 3bc171eb8..346f49021 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/NoSuchCommandException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/NoSuchCommandException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class NoSuchCommandException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public NoSuchCommandException(String command) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/PathNotViableException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/PathNotViableException.java index 38a3a025d..08287776d 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/PathNotViableException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/PathNotViableException.java @@ -1,9 +1,12 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + import de.bwaldvogel.mongo.bson.Document; public class PathNotViableException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; private final String field; diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/TypeMismatchException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/TypeMismatchException.java index 9e4244d2c..4d37ddff1 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/TypeMismatchException.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/TypeMismatchException.java @@ -1,7 +1,10 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + public class TypeMismatchException extends MongoServerError { + @Serial private static final long serialVersionUID = 1L; public TypeMismatchException(String message) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/UnsupportedConversionError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/UnsupportedConversionError.java index 7438c98a1..6ef421127 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/UnsupportedConversionError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/UnsupportedConversionError.java @@ -1,9 +1,12 @@ package de.bwaldvogel.mongo.exception; +import java.io.Serial; + import static de.bwaldvogel.mongo.backend.Utils.describeType; public class UnsupportedConversionError extends ConversionFailureException { + @Serial private static final long serialVersionUID = 1L; public UnsupportedConversionError(Object value, Class targetType) { diff --git a/core/src/test/java/de/bwaldvogel/mongo/wire/MongoExceptionHandlerTest.java b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoExceptionHandlerTest.java index 7916c2b40..8796ae076 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/wire/MongoExceptionHandlerTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoExceptionHandlerTest.java @@ -5,6 +5,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.Serial; + import org.junit.jupiter.api.Test; import io.netty.channel.Channel; @@ -32,6 +34,7 @@ void exceptionCaught() { static class MockChannelId implements ChannelId { + @Serial private static final long serialVersionUID = 1L; private final String id; From dc0e14b7f824e0fd0b1e7c93da16c8732d4fd076 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sun, 15 Nov 2026 15:57:34 +0100 Subject: [PATCH 2/5] Remove unused Collections imports from core tests --- .../java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java | 1 - .../test/java/de/bwaldvogel/mongo/backend/LinkedTreeSetTest.java | 1 - 2 files changed, 2 deletions(-) diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java index d8de29cf1..61366e7e9 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/LinkedTreeSetTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/LinkedTreeSetTest.java index f25915a0a..6a3756b43 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/LinkedTreeSetTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/LinkedTreeSetTest.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; From a45dbf1da3817e307dbf2a6a91ac8f741a5ce351 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sun, 15 Nov 2026 15:27:48 +0100 Subject: [PATCH 3/5] Remove legacy MongoDB Java driver dependencies and example Use the standalone BSON module in core tests and the current sync driver in examples. Remove the legacy client example and update dependency locks. --- core/build.gradle | 2 +- core/gradle.lockfile | 2 +- examples/build.gradle | 2 +- examples/gradle.lockfile | 5 +- ...nClientTest.java => SimpleJUnit5Test.java} | 2 +- .../SimpleJUnit5WithLegacyClientTest.java | 52 ------------------- gradle.lockfile | 1 - 7 files changed, 8 insertions(+), 58 deletions(-) rename examples/src/main/java/{SimpleJUnit5WithModernClientTest.java => SimpleJUnit5Test.java} (97%) delete mode 100644 examples/src/main/java/SimpleJUnit5WithLegacyClientTest.java diff --git a/core/build.gradle b/core/build.gradle index 82f103645..881f3fe54 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -3,7 +3,7 @@ dependencies { implementation 'io.netty:netty-codec:latest.release' implementation 'io.netty:netty-handler:latest.release' - testImplementation 'org.mongodb:mongo-java-driver:latest.release' + testImplementation 'org.mongodb:bson:latest.release' testImplementation "org.mockito:mockito-core:latest.release" testImplementation "org.mockito:mockito-junit-jupiter:latest.release" testImplementation "nl.jqno.equalsverifier:equalsverifier:latest.release" diff --git a/core/gradle.lockfile b/core/gradle.lockfile index d3f322700..7450e0360 100644 --- a/core/gradle.lockfile +++ b/core/gradle.lockfile @@ -34,7 +34,7 @@ org.junit.platform:junit-platform-launcher:6.1.3=testRuntimeClasspath org.junit:junit-bom:6.1.3=testCompileClasspath,testRuntimeClasspath org.mockito:mockito-core:5.24.0=testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.24.0=testCompileClasspath,testRuntimeClasspath -org.mongodb:mongo-java-driver:3.12.14=testCompileClasspath,testRuntimeClasspath +org.mongodb:bson:5.14.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.6=testCompileClasspath,testRuntimeClasspath org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath org.ow2.asm:asm-commons:9.10.1=jacocoAnt diff --git a/examples/build.gradle b/examples/build.gradle index 716d8a321..aa8a59db7 100644 --- a/examples/build.gradle +++ b/examples/build.gradle @@ -1,7 +1,7 @@ dependencies { api project(':mongo-java-server-memory-backend') - api 'org.mongodb:mongo-java-driver:latest.release' + api 'org.mongodb:mongodb-driver-sync:latest.release' api 'org.junit.jupiter:junit-jupiter-api:latest.release' api 'org.junit.jupiter:junit-jupiter-params:latest.release' diff --git a/examples/gradle.lockfile b/examples/gradle.lockfile index ef7f1615d..d18020c3d 100644 --- a/examples/gradle.lockfile +++ b/examples/gradle.lockfile @@ -30,7 +30,10 @@ org.junit.platform:junit-platform-commons:6.1.3=compileClasspath,runtimeClasspat org.junit.platform:junit-platform-engine:6.1.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.1.3=testRuntimeClasspath org.junit:junit-bom:6.1.3=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.mongodb:mongo-java-driver:3.12.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.mongodb:bson-record-codec:5.14.0=runtimeClasspath,testRuntimeClasspath +org.mongodb:bson:5.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.mongodb:mongodb-driver-core:5.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.mongodb:mongodb-driver-sync:5.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.opentest4j:opentest4j:1.3.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.ow2.asm:asm-commons:9.10.1=jacocoAnt org.ow2.asm:asm-tree:9.10.1=jacocoAnt diff --git a/examples/src/main/java/SimpleJUnit5WithModernClientTest.java b/examples/src/main/java/SimpleJUnit5Test.java similarity index 97% rename from examples/src/main/java/SimpleJUnit5WithModernClientTest.java rename to examples/src/main/java/SimpleJUnit5Test.java index ab945f8f7..46ba6fcfa 100644 --- a/examples/src/main/java/SimpleJUnit5WithModernClientTest.java +++ b/examples/src/main/java/SimpleJUnit5Test.java @@ -12,7 +12,7 @@ import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; -class SimpleJUnit5WithModernClientTest { +class SimpleJUnit5Test { private MongoCollection collection; private MongoClient client; diff --git a/examples/src/main/java/SimpleJUnit5WithLegacyClientTest.java b/examples/src/main/java/SimpleJUnit5WithLegacyClientTest.java deleted file mode 100644 index 2c29ec76d..000000000 --- a/examples/src/main/java/SimpleJUnit5WithLegacyClientTest.java +++ /dev/null @@ -1,52 +0,0 @@ -import static org.assertj.core.api.Assertions.assertThat; - -import java.net.InetSocketAddress; - -import org.bson.Document; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import com.mongodb.MongoClient; -import com.mongodb.ServerAddress; -import com.mongodb.client.MongoCollection; - -import de.bwaldvogel.mongo.MongoServer; -import de.bwaldvogel.mongo.backend.memory.MemoryBackend; - -class SimpleJUnit5WithLegacyClientTest { - - private MongoCollection collection; - private MongoClient client; - private MongoServer server; - - @BeforeEach - void setUp() { - server = new MongoServer(new MemoryBackend()); - - // bind on a random local port - InetSocketAddress serverAddress = server.bind(); - - client = new MongoClient(new ServerAddress(serverAddress)); - collection = client.getDatabase("testdb").getCollection("testcollection"); - } - - @AfterEach - void tearDown() { - client.close(); - server.shutdown(); - } - - @Test - void testSimpleInsertQuery() throws Exception { - assertThat(collection.countDocuments()).isZero(); - - // creates the database and collection in memory and insert the object - Document obj = new Document("_id", 1).append("key", "value"); - collection.insertOne(obj); - - assertThat(collection.countDocuments()).isEqualTo(1L); - assertThat(collection.find().first()).isEqualTo(obj); - } - -} diff --git a/gradle.lockfile b/gradle.lockfile index e768052dd..e7b5e78cb 100644 --- a/gradle.lockfile +++ b/gradle.lockfile @@ -41,7 +41,6 @@ org.mockito:mockito-core:5.24.0=aggregateCodeCoverageReportResults org.mockito:mockito-junit-jupiter:5.24.0=aggregateCodeCoverageReportResults org.mongodb:bson-record-codec:5.14.0=aggregateCodeCoverageReportResults org.mongodb:bson:5.14.0=aggregateCodeCoverageReportResults -org.mongodb:mongo-java-driver:3.12.14=aggregateCodeCoverageReportResults org.mongodb:mongodb-driver-core:5.14.0=aggregateCodeCoverageReportResults org.mongodb:mongodb-driver-reactivestreams:5.14.0=aggregateCodeCoverageReportResults org.mongodb:mongodb-driver-sync:5.14.0=aggregateCodeCoverageReportResults From 09e55aebe48a3192ebe2dead33af03fb50a54445 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sun, 15 Nov 2026 15:34:27 +0100 Subject: [PATCH 4/5] Remove obsolete last-error commands and bookkeeping Drop getLastError and resetError, including per-connection error history and synchronized bookkeeping hooks. Assert removed commands directly and check write failures from CRUD responses without querying getLastError. --- core/build.gradle | 1 + core/gradle.lockfile | 2 + .../de/bwaldvogel/mongo/MongoBackend.java | 5 +- .../de/bwaldvogel/mongo/MongoDatabase.java | 5 +- .../java/de/bwaldvogel/mongo/MongoServer.java | 20 +- .../mongo/backend/AbstractMongoBackend.java | 27 +- .../mongo/backend/AbstractMongoDatabase.java | 169 +---------- .../AbstractSynchronizedMongoDatabase.java | 11 - .../de/bwaldvogel/mongo/backend/Command.java | 2 - .../mongo/backend/ReadOnlyProxy.java | 11 +- .../mongo/wire/MongoDatabaseHandler.java | 61 ++-- .../mongo/wire/MongoWireProtocolHandler.java | 14 +- .../mongo/wire/message/ClientRequest.java | 9 +- .../mongo/wire/message/MongoMessage.java | 9 +- .../mongo/wire/message/MongoQuery.java | 5 +- .../mongo/MongoServerShutdownTest.java | 53 ++-- .../backend/AbstractMongoBackendTest.java | 24 +- .../mongo/wire/MongoDatabaseHandlerTest.java | 51 +++- .../wire/MongoWireMessageEncoderTest.java | 2 +- .../postgresql/PostgresqlBackendTest.java | 2 +- .../mongo/backend/AbstractBackendTest.java | 286 ++++++++---------- .../mongo/RealMongoBackendTest.java | 9 - 22 files changed, 284 insertions(+), 494 deletions(-) diff --git a/core/build.gradle b/core/build.gradle index 881f3fe54..fc9c74b0a 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -4,6 +4,7 @@ dependencies { implementation 'io.netty:netty-handler:latest.release' testImplementation 'org.mongodb:bson:latest.release' + testImplementation 'org.awaitility:awaitility:latest.release' testImplementation "org.mockito:mockito-core:latest.release" testImplementation "org.mockito:mockito-junit-jupiter:latest.release" testImplementation "nl.jqno.equalsverifier:equalsverifier:latest.release" diff --git a/core/gradle.lockfile b/core/gradle.lockfile index 7450e0360..98d843577 100644 --- a/core/gradle.lockfile +++ b/core/gradle.lockfile @@ -20,6 +20,8 @@ net.bytebuddy:byte-buddy:1.18.5=testCompileClasspath,testRuntimeClasspath nl.jqno.equalsverifier:equalsverifier:4.5.2=testCompileClasspath,testRuntimeClasspath org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.hamcrest:hamcrest:2.1=testCompileClasspath,testRuntimeClasspath org.jacoco:org.jacoco.agent:0.8.15=jacocoAgent,jacocoAnt org.jacoco:org.jacoco.ant:0.8.15=jacocoAnt org.jacoco:org.jacoco.core:0.8.15=jacocoAnt diff --git a/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java b/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java index ffdf0d038..7076bc859 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java +++ b/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java @@ -9,13 +9,12 @@ import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; -import io.netty.channel.Channel; public interface MongoBackend { - void handleClose(Channel channel); + void handleClose(); - Document handleCommand(Channel channel, String database, DatabaseCommand command, Document query); + Document handleCommand(String database, DatabaseCommand command, Document query); QueryResult handleQuery(MongoQuery query); diff --git a/core/src/main/java/de/bwaldvogel/mongo/MongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/MongoDatabase.java index 62fdaad5f..8f2854ec0 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/MongoDatabase.java +++ b/core/src/main/java/de/bwaldvogel/mongo/MongoDatabase.java @@ -7,15 +7,12 @@ import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.oplog.Oplog; import de.bwaldvogel.mongo.wire.message.MongoQuery; -import io.netty.channel.Channel; public interface MongoDatabase { String getDatabaseName(); - void handleClose(Channel channel); - - Document handleCommand(Channel channel, DatabaseCommand command, Document query, DatabaseResolver databaseResolver, Oplog oplog); + Document handleCommand(DatabaseCommand command, Document query, DatabaseResolver databaseResolver, Oplog oplog); QueryResult handleQuery(MongoQuery query); diff --git a/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java b/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java index fcaec38c7..2c3bf8055 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java +++ b/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java @@ -93,14 +93,7 @@ public void bind(SocketAddress socketAddress, int numberOfBossThreads, int numbe .childHandler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { - if (sslContext != null) { - ch.pipeline().addLast(sslContext.newHandler(ch.alloc())); - } - ch.pipeline().addLast(new MongoWireReplyEncoder()); - ch.pipeline().addLast(new MongoWireMessageEncoder()); - ch.pipeline().addLast(new MongoWireProtocolHandler()); - ch.pipeline().addLast(new MongoDatabaseHandler(backend, channelGroup)); - ch.pipeline().addLast(new MongoExceptionHandler()); + MongoServer.this.initChannel(ch); } }); @@ -113,6 +106,17 @@ public void initChannel(SocketChannel ch) throws Exception { } } + void initChannel(SocketChannel channel) { + if (sslContext != null) { + channel.pipeline().addLast(sslContext.newHandler(channel.alloc())); + } + channel.pipeline().addLast(new MongoWireReplyEncoder()); + channel.pipeline().addLast(new MongoWireMessageEncoder()); + channel.pipeline().addLast(new MongoWireProtocolHandler()); + channel.pipeline().addLast(new MongoDatabaseHandler(backend, channelGroup)); + channel.pipeline().addLast(new MongoExceptionHandler()); + } + /** * Starts and binds the server on a local random port *

diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java index 456847de0..0979c94ea 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java @@ -2,7 +2,6 @@ import java.lang.management.ManagementFactory; import java.net.InetAddress; -import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.time.Clock; import java.time.Duration; @@ -37,7 +36,6 @@ import de.bwaldvogel.mongo.wire.message.Message; import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; -import io.netty.channel.Channel; public abstract class AbstractMongoBackend implements MongoBackend { @@ -161,10 +159,6 @@ private Document handleAdminCommand(DatabaseCommand command, Document query) { yield getLog(argument == null ? null : argument.toString()); } case RENAME_COLLECTION -> handleRenameCollection(command.getQueryValue(), query); - case GET_LAST_ERROR -> { - log.debug("getLastError on admin database"); - yield successResponse(); - } case CONNECTION_STATUS -> handleConnectionStatus(); case HOST_INFO -> handleHostInfo(); case GET_CMD_LINE_OPTS -> handleGetCmdLineOpts(); @@ -307,9 +301,8 @@ private MongoCollection resolveCollection(String namespace) { protected abstract MongoDatabase openOrCreateDatabase(String databaseName); @Override - public Document handleCommand(Channel channel, String databaseName, DatabaseCommand command, Document query) { + public Document handleCommand(String databaseName, DatabaseCommand command, Document query) { return switch (command.getCommand()) { - case WHATS_MY_URI -> handleWhatsMyUri(channel); case IS_MASTER -> handleIsMaster(); case BUILD_INFO -> handleBuildInfo(); case DROP_DATABASE -> handleDropDatabase(databaseName); @@ -322,7 +315,7 @@ public Document handleCommand(Channel channel, String databaseName, DatabaseComm yield handleAdminCommand(command, query); } MongoDatabase mongoDatabase = resolveDatabase(databaseName); - yield mongoDatabase.handleCommand(channel, command, query, this::resolveDatabase, oplog); + yield mongoDatabase.handleCommand(command, query, this::resolveDatabase, oplog); } }; } @@ -343,14 +336,6 @@ public void closeCursors(List cursorIds) { cursorIds.forEach(cursorRegistry::remove); } - private static Document handleWhatsMyUri(Channel channel) { - Document response = new Document(); - InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress(); - response.put("you", remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort()); - Utils.markOkay(response); - return response; - } - private Document handleIsMaster() { Document response = new Document("ismaster", Boolean.TRUE); response.put("maxBsonObjectSize", Integer.valueOf(BsonConstants.MAX_BSON_OBJECT_SIZE)); @@ -422,11 +407,10 @@ protected Document handleDropDatabase(String databaseName) { @Override public Document handleMessage(MongoMessage message) { - Channel channel = message.getChannel(); String databaseName = message.getDatabaseName(); Document query = message.getDocument(); DatabaseCommand command = DatabaseCommand.of(query.keySet().iterator().next()); - return handleCommand(channel, databaseName, command, query); + return handleCommand(databaseName, command, query); } @Override @@ -438,10 +422,7 @@ public void dropDatabase(String databaseName) { } @Override - public void handleClose(Channel channel) { - for (MongoDatabase db : databases.values()) { - db.handleClose(channel); - } + public void handleClose() { } @Override diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java index 710286dac..1bb995e0b 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java @@ -35,7 +35,6 @@ import de.bwaldvogel.mongo.oplog.NoopOplog; import de.bwaldvogel.mongo.oplog.Oplog; import de.bwaldvogel.mongo.wire.message.MongoQuery; -import io.netty.channel.Channel; public abstract class AbstractMongoDatabase

implements MongoDatabase { @@ -51,8 +50,6 @@ public abstract class AbstractMongoDatabase

implements MongoDatabase { protected final AtomicReference> indexes = new AtomicReference<>(); - private final Map> lastResults = new ConcurrentHashMap<>(); - private MongoCollection

namespaces; protected final CursorRegistry cursorRegistry; @@ -94,31 +91,14 @@ public String toString() { return getClass().getSimpleName() + "(" + getDatabaseName() + ")"; } - private Document commandError(Channel channel, DatabaseCommand command, Document query) { - // getlasterror must not clear the last error - if (command.getCommand() == Command.GET_LAST_ERROR) { - return commandGetLastError(channel, command.getQueryValue(), query); - } else if (command.getCommand() == Command.RESET_ERROR) { - return commandResetError(channel); - } - return null; - } - @Override - public Document handleCommand(Channel channel, DatabaseCommand command, Document query, DatabaseResolver databaseResolver, Oplog oplog) { - Document commandErrorDocument = commandError(channel, command, query); - if (commandErrorDocument != null) { - return commandErrorDocument; - } - - clearLastStatus(channel); - + public Document handleCommand(DatabaseCommand command, Document query, DatabaseResolver databaseResolver, Oplog oplog) { final String commandName = command.getQueryValue(); return switch (command.getCommand()) { case FIND -> commandFind(commandName, query); - case INSERT -> commandInsert(channel, commandName, query, oplog); - case UPDATE -> commandUpdate(channel, commandName, query, oplog); - case DELETE -> commandDelete(channel, commandName, query, oplog); + case INSERT -> commandInsert(commandName, query, oplog); + case UPDATE -> commandUpdate(commandName, query, oplog); + case DELETE -> commandDelete(commandName, query, oplog); case CREATE -> commandCreate(commandName, query); case CREATE_INDEXES -> commandCreateIndexes(query, query.get(commandName).toString()); case COUNT -> commandCount(commandName, query); @@ -235,7 +215,7 @@ private Document toCursorResponse(MongoCollection

collection, QueryResult que return Utils.firstBatchCursorResponse(collection.getFullName(), documents, queryResult.getCursorId()); } - private Document commandInsert(Channel channel, String command, Document query, Oplog oplog) { + private Document commandInsert(String command, Document query, Oplog oplog) { String collectionName = query.get(command).toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); log.trace("ordered: {}", isOrdered); @@ -243,7 +223,7 @@ private Document commandInsert(Channel channel, String command, Document query, @SuppressWarnings("unchecked") List documents = (List) query.get("documents"); - List writeErrors = insertDocuments(channel, collectionName, documents, oplog, isOrdered); + List writeErrors = insertDocuments(collectionName, documents, oplog, isOrdered); Document result = new Document(); result.put("n", Integer.valueOf(documents.size())); if (!writeErrors.isEmpty()) { @@ -254,8 +234,7 @@ private Document commandInsert(Channel channel, String command, Document query, return result; } - private Document commandUpdate(Channel channel, String command, Document query, Oplog oplog) { - clearLastStatus(channel); + private Document commandUpdate(String command, Document query, Oplog oplog) { String collectionName = query.get(command).toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); log.trace("ordered: {}", isOrdered); @@ -302,11 +281,10 @@ private Document commandUpdate(Channel channel, String command, Document query, response.put("writeErrors", writeErrors); } Utils.markOkay(response); - putLastResult(channel, response); return response; } - private Document commandDelete(Channel channel, String command, Document query, Oplog oplog) { + private Document commandDelete(String command, Document query, Oplog oplog) { String collectionName = query.get(command).toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); log.trace("ordered: {}", isOrdered); @@ -317,7 +295,7 @@ private Document commandDelete(Channel channel, String command, Document query, for (Document delete : deletes) { final Document selector = (Document) delete.get("q"); final int limit = ((Number) delete.get("limit")).intValue(); - Document result = deleteDocuments(channel, collectionName, selector, limit, oplog); + Document result = deleteDocuments(collectionName, selector, limit, oplog); Integer resultNumber = (Integer) result.get("n"); n += resultNumber.intValue(); } @@ -528,62 +506,6 @@ private Document commandDrop(String command, Document query, Oplog oplog) { return response; } - private Document commandGetLastError(Channel channel, String command, Document query) { - query.forEach((subCommand, value) -> { - if (subCommand.equals(command)) { - return; - } - - switch (subCommand) { - case "w": - // ignore - break; - case "fsync": - // ignore - break; - case "$db": - Assert.equals(value, getDatabaseName()); - break; - default: - throw new MongoServerException("unknown subcommand: " + subCommand); - } - }); - - List results = lastResults.get(channel); - - Document result; - if (results != null && !results.isEmpty()) { - result = results.getLast(); - if (result == null) { - result = new Document(); - } - } else { - result = new Document(); - result.put("err", null); - result.put("n", 0); - } - if (result.containsKey("writeErrors")) { - @SuppressWarnings("unchecked") - List writeErrors = (List) result.get("writeErrors"); - if (writeErrors.size() == 1) { - result.putAll(CollectionUtils.getSingleElement(writeErrors)); - result.remove("writeErrors"); - } - } - Utils.markOkay(result); - return result; - } - - private Document commandResetError(Channel channel) { - List results = lastResults.get(channel); - if (results != null) { - results.clear(); - } - Document result = new Document(); - Utils.markOkay(result); - return result; - } - private Document commandCount(String command, Document query) { MongoCollection

collection = resolveCollection(command, query); Document response = new Document(); @@ -652,7 +574,6 @@ private int getOptionalNumber(Document query, String fieldName, int defaultValue @Override public QueryResult handleQuery(MongoQuery query) { - clearLastStatus(query.getChannel()); String collectionName = query.getCollectionName(); MongoCollection

collection = resolveCollection(collectionName, false); if (collection == null) { @@ -670,16 +591,6 @@ public QueryResult handleQuery(MongoQuery query) { return collection.handleQuery(queryParameters); } - @Override - public void handleClose(Channel channel) { - lastResults.remove(channel); - } - - protected void clearLastStatus(Channel channel) { - List results = lastResults.computeIfAbsent(channel, k -> new LimitedList<>(10)); - results.add(null); - } - private MongoCollection

resolveCollection(String command, Document query) { String collectionName = query.get(command).toString(); return resolveCollection(collectionName, false); @@ -802,8 +713,7 @@ private Index

openOrCreateIdIndex(String collectionName, String indexName, bo protected abstract Index

openOrCreateUniqueIndex(String collectionName, String indexName, List keys, boolean sparse); - private List insertDocuments(Channel channel, String collectionName, List documents, Oplog oplog, boolean isOrdered) { - clearLastStatus(channel); + private List insertDocuments(String collectionName, List documents, Oplog oplog, boolean isOrdered) { try { if (isSystemCollection(collectionName)) { throw new MongoServerError(16459, "attempt to insert in system namespace"); @@ -811,42 +721,19 @@ private List insertDocuments(Channel channel, String collectionName, L MongoCollection

collection = resolveOrCreateCollection(collectionName); List writeErrors = collection.insertDocuments(documents, isOrdered); oplog.handleInsert(collection.getFullName(), documents); - if (!writeErrors.isEmpty()) { - Document writeError = new Document(writeErrors.get(0)); - writeError.put("err", writeError.remove("errmsg")); - putLastResult(channel, writeError); - } else { - Document result = new Document("n", 0); - result.put("err", null); - putLastResult(channel, result); - } return writeErrors; } catch (MongoServerError e) { - putLastError(channel, e); return List.of(toWriteError(0, e)); } } - private Document deleteDocuments(Channel channel, String collectionName, Document selector, int limit, Oplog oplog) { - clearLastStatus(channel); - try { - if (isSystemCollection(collectionName)) { - throw new InvalidNamespaceError(getFullCollectionNamespace(collectionName)); - } - MongoCollection

collection = resolveCollection(collectionName, false); - final int n; - if (collection == null) { - n = 0; - } else { - n = collection.deleteDocuments(selector, limit, oplog); - } - Document result = new Document("n", Integer.valueOf(n)); - putLastResult(channel, result); - return result; - } catch (MongoServerError e) { - putLastError(channel, e); - throw e; + private Document deleteDocuments(String collectionName, Document selector, int limit, Oplog oplog) { + if (isSystemCollection(collectionName)) { + throw new InvalidNamespaceError(getFullCollectionNamespace(collectionName)); } + MongoCollection

collection = resolveCollection(collectionName, false); + int n = collection == null ? 0 : collection.deleteDocuments(selector, limit, oplog); + return new Document("n", Integer.valueOf(n)); } private Document updateDocuments(String collectionName, Document selector, @@ -861,11 +748,6 @@ private Document updateDocuments(String collectionName, Document selector, return collection.updateDocuments(selector, update, arrayFilters, multi, upsert, oplog); } - private void putLastError(Channel channel, MongoServerException ex) { - Document error = toError(channel, ex); - putLastResult(channel, error); - } - private Document toWriteError(int index, MongoServerException e) { Document error = new Document(); error.put("index", index); @@ -877,25 +759,6 @@ private Document toWriteError(int index, MongoServerException e) { return error; } - private Document toError(Channel channel, MongoServerException ex) { - Document error = new Document(); - error.put("err", ex.getMessageWithoutErrorCode()); - if (ex instanceof MongoServerError err) { - error.put("code", Integer.valueOf(err.getCode())); - error.putIfNotNull("codeName", err.getCodeName()); - } - error.put("connectionId", channel.id().asShortText()); - return error; - } - - protected void putLastResult(Channel channel, Document result) { - List results = lastResults.get(channel); - // list must not be empty - Document last = results.getLast(); - Assert.isNull(last, () -> "last result already set: " + last); - results.set(results.size() - 1, result); - } - private MongoCollection

createCollection(String collectionName, CollectionOptions options) { checkCollectionName(collectionName); if (collectionName.contains("$")) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractSynchronizedMongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractSynchronizedMongoDatabase.java index f6398e89e..e0f59ac2d 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractSynchronizedMongoDatabase.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractSynchronizedMongoDatabase.java @@ -2,7 +2,6 @@ import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.bson.Document; -import io.netty.channel.Channel; public abstract class AbstractSynchronizedMongoDatabase

extends AbstractMongoDatabase

{ @@ -15,11 +14,6 @@ protected synchronized MongoCollection

resolveOrCreateCollection(String colle return super.resolveOrCreateCollection(collectionName); } - @Override - protected synchronized void clearLastStatus(Channel channel) { - super.clearLastStatus(channel); - } - @Override public synchronized MongoCollection

resolveCollection(String collectionName, boolean throwIfNotFound) { return super.resolveCollection(collectionName, throwIfNotFound); @@ -37,11 +31,6 @@ protected MongoCollection

getOrCreateIndexesCollection() { } } - @Override - protected synchronized void putLastResult(Channel channel, Document result) { - super.putLastResult(channel, result); - } - @Override protected int countIndexes() { synchronized (indexes) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java index d9c5b186f..18bbd53ca 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java @@ -18,10 +18,8 @@ public enum Command { DELETE("delete"), FIND("find"), FIND_AND_MODIFY("findAndModify"), - GET_LAST_ERROR("getLastError"), // removed in 5.1 GET_MORE("getMore"), INSERT("insert"), - RESET_ERROR("resetError"), UPDATE("update"), // Replication diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java b/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java index 462ac473f..fe42bb0d8 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java @@ -6,7 +6,6 @@ import static de.bwaldvogel.mongo.backend.Command.DB_STATS; import static de.bwaldvogel.mongo.backend.Command.DISTINCT; import static de.bwaldvogel.mongo.backend.Command.FIND; -import static de.bwaldvogel.mongo.backend.Command.GET_LAST_ERROR; import static de.bwaldvogel.mongo.backend.Command.GET_MORE; import static de.bwaldvogel.mongo.backend.Command.IS_MASTER; import static de.bwaldvogel.mongo.backend.Command.LIST_DATABASES; @@ -27,7 +26,6 @@ import de.bwaldvogel.mongo.exception.NoSuchCommandException; import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; -import io.netty.channel.Channel; public class ReadOnlyProxy implements MongoBackend { @@ -41,7 +39,6 @@ public class ReadOnlyProxy implements MongoBackend { COLL_STATS, SERVER_STATUS, BUILD_INFO, - GET_LAST_ERROR, GET_MORE ); @@ -63,14 +60,14 @@ public static class ReadOnlyException extends MongoServerException { } @Override - public void handleClose(Channel channel) { - backend.handleClose(channel); + public void handleClose() { + backend.handleClose(); } @Override - public Document handleCommand(Channel channel, String database, DatabaseCommand command, Document query) { + public Document handleCommand(String database, DatabaseCommand command, Document query) { if (isAllowed(command.getCommand(), query)) { - return backend.handleCommand(channel, database, command, query); + return backend.handleCommand(database, command, query); } throw new NoSuchCommandException(command.getQueryValue()); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandler.java b/core/src/main/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandler.java index 319760163..f8299aff1 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandler.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandler.java @@ -1,5 +1,7 @@ package de.bwaldvogel.mongo.wire; +import java.net.InetSocketAddress; +import java.net.SocketAddress; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -50,17 +52,17 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) throws Exception { log.info("channel {} closed", ctx.channel()); channelGroup.remove(ctx.channel()); - mongoBackend.handleClose(ctx.channel()); + mongoBackend.handleClose(); super.channelInactive(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, ClientRequest object) { if (object instanceof MongoQuery mongoQuery) { - MongoReply mongoReply = handleQuery(mongoQuery); + MongoReply mongoReply = handleQuery(mongoQuery, ctx.channel().remoteAddress()); ctx.channel().writeAndFlush(mongoReply); } else if (object instanceof MongoMessage mongoMessage) { - MongoMessage response = handleMessage(mongoMessage); + MongoMessage response = handleMessage(mongoMessage, ctx.channel().remoteAddress()); if (mongoMessage.isMoreToCome()) { // the client does not read a reply, so sending one would desynchronize the connection log.debug("not replying to {} with moreToCome set", mongoMessage); @@ -73,10 +75,15 @@ protected void channelRead0(ChannelHandlerContext ctx, ClientRequest object) { } // visible for testing - MongoMessage handleMessage(MongoMessage message) { + MongoMessage handleMessage(MongoMessage message, SocketAddress remoteAddress) { Document document = null; try { - document = mongoBackend.handleMessage(message); + String command = message.getDocument().keySet().iterator().next(); + if ("whatsmyuri".equalsIgnoreCase(command)) { + document = handleWhatsMyUri(remoteAddress); + } else { + document = mongoBackend.handleMessage(message); + } } catch (MongoServerException e) { log.error("failed to handle {}", message.getDocument(), e); document = errorResponse(e, Collections.emptyMap()); @@ -85,12 +92,12 @@ MongoMessage handleMessage(MongoMessage message) { MongoServerException e = new MongoServerException("Unknown error: " + ex.getMessage(), ex); document = errorResponse(e, Collections.emptyMap()); } - return new MongoMessage(message.getChannel(), createResponseHeader(message), document); + return new MongoMessage(createResponseHeader(message), document); } - private MongoReply handleQuery(MongoQuery query) { + private MongoReply handleQuery(MongoQuery query, SocketAddress remoteAddress) { if (query.getCollectionName().startsWith("$cmd")) { - Document document = handleCommand(query); + Document document = handleCommand(query, remoteAddress); MessageHeader header = createResponseHeader(query); return new MongoReply(header, @@ -124,7 +131,7 @@ private Document errorResponse(MongoServerException exception, Map ad } // visible for testing - Document handleCommand(MongoQuery query) { + Document handleCommand(MongoQuery query, SocketAddress remoteAddress) { String collectionName = query.getCollectionName(); if ("$cmd.sys.inprog".equals(collectionName)) { @@ -136,24 +143,32 @@ Document handleCommand(MongoQuery query) { if ("$query".equals(command)) { Document actualQuery = (Document) query.getQuery().get("$query"); command = actualQuery.keySet().iterator().next(); - return mongoBackend.handleCommand(query.getChannel(), query.getDatabaseName(), DatabaseCommand.of(command), actualQuery); - } - DatabaseCommand cmd = DatabaseCommand.of(command); - switch (cmd.getCommand()) { - case SERVER_STATUS: - return mongoBackend.getServerStatus(); - - case PING: - Document response = new Document(); - Utils.markOkay(response); - return response; - - default: - return mongoBackend.handleCommand(query.getChannel(), query.getDatabaseName(), cmd, query.getQuery()); + return handleCommand(query.getDatabaseName(), DatabaseCommand.of(command), actualQuery, remoteAddress); } + return handleCommand(query.getDatabaseName(), DatabaseCommand.of(command), query.getQuery(), remoteAddress); } throw new MongoServerException("unknown collection: " + collectionName); } + private Document handleCommand(String databaseName, DatabaseCommand command, Document query, SocketAddress remoteAddress) { + return switch (command.getCommand()) { + case WHATS_MY_URI -> handleWhatsMyUri(remoteAddress); + case SERVER_STATUS -> mongoBackend.getServerStatus(); + case PING -> { + Document response = new Document(); + Utils.markOkay(response); + yield response; + } + default -> mongoBackend.handleCommand(databaseName, command, query); + }; + } + + private static Document handleWhatsMyUri(SocketAddress remoteAddress) { + InetSocketAddress address = (InetSocketAddress) remoteAddress; + Document response = new Document("you", address.getAddress().getHostAddress() + ":" + address.getPort()); + Utils.markOkay(response); + return response; + } + } diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/MongoWireProtocolHandler.java b/core/src/main/java/de/bwaldvogel/mongo/wire/MongoWireProtocolHandler.java index 483d53d3b..330ed8acf 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/MongoWireProtocolHandler.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/MongoWireProtocolHandler.java @@ -19,7 +19,6 @@ import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; import io.netty.buffer.ByteBuf; -import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; @@ -78,15 +77,14 @@ protected ClientRequest decode(ChannelHandlerContext ctx, ByteBuf buf) throws Ex throw new IOException("opCode " + opCodeId + " not supported"); } - final Channel channel = ctx.channel(); final ClientRequest request; switch (opCode) { case OP_QUERY: - request = handleQuery(channel, header, in); + request = handleQuery(header, in); break; case OP_MSG: - request = handleMessage(channel, header, in); + request = handleMessage(header, in); break; default: throw new UnsupportedOperationException("unsupported opcode: " + opCode); @@ -101,7 +99,7 @@ protected ClientRequest decode(ChannelHandlerContext ctx, ByteBuf buf) throws Ex return request; } - private ClientRequest handleQuery(Channel channel, MessageHeader header, ByteBuf buffer) { + private ClientRequest handleQuery(MessageHeader header, ByteBuf buffer) { int flags = buffer.readIntLE(); final String fullCollectionName = BsonDecoder.decodeCString(buffer); @@ -114,7 +112,7 @@ private ClientRequest handleQuery(Channel channel, MessageHeader header, ByteBuf returnFieldSelector = BsonDecoder.decodeBson(buffer); } - MongoQuery mongoQuery = new MongoQuery(channel, header, fullCollectionName, numberToSkip, numberToReturn, + MongoQuery mongoQuery = new MongoQuery(header, fullCollectionName, numberToSkip, numberToReturn, query, returnFieldSelector); if (QueryFlag.SLAVE_OK.isSet(flags)) { @@ -134,7 +132,7 @@ private ClientRequest handleQuery(Channel channel, MessageHeader header, ByteBuf return mongoQuery; } - private ClientRequest handleMessage(Channel channel, MessageHeader header, ByteBuf buffer) { + private ClientRequest handleMessage(MessageHeader header, ByteBuf buffer) { int flagBits = buffer.readIntLE(); Set flags = EnumSet.noneOf(MessageFlag.class); @@ -185,7 +183,7 @@ private ClientRequest handleMessage(Channel channel, MessageHeader header, ByteB Assert.isNull(old); } - return new MongoMessage(channel, header, body, flags); + return new MongoMessage(header, body, flags); } private void decodeKindDocumentSequence(ByteBuf buffer, Document documentSequence) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/message/ClientRequest.java b/core/src/main/java/de/bwaldvogel/mongo/wire/message/ClientRequest.java index 671af6fe5..62775865e 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/message/ClientRequest.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/message/ClientRequest.java @@ -1,24 +1,17 @@ package de.bwaldvogel.mongo.wire.message; import de.bwaldvogel.mongo.backend.Utils; -import io.netty.channel.Channel; public abstract class ClientRequest implements Message { private final MessageHeader header; private final String fullCollectionName; - private final Channel channel; - protected ClientRequest(Channel channel, MessageHeader header, String fullCollectionName) { - this.channel = channel; + protected ClientRequest(MessageHeader header, String fullCollectionName) { this.header = header; this.fullCollectionName = fullCollectionName; } - public Channel getChannel() { - return channel; - } - public MessageHeader getHeader() { return header; } diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoMessage.java b/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoMessage.java index f09e8480c..72ca45018 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoMessage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoMessage.java @@ -3,7 +3,6 @@ import java.util.Set; import de.bwaldvogel.mongo.bson.Document; -import io.netty.channel.Channel; public class MongoMessage extends ClientRequest { @@ -13,12 +12,12 @@ public class MongoMessage extends ClientRequest { private final Document document; private final Set flags; - public MongoMessage(Channel channel, MessageHeader header, Document document) { - this(channel, header, document, Set.of()); + public MongoMessage(MessageHeader header, Document document) { + this(header, document, Set.of()); } - public MongoMessage(Channel channel, MessageHeader header, Document document, Set flags) { - super(channel, header, null); + public MongoMessage(MessageHeader header, Document document, Set flags) { + super(header, null); this.document = document; this.flags = Set.copyOf(flags); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoQuery.java b/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoQuery.java index 3c0d8b29d..a4cdf3fef 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoQuery.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoQuery.java @@ -1,7 +1,6 @@ package de.bwaldvogel.mongo.wire.message; import de.bwaldvogel.mongo.bson.Document; -import io.netty.channel.Channel; public class MongoQuery extends ClientRequest { @@ -10,9 +9,9 @@ public class MongoQuery extends ClientRequest { private final int numberToSkip; private final int numberToReturn; - public MongoQuery(Channel channel, MessageHeader header, String fullCollectionName, int numberToSkip, + public MongoQuery(MessageHeader header, String fullCollectionName, int numberToSkip, int numberToReturn, Document query, Document returnFieldSelector) { - super(channel, header, fullCollectionName); + super(header, fullCollectionName); this.numberToSkip = numberToSkip; this.numberToReturn = numberToReturn; this.query = query; diff --git a/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java b/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java index 01efe5dcb..29d7208e4 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java @@ -1,9 +1,8 @@ package de.bwaldvogel.mongo; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import java.net.InetSocketAddress; @@ -11,12 +10,13 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import java.util.function.BooleanSupplier; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.socket.SocketChannel; import io.netty.util.concurrent.SingleThreadEventExecutor; class MongoServerShutdownTest { @@ -30,14 +30,21 @@ void testShutdownNowAfterClientConnectedDuringShutdown() throws Exception { CountDownLatch secondClientQueued = new CountDownLatch(1); MongoBackend backend = mock(MongoBackend.class); - doAnswer(invocation -> { - if (workerHeld.getCount() > 0) { - holdWorker(invocation.getArgument(0), workerHeld, secondClientQueued); + MongoServer server = new MongoServer(backend) { + @Override + void initChannel(SocketChannel channel) { + super.initChannel(channel); + channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + super.channelInactive(ctx); + if (workerHeld.getCount() > 0) { + holdWorker((SingleThreadEventExecutor) ctx.executor(), workerHeld, secondClientQueued); + } + } + }); } - return null; - }).when(backend).handleClose(any()); - - MongoServer server = new MongoServer(backend); + }; try { // a single worker thread, so that the second client is registered only after the first client's close server.bind(new InetSocketAddress("localhost", 0), 1, 1); @@ -64,28 +71,14 @@ void testShutdownNowAfterClientConnectedDuringShutdown() throws Exception { * Keeps the only worker thread in the first client's close until the second client's registration is queued * behind it and the server has started to shut down. */ - private static void holdWorker(Channel channel, CountDownLatch workerHeld, CountDownLatch secondClientQueued) { - SingleThreadEventExecutor worker = (SingleThreadEventExecutor) channel.eventLoop(); + private static void holdWorker(SingleThreadEventExecutor worker, CountDownLatch workerHeld, CountDownLatch secondClientQueued) { int pendingTasks = worker.pendingTasks(); workerHeld.countDown(); - awaitCondition(() -> worker.pendingTasks() > pendingTasks); + await().pollInSameThread().pollDelay(Duration.ZERO).pollInterval(Duration.ofMillis(1)) + .atMost(Duration.ofSeconds(TIMEOUT_SECONDS)).until(() -> worker.pendingTasks() > pendingTasks); secondClientQueued.countDown(); - awaitCondition(worker::isShuttingDown); - } - - private static void awaitCondition(BooleanSupplier condition) { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); - while (!condition.getAsBoolean()) { - if (System.nanoTime() > deadline) { - throw new IllegalStateException("Condition not met within " + TIMEOUT_SECONDS + " seconds"); - } - try { - Thread.sleep(1); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(e); - } - } + await().pollInSameThread().pollDelay(Duration.ZERO).pollInterval(Duration.ofMillis(1)) + .atMost(Duration.ofSeconds(TIMEOUT_SECONDS)).until(worker::isShuttingDown); } } diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoBackendTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoBackendTest.java index f0bea93da..c74b2bd3f 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoBackendTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoBackendTest.java @@ -5,8 +5,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import java.net.InetSocketAddress; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -14,7 +12,6 @@ import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.bson.Document; -import io.netty.channel.Channel; class AbstractMongoBackendTest { @@ -33,7 +30,7 @@ protected MongoDatabase openOrCreateDatabase(String databaseName) { Utils.markOkay(fakeResponse); fakeResponse.put("message", "fakeResponse"); - when(mockDatabase.handleCommand(any(), any(), any(), any(), any())).thenReturn(fakeResponse); + when(mockDatabase.handleCommand(any(), any(), any(), any())).thenReturn(fakeResponse); return mockDatabase; } @@ -53,31 +50,16 @@ public void dropDatabase(String database) { }; } - @Test - void testHandleCommand() { - Channel channel = Mockito.mock(Channel.class); - when(channel.remoteAddress()).thenReturn(new InetSocketAddress("127.0.1.254", 27017)); - - Document response = backend.handleCommand(channel, null, DatabaseCommand.of(Command.WHATS_MY_URI), null); - assertThat(response).isNotNull(); - assertThat(response.get("ok")).isEqualTo(1.0); - assertThat(response.get("you")).isEqualTo("127.0.1.254:27017"); - } - @Test void testHandleAdminCommand() { - Channel channel = Mockito.mock(Channel.class); - - Document response = backend.handleCommand(channel, ADMIN_DB_NAME, DatabaseCommand.of(Command.PING), null); + Document response = backend.handleCommand(ADMIN_DB_NAME, DatabaseCommand.of(Command.PING), null); assertThat(response).isNotNull(); assertThat(response.get("ok")).isEqualTo(1.0); } @Test void testMongoDatabaseHandleCommand() { - Channel channel = Mockito.mock(Channel.class); - - Document response = backend.handleCommand(channel, "mockDatabase", DatabaseCommand.of(Command.FIND), null); + Document response = backend.handleCommand("mockDatabase", DatabaseCommand.of(Command.FIND), null); assertThat(response).isNotNull(); assertThat(response.get("ok")).isEqualTo(1.0); assertThat(response.get("message")).isEqualTo("fakeResponse"); diff --git a/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java index f633b8b4b..84bea7b1b 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java @@ -8,6 +8,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.net.InetSocketAddress; +import java.util.List; import java.util.Set; import de.bwaldvogel.mongo.backend.Command; @@ -30,32 +32,30 @@ class MongoDatabaseHandlerTest { @Test void testWrappedCommand() throws Exception { MongoBackend backend = mock(MongoBackend.class); - Channel channel = mock(Channel.class); Document queryDoc = json("'$query': { 'count': 'collectionName' }, '$readPreference': { 'mode': 'secondaryPreferred' }"); Document subQueryDoc = json("'count': 'collectionName'"); - MongoQuery query = new MongoQuery(channel, null, "dbName.$cmd", 0, 0, queryDoc, null); + MongoQuery query = new MongoQuery(null, "dbName.$cmd", 0, 0, queryDoc, null); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); - handler.handleCommand(query); + handler.handleCommand(query, null); - verify(backend).handleCommand(channel, "dbName", DatabaseCommand.of(Command.COUNT), subQueryDoc); + verify(backend).handleCommand("dbName", DatabaseCommand.of(Command.COUNT), subQueryDoc); } @Test void testNonWrappedCommand() throws Exception { MongoBackend backend = mock(MongoBackend.class); - Channel channel = mock(Channel.class); Document queryDoc = json("'count': 'collectionName'"); - MongoQuery query = new MongoQuery(channel, null, "dbName.$cmd", 0, 0, queryDoc, null); + MongoQuery query = new MongoQuery(null, "dbName.$cmd", 0, 0, queryDoc, null); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); - handler.handleCommand(query); + handler.handleCommand(query, null); - verify(backend).handleCommand(channel, "dbName", DatabaseCommand.of(Command.COUNT), queryDoc); + verify(backend).handleCommand("dbName", DatabaseCommand.of(Command.COUNT), queryDoc); } @Test @@ -63,15 +63,13 @@ void testHandleMessageUnknownError() throws Exception { MongoBackend backend = mock(MongoBackend.class); when(backend.handleMessage(any())).thenThrow(new RuntimeException("unexpected")); - Channel channel = mock(Channel.class); - MessageHeader header = new MessageHeader(0, 0); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); - MongoMessage requestMessage = new MongoMessage(channel, header, new Document("key", "1")); + MongoMessage requestMessage = new MongoMessage(header, new Document("key", "1")); - MongoMessage responseMessage = handler.handleMessage(requestMessage); + MongoMessage responseMessage = handler.handleMessage(requestMessage, null); assertThat(responseMessage).isNotNull(); Document responseMessageDoc = responseMessage.getDocument(); @@ -89,7 +87,7 @@ void testMessageWithMoreToComeIsHandledWithoutReply() throws Exception { when(ctx.channel()).thenReturn(channel); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); - MongoMessage requestMessage = new MongoMessage(channel, new MessageHeader(0, 0), json("insert: 'coll'"), + MongoMessage requestMessage = new MongoMessage(new MessageHeader(0, 0), json("insert: 'coll'"), Set.of(MessageFlag.MORE_TO_COME)); handler.channelRead0(ctx, requestMessage); @@ -106,11 +104,36 @@ void testMessageWithoutMoreToComeIsReplied() throws Exception { when(ctx.channel()).thenReturn(channel); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); - MongoMessage requestMessage = new MongoMessage(channel, new MessageHeader(0, 0), json("insert: 'coll'")); + MongoMessage requestMessage = new MongoMessage(new MessageHeader(0, 0), json("insert: 'coll'")); handler.channelRead0(ctx, requestMessage); verify(channel).writeAndFlush(any(MongoMessage.class)); } + @Test + void testWhatsMyUriMessage() { + MongoBackend backend = mock(MongoBackend.class); + MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); + MongoMessage request = new MongoMessage(new MessageHeader(1, 0), json("whatsmyuri: 1, $db: 'admin'")); + + MongoMessage response = handler.handleMessage(request, new InetSocketAddress("127.0.1.254", 27017)); + + assertThat(response.getDocument()).isEqualTo(json("you: '127.0.1.254:27017', ok: 1.0")); + verify(backend, never()).handleMessage(any()); + } + + @Test + void testWhatsMyUriQuery() { + MongoBackend backend = mock(MongoBackend.class); + MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); + for (Document document : List.of(json("whatsmyuri: 1"), json("$query: {whatsmyuri: 1}"))) { + MongoQuery query = new MongoQuery(null, "admin.$cmd", 0, 0, document, null); + + Document response = handler.handleCommand(query, new InetSocketAddress("127.0.1.254", 27017)); + + assertThat(response).isEqualTo(json("you: '127.0.1.254:27017', ok: 1.0")); + } + } + } diff --git a/core/src/test/java/de/bwaldvogel/mongo/wire/MongoWireMessageEncoderTest.java b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoWireMessageEncoderTest.java index ffcbb7b66..3f217c74e 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/wire/MongoWireMessageEncoderTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoWireMessageEncoderTest.java @@ -37,7 +37,7 @@ void testExceptionHandling() throws Exception { MongoWireMessageEncoder mongoWireEncoder = new MongoWireMessageEncoder(); MessageHeader header = new MessageHeader(0, 0); - MongoMessage reply = new MongoMessage(channel, header, new Document("key", Missing.getInstance())); + MongoMessage reply = new MongoMessage(header, new Document("key", Missing.getInstance())); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> mongoWireEncoder.encode(ctx, reply, Unpooled.buffer())) diff --git a/postgresql-backend/src/test/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlBackendTest.java b/postgresql-backend/src/test/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlBackendTest.java index 970f38a14..083d15071 100644 --- a/postgresql-backend/src/test/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlBackendTest.java +++ b/postgresql-backend/src/test/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlBackendTest.java @@ -390,7 +390,7 @@ void testUuidDuplicate() { collection.insertOne(document1); assertMongoWriteException(() -> collection.insertOne(document1), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index:" + + 11000, "E11000 duplicate key error collection: testdb.testcoll index:" + " ERROR: duplicate key value violates unique constraint \"testcoll__id_\"\n" + " Detail: Key ((data ->> '_id'::text))=([\"java.util.UUID\",\"5542cbb9-7833-96a2-b456-f13b6ae1bc80\"]) already exists."); diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java index ad401b122..2862add9e 100755 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java @@ -349,7 +349,7 @@ void testCreateCollectionAlreadyExists() { void testUnsupportedModifier() { collection.insertOne(json("")); assertMongoWriteException(() -> collection.updateOne(json(""), json("$foo: {}")), - 9, "FailedToParse", "Unknown modifier: $foo. Expected a valid update modifier or pipeline-style update specified as an array"); + 9, "Unknown modifier: $foo. Expected a valid update modifier or pipeline-style update specified as an array"); } @Test @@ -599,7 +599,7 @@ void testDropAndRecreateIndex() { .withMessageStartingWith("Command execution failed on MongoDB server with error 27 (IndexNotFound): 'can't find index with key: { n: 1 }'"); assertMongoWriteException(() -> collection.insertOne(json("_id: 2, c: 10")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: c_1 dup key: { c: 10 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: c_1 dup key: { c: 10 }"); collection.dropIndex(new Document("c", 1)); @@ -1076,11 +1076,11 @@ public void testUuidAsId() { collection.insertOne(new Document("_id", new UUID(999999, 128))); assertMongoWriteException(() -> collection.insertOne(new Document("_id", new UUID(0, 1))), - 11000, "DuplicateKey", + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: UUID(\"00000000-0000-0000-0000-000000000001\") }"); assertMongoWriteException(() -> collection.insertOne(new Document("_id", new UUID(999999, 128))), - 11000, "DuplicateKey", + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: UUID(\"00000000-000f-423f-0000-000000000080\") }"); collection.deleteOne(new Document("_id", new UUID(0, 2))); @@ -1962,7 +1962,7 @@ void testNullId() { assertThat(result.getObjectId(Constants.ID_FIELD)).isNull(); assertMongoWriteException(() -> collection.insertOne(json("_id: null")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: null }"); assertThat(collection.countDocuments()).isEqualTo(1); assertThat(collection.find(json("_id: null")).first()).isEqualTo(json("_id: null, name: 'test'")); @@ -2028,12 +2028,12 @@ void testIdNotAllowedToBeUpdated() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.replaceOne(json("_id: 1"), json("_id: 2, a: 4")), - 66, "ImmutableField", "After applying the update, the (immutable) field '_id' was found to have been altered to _id: 2"); + 66, "After applying the update, the (immutable) field '_id' was found to have been altered to _id: 2"); // test with $set assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), new Document("$set", json("_id: 2"))), - 66, "ImmutableField", "Performing an update on the path '_id' would modify the immutable field '_id'"); + 66, "Performing an update on the path '_id' would modify the immutable field '_id'"); } @Test @@ -2077,7 +2077,7 @@ void testInsertDuplicate() { assertThat(collection.countDocuments()).isEqualTo(1); assertMongoWriteException(() -> collection.insertOne(json("_id: 1.0")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1.0 }"); assertThat(collection.countDocuments()).isEqualTo(1); } @@ -2087,7 +2087,7 @@ void testInsertDuplicateThrows() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.insertOne(json("_id: 1")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1 }"); } @Test @@ -2095,7 +2095,7 @@ void testInsertDuplicateWithConcernThrows() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.withWriteConcern(WriteConcern.ACKNOWLEDGED).insertOne(json("_id: 1")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1 }"); } @ParameterizedTest @@ -2740,14 +2740,14 @@ void testUpdateBlank() { void testUpdateEmptyPositional() { collection.insertOne(json("")); assertMongoWriteException(() -> collection.updateOne(json(""), json("$set: {'a.$.b': 1}")), - 2, "BadValue", "The positional operator did not find the match needed from the query."); + 2, "The positional operator did not find the match needed from the query."); } @Test void testUpdateMultiplePositional() { collection.insertOne(json("a: {b: {c: 1}}")); assertMongoWriteException(() -> collection.updateOne(json("'a.b.c': 1"), json("$set: {'a.$.b.$.c': 1}")), - 2, "BadValue", "Too many positional (i.e. '$') elements found in path 'a.$.b.$.c'"); + 2, "Too many positional (i.e. '$') elements found in path 'a.$.b.$.c'"); } @Test @@ -2759,18 +2759,18 @@ void testUpdateIllegalFieldName() { collection.updateOne(json("x: 1"), json("$set: {y: 1}")); // ok assertMongoWriteException(() -> collection.updateOne(json("x: 1"), json("$set: {$z: 1}")), - 52, "DollarPrefixedFieldName", "The dollar ($) prefixed field '$z' in '$z' is not allowed in the context of an update's replacement document. " + + 52, "The dollar ($) prefixed field '$z' in '$z' is not allowed in the context of an update's replacement document. " + "Consider using an aggregation pipeline with $replaceWith."); // unset ok to remove bad fields collection.updateOne(json("x: 1"), json("$unset: {$z: 1}")); assertMongoWriteException(() -> collection.updateOne(json("x: 1"), json("$inc: {$z: 1}")), - 52, "DollarPrefixedFieldName", "The dollar ($) prefixed field '$z' in '$z' is not allowed in the context of an update's replacement document. " + + 52, "The dollar ($) prefixed field '$z' in '$z' is not allowed in the context of an update's replacement document. " + "Consider using an aggregation pipeline with $replaceWith."); assertMongoWriteException(() -> collection.updateOne(json("x: 1"), json("$push: {$z: [1, 2, 3]}")), - 52, "DollarPrefixedFieldName", "The dollar ($) prefixed field '$z' in '$z' is not allowed in the context of an update's replacement document. " + + 52, "The dollar ($) prefixed field '$z' in '$z' is not allowed in the context of an update's replacement document. " + "Consider using an aggregation pipeline with $replaceWith."); } @@ -2820,7 +2820,7 @@ void testUpdatePush() { // push to non-array collection.updateOne(idObj, json("$set: {field: 'value'}")); assertMongoWriteException(() -> collection.updateOne(idObj, json("$push: {field: 'value'}")), - 2, "BadValue", "The field 'field' must be an array but is of type string in document {_id: 1}"); + 2, "The field 'field' must be an array but is of type string in document {_id: 1}"); // push with multiple fields @@ -2942,7 +2942,7 @@ void testUpdatePushEach_unknownModifier() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$push: {value: {$each: [1, 2, 3], $illegal: 1}}")), - 2, "BadValue", "Unrecognized clause in $push: $illegal"); + 2, "Unrecognized clause in $push: $illegal"); } @Test @@ -2950,13 +2950,13 @@ void testUpdatePushEach_illegalOptions() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.updateOne(json(""), json("$push: {value: {$each: [1, 2, 3], $slice: 'abc'}}")), - 2, "BadValue", "The value for $slice must be an integer value but was given type: string"); + 2, "The value for $slice must be an integer value but was given type: string"); assertMongoWriteException(() -> collection.updateOne(json(""), json("$push: {value: {$each: [1, 2, 3], $sort: 'abc'}}")), - 2, "BadValue", "The $sort is invalid: use 1/-1 to sort the whole element, or {field:1/-1} to sort embedded fields"); + 2, "The $sort is invalid: use 1/-1 to sort the whole element, or {field:1/-1} to sort embedded fields"); assertMongoWriteException(() -> collection.updateOne(json(""), json("$push: {value: {$each: [1, 2, 3], $position: 'abc'}}")), - 2, "BadValue", "The value for $position must be an integer value, not of type: string"); + 2, "The value for $position must be an integer value, not of type: string"); } @Test @@ -2964,7 +2964,7 @@ void testUpdatePushAll() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.updateOne(json(""), json("$pushAll: {field: 'value'}")), - 9, "FailedToParse", "Unknown modifier: $pushAll. Expected a valid update modifier or pipeline-style update specified as an array"); + 9, "Unknown modifier: $pushAll. Expected a valid update modifier or pipeline-style update specified as an array"); } @Test @@ -3020,10 +3020,10 @@ void testUpdateAddToSetEach_unknownModifier() { collection.insertOne(json("_id: 1")); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$addToSet: {value: {$each: [1, 2, 3], $slice: 2}}")), - 2, "BadValue", "Found unexpected fields after $each in $addToSet: { $each: [ 1, 2, 3 ], $slice: 2 }"); + 2, "Found unexpected fields after $each in $addToSet: { $each: [ 1, 2, 3 ], $slice: 2 }"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$addToSet: {value: {$each: [1, 2, 3], value: 2}}")), - 2, "BadValue", "Found unexpected fields after $each in $addToSet: { $each: [ 1, 2, 3 ], value: 2 }"); + 2, "Found unexpected fields after $each in $addToSet: { $each: [ 1, 2, 3 ], value: 2 }"); collection.updateOne(json("_id: 1"), json("$addToSet: {value: {key: 2, $each: [1, 2, 3]}}")); @@ -3072,7 +3072,7 @@ void testUpdatePull() { collection.updateOne(obj, set("field", "value")); assertMongoWriteException(() -> collection.updateOne(obj, pull("field", "value")), - 2, "BadValue", "Cannot apply $pull to a non-array value"); + 2, "Cannot apply $pull to a non-array value"); // pull standard collection.updateOne(obj, json("$set: {field: ['value1', 'value2', 'value1']}")); @@ -3128,7 +3128,7 @@ void testUpdatePullAll() { collection.insertOne(obj); collection.updateOne(obj, json("$set: {field: 'value'}")); assertMongoWriteException(() -> collection.updateOne(obj, json("$pullAll: {field: 'value'}")), - 2, "BadValue", "$pullAll requires an array argument but was given a string"); + 2, "$pullAll requires an array argument but was given a string"); collection.updateOne(obj, json("$set: {field1: ['value1', 'value2', 'value1', 'value3', 'value4', 'value3']}")); @@ -3137,7 +3137,7 @@ void testUpdatePullAll() { assertThat(collection.find(obj).first().get("field1")).isEqualTo(List.of("value2", "value4")); assertMongoWriteException(() -> collection.updateOne(obj, json("$pullAll: {field1: 'bar'}")), - 2, "BadValue", "$pullAll requires an array argument but was given a string"); + 2, "$pullAll requires an array argument but was given a string"); } @Test @@ -3168,7 +3168,7 @@ void testUpdateSet() { assertThat(collection.find(object).first()).isEqualTo(expected); assertMongoWriteException(() -> collection.updateOne(object, json("$set: {'foo.bar': 'bla'}")), - 28, "PathNotViable", "Cannot create field 'bar' in element {foo: \"bar\"}"); + 28, "Cannot create field 'bar' in element {foo: \"bar\"}"); assertThat(collection.find(object).first()).isEqualTo(expected); collection.updateOne(object, json("$set: {'other.foo': '123'}")); @@ -3201,7 +3201,7 @@ void testUpdateSet_arrayOfDocuments() { collection.insertOne(json("_id: 1, foo: [{bar: 1}, {bar: 2}]")); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$set: {'foo.bar': 3}")), - 28, "PathNotViable", "Cannot create field 'bar' in element {foo: [ { bar: 1 }, { bar: 2 } ]}"); + 28, "Cannot create field 'bar' in element {foo: [ { bar: 1 }, { bar: 2 } ]}"); } @Test @@ -3433,13 +3433,13 @@ void testUpdatePop() { assertThat(collection.find(object).first()).isEqualTo(json("_id: 1, foo: {bar: [2]}")); assertMongoWriteException(() -> collection.updateOne(object, json("$pop: {'foo.bar': null}")), - 9, "FailedToParse", "Expected a number in: foo.bar: null"); + 9, "Expected a number in: foo.bar: null"); assertMongoWriteException(() -> collection.updateOne(object, json("$pop: {'foo.bar': 'x'}")), - 9, "FailedToParse", "Expected a number in: foo.bar: \"x\""); + 9, "Expected a number in: foo.bar: \"x\""); assertMongoWriteException(() -> collection.updateOne(object, json("$pop: {'foo.bar': 2}")), - 9, "FailedToParse", "$pop expects 1 or -1, found: 2"); + 9, "$pop expects 1 or -1, found: 2"); } @Test @@ -3447,7 +3447,7 @@ void testUpdateUnset() { Document obj = json("_id: 1, a: 1, b: null, c: 'value'"); collection.insertOne(obj); assertMongoWriteException(() -> collection.updateOne(obj, json("$unset: {_id: ''}")), - 66, "ImmutableField", "Performing an update on the path '_id' would modify the immutable field '_id'"); + 66, "Performing an update on the path '_id' would modify the immutable field '_id'"); collection.updateOne(json("_id: 1"), json("$unset: {'a.b.z': 1}")); assertThat(collection.find().first()).isEqualTo(json("_id: 1, a: 1, b: null, c: 'value'")); @@ -3497,7 +3497,7 @@ void testUpdateIllegalInt() { collection.insertOne(json("_id: 1, a: {x: 1}")); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$inc: {a: 1}")), - 14, "TypeMismatch", "Cannot apply $inc to a value of non-numeric type. {_id: 1} has the field 'a' of non-numeric type object"); + 14, "Cannot apply $inc to a value of non-numeric type. {_id: 1} has the field 'a' of non-numeric type object"); assertThatExceptionOfType(MongoServerException.class) .isThrownBy(() -> collection.updateOne(json("_id: 1"), json("$inc: {'a.x': 'b'}"))) @@ -3757,7 +3757,7 @@ void testUpsertWithId_duplicateKey() { Document update = json("$set: { _id: 'someid', somekey: 'some value' }"); assertMongoWriteException(() -> collection.updateOne(query, update, new UpdateOptions().upsert(true)), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: \"someid\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: \"someid\" }"); } // https://github.com/bwaldvogel/mongo-java-server/issues/93 @@ -3777,7 +3777,7 @@ void testReplaceOneWithId() { ); assertMongoWriteException(() -> collection.replaceOne(json("value: 'z'"), json("_id: 2, value: 'z'"), new ReplaceOptions().upsert(true)), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 2 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 2 }"); } // https://github.com/bwaldvogel/mongo-java-server/issues/154 @@ -3885,13 +3885,13 @@ void testUpdateWithIllegalMultiplyFails() { collection.insertOne(object); assertMongoWriteException(() -> collection.updateOne(object, json("$mul: {_id: 2}")), - 66, "ImmutableField", "Performing an update on the path '_id' would modify the immutable field '_id'"); + 66, "Performing an update on the path '_id' would modify the immutable field '_id'"); assertMongoWriteException(() -> collection.updateOne(object, json("$mul: {foo: 2}")), - 14, "TypeMismatch", "Cannot apply $mul to a value of non-numeric type. {_id: 1} has the field 'foo' of non-numeric type string"); + 14, "Cannot apply $mul to a value of non-numeric type. {_id: 1} has the field 'foo' of non-numeric type string"); assertMongoWriteException(() -> collection.updateOne(object, json("$mul: {bar: 'x'}")), - 14, "TypeMismatch", "Cannot multiply with non-numeric argument: {bar: \"x\"}"); + 14, "Cannot multiply with non-numeric argument: {bar: \"x\"}"); } @Test @@ -3937,7 +3937,7 @@ void testFindWithNullOrNoFieldFilter() { @Test void testInsertWithIllegalId() { assertMongoWriteException(() -> collection.insertOne(json("_id: [1, 2, 3]")), - 53, "InvalidIdField", "The '_id' value cannot be of type array"); + 53, "The '_id' value cannot be of type array"); } @Test @@ -3949,13 +3949,13 @@ void testInsertsWithUniqueIndex() { collection.insertOne(json("uniqueKeyField: 'abc3', afield: 'avalue'")); assertMongoWriteException(() -> collection.insertOne(json("uniqueKeyField: 'abc2', afield: 'avalue'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: uniqueKeyField_1 dup key: { uniqueKeyField: \"abc2\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: uniqueKeyField_1 dup key: { uniqueKeyField: \"abc2\" }"); collection.insertOne(json("uniqueKeyField: 1")); collection.insertOne(json("uniqueKeyField: 1.1")); assertMongoWriteException(() -> collection.insertOne(json("uniqueKeyField: 1.0")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: uniqueKeyField_1 dup key: { uniqueKeyField: 1.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: uniqueKeyField_1 dup key: { uniqueKeyField: 1.0 }"); } @Test @@ -3974,7 +3974,7 @@ void testUniqueIndexWithSubdocument() { collection.insertOne(json("_id: 4, action: {actionId: 3}")); assertMongoWriteException(() -> collection.insertOne(json("action: {actionId: 1.0}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: action.actionId_1 dup key: { action.actionId: 1.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: action.actionId_1 dup key: { action.actionId: 1.0 }"); assertThat(collection.find(json("action: 'abc1'"))) .containsExactly(json("_id: 1, action: 'abc1'")); @@ -4003,19 +4003,19 @@ public void testUniqueIndexWithDeepDocuments() { collection.insertOne(json("_id: 9, a: {c: 1}")); assertMongoWriteException(() -> collection.insertOne(json("a: {b: 0}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: 0 } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: 0 } }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: 0.00}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: 0.0 } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: 0.0 } }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: -0.0}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: -0.0 } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: -0.0 } }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 1.0}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: { c: 1.0 } } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: { c: 1.0 } } }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 1, d: 1.0}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: { c: 1, d: 1.0 } } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: { b: { c: 1, d: 1.0 } } }"); } // see https://github.com/bwaldvogel/mongo-java-server/issues/39 @@ -4028,16 +4028,16 @@ void testSecondaryUniqueIndexUpdate() { collection.insertOne(json("_id: 3")); assertMongoWriteException(() -> collection.insertOne(json("_id: 4")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), new Document("$set", json("text: 'def'"))), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: \"def\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: \"def\" }"); collection.updateOne(json("_id: 1"), new Document("$set", json("text: 'xyz'"))); collection.updateOne(json("_id: 2"), new Document("$set", json("text: 'abc'"))); assertMongoWriteException(() -> collection.updateOne(json("_id: 2"), new Document("$set", json("text: null"))), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); collection.deleteOne(json("text: 'xyz'")); @@ -4060,13 +4060,13 @@ public void testSecondarySparseUniqueIndex() { collection.insertOne(json("_id: 5, text: null")); assertMongoWriteException(() -> collection.insertOne(json("_id: 6, text: null")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); assertMongoWriteException(() -> collection.insertOne(json("_id: 7, text: 'abc'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: \"abc\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: \"abc\" }"); assertMongoWriteException(() -> collection.updateOne(json("_id: 2"), new Document("$set", json("text: null"))), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: text_1 dup key: { text: null }"); collection.deleteOne(json("_id: 5")); @@ -4091,10 +4091,10 @@ public void testCompoundSparseUniqueIndex() { collection.insertOne(json("_id: 6, a: null")); assertMongoWriteException(() -> collection.insertOne(json("_id: 7, a: null")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: null, b: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: null, b: null }"); assertMongoWriteException(() -> collection.insertOne(json("_id: 7, b: null")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: null, b: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: null, b: null }"); collection.deleteMany(json("a: null, b: null")); @@ -4121,10 +4121,10 @@ public void testCompoundSparseUniqueIndexOnEmbeddedDocuments() { collection.insertOne(json("_id: 9")); assertMongoWriteException(() -> collection.insertOne(json("_id: 10, a: {x: 1.0}, b: {x: 2.0}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.x_1_b.x_1 dup key: { a.x: 1.0, b.x: 2.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.x_1_b.x_1 dup key: { a.x: 1.0, b.x: 2.0 }"); assertMongoWriteException(() -> collection.insertOne(json("_id: 11, a: {x: null}, b: {x: null}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.x_1_b.x_1 dup key: { a.x: null, b.x: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.x_1_b.x_1 dup key: { a.x: null, b.x: null }"); collection.deleteMany(json("a: {x: null}, b: {x: null}")); collection.deleteMany(json("a: 10")); @@ -4152,7 +4152,7 @@ void testUpdateWithSparseUniqueIndex() { collection.updateOne(json("_id: 2"), json("$set: {a: 'y'}")); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$set: {a: 'y'}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"y\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"y\" }"); collection.updateOne(json("_id: 2"), json("$unset: {a: 1}")); collection.updateOne(json("_id: 1"), json("$set: {a: 'y'}")); @@ -4177,19 +4177,19 @@ public void testSparseUniqueIndexOnEmbeddedDocument() { collection.insertOne(json("a: {b: {c: {d: null}}}")); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 1}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: null}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: null }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 1, x: 100}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: {d: 1}}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: { d: 1 } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: { d: 1 } }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: {d: null}}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: { d: null } }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: { d: null } }"); } // https://github.com/bwaldvogel/mongo-java-server/issues/201 @@ -4203,7 +4203,7 @@ public void testUniqueIndexOnArrayField() { collection.insertOne(json("_id: 4, a: ['val5']")); assertMongoWriteException(() -> collection.insertOne(json("a: ['val1']")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"val1\" }'"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"val1\" }'"); assertThat(collection.find(json("a: ['val1']"))) .isEmpty(); @@ -4241,10 +4241,10 @@ public void testUniqueIndexOnArrayField_updates() { collection.insertOne(json("_id: 2, a: ['val3', 'val4']")); assertMongoWriteException(() -> collection.replaceOne(json("_id: 1"), json("_id: 1, a: ['val1', 'val3']")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"val3\" }'"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"val3\" }'"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$push: {a: 'val3'}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"val3\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: \"val3\" }"); collection.replaceOne(json("_id: 1"), json("_id: 1, a: ['val1', 'val5']")); collection.insertOne(json("_id: 3, a: ['val2']")); @@ -4271,7 +4271,7 @@ public void testUniqueIndexOnArrayFieldInSubdocument() { collection.insertOne(json("_id: 4, a: {b: 'val5'}")); assertMongoWriteException(() -> collection.insertOne(json("a: {b: ['val1']}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b_1 dup key: { a.b: \"val1\" }'"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b_1 dup key: { a.b: \"val1\" }'"); assertThat(collection.find(json("'a.b': 'val5'"))) .containsExactly(json("_id: 4, a: {b: 'val5'}")); @@ -4352,13 +4352,13 @@ void testCompoundUniqueIndices() { collection.insertOne(json("_id: 8, a: {x: 1, y: 2}, b: 'foo'")); assertMongoWriteException(() -> collection.insertOne(json("a: 'foo', b: 'foo'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: \"foo\", b: \"foo\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: \"foo\", b: \"foo\" }"); assertMongoWriteException(() -> collection.insertOne(json("b: 'foo'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: null, b: \"foo\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: null, b: \"foo\" }"); assertMongoWriteException(() -> collection.insertOne(json("a: {x: 1, y: 1}, b: 'foo'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: { x: 1, y: 1 }, b: \"foo\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: { x: 1, y: 1 }, b: \"foo\" }"); assertThat(collection.find(json("a: 'bar'"))) .containsExactly(json("_id: 6, a: 'bar', b: 'foo'")); @@ -4384,7 +4384,7 @@ void testCompoundUniqueIndices_Subdocument() { collection.insertOne(json("_id: 4, a: 'bar', b: {c: 2}")); assertMongoWriteException(() -> collection.insertOne(json("a: 'bar', b: {c: 1}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b.c_1 dup key: { a: \"bar\", b.c: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b.c_1 dup key: { a: \"bar\", b.c: 1 }"); } // https://github.com/bwaldvogel/mongo-java-server/issues/80 @@ -4412,7 +4412,7 @@ void testAddUniqueIndexOnExistingDocuments() { collection.createIndex(json("value: 1"), new IndexOptions().unique(true)); assertMongoWriteException(() -> collection.insertOne(json("value: 'c'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: \"c\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: \"c\" }"); collection.insertOne(json("_id: 4, value: 'd'")); } @@ -4536,16 +4536,16 @@ void testUpdateCurrentDateIllegalTypeSpecification() { collection.insertOne(object); assertMongoWriteException(() -> collection.updateOne(object, json("$currentDate: {lastModified: null}")), - 2, "BadValue", "null is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'})."); + 2, "null is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'})."); assertMongoWriteException(() -> collection.updateOne(object, json("$currentDate: {lastModified: 123.456}")), - 2, "BadValue", "double is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'})."); + 2, "double is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'})."); assertMongoWriteException(() -> collection.updateOne(object, json("$currentDate: {lastModified: 'foo'}")), - 2, "BadValue", "string is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'})."); + 2, "string is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'})."); assertMongoWriteException(() -> collection.updateOne(object, json("$currentDate: {lastModified: {$type: 'foo'}}")), - 2, "BadValue", "The '$type' string field is required to be 'date' or 'timestamp': {$currentDate: {field : {$type: 'date'}}}"); + 2, "The '$type' string field is required to be 'date' or 'timestamp': {$currentDate: {field : {$type: 'date'}}}"); assertThat(collection.find(object).first()).isEqualTo(object); } @@ -4610,19 +4610,19 @@ void testRenameFieldIllegalValue() { collection.insertOne(object); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$rename: {foo: 12345}")), - 2, "BadValue", "The 'to' field for $rename must be a string: foo: 12345"); + 2, "The 'to' field for $rename must be a string: foo: 12345"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$rename: {'_id': 'id'}")), - 66, "ImmutableField", "Performing an update on the path '_id' would modify the immutable field '_id'"); + 66, "Performing an update on the path '_id' would modify the immutable field '_id'"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$rename: {foo: '_id'}")), - 66, "ImmutableField", "Performing an update on the path '_id' would modify the immutable field '_id'"); + 66, "Performing an update on the path '_id' would modify the immutable field '_id'"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$rename: {foo: 'bar', 'bar': 'bar2'}")), - 40, "ConflictingUpdateOperators", "Updating the path 'bar' would create a conflict at 'bar'"); + 40, "Updating the path 'bar' would create a conflict at 'bar'"); assertMongoWriteException(() -> collection.updateOne(json("_id: 1"), json("$rename: {bar: 'foo', bar2: 'foo'}")), - 40, "ConflictingUpdateOperators", "Updating the path 'foo' would create a conflict at 'foo'"); + 40, "Updating the path 'foo' would create a conflict at 'foo'"); } @Test @@ -5327,40 +5327,14 @@ void testValidate() { assertThat(result.get("nrecords")).isEqualTo(2); } - @Test - void testGetLastError() { - collection.insertOne(json("_id: 1")); - - Document actual = db.runCommand(json("getLastError: 1")); - assertThat(actual.get("n")).isEqualTo(0); - assertThat(actual).containsKey("err"); - assertThat(actual.get("err")).isNull(); - assertThat(actual.get("ok")).isEqualTo(1.0); - - assertThatExceptionOfType(MongoWriteException.class) - .isThrownBy(() -> collection.insertOne(json("_id: 1.0"))) - .withMessageContaining("E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1.0 }"); - - Document lastError = db.runCommand(json("getLastError: 1")); - assertThat(lastError.get("code")).isEqualTo(11000); - assertThat(lastError.getString("err")).contains("duplicate key"); - assertThat(lastError.getString("codeName")).isEqualTo("DuplicateKey"); - assertThat(lastError.get("ok")).isEqualTo(1.0); - } - - @Test - public void testResetError() { - collection.insertOne(json("_id: 1")); - - assertThatExceptionOfType(MongoWriteException.class) - .isThrownBy(() -> collection.insertOne(json("_id: 1.0"))) - .withMessageContaining("duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1.0 }"); - - assertThat(db.runCommand(json("resetError: 1"))) - .isEqualTo(json("ok: 1.0")); - - assertThat(db.runCommand(json("getLastError: 1"))) - .containsAllEntriesOf(json("err: null, n: 0, ok: 1.0")); + @ParameterizedTest + @ValueSource(strings = {"getLastError", "getlasterror", "resetError", "reseterror"}) + void testRemovedCommands(String command) { + for (String databaseName : List.of(TEST_DATABASE_NAME, ADMIN_DB_NAME)) { + assertThatExceptionOfType(MongoCommandException.class) + .isThrownBy(() -> syncClient.getDatabase(databaseName).runCommand(new Document(command, 1))) + .withMessageStartingWith("Command execution failed on MongoDB server with error 59 (CommandNotFound): 'no such command: '" + command + "'"); + } } @Test @@ -5736,13 +5710,13 @@ void testUniqueIndexWithNegativeZero() { collection.insertOne(json("_id: 1, value: -0.0")); assertMongoWriteException(() -> collection.insertOne(json("_id: 2, value: 0.0")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: 0.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: 0.0 }"); assertMongoWriteException(() -> collection.insertOne(json("_id: 3, value: -0.0")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: -0.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: -0.0 }"); assertMongoWriteException(() -> collection.insertOne(json("_id: 4, value: 0")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: 0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: { value: 0 }"); } // https://github.com/bwaldvogel/mongo-java-server/issues/45 @@ -5754,7 +5728,7 @@ public void testDecimal128() { collection.insertOne(json("_id: {'$numberDecimal': '200000000000000000000000000000000.5'}")); assertMongoWriteException(() -> collection.insertOne(json("_id: {'$numberDecimal': '1'}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: 1 }"); assertThat(collection.find(json("_id: {$eq: {'$numberDecimal': '3'}}"))) .containsExactly( @@ -6076,19 +6050,11 @@ private void removeInBulk(boolean ordered) { } protected static void assertMongoWriteException(ThrowingCallable callable, int expectedErrorCode, String expectedMessage) { - assertMongoWriteException(callable, expectedErrorCode, "Location" + expectedErrorCode, expectedMessage); - } - - protected static void assertMongoWriteException(ThrowingCallable callable, int expectedErrorCode, String expectedCodeName, - String expectedMessage) { assertThatExceptionOfType(MongoWriteException.class) .isThrownBy(callable) .withMessageContaining(expectedMessage) .extracting(e -> e.getError().getCode()) .isEqualTo(expectedErrorCode); - - Document lastError = db.runCommand(json("getlasterror: 1")); - assertThat(lastError.getString("codeName")).isEqualTo(expectedCodeName); } // https://github.com/bwaldvogel/mongo-java-server/issues/76 @@ -6127,28 +6093,28 @@ public void testMultikeyIndex_simpleArrayValues() { collection.insertOne(json("_id: 7, a: [[2, 1], [4, 3]]")); assertMongoWriteException(() -> collection.insertOne(json("a: [1]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: [6, 1]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: [2.0, 4.0]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 2.0 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 2.0 }"); assertMongoWriteException(() -> collection.insertOne(json("a: [[1, 4], [3, 4]]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: [ 3, 4 ] }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: [ 3, 4 ] }"); collection.deleteOne(json("_id: 3")); collection.insertOne(json("_id: 8, a: [2, 3]")); assertMongoWriteException(() -> collection.replaceOne(json("_id: 1"), json("_id: 1, a: [3, 4]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 3 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 3 }"); collection.replaceOne(json("_id: 4"), json("_id: 4, a: ['x', 'y']")); collection.insertOne(json("_id: 9, a: [4, 6]")); assertMongoWriteException(() -> collection.updateOne(json("_id: 9"), json("$push: {a: 2}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 2 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1 dup key: { a: 2 }"); Document result = collection.findOneAndUpdate(json("_id: 8"), json("$pull: {a: 2}"), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); @@ -6174,19 +6140,19 @@ public void testCompoundMultikeyIndex_simpleArrayValues() { collection.insertOne(json("_id: 5, a: [1, 2, 3, 4, 5], b: 2")); assertMongoWriteException(() -> collection.insertOne(json("a: [1]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: 1, b: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: 1, b: null }"); assertMongoWriteException(() -> collection.insertOne(json("a: [6, 2], b: 1")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: 2, b: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: 2, b: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: ['abc'], b: [1, 2, 3]")), - 171, "CannotIndexParallelArrays", "cannot index parallel arrays [b] [a]"); + 171, "cannot index parallel arrays [b] [a]"); collection.deleteOne(json("_id: 3")); collection.insertOne(json("_id: 6, a: [2, 3], b: 1")); assertMongoWriteException(() -> collection.replaceOne(json("_id: 1"), json("_id: 1, a: [3, 4], b: 1")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: 3, b: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a_1_b_1 dup key: { a: 3, b: 1 }"); collection.replaceOne(json("_id: 4"), json("_id: 4, a: ['x', 'y'], b: 1")); collection.insertOne(json("_id: 7, a: [4, 6], b: 1")); @@ -6197,7 +6163,7 @@ public void testCompoundMultikeyIndex_threeKeys() { collection.createIndex(json("b: 1, a: 1, c: 1"), new IndexOptions().unique(true)); assertMongoWriteException(() -> collection.insertOne(json("b: [1, 2, 3], a: ['abc'], c: ['x', 'y']")), - 171, "CannotIndexParallelArrays", "cannot index parallel arrays [a] [b]"); + 171, "cannot index parallel arrays [a] [b]"); } // https://github.com/bwaldvogel/mongo-java-server/issues/69 @@ -6214,16 +6180,16 @@ public void testCompoundMultikeyIndex_documents() { collection.insertOne(json("_id: 7, item: 'xyz', stock: [1, 2, 3]")); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: null }"); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc', stock: [{color: 'black'}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: null }"); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc', stock: [{size: 'S'}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: \"S\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: \"S\" }"); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc', stock: [{size: 'XL'}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: \"XL\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1 dup key: { item: \"abc\", stock.size: \"XL\" }"); } @Test @@ -6240,13 +6206,13 @@ public void testCompoundMultikeyIndex_multiple_document_keys() { collection.insertOne(json("_id: 9, item: 'xyz', stock: [1, 2, 3]")); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc'")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1_stock.color_1 dup key: { item: \"abc\", stock.size: null, stock.color: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1_stock.color_1 dup key: { item: \"abc\", stock.size: null, stock.color: null }"); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc', stock: [{color: 'red'}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1_stock.color_1 dup key: { item: \"abc\", stock.size: null, stock.color: \"red\" }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1_stock.color_1 dup key: { item: \"abc\", stock.size: null, stock.color: \"red\" }"); assertMongoWriteException(() -> collection.insertOne(json("item: 'abc', stock: [{size: 'XL'}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1_stock.color_1 dup key: { item: \"abc\", stock.size: \"XL\", stock.color: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: item_1_stock.size_1_stock.color_1 dup key: { item: \"abc\", stock.size: \"XL\", stock.color: null }"); } @Test @@ -6260,22 +6226,22 @@ public void testCompoundMultikeyIndex_deepDocuments() { collection.insertOne(json("_id: 5, a: [{b: [{c: 5}, {c: 6}]}, {b: [{c: 7}, {c: 8}]}]")); assertMongoWriteException(() -> collection.insertOne(json("a: {b: 1}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: null }"); assertMongoWriteException(() -> collection.insertOne(json("a: [{b: 1}, {b: 2}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: null }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 1}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: [1, 2]}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 1 }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 4}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 4 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 4 }"); assertMongoWriteException(() -> collection.insertOne(json("a: {b: {c: 8}}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 8 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: a.b.c_1 dup key: { a.b.c: 8 }"); } // https://github.com/bwaldvogel/mongo-java-server/issues/82 @@ -6414,7 +6380,7 @@ private static Stream upsertWithIllegalFilterTestData() { void testUpsertWithIllegalFilter(String filter, String expectedErrorMessage) { assertMongoWriteException(() -> { collection.updateOne(json(filter), json("$set: {dummy: 'dummy'}"), new UpdateOptions().upsert(true)); - }, 54, "NotSingleValueField", expectedErrorMessage); + }, 54, expectedErrorMessage); } // https://github.com/bwaldvogel/mongo-java-server/issues/164 @@ -6547,19 +6513,19 @@ public void testGetKeyValues_multiKey_document_nested_objects() { .withMessageContaining("cannot index parallel arrays [quantity] [size]"); assertMongoWriteException(() -> collection.insertOne(json("stock: {size: 'S', quantity: 10}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"S\", stock.quantity: 10 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"S\", stock.quantity: 10 }"); assertMongoWriteException(() -> collection.insertOne(json("stock: [{size: 'XL', quantity: 7}, {size: 'M', quantity: 10}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"M\", stock.quantity: 10 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"M\", stock.quantity: 10 }"); assertMongoWriteException(() -> collection.insertOne(json("stock: [{size: 'M'}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"M\", stock.quantity: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"M\", stock.quantity: null }"); assertMongoWriteException(() -> collection.insertOne(json("stock: {size: 'XL'}")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"XL\", stock.quantity: null }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: \"XL\", stock.quantity: null }"); assertMongoWriteException(() -> collection.insertOne(json("stock: [{quantity: 20}]")), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: null, stock.quantity: 20 }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: stock.size_1_stock.quantity_1 dup key: { stock.size: null, stock.quantity: 20 }"); } @Test @@ -6698,12 +6664,12 @@ public void testOldAndNewUuidTypes() { collectionWithLegacyUuid.insertOne(document1); assertMongoWriteException(() -> collectionWithLegacyUuid.insertOne(document1), - 11000, null, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: BinData(3, A2963378B9CB425580BCE16A3BF156B4) }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: BinData(3, A2963378B9CB425580BCE16A3BF156B4) }"); collection.insertOne(document1); assertMongoWriteException(() -> collection.insertOne(document1), - 11000, "DuplicateKey", "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: UUID(\"5542cbb9-7833-96a2-b456-f13b6ae1bc80\") }"); + 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: UUID(\"5542cbb9-7833-96a2-b456-f13b6ae1bc80\") }"); Document document2 = new Document("_id", UUID.fromString("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")); collection.insertOne(document2); @@ -6895,7 +6861,7 @@ void testInsertDuplicate_byteArray() { collection.insertOne(document); - assertMongoWriteException(() -> collection.insertOne(document), 11000, "DuplicateKey", + assertMongoWriteException(() -> collection.insertOne(document), 11000, "E11000 duplicate key error collection: testdb.testcoll index: _id_ dup key: { _id: BinData(0, 202122) }"); } diff --git a/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoBackendTest.java b/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoBackendTest.java index 88e0f3501..485d5c52b 100644 --- a/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoBackendTest.java +++ b/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoBackendTest.java @@ -138,15 +138,6 @@ public void testCursor_iteratingACursorThatNoLongerExists() { // disabled on real MongoDB } - @Test - @Override - public void testResetError() { - // Note: No longer implemented since MongoDB 5: "Command execution failed on MongoDB server with error 59 (CommandNotFound): 'no such command: 'reseterror'" - assertThatExceptionOfType(MongoCommandException.class) - .isThrownBy(() -> db.runCommand(json("reseterror: 1"))) - .withMessageStartingWith("Command execution failed on MongoDB server with error 59 (CommandNotFound): 'no such command: 'reseterror'"); - } - @Test @Override public void testCommandThatTriggersAnInternalException() { From 6b696180e33dfd2e8c38fbdcbabc73fc73500af8 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sun, 15 Nov 2026 15:34:27 +0100 Subject: [PATCH 5/5] Align backend and integration tests with MongoDB 7.0.48 Remove the obsolete free-monitoring command. Match MongoDB 7 collection creation, database statistics and aggregation errors using shared test expectations. Upgrade Compose and Testcontainers to MongoDB 7.0.48, use mongosh for the healthcheck and set nofile to 2048. Integration tests passed twice at 2048; 1024 exhausted file descriptors and crashed MongoDB. --- .../mongo/backend/AbstractMongoBackend.java | 15 ++------ .../mongo/backend/AbstractMongoDatabase.java | 22 ++++++------ .../de/bwaldvogel/mongo/backend/Command.java | 3 -- .../backend/aggregation/stage/MergeStage.java | 14 ++++++-- .../aggregation/stage/ReplaceRootStage.java | 2 +- .../bwaldvogel/mongo/exception/ErrorCode.java | 2 ++ .../mongo/exception/MongoServerError.java | 6 +++- .../stage/ReplaceRootStageTest.java | 8 ++--- docker-compose.yml | 8 +++-- .../backend/AbstractAggregationTest.java | 7 ++-- .../mongo/backend/AbstractBackendTest.java | 34 ++++++++----------- .../bwaldvogel/mongo/RealMongoContainer.java | 6 +++- 12 files changed, 66 insertions(+), 61 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java index 0979c94ea..cf9d3c278 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java @@ -23,8 +23,9 @@ import de.bwaldvogel.mongo.MongoVersion; import de.bwaldvogel.mongo.ServerVersion; import de.bwaldvogel.mongo.bson.Document; +import de.bwaldvogel.mongo.exception.ErrorCode; +import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.MongoServerException; -import de.bwaldvogel.mongo.exception.MongoSilentServerException; import de.bwaldvogel.mongo.exception.NamespaceExistsException; import de.bwaldvogel.mongo.exception.NoReplicationEnabledException; import de.bwaldvogel.mongo.exception.NoSuchCommandException; @@ -144,7 +145,7 @@ private Document getLog(String argument) { Utils.markOkay(response); break; default: - throw new MongoSilentServerException("no RamLog named: " + argument); + throw new MongoServerError(ErrorCode.OperationFailed, "No log named '" + argument + "'"); } return response; } @@ -162,7 +163,6 @@ private Document handleAdminCommand(DatabaseCommand command, Document query) { case CONNECTION_STATUS -> handleConnectionStatus(); case HOST_INFO -> handleHostInfo(); case GET_CMD_LINE_OPTS -> handleGetCmdLineOpts(); - case GET_FREE_MONITORING_STATUS -> handleGetFreeMonitoringStatus(); case END_SESSIONS -> { log.debug("endSessions on admin database"); yield successResponse(); @@ -241,15 +241,6 @@ private Document handleGetCmdLineOpts() { return response; } - private Document handleGetFreeMonitoringStatus() { - Document response = new Document(); - response.append("state", "disabled"); - response.append("debug", Map.of("state", "undecided")); - response.append("message", "Free monitoring is deprecated, refer to 'debug' field for actual status"); - Utils.markOkay(response); - return response; - } - @VisibleForExternalBackends protected Set listDatabaseNames() { return databases.keySet(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java index 1bb995e0b..a0179b0e2 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java @@ -305,12 +305,14 @@ private Document commandDelete(String command, Document query, Oplog oplog) { return response; } - private Document commandCreate(String command, Document query) { + private synchronized Document commandCreate(String command, Document query) { String collectionName = query.get(command).toString(); CollectionOptions collectionOptions = CollectionOptions.fromQuery(query); collectionOptions.validate(); - createCollectionOrThrowIfExists(collectionName, collectionOptions); + if (resolveCollection(collectionName, false) == null) { + createCollection(collectionName, collectionOptions); + } Document response = new Document(); Utils.markOkay(response); @@ -416,18 +418,18 @@ private Collection> collections() { private Document commandDatabaseStats() { Document response = new Document("db", getDatabaseName()); - response.put("collections", Integer.valueOf(collections().size())); + response.put("collections", Long.valueOf(collections().size())); long storageSize = getStorageSize(); long fileSize = getFileSize(); long indexSize = 0; - int objects = 0; + long objects = 0; double dataSize = 0; double averageObjectSize = 0; for (MongoCollection

collection : collections()) { Document stats = collection.getStats(); - objects += ((Number) stats.get("count")).intValue(); + objects += ((Number) stats.get("count")).longValue(); dataSize += ((Number) stats.get("size")).doubleValue(); Document indexSizes = (Document) stats.get("indexSize"); @@ -439,16 +441,12 @@ private Document commandDatabaseStats() { if (objects > 0) { averageObjectSize = dataSize / ((double) objects); } - response.put("objects", Integer.valueOf(objects)); + response.put("objects", Long.valueOf(objects)); response.put("avgObjSize", Double.valueOf(averageObjectSize)); - if (dataSize == 0.0) { - response.put("dataSize", Integer.valueOf(0)); - } else { - response.put("dataSize", Double.valueOf(dataSize)); - } + response.put("dataSize", Double.valueOf(dataSize)); response.put("storageSize", Long.valueOf(storageSize)); response.put("numExtents", Integer.valueOf(0)); - response.put("indexes", Integer.valueOf(countIndexes())); + response.put("indexes", Long.valueOf(countIndexes())); response.put("indexSize", Long.valueOf(indexSize)); response.put("fileSize", Long.valueOf(fileSize)); response.put("nsSizeMB", Integer.valueOf(0)); diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java index 18bbd53ca..8a7a4f9a6 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Command.java @@ -54,9 +54,6 @@ public enum Command { VALIDATE("validate"), WHATS_MY_URI("whatsmyuri"), - // Monitoring - GET_FREE_MONITORING_STATUS("getFreeMonitoringStatus"), - // internal use TRIGGER_INTERNAL_EXCEPTION("triggerInternalException"); diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java index b8db53bfd..a8247a6fd 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java @@ -23,6 +23,8 @@ import de.bwaldvogel.mongo.backend.aggregation.Aggregation; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.BadValueException; +import de.bwaldvogel.mongo.exception.DuplicateKeyError; +import de.bwaldvogel.mongo.exception.ErrorCode; import de.bwaldvogel.mongo.exception.ImmutableFieldException; import de.bwaldvogel.mongo.exception.InvalidOptionsException; import de.bwaldvogel.mongo.exception.MergeStageNoMatchingDocumentException; @@ -66,7 +68,7 @@ public MergeStage(DatabaseResolver databaseResolver, MongoDatabase database, Obj Document paramsDocument = (Document) params; for (String key : paramsDocument.keySet()) { if (!KNOWN_KEYS.contains(key)) { - throw new MongoServerError(40415, "BSON field '$merge." + key + "' is an unknown field."); + throw new MongoServerError(ErrorCode.IDLUnknownField, "BSON field '$merge." + key + "' is an unknown field."); } } @@ -118,7 +120,7 @@ private static Supplier> getTargetCollectionSupplier(Database } else if (into instanceof Document intoDocument) { for (String intoKey : intoDocument.keySet()) { if (!intoKey.equals("db") && !intoKey.equals("coll")) { - throw new MongoServerError(40415, "BSON field 'into." + intoKey + "' is an unknown field."); + throw new MongoServerError(ErrorCode.IDLUnknownField, "BSON field 'into." + intoKey + "' is an unknown field."); } } String collectionName = (String) intoDocument.get("coll"); @@ -240,7 +242,13 @@ public void applyLast(Stream stream) { break; case fail: // this triggers a DuplicateKeyError - collection.addDocument(document); + try { + collection.addDocument(document); + } catch (DuplicateKeyError e) { + throw new MongoServerError(ErrorCode.DuplicateKey, + "$merge with whenMatched: fail found an existing document with the same values for the 'on' fields :: caused by :: " + + e.getMessageWithoutErrorCode(), e); + } break; case keepExisting: break; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStage.java index fb29fd533..6a337817d 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStage.java @@ -36,7 +36,7 @@ Document replaceRoot(Document document) { Object evaluatedNewRoot = Expression.evaluateDocument(newRoot, document); if (!(evaluatedNewRoot instanceof Document)) { - throw new MongoServerError(40228, "'newRoot' expression must evaluate to an object, but resulting value was: " + Json.toJsonValue(evaluatedNewRoot, true, "{", "}") + throw new MongoServerError(40228, "'newRoot' expression must evaluate to an object, but resulting value was: " + Json.toJsonValue(evaluatedNewRoot, true, "{", "}") + ". Type of resulting value: '" + describeType(evaluatedNewRoot) + "'. Input document: " + document.toString(true)); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/ErrorCode.java b/core/src/main/java/de/bwaldvogel/mongo/exception/ErrorCode.java index 06330bce1..61083233e 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/ErrorCode.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/ErrorCode.java @@ -18,9 +18,11 @@ public enum ErrorCode { InvalidOptions(72), InvalidNamespace(73), IndexKeySpecsConflict(86), + OperationFailed(96), CannotIndexParallelArrays(171), ConversionFailure(241), DuplicateKey(11000), + IDLUnknownField(40415), MergeStageNoMatchingDocument(13113), _15998(15998) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java index 57022891f..679879c0c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java +++ b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerError.java @@ -17,7 +17,11 @@ public MongoServerError(int errorCode, String message) { } public MongoServerError(ErrorCode errorCode, String message) { - this(errorCode.getValue(), errorCode.getName(), message); + this(errorCode, message, null); + } + + public MongoServerError(ErrorCode errorCode, String message, Throwable cause) { + this(errorCode.getValue(), errorCode.getName(), message, cause); } public MongoServerError(int errorCode, String codeName, String message) { diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java index 7f20f1686..334d85bf2 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java @@ -30,19 +30,19 @@ void testIllegalReplaceRoot() throws Exception { assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: 1")).replaceRoot(json("a: { b: {} }"))) - .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: 1. Type of resulting value: 'int'. Input document: {a: {b: {}}}"); + .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: 1. Type of resulting value: 'int'. Input document: {a: {b: {}}}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: 'x'")).replaceRoot(json("a: { b: {} }"))) - .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: \"x\". Type of resulting value: 'string'. Input document: {a: {b: {}}}"); + .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: \"x\". Type of resulting value: 'string'. Input document: {a: {b: {}}}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: '$c'")).replaceRoot(json("a: { b: {} }"))) - .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'missing'. Input document: {a: {b: {}}}"); + .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'missing'. Input document: {a: {b: {}}}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: '$a.c'")).replaceRoot(json("a: { b: {} }"))) - .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'missing'. Input document: {a: {b: {}}}"); + .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'missing'. Input document: {a: {b: {}}}"); } } diff --git a/docker-compose.yml b/docker-compose.yml index 057b56643..232426dd0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,13 +1,17 @@ services: mongodb: - image: mongo:5.0.18 + image: mongo:7.0.48 container_name: mongo-java-server-test + ulimits: + nofile: + soft: 2048 + hard: 2048 tmpfs: - /data:rw ports: - 127.0.0.1:27018:27017 healthcheck: - test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1 + test: ["CMD", "mongosh", "--quiet", "--eval", "quit(db.runCommand({ping: 1}).ok ? 0 : 1)"] interval: 10s timeout: 5s retries: 5 diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java index ca01f57b5..f4e747338 100644 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java @@ -1615,7 +1615,7 @@ void testAggregateWithIllegalReplaceRoot() { assertThatExceptionOfType(MongoCommandException.class) .isThrownBy(() -> collection.aggregate(pipeline).first()) .withMessageContaining("Command execution failed on MongoDB server with error 40228 (Location40228): " + - "'PlanExecutor error during aggregation :: caused by :: 'newRoot' expression must evaluate to an object, but resulting value was: 10." + + "'PlanExecutor error during aggregation :: caused by :: 'newRoot' expression must evaluate to an object, but resulting value was: 10." + " Type of resulting value: 'int'.") .withMessageContaining("a: {b: 10}"); } @@ -2450,6 +2450,7 @@ void testAggregateWithMerge_whenMatched_fail() throws Exception { .isThrownBy(() -> collection.aggregate(jsonList("$merge: { into: 'other', whenMatched: 'fail' }")).first()) .withMessageStartingWith("Command execution failed on MongoDB server with error 11000 (DuplicateKey): " + "'PlanExecutor error during aggregation :: caused by :: " + + "$merge with whenMatched: fail found an existing document with the same values for the 'on' fields :: caused by :: " + "E11000 duplicate key error collection: testdb.other index: _id_ dup key: { _id: 1 }'"); } @@ -2678,13 +2679,13 @@ private static Stream aggregateWithMerge_illegalParametersArguments() "Cannot return a cursor when the value for $merge stage is not a string or a document"), Arguments.of("$merge: { otherParam: 1 }", MongoCommandException.class, - "Command execution failed on MongoDB server with error 40415 (Location40415): 'BSON field '$merge.otherParam' is an unknown field.'"), + "Command execution failed on MongoDB server with error 40415 (IDLUnknownField): 'BSON field '$merge.otherParam' is an unknown field.'"), Arguments.of("$merge: { into: {} }", BsonInvalidOperationException.class, "Document does not contain key coll"), Arguments.of("$merge: { into: { coll: 'abc', other: 1} }", MongoCommandException.class, - "Command execution failed on MongoDB server with error 40415 (Location40415): 'BSON field 'into.other' is an unknown field.'"), + "Command execution failed on MongoDB server with error 40415 (IDLUnknownField): 'BSON field 'into.other' is an unknown field.'"), Arguments.of("$merge: { into: { coll: 1} }", BsonInvalidOperationException.class, "Value expected to be of type STRING is of unexpected type INT32"), diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java index 2862add9e..ab4f93a5d 100755 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java @@ -339,10 +339,13 @@ void testCreateCappedCollection_invalidOptions() { @Test void testCreateCollectionAlreadyExists() { db.createCollection("some-collection", new CreateCollectionOptions()); + MongoCollection existingCollection = db.getCollection("some-collection"); + existingCollection.insertOne(json("_id: 1, value: 'preserved'")); - assertThatExceptionOfType(MongoCommandException.class) - .isThrownBy(() -> db.createCollection("some-collection", new CreateCollectionOptions())) - .withMessageStartingWith("Command execution failed on MongoDB server with error 48 (NamespaceExists): 'Collection already exists. NS: testdb.some-collection'"); + db.createCollection("some-collection", new CreateCollectionOptions()); + + assertThat(db.listCollectionNames()).containsExactly("some-collection"); + assertThat(existingCollection.find()).containsExactly(json("_id: 1, value: 'preserved'")); } @Test @@ -415,7 +418,7 @@ public void testGetLogStartupWarnings() { void testGetLogWhichDoesNotExist() { assertThatExceptionOfType(MongoCommandException.class) .isThrownBy(() -> runCommand(json("getLog: 'illegal'"))) - .withMessageStartingWith("Command execution failed on MongoDB server with error -1: 'no RamLog named: illegal'"); + .withMessageStartingWith("Command execution failed on MongoDB server with error 96 (OperationFailed): 'No log named 'illegal''"); } @Test @@ -878,10 +881,10 @@ public void testSystemNamespaces() { void testDatabaseStats() { Document stats = db.runCommand(new Document("dbStats", 1).append("scale", 1)); assertThat(stats.getDouble("ok")).isEqualTo(1.0); - assertThat(stats.getInteger("objects")).isZero(); - assertThat(stats.getInteger("collections")).isZero(); - assertThat(stats.getInteger("indexes")).isZero(); - assertThat(stats.getInteger("dataSize")).isZero(); + assertThat(stats.getLong("objects")).isZero(); + assertThat(stats.getLong("collections")).isZero(); + assertThat(stats.getLong("indexes")).isZero(); + assertThat(stats.getDouble("dataSize")).isZero(); getCollection("foo").insertOne(json("")); getCollection("foo").insertOne(json("")); @@ -889,9 +892,9 @@ void testDatabaseStats() { stats = db.runCommand(new Document("dbStats", 1).append("scale", 1)); assertThat(stats.getDouble("ok")).isEqualTo(1.0); - assertThat(stats.getInteger("objects")).isEqualTo(3); - assertThat(stats.getInteger("collections")).isEqualTo(2); - assertThat(stats.getInteger("indexes")).isEqualTo(2); + assertThat(stats.getLong("objects")).isEqualTo(3); + assertThat(stats.getLong("collections")).isEqualTo(2); + assertThat(stats.getLong("indexes")).isEqualTo(2); assertThat(stats.getDouble("dataSize")).isEqualTo(66.0); } @@ -5328,7 +5331,7 @@ void testValidate() { } @ParameterizedTest - @ValueSource(strings = {"getLastError", "getlasterror", "resetError", "reseterror"}) + @ValueSource(strings = {"getLastError", "getlasterror", "resetError", "reseterror", "getFreeMonitoringStatus"}) void testRemovedCommands(String command) { for (String databaseName : List.of(TEST_DATABASE_NAME, ADMIN_DB_NAME)) { assertThatExceptionOfType(MongoCommandException.class) @@ -6724,13 +6727,6 @@ void testGetCmdLineOpts() { assertThat(result).containsOnlyKeys("ok", "argv", "parsed"); } - @Test - void testGetFreeMonitoringStatus() { - Document result = runCommand(Command.GET_FREE_MONITORING_STATUS); - assertThat(result).isEqualTo(json("ok: 1.0, state: 'disabled', debug: {state: 'undecided'}," + - " message: 'Free monitoring is deprecated, refer to \\'debug\\' field for actual status'")); - } - @Test void testUpdateWithDollarFieldNames() { collection.insertOne(json("_id: 1")); diff --git a/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoContainer.java b/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoContainer.java index a6ff0dc54..0339dd26c 100644 --- a/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoContainer.java +++ b/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoContainer.java @@ -7,6 +7,7 @@ import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; +import com.github.dockerjava.api.model.Ulimit; import com.mongodb.ConnectionString; import de.bwaldvogel.mongo.backend.Assert; @@ -52,7 +53,10 @@ private static boolean shouldUseExistingContainer() { } static GenericContainer start() { - GenericContainer mongoContainer = new GenericContainer<>("mongo:5.0.18").withExposedPorts(27017); + GenericContainer mongoContainer = new GenericContainer<>("mongo:7.0.48") + .withExposedPorts(27017) + .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig() + .withUlimits(new Ulimit[] { new Ulimit("nofile", 2048L, 2048L) })); mongoContainer.start(); return mongoContainer; }