package com.mongodb.internal.operation;
import com.mongodb.Function;
import com.mongodb.WriteConcern;
import com.mongodb.internal.async.SingleResultCallback;
import com.mongodb.connection.ConnectionDescription;
import com.mongodb.connection.ServerDescription;
import com.mongodb.internal.binding.AsyncWriteBinding;
import com.mongodb.internal.binding.WriteBinding;
import com.mongodb.internal.operation.CommandOperationHelper.CommandCreator;
import com.mongodb.internal.validator.NoOpFieldNameValidator;
import org.bson.BsonDocument;
import org.bson.BsonInt32;
import org.bson.codecs.BsonDocumentCodec;
import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback;
import static com.mongodb.internal.operation.CommandOperationHelper.executeRetryableCommand;
import static com.mongodb.internal.operation.CommandOperationHelper.writeConcernErrorTransformer;
import static com.mongodb.internal.operation.CommandOperationHelper.writeConcernErrorTransformerAsync;
import static com.mongodb.internal.operation.OperationHelper.LOGGER;
public abstract class TransactionOperation implements WriteOperation<Void>, AsyncWriteOperation<Void> {
private final WriteConcern writeConcern;
TransactionOperation(final WriteConcern writeConcern) {
this.writeConcern = notNull("writeConcern", writeConcern);
}
public WriteConcern getWriteConcern() {
return writeConcern;
}
@Override
public Void execute(final WriteBinding binding) {
isTrue("in transaction", binding.getSessionContext().hasActiveTransaction());
return executeRetryableCommand(binding, "admin", null, new NoOpFieldNameValidator(),
new BsonDocumentCodec(), getCommandCreator(), writeConcernErrorTransformer(), getRetryCommandModifier());
}
@Override
public void executeAsync(final AsyncWriteBinding binding, final SingleResultCallback<Void> callback) {
isTrue("in transaction", binding.getSessionContext().hasActiveTransaction());
executeRetryableCommand(binding, "admin", null, new NoOpFieldNameValidator(),
new BsonDocumentCodec(), getCommandCreator(), writeConcernErrorTransformerAsync(), getRetryCommandModifier(),
errorHandlingCallback(callback, LOGGER));
}
CommandCreator getCommandCreator() {
return new CommandCreator() {
@Override
public BsonDocument create(final ServerDescription serverDescription, final ConnectionDescription connectionDescription) {
BsonDocument command = new BsonDocument(getCommandName(), new BsonInt32(1));
if (!writeConcern.isServerDefault()) {
command.put("writeConcern", writeConcern.asDocument());
}
return command;
}
};
}
protected abstract String getCommandName();
protected abstract Function<BsonDocument, BsonDocument> getRetryCommandModifier();
}