<commit_before>/*
 * Copyright 2008-present MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mongodb.reactivestreams.client.internal;

import com.mongodb.MongoClientException;
import com.mongodb.MongoException;
import com.mongodb.MongoInternalException;
import com.mongodb.MongoQueryException;
import com.mongodb.MongoSocketException;
import com.mongodb.MongoTimeoutException;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.internal.async.client.ClientSessionBinding;
import com.mongodb.internal.binding.AsyncClusterAwareReadWriteBinding;
import com.mongodb.internal.binding.AsyncClusterBinding;
import com.mongodb.internal.binding.AsyncReadWriteBinding;
import com.mongodb.internal.operation.AsyncReadOperation;
import com.mongodb.internal.operation.AsyncWriteOperation;
import com.mongodb.lang.Nullable;
import com.mongodb.reactivestreams.client.ClientSession;
import com.mongodb.reactivestreams.client.internal.crypt.Crypt;
import com.mongodb.reactivestreams.client.internal.crypt.CryptBinding;
import reactor.core.publisher.Mono;

import static com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL;
import static com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL;
import static com.mongodb.ReadPreference.primary;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback;

public class OperationExecutorImpl implements OperationExecutor {

    private final MongoClientImpl mongoClient;
    private final ClientSessionHelper clientSessionHelper;

    OperationExecutorImpl(final MongoClientImpl mongoClient, final ClientSessionHelper clientSessionHelper) {
        this.mongoClient = mongoClient;
        this.clientSessionHelper = clientSessionHelper;
    }

    @Override
    public <T> Mono<T> execute(final AsyncReadOperation<T> operation, final ReadPreference readPreference, final ReadConcern readConcern,
            @Nullable final ClientSession session) {
        notNull("operation", operation);
        notNull("readPreference", readPreference);
        notNull("readConcern", readConcern);
          return clientSessionHelper.withClientSession(session, this)
                .map(clientSession -> getReadWriteBinding(readPreference, readConcern, clientSession,
                                                              session == null && clientSession != null))
                .switchIfEmpty(Mono.fromCallable(() -> getReadWriteBinding(readPreference, readConcern, session, false)))
                .flatMap(binding -> {
                    if (session != null && session.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) {
                        binding.release();
                        throw new MongoClientException("Read preference in a transaction must be primary");
                    } else {
                        return Mono.<T>create(sink -> operation.executeAsync(binding, sinkToCallback(sink)))
                                .doOnTerminate(binding::release)
                                .doOnError((t) -> {
                                    labelException(session, t);
                                    unpinServerAddressOnTransientTransactionError(session, t);
                                });
                    }
                });<commit_msg>Return Mono.error in flatMap rather than throw an exception<commit_after>/*
 * Copyright 2008-present MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mongodb.reactivestreams.client.internal;

import com.mongodb.MongoClientException;
import com.mongodb.MongoException;
import com.mongodb.MongoInternalException;
import com.mongodb.MongoQueryException;
import com.mongodb.MongoSocketException;
import com.mongodb.MongoTimeoutException;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.internal.async.client.ClientSessionBinding;
import com.mongodb.internal.binding.AsyncClusterAwareReadWriteBinding;
import com.mongodb.internal.binding.AsyncClusterBinding;
import com.mongodb.internal.binding.AsyncReadWriteBinding;
import com.mongodb.internal.operation.AsyncReadOperation;
import com.mongodb.internal.operation.AsyncWriteOperation;
import com.mongodb.lang.Nullable;
import com.mongodb.reactivestreams.client.ClientSession;
import com.mongodb.reactivestreams.client.internal.crypt.Crypt;
import com.mongodb.reactivestreams.client.internal.crypt.CryptBinding;
import reactor.core.publisher.Mono;

import static com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL;
import static com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL;
import static com.mongodb.ReadPreference.primary;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback;

public class OperationExecutorImpl implements OperationExecutor {

    private final MongoClientImpl mongoClient;
    private final ClientSessionHelper clientSessionHelper;

    OperationExecutorImpl(final MongoClientImpl mongoClient, final ClientSessionHelper clientSessionHelper) {
        this.mongoClient = mongoClient;
        this.clientSessionHelper = clientSessionHelper;
    }

    @Override
    public <T> Mono<T> execute(final AsyncReadOperation<T> operation, final ReadPreference readPreference, final ReadConcern readConcern,
            @Nullable final ClientSession session) {
        notNull("operation", operation);
        notNull("readPreference", readPreference);
        notNull("readConcern", readConcern);
          return clientSessionHelper.withClientSession(session, this)
                .map(clientSession -> getReadWriteBinding(readPreference, readConcern, clientSession,
                                                              session == null && clientSession != null))
                .switchIfEmpty(Mono.fromCallable(() -> getReadWriteBinding(readPreference, readConcern, session, false)))
                .flatMap(binding -> {
                    if (session != null && session.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) {
                        binding.release();
                        return Mono.error(new MongoClientException("Read preference in a transaction must be primary"));
                    } else {
                        return Mono.<T>create(sink -> operation.executeAsync(binding, sinkToCallback(sink)))
                                .doOnTerminate(binding::release)
                                .doOnError((t) -> {
                                    labelException(session, t);
                                    unpinServerAddressOnTransientTransactionError(session, t);
                                });
                    }
                });
{'fraction_non_alphanumeric': 0.08047576869543212, 'fraction_numerical': 0.002024547640136657, 'mean_word_length': 3.2609164420485177, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3408817', 'n_tokens_mistral': 2060, 'n_tokens_neox': 1925, 'n_words': 464}