Search in sources :

Example 1 with AsyncCallbackLoop

use of com.mongodb.internal.async.function.AsyncCallbackLoop 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);
        }
    });
}
Also used : LoopState(com.mongodb.internal.async.function.LoopState) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) LoopState(com.mongodb.internal.async.function.LoopState) WriteRequest(com.mongodb.internal.bulk.WriteRequest) CommandOperationHelper.addRetryableWriteErrorLabel(com.mongodb.internal.operation.CommandOperationHelper.addRetryableWriteErrorLabel) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) MongoWriteConcernWithResponseException(com.mongodb.internal.connection.MongoWriteConcernWithResponseException) ProtocolHelper(com.mongodb.internal.connection.ProtocolHelper) ConnectionDescription(com.mongodb.connection.ConnectionDescription) BsonArray(org.bson.BsonArray) OperationHelper.validateWriteRequests(com.mongodb.internal.operation.OperationHelper.validateWriteRequests) OperationHelper.withSourceAndConnection(com.mongodb.internal.operation.OperationHelper.withSourceAndConnection) MongoException(com.mongodb.MongoException) AsyncCallbackSupplier(com.mongodb.internal.async.function.AsyncCallbackSupplier) Set(java.util.Set) Collectors(java.util.stream.Collectors) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) ServerVersionHelper.serverIsAtLeastVersionThreeDotSix(com.mongodb.internal.operation.ServerVersionHelper.serverIsAtLeastVersionThreeDotSix) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) REPLACE(com.mongodb.internal.bulk.WriteRequest.Type.REPLACE) RetryState(com.mongodb.internal.async.function.RetryState) List(java.util.List) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) Optional(java.util.Optional) RetryingSyncSupplier(com.mongodb.internal.async.function.RetryingSyncSupplier) InsertRequest(com.mongodb.internal.bulk.InsertRequest) RetryingAsyncCallbackSupplier(com.mongodb.internal.async.function.RetryingAsyncCallbackSupplier) CommandOperationHelper.logRetryExecute(com.mongodb.internal.operation.CommandOperationHelper.logRetryExecute) CommandOperationHelper.exceptionTransformingCallback(com.mongodb.internal.operation.CommandOperationHelper.exceptionTransformingCallback) ErrorHandlingResultCallback.errorHandlingCallback(com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback) BsonString(org.bson.BsonString) Supplier(java.util.function.Supplier) BsonDocument(org.bson.BsonDocument) LOGGER(com.mongodb.internal.operation.OperationHelper.LOGGER) Connection(com.mongodb.internal.connection.Connection) NoOpFieldNameValidator(com.mongodb.internal.validator.NoOpFieldNameValidator) WriteBinding(com.mongodb.internal.binding.WriteBinding) Assertions(com.mongodb.assertions.Assertions) WriteConcernResult(com.mongodb.WriteConcernResult) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) AsyncWriteBinding(com.mongodb.internal.binding.AsyncWriteBinding) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) SessionContext(com.mongodb.internal.session.SessionContext) FieldNameValidator(org.bson.FieldNameValidator) OperationHelper.validateWriteRequestsAndCompleteIfInvalid(com.mongodb.internal.operation.OperationHelper.validateWriteRequestsAndCompleteIfInvalid) INSERT(com.mongodb.internal.bulk.WriteRequest.Type.INSERT) MongoNamespace(com.mongodb.MongoNamespace) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) OperationHelper.isRetryableWrite(com.mongodb.internal.operation.OperationHelper.isRetryableWrite) CommandOperationHelper.transformWriteException(com.mongodb.internal.operation.CommandOperationHelper.transformWriteException) Assertions.isTrueArgument(com.mongodb.assertions.Assertions.isTrueArgument) Assertions.assertTrue(com.mongodb.assertions.Assertions.assertTrue) OperationHelper.withAsyncSourceAndConnection(com.mongodb.internal.operation.OperationHelper.withAsyncSourceAndConnection) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) Nullable(com.mongodb.lang.Nullable) WriteConcern(com.mongodb.WriteConcern) UPDATE(com.mongodb.internal.bulk.WriteRequest.Type.UPDATE) AsyncConnection(com.mongodb.internal.connection.AsyncConnection) AttachmentKeys(com.mongodb.internal.operation.retry.AttachmentKeys) WriteConcernResult(com.mongodb.WriteConcernResult) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest)

Example 2 with AsyncCallbackLoop

use of com.mongodb.internal.async.function.AsyncCallbackLoop in project mongo-java-driver by mongodb.

the class MixedBulkWriteOperation method executeBulkWriteBatchAsync.

