You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2021/02/25 05:22:26 UTC

[GitHub] [kafka] chia7712 commented on a change in pull request #10206: KAFKA-12369; Implement `ListTransactions` API

chia7712 commented on a change in pull request #10206:
URL: https://github.com/apache/kafka/pull/10206#discussion_r582545612



##########
File path: clients/src/main/java/org/apache/kafka/common/requests/ListTransactionsRequest.java
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.kafka.common.requests;
+
+import org.apache.kafka.common.message.ListTransactionsRequestData;
+import org.apache.kafka.common.message.ListTransactionsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+
+public class ListTransactionsRequest extends AbstractRequest {
+    public static class Builder extends AbstractRequest.Builder<ListTransactionsRequest> {
+        public final ListTransactionsRequestData data;
+
+        public Builder(ListTransactionsRequestData data) {
+            super(ApiKeys.LIST_TRANSACTIONS);
+            this.data = data;
+        }
+
+        @Override
+        public ListTransactionsRequest build(short version) {
+            return new ListTransactionsRequest(data, version);
+        }
+
+        @Override
+        public String toString() {
+            return data.toString();
+        }
+    }
+
+    private final ListTransactionsRequestData data;
+
+    private ListTransactionsRequest(ListTransactionsRequestData data, short version) {
+        super(ApiKeys.LIST_TRANSACTIONS, version);
+        this.data = data;
+    }
+
+    public ListTransactionsRequestData data() {
+        return data;
+    }
+
+    @Override
+    public ListTransactionsResponse getErrorResponse(int throttleTimeMs, Throwable e) {
+        Errors error = Errors.forException(e);
+        ListTransactionsResponseData response = new ListTransactionsResponseData()

Review comment:
       `throttleTimeMs` is neglected.

##########
File path: core/src/main/scala/kafka/coordinator/transaction/TransactionStateManager.scala
##########
@@ -223,6 +224,46 @@ class TransactionStateManager(brokerId: Int,
       throw new IllegalStateException(s"Unexpected empty transaction metadata returned while putting $txnMetadata")))
   }
 
