aweisberg commented on code in PR #3395:
URL: https://github.com/apache/cassandra/pull/3395#discussion_r1706132013


##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.cassandra.service.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static 
org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static 
org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static 
org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static 
org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and 
blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and 
splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+    private static ConsistencyLevel consistencyLevelForCommit(Collection<? 
extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+    {
+        // Null means no specific consistency behavior is required from 
Accord, it's functionally similar to ANY
+        // if you aren't reading the result back via Accord
+        if (consistencyLevel == null)
+            return null;
+
+        for (IMutation mutation : mutations)
+        {
+            for (TableId tableId : mutation.getTableIds())
+            {
+                TransactionalMode mode = 
Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+                // commitCLForStrategy should return either null or the 
supplied consistency level
+                // in which case we will commit everything at that CL since 
Accord doesn't support per table
+                // commit consistency
+                ConsistencyLevel commitCL = 
mode.commitCLForStrategy(consistencyLevel);
+                if (commitCL != null)
+                    return commitCL;
+            }
+        }
+        return null;
+    }
+
+    public static <T extends IMutation> Pair<List<T>, List<T>> 
splitMutationsIntoAccordAndNormal(List<T> mutations)
+    {
+        ClusterMetadata cm = ClusterMetadata.current();
+        List<T> accordMutations = null;
+        List<T> normalMutations = null;
+        for (int i=0,mi=mutations.size(); i<mi; i++)
+        {
+            T mutation = mutations.get(i);
+            Pair<T, T> accordAndNormalMutation = 
splitMutationIntoAccordAndNormal(mutation, cm);
+            T accordMutation = accordAndNormalMutation.left;
+            if (accordMutation != null)
+            {
+                if (accordMutations == null)
+                    accordMutations = new 
ArrayList<>(Math.min(mutations.size(), 10));
+                accordMutations.add(accordMutation);
+            }
+            T normalMutation = accordAndNormalMutation.right;
+            if (normalMutation != null)
+            {
+                if (normalMutations == null)
+                    normalMutations = new 
ArrayList<>(Math.min(mutations.size(), 10));
+                normalMutations.add(normalMutation);
+            }
+        }
+        return Pair.create(accordMutations, normalMutations);
+    }
+
+    public static <T extends IMutation> Pair<T, T> 
splitMutationIntoAccordAndNormal(T mutation, ClusterMetadata cm)
+    {
+        if (mutation.allowPotentialTransactionConflicts())
+            return Pair.create(null, mutation);
+
+        Token token = mutation.key().getToken();
+        Predicate<TableId> isAccordUpdate = tableId -> {
+            TableMetadata tm = getTableMetadata(cm, tableId);
+            if (tm == null)
+                return false;
+            return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+        };
+
+        T accordMutation = (T)mutation.filter(isAccordUpdate);
+        T normalMutation = (T)mutation.filter(not(isAccordUpdate));
+        for (PartitionUpdate pu : mutation.getPartitionUpdates())
+            checkState((accordMutation == null ? false : 
accordMutation.hasUpdateForTable(pu.metadata().id))
+                       || (normalMutation == null ? false : 
normalMutation.hasUpdateForTable(pu.metadata().id)),
+                       "All partition updates should still be present after 
splitting");
+        return Pair.create(accordMutation, normalMutation);
+    }
+
+    public static Pair<List<? extends IMutation>, 
List<WriteResponseHandlerWrapper>> 
splitWrappersIntoAccordAndNormal(List<WriteResponseHandlerWrapper> wrappers)
+    {
+        ClusterMetadata cm = ClusterMetadata.current();
+        List<IMutation> accordMutations = null;
+        List<WriteResponseHandlerWrapper> normalWrappers = null;
+        for (int i=0,mi=wrappers.size(); i<mi; i++)
+        {
+            WriteResponseHandlerWrapper wrapper = wrappers.get(i);
+            Pair<IMutation, WriteResponseHandlerWrapper> 
accordAndNormalMutation = splitWrapperIntoAccordAndNormal(wrapper, cm);
+            IMutation accordMutation = accordAndNormalMutation.left;
+            if (accordMutation != null)
+            {
+                if (accordMutations == null)
+                    accordMutations = new 
ArrayList<>(Math.min(wrappers.size(), 10));
+                accordMutations.add(accordMutation);
+            }
+            WriteResponseHandlerWrapper normalWrapper = 
accordAndNormalMutation.right;
+            if (normalWrapper != null)
+            {
+                if (normalWrappers == null)
+                    normalWrappers = new ArrayList<>(Math.min(wrappers.size(), 
10));
+                normalWrappers.add(normalWrapper);
+            }
+        }
+        return Pair.create(accordMutations, normalWrappers);
+    }
+
+    private static Pair<IMutation, WriteResponseHandlerWrapper> 
splitWrapperIntoAccordAndNormal(WriteResponseHandlerWrapper wrapper, 
ClusterMetadata cm)
+    {
+        Mutation mutation = wrapper.mutation;
+        if (mutation.allowPotentialTransactionConflicts())
+            return Pair.create(null, wrapper);
+
+        Token token = mutation.key().getToken();
+        Predicate<TableId> isAccordUpdate = tableId -> {
+            TableMetadata tm = getTableMetadata(cm, tableId);
+            if (tm == null)
+                return false;
+            return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+        };
+
+        IMutation accordMutation = mutation.filter(isAccordUpdate);
+        Mutation normalMutation = mutation.filter(not(isAccordUpdate));
+        for (PartitionUpdate pu : mutation.getPartitionUpdates())
+            checkState((accordMutation == null ? false : 
accordMutation.hasUpdateForTable(pu.metadata().id))
+                       || (normalMutation == null ? false : 
normalMutation.hasUpdateForTable(pu.metadata().id)),
+                       "All partition updates should still be present after 
splitting");
+        if (accordMutation == null)
+            return Pair.create(null, wrapper);
+        if (normalMutation == null)
+            return Pair.create( accordMutation, null);
+        // Since this now depends on an Accord txn need to wait for that to 
complete first
+        wrapper.handler.deferCleanup();
+        return Pair.create(accordMutation, new 
WriteResponseHandlerWrapper(wrapper.handler, normalMutation));
+    }
+
+    public static Pair<TxnId, Future<TxnResult>> 
mutateWithAccordAsync(Mutation mutation, @Nullable ConsistencyLevel 
consistencyLevel, long queryStartNanoTime)
+    {
+        return mutateWithAccordAsync(ImmutableList.of(mutation), 
consistencyLevel, queryStartNanoTime);
+    }
+
+
+    public static Pair<TxnId, Future<TxnResult>> 
mutateWithAccordAsync(Collection<? extends IMutation> mutations, @Nullable 
ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+    {
+        int fragmentIndex = 0;
+        List<TxnWrite.Fragment> fragments = new ArrayList<>(mutations.size());
+        List<PartitionKey> partitionKeys = new ArrayList<>(mutations.size());
+        for (IMutation mutation : mutations)
+        {
+            for (PartitionUpdate update : mutation.getPartitionUpdates())
+            {
+                PartitionKey pk = PartitionKey.of(update);
+                partitionKeys.add(pk);
+                fragments.add(new TxnWrite.Fragment(PartitionKey.of(update), 
fragmentIndex++, update, TxnReferenceOperations.empty()));
+            }
+        }
+        // Potentially ignore commit consistency level if the strategy 
specifies accord and not migration
+        ConsistencyLevel clForCommit = consistencyLevelForCommit(mutations, 
consistencyLevel);
+        TxnUpdate update = new TxnUpdate(fragments, TxnCondition.none(), 
clForCommit, true);
+        Txn.InMemory txn = new Txn.InMemory(Keys.of(partitionKeys), 
TxnRead.EMPTY, TxnQuery.NONE, update);
+        IAccordService accordService = AccordService.instance();
+        return accordService.coordinateAsync(txn, consistencyLevel, 
queryStartNanoTime);
+    }
+
+    public static void dispatchMutationsWithRetryOnDifferentSystem(List<? 
extends IMutation> mutations, ConsistencyLevel consistencyLevel, long 
queryStartNanoTime)

Review Comment:
   We can, I was trying to not further explode the amount of code that is in 
`StorageProxy`. Is there any way we can accomplish that?
   
   I actually want to reduce the scope of the change for `mutateAtomic` that is 
in `StorageProxy` as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to