use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.
the class RetryableWritesProseTest method poolClearedExceptionMustBeRetryable.
@SuppressWarnings("try")
public static <R> void poolClearedExceptionMustBeRetryable(final Function<MongoClientSettings, MongoClient> clientCreator, final Function<MongoCollection<Document>, R> operation, final String operationName, final boolean write) throws InterruptedException, ExecutionException, TimeoutException {
assumeTrue(serverVersionAtLeast(4, 3) && !(write && isStandalone()));
assumeFalse(isServerlessTest());
TestConnectionPoolListener connectionPoolListener = new TestConnectionPoolListener(asList("connectionCheckedOutEvent", "poolClearedEvent", "connectionCheckOutFailedEvent"));
TestCommandListener commandListener = new TestCommandListener(singletonList("commandStartedEvent"), asList("configureFailPoint", "drop"));
MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applyToConnectionPoolSettings(builder -> builder.maxSize(1).addConnectionPoolListener(connectionPoolListener)).applyToServerSettings(builder -> builder.minHeartbeatFrequency(50, TimeUnit.MILLISECONDS).heartbeatFrequency(50, TimeUnit.MILLISECONDS)).retryReads(true).retryWrites(true).addCommandListener(commandListener).build();
BsonDocument configureFailPoint = new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(1))).append("data", new BsonDocument().append("failCommands", new BsonArray(singletonList(new BsonString(operationName)))).append("errorCode", new BsonInt32(91)).append("errorLabels", write ? new BsonArray(singletonList(new BsonString("RetryableWriteError"))) : new BsonArray()).append("blockConnection", BsonBoolean.valueOf(true)).append("blockTimeMS", new BsonInt32(1000)));
int timeoutSeconds = 5;
try (MongoClient client = clientCreator.apply(clientSettings);
FailPoint ignored = FailPoint.enable(configureFailPoint, client)) {
MongoCollection<Document> collection = client.getDatabase(getDefaultDatabaseName()).getCollection("poolClearedExceptionMustBeRetryable");
collection.drop();
ExecutorService ex = Executors.newFixedThreadPool(2);
try {
Future<R> result1 = ex.submit(() -> operation.apply(collection));
Future<R> result2 = ex.submit(() -> operation.apply(collection));
connectionPoolListener.waitForEvent(ConnectionCheckedOutEvent.class, 1, timeoutSeconds, SECONDS);
connectionPoolListener.waitForEvent(ConnectionPoolClearedEvent.class, 1, timeoutSeconds, SECONDS);
connectionPoolListener.waitForEvent(ConnectionCheckOutFailedEvent.class, 1, timeoutSeconds, SECONDS);
result1.get(timeoutSeconds, SECONDS);
result2.get(timeoutSeconds, SECONDS);
} finally {
ex.shutdownNow();
}
assertEquals(3, commandListener.getCommandStartedEvents().size());
commandListener.getCommandStartedEvents().forEach(event -> assertEquals(operationName, event.getCommandName()));
}
}
use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.
the class ServerDiscoveryAndMonitoringProseTests method monitorsSleepAtLeastMinHeartbeatFreqencyMSBetweenChecks.
/**
* See
* <a href="https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-tests.rst#monitors-sleep-at-least-minheartbeatfreqencyms-between-checks">
* Monitors sleep at least minHeartbeatFreqencyMS between checks</a>.
*/
@Test
@SuppressWarnings("try")
public void monitorsSleepAtLeastMinHeartbeatFreqencyMSBetweenChecks() {
assumeTrue(serverVersionAtLeast(4, 3));
assumeFalse(isServerlessTest());
long defaultMinHeartbeatIntervalMillis = MongoClientSettings.builder().build().getServerSettings().getMinHeartbeatFrequency(MILLISECONDS);
assertEquals(500, defaultMinHeartbeatIntervalMillis);
String appName = "SDAMMinHeartbeatFrequencyTest";
MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applicationName(appName).applyToClusterSettings(ClusterFixture::setDirectConnection).applyToClusterSettings(builder -> builder.serverSelectionTimeout(5000, MILLISECONDS)).applyToServerSettings(builder -> builder.minHeartbeatFrequency(defaultMinHeartbeatIntervalMillis, MILLISECONDS)).build();
BsonDocument configureFailPoint = new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(5))).append("data", new BsonDocument().append("failCommands", new BsonArray(asList(new BsonString("hello"), new BsonString("isMaster")))).append("errorCode", new BsonInt32(1234)).append("appName", new BsonString(appName)));
try (FailPoint ignored = FailPoint.enable(configureFailPoint, clientSettings.getClusterSettings().getHosts().get(0));
MongoClient client = MongoClients.create(clientSettings)) {
long startNanos = System.nanoTime();
client.getDatabase(getDefaultDatabaseName()).runCommand(new BsonDocument("ping", BsonNull.VALUE));
long durationMillis = NANOSECONDS.toMillis(System.nanoTime() - startNanos);
String msg = durationMillis + " ms";
assertTrue(msg, durationMillis >= 2000);
assertTrue(msg, durationMillis <= 3500);
}
}
use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.
the class CrudProseTest method testWriteConcernErrInfoIsPropagated.
/**
* 1. WriteConcernError.details exposes writeConcernError.errInfo
*/
@Test
public void testWriteConcernErrInfoIsPropagated() {
assumeTrue(isDiscoverableReplicaSet() && serverVersionAtLeast(4, 0));
try {
setFailPoint();
collection.insertOne(Document.parse("{ x: 1 }"));
} catch (MongoWriteConcernException e) {
assertEquals(e.getWriteConcernError().getCode(), 100);
assertEquals("UnsatisfiableWriteConcern", e.getWriteConcernError().getCodeName());
assertEquals(e.getWriteConcernError().getDetails(), new BsonDocument("writeConcern", new BsonDocument("w", new BsonInt32(2)).append("wtimeout", new BsonInt32(0)).append("provenance", new BsonString("clientSupplied"))));
} catch (Exception ex) {
fail(format("Incorrect exception thrown in test: %s", ex.getClass()));
} finally {
disableFailPoint();
}
}
use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.
the class AbstractFindBenchmark method insertCopiesOfDocument.
private void insertCopiesOfDocument(final MongoCollection<BsonDocument> collection, final BsonDocument document) {
List<BsonDocument> documents = new ArrayList<BsonDocument>(NUM_INTERNAL_ITERATIONS);
for (int i = 0; i < NUM_INTERNAL_ITERATIONS; i++) {
BsonDocument copy = document.clone();
copy.put("_id", new BsonInt32(i));
documents.add(copy);
}
collection.insertMany(documents);
}
use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.
the class BatchCursorFluxTest method ensureExists.
/**
* This method ensures that the server considers the specified {@code collection} existing for the purposes of, e.g.,
* {@link MongoCollection#drop()}, instead of replying with
* {@code "errmsg": "ns not found", "code": 26, "codeName": "NamespaceNotFound"}.
*
* @return {@code operationTime} starting at which the {@code collection} is guaranteed to exist.
*/
private static BsonTimestamp ensureExists(final MongoClient client, final MongoCollection<Document> collection) {
BsonValue insertedId = Mono.from(collection.insertOne(Document.parse("{}"))).map(InsertOneResult::getInsertedId).block(TIMEOUT_DURATION);
BsonArray deleteStatements = new BsonArray();
deleteStatements.add(new BsonDocument().append("q", new BsonDocument().append("_id", insertedId)).append("limit", new BsonInt32(1)));
Publisher<Document> deletePublisher = client.getDatabase(collection.getNamespace().getDatabaseName()).runCommand(new BsonDocument().append("delete", new BsonString(collection.getNamespace().getCollectionName())).append("deletes", deleteStatements));
BsonTimestamp operationTime = Mono.from(deletePublisher).map(doc -> doc.get("operationTime", BsonTimestamp.class)).block(TIMEOUT_DURATION);
assertNotNull(operationTime);
return operationTime;
}
Aggregations