use of com.mongodb.internal.async.function.RetryState in project mongo-java-driver by mongodb.
the class FindOperation method executeAsync.
@Override
public void executeAsync(final AsyncReadBinding binding, final SingleResultCallback<AsyncBatchCursor<T>> callback) {
RetryState retryState = initialRetryState(retryReads);
binding.retain();
AsyncCallbackSupplier<AsyncBatchCursor<T>> asyncRead = CommandOperationHelper.<AsyncBatchCursor<T>>decorateReadWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
withAsyncSourceAndConnection(binding::getReadConnectionSource, false, funcCallback, (source, connection, releasingCallback) -> {
if (retryState.breakAndCompleteIfRetryAnd(() -> !canRetryRead(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()), releasingCallback)) {
return;
}
if (serverIsAtLeastVersionThreeDotTwo(connection.getDescription())) {
final SingleResultCallback<AsyncBatchCursor<T>> wrappedCallback = exceptionTransformingCallback(releasingCallback);
createReadCommandAndExecuteAsync(retryState, binding, source, namespace.getDatabaseName(), getCommandCreator(binding.getSessionContext()), CommandResultDocumentCodec.create(decoder, FIRST_BATCH), asyncTransformer(), connection, wrappedCallback);
} else {
retryState.markAsLastAttempt();
validateFindOptions(source, connection, binding.getSessionContext().getReadConcern(), collation, allowDiskUse, new AsyncCallableWithConnectionAndSource() {
@Override
public void call(final AsyncConnectionSource source, final AsyncConnection connection, final Throwable t) {
if (t != null) {
releasingCallback.onResult(null, t);
} else {
connection.queryAsync(namespace, asDocument(connection.getDescription(), binding.getReadPreference()), projection, skip, limit, batchSize, isSecondaryOk() || binding.getReadPreference().isSecondaryOk(), isTailableCursor(), isAwaitData(), isNoCursorTimeout(), isPartial(), isOplogReplay(), decoder, binding.getRequestContext(), new SingleResultCallback<QueryResult<T>>() {
@Override
public void onResult(final QueryResult<T> result, final Throwable t) {
if (t != null) {
releasingCallback.onResult(null, t);
} else {
releasingCallback.onResult(new AsyncQueryBatchCursor<T>(result, limit, batchSize, getMaxTimeForCursor(), decoder, source, connection), null);
}
}
});
}
}
});
}
});
}).whenComplete(binding::release);
asyncRead.get(errorHandlingCallback(callback, LOGGER));
}
use of com.mongodb.internal.async.function.RetryState in project mongo-java-driver by mongodb.
the class MixedBulkWriteOperation method execute.
/**
* Executes a bulk write operation.
*
* @param binding the WriteBinding for the operation
* @return the bulk write result.
* @throws MongoBulkWriteException if a failure to complete the bulk write is detected based on the server response
*/
@Override
public BulkWriteResult execute(final WriteBinding binding) {
/* We cannot use the tracking of attempts built in the `RetryState` class because conceptually we have to maintain multiple attempt
* counters while executing a single bulk write operation:
* - a counter that limits attempts to select server and checkout a connection before we created a batch;
* - a counter per each batch that limits attempts to execute the specific batch.
* Fortunately, these counters do not exist concurrently with each other. While maintaining the counters manually,
* we must adhere to the contract of `RetryingSyncSupplier`. When the retry timeout is implemented, there will be no counters,
* and the code related to the attempt tracking in `BulkWriteTracker` will be removed. */
RetryState retryState = new RetryState();
BulkWriteTracker.attachNew(retryState, retryWrites);
Supplier<BulkWriteResult> retryingBulkWrite = decorateWriteWithRetries(retryState, () -> {
logRetryExecute(retryState);
return withSourceAndConnection(binding::getWriteConnectionSource, true, (source, connection) -> {
ConnectionDescription connectionDescription = connection.getDescription();
int maxWireVersion = connectionDescription.getMaxWireVersion();
// attach `maxWireVersion` ASAP because it is used to check whether we can retry
retryState.attach(AttachmentKeys.maxWireVersion(), maxWireVersion, true);
BulkWriteTracker bulkWriteTracker = retryState.attachment(AttachmentKeys.bulkWriteTracker()).orElseThrow(Assertions::fail);
SessionContext sessionContext = binding.getSessionContext();
WriteConcern writeConcern = getAppliedWriteConcern(sessionContext);
if (!retryState.isFirstAttempt() && !isRetryableWrite(retryWrites, writeConcern, source.getServerDescription(), connectionDescription, sessionContext)) {
RuntimeException prospectiveFailedResult = (RuntimeException) retryState.exception().orElse(null);
retryState.breakAndThrowIfRetryAnd(() -> !(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException));
bulkWriteTracker.batch().ifPresent(bulkWriteBatch -> {
assertTrue(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException);
bulkWriteBatch.addResult((BsonDocument) ((MongoWriteConcernWithResponseException) prospectiveFailedResult).getResponse());
BulkWriteTracker.attachNext(retryState, bulkWriteBatch);
});
}
validateWriteRequests(connectionDescription, bypassDocumentValidation, writeRequests, writeConcern);
if (writeConcern.isAcknowledged() || serverIsAtLeastVersionThreeDotSix(connectionDescription)) {
if (!bulkWriteTracker.batch().isPresent()) {
BulkWriteTracker.attachNew(retryState, BulkWriteBatch.createBulkWriteBatch(namespace, source.getServerDescription(), connectionDescription, ordered, writeConcern, bypassDocumentValidation, retryWrites, writeRequests, sessionContext));
}
logRetryExecute(retryState);
return executeBulkWriteBatch(retryState, binding, connection, maxWireVersion);
} else {
retryState.markAsLastAttempt();
return executeLegacyBatches(binding, connection);
}
});
});
try {
return retryingBulkWrite.get();
} catch (MongoException e) {
throw transformWriteException(e);
}
}
Aggregations