use of com.mongodb.internal.binding.AsyncWriteBinding in project mongo-java-driver by mongodb.
the class CommandOperationHelper method executeRetryableWriteAsync.
static <T, R> void executeRetryableWriteAsync(final AsyncWriteBinding binding, final String database, final ReadPreference readPreference, final FieldNameValidator fieldNameValidator, final Decoder<T> commandResultDecoder, final CommandCreator commandCreator, final CommandWriteTransformerAsync<T, R> transformer, final Function<BsonDocument, BsonDocument> retryCommandModifier, final SingleResultCallback<R> callback) {
RetryState retryState = initialRetryState(true);
binding.retain();
AsyncCallbackSupplier<R> asyncWrite = CommandOperationHelper.<R>decorateWriteWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
boolean firstAttempt = retryState.isFirstAttempt();
if (!firstAttempt && binding.getSessionContext().hasActiveTransaction()) {
binding.getSessionContext().clearTransactionContext();
}
withAsyncSourceAndConnection(binding::getWriteConnectionSource, true, funcCallback, (source, connection, releasingCallback) -> {
int maxWireVersion = connection.getDescription().getMaxWireVersion();
SingleResultCallback<R> addingRetryableLabelCallback = firstAttempt ? releasingCallback : addingRetryableLabelCallback(releasingCallback, maxWireVersion);
if (retryState.breakAndCompleteIfRetryAnd(() -> !canRetryWrite(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()), addingRetryableLabelCallback)) {
return;
}
BsonDocument command;
try {
command = retryState.attachment(AttachmentKeys.command()).map(previousAttemptCommand -> {
assertFalse(firstAttempt);
return retryCommandModifier.apply(previousAttemptCommand);
}).orElseGet(() -> commandCreator.create(source.getServerDescription(), connection.getDescription()));
// attach `maxWireVersion`, `retryableCommandFlag` ASAP because they are used to check whether we should retry
retryState.attach(AttachmentKeys.maxWireVersion(), maxWireVersion, true).attach(AttachmentKeys.retryableCommandFlag(), isRetryWritesEnabled(command), true).attach(AttachmentKeys.commandDescriptionSupplier(), command::getFirstKey, true).attach(AttachmentKeys.command(), command, false);
logRetryExecute(retryState);
} catch (Throwable t) {
addingRetryableLabelCallback.onResult(null, t);
return;
}
connection.commandAsync(database, command, fieldNameValidator, readPreference, commandResultDecoder, binding.getSessionContext(), binding.getServerApi(), binding.getRequestContext(), transformingWriteCallback(transformer, connection, addingRetryableLabelCallback));
});
}).whenComplete(binding::release);
asyncWrite.get(exceptionTransformingCallback(errorHandlingCallback(callback, LOGGER)));
}
use of com.mongodb.internal.binding.AsyncWriteBinding in project mongo-java-driver by mongodb.
the class MixedBulkWriteOperation method executeAsync.
public void executeAsync(final AsyncWriteBinding binding, final SingleResultCallback<BulkWriteResult> callback) {
// see the comment in `execute(WriteBinding)` explaining the manual tracking of attempts
RetryState retryState = new RetryState();
BulkWriteTracker.attachNew(retryState, retryWrites);
binding.retain();
AsyncCallbackSupplier<BulkWriteResult> retryingBulkWrite = this.<BulkWriteResult>decorateWriteWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
withAsyncSourceAndConnection(binding::getWriteConnectionSource, true, funcCallback, (source, connection, releasingCallback) -> {
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)) {
Throwable prospectiveFailedResult = retryState.exception().orElse(null);
if (retryState.breakAndCompleteIfRetryAnd(() -> !(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException), releasingCallback)) {
return;
}
bulkWriteTracker.batch().ifPresent(bulkWriteBatch -> {
assertTrue(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException);
bulkWriteBatch.addResult((BsonDocument) ((MongoWriteConcernWithResponseException) prospectiveFailedResult).getResponse());
BulkWriteTracker.attachNext(retryState, bulkWriteBatch);
});
}
if (validateWriteRequestsAndCompleteIfInvalid(connectionDescription, bypassDocumentValidation, writeRequests, writeConcern, releasingCallback)) {
return;
}
if (writeConcern.isAcknowledged() || serverIsAtLeastVersionThreeDotSix(connectionDescription)) {
try {
if (!bulkWriteTracker.batch().isPresent()) {
BulkWriteTracker.attachNew(retryState, BulkWriteBatch.createBulkWriteBatch(namespace, source.getServerDescription(), connectionDescription, ordered, writeConcern, bypassDocumentValidation, retryWrites, writeRequests, sessionContext));
}
} catch (Throwable t) {
releasingCallback.onResult(null, t);
return;
}
logRetryExecute(retryState);
executeBulkWriteBatchAsync(retryState, binding, connection, maxWireVersion, releasingCallback);
} else {
retryState.markAsLastAttempt();
executeLegacyBatchesAsync(binding, connection, releasingCallback);
}
});
}).whenComplete(binding::release);
retryingBulkWrite.get(exceptionTransformingCallback(errorHandlingCallback(callback, LOGGER)));
}
use of com.mongodb.internal.binding.AsyncWriteBinding in project mongo-java-driver by mongodb.
the class MixedBulkWriteOperation method executeLegacyBatchesAsync.
private void executeLegacyBatchesAsync(final AsyncWriteBinding binding, final AsyncConnection connection, final SingleResultCallback<BulkWriteResult> callback) {
List<? extends WriteRequest> writeRequests = getWriteRequests();
LoopState loopState = new LoopState();
AsyncCallbackRunnable loop = new AsyncCallbackLoop(loopState, iterationCallback -> {
int i = loopState.iteration();
if (loopState.breakAndCompleteIf(() -> i == writeRequests.size(), iterationCallback)) {
return;
}
WriteRequest writeRequest = writeRequests.get(i);
SingleResultCallback<WriteConcernResult> commandCallback = (ignored, t) -> iterationCallback.onResult(null, t);
if (writeRequest.getType() == INSERT) {
connection.insertAsync(getNamespace(), isOrdered(), (InsertRequest) writeRequest, binding.getRequestContext(), commandCallback);
} else if (writeRequest.getType() == UPDATE || writeRequest.getType() == REPLACE) {
connection.updateAsync(getNamespace(), isOrdered(), (UpdateRequest) writeRequest, binding.getRequestContext(), commandCallback);
} else {
connection.deleteAsync(getNamespace(), isOrdered(), (DeleteRequest) writeRequest, binding.getRequestContext(), commandCallback);
}
});
loop.run((voidResult, t) -> {
if (t != null) {
callback.onResult(null, t);
} else {
callback.onResult(BulkWriteResult.unacknowledged(), null);
}
});
}
Aggregations