private void executeBulkWriteBatchAsync(final RetryState retryState, final AsyncWriteBinding binding, final AsyncConnection connection, final int maxWireVersion, final SingleResultCallback<BulkWriteResult> callback) {
    LoopState loopState = new LoopState();
    AsyncCallbackRunnable loop = new AsyncCallbackLoop(loopState, iterationCallback -> {
        BulkWriteTracker currentBulkWriteTracker = retryState.attachment(AttachmentKeys.bulkWriteTracker()).orElseThrow(Assertions::fail);
        loopState.attach(AttachmentKeys.bulkWriteTracker(), currentBulkWriteTracker, true);
        BulkWriteBatch currentBatch = currentBulkWriteTracker.batch().orElseThrow(Assertions::fail);
        if (loopState.breakAndCompleteIf(() -> !currentBatch.shouldProcessBatch(), iterationCallback)) {
            return;
        }
        executeCommandAsync(binding, connection, currentBatch, (result, t) -> {
            if (t == null) {
                if (currentBatch.getRetryWrites() && !binding.getSessionContext().hasActiveTransaction()) {
                    MongoException writeConcernBasedError = ProtocolHelper.createSpecialException(result, connection.getDescription().getServerAddress(), "errMsg");
                    if (writeConcernBasedError != null) {
                        if (currentBulkWriteTracker.lastAttempt()) {
                            addRetryableWriteErrorLabel(writeConcernBasedError, maxWireVersion);
                            addErrorLabelsToWriteConcern(result.getDocument("writeConcernError"), writeConcernBasedError.getErrorLabels());
                        } else if (CommandOperationHelper.shouldAttemptToRetryWrite(retryState, writeConcernBasedError)) {
                            iterationCallback.onResult(null, new MongoWriteConcernWithResponseException(writeConcernBasedError, result));
                            return;
                        }
                    }
                }
                currentBatch.addResult(result);
                BulkWriteTracker.attachNext(retryState, currentBatch);
                iterationCallback.onResult(null, null);
            } else {
                if (t instanceof MongoException) {
                    MongoException exception = (MongoException) t;
                    if (!(retryState.isFirstAttempt() || (exception instanceof MongoWriteConcernWithResponseException))) {
                        addRetryableWriteErrorLabel(exception, maxWireVersion);
                    }
                }
                iterationCallback.onResult(null, t);
            }
        });
    });
    loop.run((voidResult, t) -> {
        if (t != null) {
            callback.onResult(null, t);
        } else {
            BulkWriteResult result;
            try {
                result = loopState.attachment(AttachmentKeys.bulkWriteTracker()).flatMap(BulkWriteTracker::batch).orElseThrow(Assertions::fail).getResult();
            } catch (Throwable loopResultT) {
                if (loopResultT instanceof MongoException) {
                    retryState.markAsLastAttempt();
                }
                callback.onResult(null, loopResultT);
                return;
            }
            callback.onResult(result, null);
        }
    });
}
Also used : LoopState(com.mongodb.internal.async.function.LoopState) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) MongoWriteConcernWithResponseException(com.mongodb.internal.connection.MongoWriteConcernWithResponseException) MongoException(com.mongodb.MongoException) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) Assertions(com.mongodb.assertions.Assertions) BulkWriteResult(com.mongodb.bulk.BulkWriteResult)

Aggregations

MongoException (com.mongodb.MongoException)2 Assertions (com.mongodb.assertions.Assertions)2 BulkWriteResult (com.mongodb.bulk.BulkWriteResult)2 AsyncCallbackLoop (com.mongodb.internal.async.function.AsyncCallbackLoop)2 AsyncCallbackRunnable (com.mongodb.internal.async.function.AsyncCallbackRunnable)2 LoopState (com.mongodb.internal.async.function.LoopState)2 MongoWriteConcernWithResponseException (com.mongodb.internal.connection.MongoWriteConcernWithResponseException)2 MongoBulkWriteException (com.mongodb.MongoBulkWriteException)1 MongoNamespace (com.mongodb.MongoNamespace)1 WriteConcern (com.mongodb.WriteConcern)1 WriteConcernResult (com.mongodb.WriteConcernResult)1 Assertions.assertTrue (com.mongodb.assertions.Assertions.assertTrue)1 Assertions.isTrueArgument (com.mongodb.assertions.Assertions.isTrueArgument)1 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)1 ConnectionDescription (com.mongodb.connection.ConnectionDescription)1 ErrorHandlingResultCallback.errorHandlingCallback (com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback)1 SingleResultCallback (com.mongodb.internal.async.SingleResultCallback)1 AsyncCallbackSupplier (com.mongodb.internal.async.function.AsyncCallbackSupplier)1 RetryState (com.mongodb.internal.async.function.RetryState)1 RetryingAsyncCallbackSupplier (com.mongodb.internal.async.function.RetryingAsyncCallbackSupplier)1