+  def listTransactionStates(
+    filterProducerIds: Set[Long],
+    filterStateNames: Set[String]
+  ): Either[Errors, List[ListTransactionsResponseData.TransactionState]] = {
+    inReadLock(stateLock) {
+      if (loadingPartitions.nonEmpty) {
+        Left(Errors.COORDINATOR_LOAD_IN_PROGRESS)
+      } else {
+        val filterStates = filterStateNames.flatMap(TransactionState.fromName)
+        val states = mutable.ListBuffer.empty[ListTransactionsResponseData.TransactionState]
+
+        def shouldInclude(txnMetadata: TransactionMetadata): Boolean = {
+          if (txnMetadata.state == Dead) {
+            false
+          } else if (filterProducerIds.nonEmpty && !filterProducerIds.contains(txnMetadata.producerId)) {
+            false
+          } else if (filterStateNames.nonEmpty && !filterStates.contains(txnMetadata.state)) {
+            false
+          } else {
+            true
+          }
+        }
+
+        transactionMetadataCache.foreach { case (_, cache) =>
+          cache.metadataPerTransactionalId.values.foreach { txnMetadata =>
+            txnMetadata.inLock {
+              if (shouldInclude(txnMetadata)) {
+                states += new ListTransactionsResponseData.TransactionState()
+                  .setTransactionalId(txnMetadata.transactionalId)
+                  .setProducerId(txnMetadata.producerId)
+                  .setTransactionState(txnMetadata.state.toString)

Review comment:
       `txnMetadata.state.toString` -> `txnMetadata.state.name`

##########
File path: core/src/main/scala/kafka/coordinator/transaction/TransactionMetadata.scala
##########
@@ -25,8 +25,50 @@ import org.apache.kafka.common.record.RecordBatch
 
 import scala.collection.{immutable, mutable}
 
+
+object TransactionState {
+  val AllStates = Set(
+    Empty,
+    Ongoing,
+    PrepareCommit,
+    PrepareAbort,
+    CompleteCommit,
+    CompleteAbort,
+    Dead,
+    PrepareEpochFence
+  )
+
+  def fromName(name: String): Option[TransactionState] = {

Review comment:
       How about 'AllStates.find(_.name == name)'?

##########
File path: core/src/main/scala/kafka/coordinator/transaction/TransactionStateManager.scala
##########
@@ -223,6 +224,46 @@ class TransactionStateManager(brokerId: Int,
       throw new IllegalStateException(s"Unexpected empty transaction metadata returned while putting $txnMetadata")))
   }
 
+  def listTransactionStates(
+    filterProducerIds: Set[Long],
+    filterStateNames: Set[String]
+  ): Either[Errors, List[ListTransactionsResponseData.TransactionState]] = {
+    inReadLock(stateLock) {
+      if (loadingPartitions.nonEmpty) {

Review comment:
       Maybe we can return error only if the expected partition ids are included by loading partitions?

##########
File path: core/src/main/scala/kafka/coordinator/transaction/TransactionStateManager.scala
##########
@@ -223,6 +224,46 @@ class TransactionStateManager(brokerId: Int,
       throw new IllegalStateException(s"Unexpected empty transaction metadata returned while putting $txnMetadata")))
   }
 
+  def listTransactionStates(
+    filterProducerIds: Set[Long],
+    filterStateNames: Set[String]
+  ): Either[Errors, List[ListTransactionsResponseData.TransactionState]] = {
+    inReadLock(stateLock) {
+      if (loadingPartitions.nonEmpty) {
+        Left(Errors.COORDINATOR_LOAD_IN_PROGRESS)
+      } else {
+        val filterStates = filterStateNames.flatMap(TransactionState.fromName)
+        val states = mutable.ListBuffer.empty[ListTransactionsResponseData.TransactionState]
+
+        def shouldInclude(txnMetadata: TransactionMetadata): Boolean = {
+          if (txnMetadata.state == Dead) {
+            false
+          } else if (filterProducerIds.nonEmpty && !filterProducerIds.contains(txnMetadata.producerId)) {
+            false
+          } else if (filterStateNames.nonEmpty && !filterStates.contains(txnMetadata.state)) {
+            false
+          } else {
+            true
+          }
+        }
+
+        transactionMetadataCache.foreach { case (_, cache) =>

Review comment:
       Could you use 'forKeyValue' instead of 'foreach'?

##########
File path: core/src/test/scala/unit/kafka/coordinator/transaction/TransactionMetadataTest.scala
##########
@@ -460,6 +460,43 @@ class TransactionMetadataTest {
     assertEquals(Left(Errors.PRODUCER_FENCED), result)
   }
 
+  @Test
+  def testTransactionStateIdAndNameMapping(): Unit = {
+    for (state <- TransactionState.AllStates) {
+      assertEquals(state, TransactionState.fromId(state.id))
+      assertEquals(state, TransactionState.fromName(state.name))

Review comment:
       assertEquals(state, TransactionState.fromName(state.name)*.get*)

##########
File path: core/src/main/scala/kafka/coordinator/transaction/TransactionStateManager.scala
##########
@@ -223,6 +224,46 @@ class TransactionStateManager(brokerId: Int,
       throw new IllegalStateException(s"Unexpected empty transaction metadata returned while putting $txnMetadata")))
   }
 
+  def listTransactionStates(
+    filterProducerIds: Set[Long],
+    filterStateNames: Set[String]
+  ): Either[Errors, List[ListTransactionsResponseData.TransactionState]] = {
+    inReadLock(stateLock) {
+      if (loadingPartitions.nonEmpty) {
+        Left(Errors.COORDINATOR_LOAD_IN_PROGRESS)
+      } else {
+        val filterStates = filterStateNames.flatMap(TransactionState.fromName)

Review comment:
       Should it produce exception if it include nonexistent state?

##########
File path: core/src/main/scala/kafka/coordinator/transaction/TransactionMetadata.scala
##########
@@ -25,8 +25,50 @@ import org.apache.kafka.common.record.RecordBatch
 
 import scala.collection.{immutable, mutable}
 
+
+object TransactionState {
+  val AllStates = Set(
+    Empty,
+    Ongoing,
+    PrepareCommit,
+    PrepareAbort,
+    CompleteCommit,
+    CompleteAbort,
+    Dead,
+    PrepareEpochFence
+  )
+
+  def fromName(name: String): Option[TransactionState] = {
+    name match {
+      case "Empty" => Some(Empty)
+      case "Ongoing" => Some(Ongoing)
+      case "PrepareCommit" => Some(PrepareCommit)
+      case "PrepareAbort" => Some(PrepareAbort)
+      case "CompleteCommit" => Some(CompleteCommit)
+      case "CompleteAbort" => Some(CompleteAbort)
+      case "PrepareEpochFence" => Some(PrepareEpochFence)
+      case "Dead" => Some(Dead)
+      case _ => None
+    }
+  }
+
+  def fromId(id: Byte): TransactionState = {

Review comment:
       How about 'AllStates.find(_.id == id)'?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org