diff --git a/core/build.gradle b/core/build.gradle index 82f10364..fc9c74b0 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -3,7 +3,8 @@ 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.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 d3f32270..98d84357 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 @@ -34,7 +36,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/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java b/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java index ffdf0d03..7076bc85 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 62fdaad5..8f2854ec 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 fcaec38c..2c3bf805 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 456847de..cf9d3c27 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; @@ -24,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; @@ -37,7 +37,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 { @@ -146,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; } @@ -161,14 +160,9 @@ 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(); - case GET_FREE_MONITORING_STATUS -> handleGetFreeMonitoringStatus(); case END_SESSIONS -> { log.debug("endSessions on admin database"); yield successResponse(); @@ -247,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(); @@ -307,9 +292,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 +306,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 +327,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 +398,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 +413,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/AbstractMongoCollection.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java index 043d67ee..e623f1c8 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/AbstractMongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java index 710286da..a0179b0e 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(); } @@ -327,12 +305,14 @@ private Document commandDelete(Channel channel, String command, Document query, 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); @@ -438,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"); @@ -461,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)); @@ -528,62 +504,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 +572,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 +589,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 +711,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 +719,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 +746,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 +757,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 f6398e89..e0f59ac2 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 d9c5b186..8a7a4f9a 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 @@ -56,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/KeyValue.java b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java index da7bb637..bb197b45 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 bf14d4c0..5675919d 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 b3e1bed3..d8a710c8 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 0166de77..fe42bb0d 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java @@ -6,12 +6,12 @@ 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; 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; @@ -26,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 { @@ -40,7 +39,6 @@ public class ReadOnlyProxy implements MongoBackend { COLL_STATS, SERVER_STATUS, BUILD_INFO, - GET_LAST_ERROR, GET_MORE ); @@ -52,6 +50,7 @@ public ReadOnlyProxy(MongoBackend backend) { public static class ReadOnlyException extends MongoServerException { + @Serial private static final long serialVersionUID = 1L; ReadOnlyException(String message) { @@ -61,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/backend/aggregation/Aggregation.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java index 206341f1..d91009a3 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/MergeStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java index b8db53bf..a8247a6f 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/ProjectStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ProjectStage.java index e752ef48..933b87e9 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/backend/aggregation/stage/ReplaceRootStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStage.java index fb29fd53..6a337817 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/bson/BinData.java b/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java index a0a574e9..79b9e23a 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 ad48afa5..445f0815 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 09797d8f..05434880 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 61b3342b..66afc366 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 b2e5175f..38b6549a 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 985e8a38..a5a632d6 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 be538e17..61d76011 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 039cb4f2..2f031f62 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 2e853b9c..8fae8311 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 1e8c1c4a..1bbc28ce 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 f6d0f0dd..615d168b 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 29ff757f..009cb666 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 b3370e69..9d351c90 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 e1928574..a45a1698 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 e737f157..8b7164b0 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 4bd5819f..9a464991 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 8876d940..1e5e6127 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 87562fb3..f866acb0 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/ErrorCode.java b/core/src/main/java/de/bwaldvogel/mongo/exception/ErrorCode.java index 06330bce..61083233 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/FailedToOptimizePipelineError.java b/core/src/main/java/de/bwaldvogel/mongo/exception/FailedToOptimizePipelineError.java index 4989b3ae..447dde34 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 d55a2548..e8593908 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 394c749d..fa30f15d 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 57b23b54..734c7d8c 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 3374e6fc..2b006a9d 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 0adccd26..3c04b982 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 fea6fdeb..2df45a2f 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 26c54a41..a60d9117 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 f5aac76d..4866b62b 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 5969b860..0493c316 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 5f443628..baa7ee6a 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 7b45329e..8e298e7a 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 49acce7f..679879c0 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; @@ -15,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/main/java/de/bwaldvogel/mongo/exception/MongoServerException.java b/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerException.java index d98074fd..5515edba 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 894ff945..840e1bd9 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 16833deb..fb19cef2 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 adf6ebf1..8869c0d7 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 c7f9f3bb..d422cf68 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 3bc171eb..346f4902 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 38a3a025..08287776 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 9e4244d2..4d37ddff 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 7438c98a..6ef42112 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/main/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandler.java b/core/src/main/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandler.java index 31976016..f8299aff 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 483d53d3..330ed8ac 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 671af6fe..62775865 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 f09e8480..72ca4501 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 3c0d8b29..a4cdf3fe 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 01efe5dc..29d7208e 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 f0bea93d..c74b2bd3 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/backend/InMemoryCursorTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java index d8de29cf..61366e7e 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 f25915a0..6a3756b4 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; 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 7f20f168..334d85bf 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/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java index f633b8b4..84bea7b1 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/MongoExceptionHandlerTest.java b/core/src/test/java/de/bwaldvogel/mongo/wire/MongoExceptionHandlerTest.java index 7916c2b4..8796ae07 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; 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 ffcbb7b6..3f217c74 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/docker-compose.yml b/docker-compose.yml index 057b5664..232426dd 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/examples/build.gradle b/examples/build.gradle index 716d8a32..aa8a59db 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 ef7f1615..d18020c3 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 ab945f8f..46ba6fcf 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 2c29ec76..00000000 --- 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 e768052d..e7b5e78c 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 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 970f38a1..083d1507 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/AbstractAggregationTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java index ca01f57b..f4e74733 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 ad401b12..ab4f93a5 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,17 +339,20 @@ 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 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 @@ -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 @@ -599,7 +602,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)); @@ -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); } @@ -1076,11 +1079,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 +1965,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 +2031,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 +2080,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 +2090,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 +2098,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 +2743,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 +2762,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 +2823,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 +2945,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 +2953,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 +2967,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 +3023,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 +3075,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 +3131,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 +3140,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 +3171,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 +3204,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 +3436,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 +3450,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 +3500,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 +3760,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 +3780,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 +3888,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 +3940,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 +3952,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 +3977,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 +4006,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 +4031,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 +4063,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 +4094,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 +4124,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 +4155,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 +4180,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 +4206,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 +4244,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 +4274,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 +4355,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 +4387,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 +4415,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 +4539,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 +4613,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 +5330,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", "getFreeMonitoringStatus"}) + 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 +5713,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 +5731,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 +6053,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 +6096,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 +6143,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 +6166,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 +6183,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 +6209,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 +6229,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 +6383,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 +6516,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 +6667,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); @@ -6758,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")); @@ -6895,7 +6857,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 88e0f350..485d5c52 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() { 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 a6ff0dc5..0339dd26 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; }