kamalcph commented on code in PR #16602:
URL: https://github.com/apache/kafka/pull/16602#discussion_r1749857677


##########
core/src/main/scala/kafka/server/DelayedRemoteListOffsets.scala:
##########
@@ -0,0 +1,174 @@
+/**
+ * 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 kafka.server
+
+import com.yammer.metrics.core.Meter
+import kafka.log.AsyncOffsetReadFutureHolder
+import kafka.utils.Implicits._
+import kafka.utils.Pool
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.errors.ApiException
+import 
org.apache.kafka.common.message.ListOffsetsResponseData.{ListOffsetsPartitionResponse,
 ListOffsetsTopicResponse}
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.record.FileRecords.TimestampAndOffset
+import org.apache.kafka.common.requests.ListOffsetsResponse
+import org.apache.kafka.server.metrics.KafkaMetricsGroup
+
+import java.util.concurrent.TimeUnit
+import scala.collection.{Map, mutable}
+import scala.jdk.CollectionConverters._
+
+case class ListOffsetsPartitionStatus(var responseOpt: 
Option[ListOffsetsPartitionResponse] = None,
+                                      futureHolderOpt: 
Option[AsyncOffsetReadFutureHolder[Either[Exception, 
Option[TimestampAndOffset]]]] = None,
+                                      lastFetchableOffset: Option[Long] = None,
+                                      maybeOffsetsError: Option[ApiException] 
= None) {
+  @volatile var completed = false
+
+  override def toString: String = {
+    s"[responseOpt: $responseOpt, lastFetchableOffset: $lastFetchableOffset, " 
+
+      s"maybeOffsetsError: $maybeOffsetsError, completed: $completed]"
+  }
+}
+
+case class ListOffsetsMetadata(statusByPartition: mutable.Map[TopicPartition, 
ListOffsetsPartitionStatus]) {
+
+  override def toString: String = {
+    s"ListOffsetsMetadata(statusByPartition=$statusByPartition)"
+  }
+}
+
+class DelayedRemoteListOffsets(delayMs: Long,
+                               version: Int,
+                               metadata: ListOffsetsMetadata,
+                               responseCallback: 
List[ListOffsetsTopicResponse] => Unit) extends DelayedOperation(delayMs) {
+
+  // Mark the status as completed, if there is no async task to track.
+  // If there is a task to track, then build the response as REQUEST_TIMED_OUT 
by default.
+  metadata.statusByPartition.forKeyValue { (topicPartition, status) =>
+    status.completed = status.futureHolderOpt.isEmpty
+    if (status.futureHolderOpt.isDefined) {
+      status.responseOpt = Some(buildErrorResponse(Errors.REQUEST_TIMED_OUT, 
topicPartition.partition()))
+    }
+    trace(s"Initial partition status for $topicPartition is $status")
+  }
+
+  /**
+   * Call-back to execute when a delayed operation gets expired and hence 
forced to complete.
+   */
+  override def onExpiration(): Unit = {
+    metadata.statusByPartition.forKeyValue { (topicPartition, status) =>
+      if (!status.completed) {
+        debug(s"Expiring list offset request for partition $topicPartition 
with status $status")
+        status.futureHolderOpt.foreach(futureHolder => 
futureHolder.jobFuture.cancel(true))
+        DelayedRemoteListOffsetsMetrics.recordExpiration(topicPartition)
+      }
+    }
+  }
+
+  /**
+   * Process for completing an operation; This function needs to be defined
+   * in subclasses and will be called exactly once in forceComplete()
+   */
+  override def onComplete(): Unit = {
+    val responseTopics = metadata.statusByPartition.groupBy(e => 
e._1.topic()).map {
+      case (topic, status) =>
+        new 
ListOffsetsTopicResponse().setName(topic).setPartitions(status.values.flatMap(s 
=> s.responseOpt).toList.asJava)
+    }.toList
+    responseCallback(responseTopics)
+  }
+
+  /**
+   * Try to complete the delayed operation by first checking if the operation
+   * can be completed by now. If yes execute the completion logic by calling
+   * forceComplete() and return true iff forceComplete returns true; otherwise 
return false
+   *
+   * This function needs to be defined in subclasses
+   */
+  override def tryComplete(): Boolean = {
+    var completable = true
+    metadata.statusByPartition.forKeyValue { (partition, status) =>
+      if (!status.completed) {
+        status.futureHolderOpt.foreach { futureHolder =>
+          if (futureHolder.taskFuture.isDone) {
+            val response = futureHolder.taskFuture.get() match {
+              case Left(e) =>
+                buildErrorResponse(Errors.forException(e), 
partition.partition())
+
+              case Right(None) =>
+                val error = status.maybeOffsetsError
+                  .map(e => if (version >= 5) Errors.forException(e) else 
Errors.LEADER_NOT_AVAILABLE)
+                  .getOrElse(Errors.NONE)
+                buildErrorResponse(error, partition.partition())
+
+              case Right(Some(found)) =>
+                var partitionResponse = buildErrorResponse(Errors.NONE, 
partition.partition())
+                if (status.lastFetchableOffset.isDefined && found.offset >= 
status.lastFetchableOffset.get) {
+                  if (status.maybeOffsetsError.isDefined) {
+                    val error = if (version >= 5) 
Errors.forException(status.maybeOffsetsError.get) else 
Errors.LEADER_NOT_AVAILABLE
+                    partitionResponse.setErrorCode(error.code())
+                  }

Review Comment:
   The original logic returns `empty` when  lastFetchableOffset <= found and 
maybeOffsetsError is undefined. If the result is empty, then we return 
(no-error, -1, -1L) from KafkaApis.scala:
   
   1. 
https://sourcegraph.com/github.com/apache/kafka@049b7cde4c2f75a6af164d7308318e29878a2eca/-/blob/core/src/main/scala/kafka/cluster/Partition.scala?L1617
   2. 
https://sourcegraph.com/github.com/apache/kafka@trunk/-/blob/core/src/main/scala/kafka/server/KafkaApis.scala?L1218



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

Reply via email to