You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "lianetm (via GitHub)" <gi...@apache.org> on 2023/08/29 14:22:01 UTC

[GitHub] [kafka] lianetm opened a new pull request, #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

lianetm opened a new pull request, #14308:
URL: https://github.com/apache/kafka/pull/14308

   Implementation of the `OffsetRequestsManager`, responsible for building requests and processing responses for requests related to partition offsets. 
   
   In this PR, the manager includes support for `ListOffset` requests, generated when the user makes any of the following consumer API calls:
   
   - beginningOffsets
   - endOffsets
   - offsetsForTimes
   
   All previous consumer API calls interact with the `OffsetsRequestsManager` by generating a `ListOffsetsApplicationEvent`.
   
   Includes tests to cover the new functionality and to ensure no API level changes are introduced.  
   
   This covers KAFKA-14965 and  KAFKA-15081.
   


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309322711


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(
+            Node node,
+            Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> targetTimes,
+            boolean requireTimestamps,
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests) {
+        ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder
+                .forConsumer(requireTimestamps, isolationLevel, false)
+                .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(targetTimes));
+
+        log.debug("Creating ListOffsetRequest {} for broker {} to reset positions", builder,
+                node);
+
+        NetworkClientDelegate.UnsentRequest unsentRequest = new NetworkClientDelegate.UnsentRequest(
+                builder,
+                Optional.ofNullable(node));
+        unsentRequests.add(unsentRequest);
+        CompletableFuture<ListOffsetResult> result = new CompletableFuture<>();
+        unsentRequest.future().whenComplete((response, error) -> {
+            if (error != null) {
+                log.error("Sending ListOffsetRequest {} to broker {} failed",

Review Comment:
   `log.debug("Sending ListOffsetRequest {} to broker {}", builder, node);`



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] junrao commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1703310796

   Implementation of the OffsetRequestsManager, responsible for building requests and processing responses for requests related to partition offsets.
   
   In this PR, the manager includes support for ListOffset requests, generated when the user makes any of the following consumer API calls:
   
   beginningOffsets
   endOffsets
   offsetsForTimes
   All previous consumer API calls interact with the OffsetsRequestsManager by generating a ListOffsetsApplicationEvent.
   
   Includes tests to cover the new functionality and to ensure no API level changes are introduced.
   
   This covers KAFKA-14965 and KAFKA-15081.
   
   Reviewers: Philip Nee <pn...@confluent.io>, Kirk True <ki...@mustardgrain.com>, Jun Rao <ju...@gmail.com>


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] junrao commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1310575529


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(

Review Comment:
   `sendListOffsetsRequests` seems a bit confusing since we don't send the requests in this method. It just generates requests to be sent by the caller. We probably want to adjust the comment accordingly too.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313203382


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/DefaultBackgroundThread.java:
##########
@@ -42,6 +42,7 @@
 import static java.util.Objects.requireNonNull;
 import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.CONSUMER_MAX_INFLIGHT_REQUESTS_PER_CONNECTION;
 import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.CONSUMER_METRIC_GROUP_PREFIX;
+import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.configuredIsolationLevel;

Review Comment:
   Noted, will do in separate PR. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311939026


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));

Review Comment:
   Those are topics that get a special treatment regarding consumer metadata lifecycle: always included in metadata requests and retained. Given that the offsets fetch requests heavily rely on metadata to get the leader to get offsets from, topics involved in the request are marked as transient for the duration of the request.
   
   This is used in all the 3 functions related to retrieving partition offsets in the the current consumer (ex. beginningOffsets [here](https://github.com/apache/kafka/blob/c2bb8eb875d94568d1ad19bf207ec69c182405d4/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetFetcher.java#L200)), and it was added in the same way for those 3 funcs here, on this [fetchOffsets](url).
   
   Please let me know if there something I might be missing regarding how that logic applies into the new consumer. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313041137


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,

Review Comment:
   That's definitely a mistake there. I see now that the actual test for unknown offsets if a few lines down, called `testListOffsetsRequestUnknownOffset`, so removing this one.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309328436


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",

Review Comment:
   love to hear your opinion: i wonder if using debug is suffice.  I think failing list offsets will eventually result in failing the API, I wonder if failed API calls is enough from logging prospective? Usually i'm a bit protective about logging at error level.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] junrao commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1310604128


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java:
##########
@@ -132,4 +138,12 @@ private boolean process(final AssignmentChangeApplicationEvent event) {
         manager.maybeAutoCommit(event.offsets);
         return true;
     }
+
+    private boolean process(final ListOffsetsApplicationEvent event) {
+        final CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> future =
+                requestManagers.offsetsRequestManager.fetchOffsets(event.timestampsToSearch(),
+                        event.requireTimestamps());
+        event.chain(future);

Review Comment:
   Could we use e`vent.chain` for handing other events like OffsetFetchApplicationEvent too?



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313134230


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+    }
+
+    @Test
+    public void testListOffsetsRequestMultiplePartitions() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_1);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequestEmpty() throws ExecutionException, InterruptedException {
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                Collections.emptyMap(),
+                false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        NetworkClientDelegate.PollResult pollResult = requestManager.poll(time.milliseconds());
+        assertTrue(pollResult.unsentRequests.isEmpty());
+
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        assertTrue(result.isDone());
+        assertFalse(result.isCompletedExceptionally());
+        assertTrue(result.get().isEmpty());
+    }
+
+    @Test
+    public void testListOffsetsRequestUnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        List<ListOffsetsResponseData.ListOffsetsTopicResponse> topicResponses = Collections.singletonList(
+                mockUnknownOffsetResponse(TEST_PARTITION_1));
+
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest, topicResponses);
+        clientResponse.onComplete();
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets =
+                Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(result, expectedOffsets);
+
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_RetrySucceeds() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch,
+                        false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Cluster metadata update. Previously failed attempt to build the request should be retried
+        // and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(
+                TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @ParameterizedTest
+    @MethodSource("retriableErrors")
+    public void testRequestFailsWithRetriableError_RetrySucceeds(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestNotSupportedErrorReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT);
+    }
+
+    @Test
+    public void testRequestWithUnknownOffsetInResponseReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.NONE);

Review Comment:
   Agree. Given that the logic is the same I will opt for renaming it to "error code" instead of "error", to better group Errors.NONE and Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT. So including `testResponseWithErrorCodeAndUnknownOffsets` 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311767255


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(

Review Comment:
   Agree, this is only building the requests so renamed it `buildListOffsetRequestToNode`, aligned with the java doc



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1698093976

   Thank you @lianetm - I left a couple comments regarding logging level.  Otherwise it looks good.


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313096461


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+    }
+
+    @Test
+    public void testListOffsetsRequestMultiplePartitions() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_1);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequestEmpty() throws ExecutionException, InterruptedException {
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                Collections.emptyMap(),
+                false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        NetworkClientDelegate.PollResult pollResult = requestManager.poll(time.milliseconds());
+        assertTrue(pollResult.unsentRequests.isEmpty());
+
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        assertTrue(result.isDone());
+        assertFalse(result.isCompletedExceptionally());
+        assertTrue(result.get().isEmpty());
+    }
+
+    @Test
+    public void testListOffsetsRequestUnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        List<ListOffsetsResponseData.ListOffsetsTopicResponse> topicResponses = Collections.singletonList(
+                mockUnknownOffsetResponse(TEST_PARTITION_1));
+
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest, topicResponses);
+        clientResponse.onComplete();
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets =
+                Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(result, expectedOffsets);
+
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_RetrySucceeds() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch,
+                        false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Cluster metadata update. Previously failed attempt to build the request should be retried
+        // and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(
+                TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @ParameterizedTest
+    @MethodSource("retriableErrors")
+    public void testRequestFailsWithRetriableError_RetrySucceeds(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestNotSupportedErrorReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT);
+    }
+
+    @Test
+    public void testRequestWithUnknownOffsetInResponseReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.NONE);
+    }
+
+    private void testResponseWithErrorAndUnknownOffsets(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+
+        // Null offsets should be returned for each partition
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestPartiallyFailsWithRetriableError_RetrySucceeds() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+
+        // List offsets request to 2 brokers successfully built
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_2);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(2, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Requests successfully sent to both brokers
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res, 2);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Mixed response with failures and successes. Offsets successfully fetched from one
+        // broker but retriable UNKNOWN_LEADER_EPOCH received from second broker.
+        NetworkClientDelegate.UnsentRequest unsentRequest1 = res.unsentRequests.get(0);
+        ClientResponse clientResponse1 = buildClientResponse(
+                unsentRequest1,
+                Collections.singletonMap(TEST_PARTITION_1, expectedOffsets.get(TEST_PARTITION_1)));
+        clientResponse1.onComplete();
+        NetworkClientDelegate.UnsentRequest unsentRequest2 = res.unsentRequests.get(1);
+        ClientResponse clientResponse2 = buildClientResponseWithErrors(
+                unsentRequest2,
+                Collections.singletonMap(TEST_PARTITION_2, Errors.UNKNOWN_LEADER_EPOCH));
+        clientResponse2.onComplete();
+
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried
+        expectSuccessfulRequest(partitionLeaders);
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        // Following poll should send the request and get a successful response
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_2, expectedOffsets.get(TEST_PARTITION_2)));
+        clientResponse.onComplete();
+
+        // Verify global result with the offset initially retrieved, and the offset that
+        // initially failed but succeeded after a metadata update
+        verifyRequestSuccessfullyCompleted(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestFailedResponse_NonRetriableAuthError() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received with non-retriable auth error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest, Collections.singletonMap(TEST_PARTITION_2, Errors.TOPIC_AUTHORIZATION_FAILED));
+        clientResponse.onComplete();
+
+        verifyRequestCompletedWithErrorResponse(fetchOffsetsFuture, TopicAuthorizationException.class);
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    @Test
+    public void testRequestFailedResponse_NonRetriableErrorTimeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest, Collections.singletonMap(TEST_PARTITION_2, Errors.BROKER_NOT_AVAILABLE));
+        clientResponse.onComplete();
+
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+
+        // Request completed with error. Nothing pending to be sent or retried
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    @Test
+    public void testRequestFails_AuthenticationException() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received with auth error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse =
+                buildClientResponseWithAuthenticationException(unsentRequest);
+        clientResponse.onComplete();
+
+        // Request completed with error. Nothing pending to be sent or retried
+        verifyRequestCompletedWithErrorResponse(fetchOffsetsFuture, AuthenticationException.class);
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    private ListOffsetsResponseData.ListOffsetsTopicResponse mockUnknownOffsetResponse(
+            TopicPartition tp) {
+        return new ListOffsetsResponseData.ListOffsetsTopicResponse()
+                .setName(tp.topic())
+                .setPartitions(Collections.singletonList(new ListOffsetsResponseData.ListOffsetsPartitionResponse()
+                        .setPartitionIndex(tp.partition())
+                        .setErrorCode(Errors.NONE.code())
+                        .setTimestamp(ListOffsetsResponse.UNKNOWN_TIMESTAMP)
+                        .setOffset(ListOffsetsResponse.UNKNOWN_OFFSET)));
+    }
+
+    private static Stream<Arguments> retriableErrors() {
+        return Stream.of(
+                Arguments.of(Errors.NOT_LEADER_OR_FOLLOWER),
+                Arguments.of(Errors.REPLICA_NOT_AVAILABLE),
+                Arguments.of(Errors.KAFKA_STORAGE_ERROR),
+                Arguments.of(Errors.OFFSET_NOT_AVAILABLE),
+                Arguments.of(Errors.LEADER_NOT_AVAILABLE),
+                Arguments.of(Errors.FENCED_LEADER_EPOCH),
+                Arguments.of(Errors.BROKER_NOT_AVAILABLE),
+                Arguments.of(Errors.INVALID_REQUEST),
+                Arguments.of(Errors.UNKNOWN_LEADER_EPOCH),
+                Arguments.of(Errors.UNKNOWN_TOPIC_OR_PARTITION));
+    }
+
+    private void verifySuccessfulPollAndResponseReceived(
+            CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> actualResult,
+            Map<TopicPartition, OffsetAndTimestamp> expectedResult) throws ExecutionException,
+            InterruptedException {
+        // Following poll should send the request and get a response
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest,
+                expectedResult);
+        clientResponse.onComplete();
+        verifyRequestSuccessfullyCompleted(actualResult, expectedResult);
+    }
+
+    private void expectSuccessfulRequest(Map<TopicPartition, Node> partitionLeaders) {
+        partitionLeaders.forEach((tp, broker) -> {
+            when(metadata.currentLeader(tp)).thenReturn(testLeaderEpoch(broker));
+            when(subscriptionState.isAssigned(tp)).thenReturn(true);
+        });
+        when(metadata.fetch()).thenReturn(testClusterMetadata(partitionLeaders));
+    }
+
+    private void expectFailedRequest_MissingLeader() {
+        when(metadata.currentLeader(any(TopicPartition.class))).thenReturn(
+                new Metadata.LeaderAndEpoch(Optional.empty(), Optional.of(1)));

Review Comment:
   Well this is seeing it from the stand point that there is a last known epoch of 1. 
   
   If the leader is missing at any point in time, or even if there were errors in the partition metadata received, epochs are still updated on the client side when received in a metadata response ([here](https://github.com/apache/kafka/blob/6391c6603582a4e4b5bb670233c345e53f82a77b/clients/src/main/java/org/apache/kafka/clients/Metadata.java#L352)).  So the `currentLeader` used here will always return an empty leader but with the last seen epoch. I can add a comment to clarify or just use an emtpy epoch here, it would also be ok.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1703196406

   The failure they were after with that fix seems different to this though, here is about hanging threads on the base `QuorumTestHarness`, so I would say it is not specific to the `OffloadAndConsumeFromLeaderTest` (it happened to be the one finding the hanging threads before starting I expect). I think there is ongoing work in AK for finding the tests leaving hanging thread (will double check on the issues)


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313167529


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/PrototypeAsyncConsumerTest.java:
##########
@@ -220,6 +225,95 @@ public void testAssignOnEmptyTopicInPartition() {
     }
 
     @Test
+    public void testBeginningOffsetsFailsIfNullPartitions() {
+        consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        assertThrows(NullPointerException.class, () -> consumer.beginningOffsets(null,
+                Duration.ofMillis(1)));
+    }
+
+    @Test
+    public void testBeginningOffsets() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsetsAndTimestamp =
+                mockOffsetAndTimestamp();
+        Set<TopicPartition> partitions = expectedOffsetsAndTimestamp.keySet();
+        doReturn(expectedOffsetsAndTimestamp).when(eventHandler).addAndGet(any(), any());
+        Map<TopicPartition, Long> result =
+                assertDoesNotThrow(() -> consumer.beginningOffsets(partitions,
+                        Duration.ofMillis(1)));
+        Map<TopicPartition, Long> expectedOffsets = expectedOffsetsAndTimestamp.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().offset()));
+        assertEquals(expectedOffsets, result);
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }
+
+    @Test
+    public void testBeginningOffsetsThrowsKafkaExceptionForUnderlyingExecutionFailure() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        Set<TopicPartition> partitions = mockTopicPartitionOffset().keySet();
+        Throwable eventProcessingFailure = new KafkaException("Unexpected failure " +
+                "processing List Offsets event");
+        doThrow(eventProcessingFailure).when(eventHandler).addAndGet(any(), any());
+        Throwable consumerError = assertThrows(KafkaException.class,
+                () -> consumer.beginningOffsets(partitions,
+                        Duration.ofMillis(1)));
+        assertEquals(eventProcessingFailure, consumerError);
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class), ArgumentMatchers.isA(Timer.class));
+    }
+
+    @Test
+    public void testBeginningOffsetsTimeoutOnEventProcessingTimeout() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        doThrow(new TimeoutException()).when(eventHandler).addAndGet(any(), any());
+        assertThrows(TimeoutException.class,
+                () -> consumer.beginningOffsets(
+                        Collections.singletonList(new TopicPartition("t1", 0)),
+                        Duration.ofMillis(1)));
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }
+
+    @Test
+    public void testOffsetsForTimesOnNullPartitions() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        assertThrows(NullPointerException.class, () -> consumer.offsetsForTimes(null,
+                Duration.ofMillis(1)));
+    }
+
+    @Test
+    public void testOffsetsForTimes() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        Map<TopicPartition, OffsetAndTimestamp> expectedResult = mockOffsetAndTimestamp();
+        Map<TopicPartition, Long> timestampToSearch = mockTimestampToSearch();
+
+        doReturn(expectedResult).when(eventHandler).addAndGet(any(), any());
+        Map<TopicPartition, OffsetAndTimestamp> result =
+                assertDoesNotThrow(() -> consumer.offsetsForTimes(timestampToSearch, Duration.ofMillis(1)));
+        assertEquals(expectedResult, result);
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }
+
+    // This test ensures same behaviour as the current consumer when offsetsForTimes is called
+    // with 0 timeout. It should return map with all requested partitions as keys, with null
+    // OffsetAndTimestamp as value.
+    @Test
+    public void testOffsetsForTimesWithZeroTimeout() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        TopicPartition tp = new TopicPartition("topic1", 0);
+        Map<TopicPartition, OffsetAndTimestamp> expectedResult =
+                Collections.singletonMap(tp, null);
+        Map<TopicPartition, Long> timestampToSearch = Collections.singletonMap(tp, 5L);
+
+        Map<TopicPartition, OffsetAndTimestamp> result =
+                assertDoesNotThrow(() -> consumer.offsetsForTimes(timestampToSearch,
+                        Duration.ofMillis(0)));
+        assertEquals(expectedResult, result);
+        verify(eventHandler, never()).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }

Review Comment:
   Removed the unused code. 
   
   Do you refer to a reported issue with the behaviour of the consumer `offsetsForTimes` returning null when 0 timeout? (can't find any). 
   
   For now we want to ensure the same API level behaviour so we are including this test, similar to the one defined for the old Consumer [here](https://github.com/apache/kafka/blob/6391c6603582a4e4b5bb670233c345e53f82a77b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetFetcherTest.java#L971). Both wil definitely have to be updated/removed eventually if we change the behaviour.  



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1702962811

   Thanks for all the comment @junrao . All addressed. (I'm keeping an eye on the build and will update relevant results here) 


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1703188741

   [KAFKA-15399](https://issues.apache.org/jira/browse/KAFKA-15399) - Chris L. mentioned that he fixed the OffloadAndConsumeFromLeaderTest issue, but apparently we are still seeing it on trunk. I replied the thread.


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311738190


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(
+            Node node,
+            Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> targetTimes,
+            boolean requireTimestamps,
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests) {
+        ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder
+                .forConsumer(requireTimestamps, isolationLevel, false)
+                .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(targetTimes));
+
+        log.debug("Creating ListOffsetRequest {} for broker {} to reset positions", builder,
+                node);
+
+        NetworkClientDelegate.UnsentRequest unsentRequest = new NetworkClientDelegate.UnsentRequest(
+                builder,
+                Optional.ofNullable(node));
+        unsentRequests.add(unsentRequest);
+        CompletableFuture<ListOffsetResult> result = new CompletableFuture<>();
+        unsentRequest.future().whenComplete((response, error) -> {
+            if (error != null) {
+                log.error("Sending ListOffsetRequest {} to broker {} failed",
+                        builder,
+                        node,
+                        error);
+                result.completeExceptionally(error);
+            } else {
+                ListOffsetsResponse lor = (ListOffsetsResponse) response.responseBody();
+                log.trace("Received ListOffsetResponse {} from broker {}", lor, node);
+                try {
+                    ListOffsetResult listOffsetResult =
+                            offsetFetcherUtils.handleListOffsetResponse(lor);
+                    result.complete(listOffsetResult);
+                } catch (RuntimeException e) {
+                    result.completeExceptionally(e);
+                }
+            }
+        });
+        return result;
+    }
+
+    private static class ListOffsetsRequestState {
+
+        private final Map<TopicPartition, Long> timestampsToSearch;
+        private final Map<TopicPartition, ListOffsetData> fetchedOffsets;
+        private final Map<TopicPartition, Long> remainingToSearch;
+        private final CompletableFuture<ListOffsetResult> globalResult;
+        final boolean requireTimestamps;
+        final OffsetFetcherUtils offsetFetcherUtils;
+        final IsolationLevel isolationLevel;
+
+        private ListOffsetsRequestState(Map<TopicPartition, Long> timestampsToSearch,
+                                        boolean requireTimestamps,
+                                        OffsetFetcherUtils offsetFetcherUtils,
+                                        IsolationLevel isolationLevel) {
+            remainingToSearch = new HashMap<>();
+            fetchedOffsets = new HashMap<>();
+            globalResult = new CompletableFuture<>();
+
+            this.timestampsToSearch = timestampsToSearch;
+            this.requireTimestamps = requireTimestamps;
+            this.offsetFetcherUtils = offsetFetcherUtils;
+            this.isolationLevel = isolationLevel;
+        }
+
+        private void addPartitionsToRetry(Set<TopicPartition> partitionsToRetry) {
+            remainingToSearch.putAll(partitionsToRetry.stream()
+                    .collect(Collectors.toMap(tp -> tp, timestampsToSearch::get)));
+        }
+    }
+
+    private static class MultiNodeRequest {
+        final Map<TopicPartition, ListOffsetData> fetchedTimestampOffsets;
+        final Set<TopicPartition> partitionsToRetry;
+        final AtomicInteger expectedResponses;
+        final CompletableFuture<ListOffsetResult> resultFuture;
+
+        private MultiNodeRequest(int nodeCount) {
+            fetchedTimestampOffsets = new HashMap<>();
+            partitionsToRetry = new HashSet<>();
+            expectedResponses = new AtomicInteger(nodeCount);
+            resultFuture = new CompletableFuture<>();
+        }
+
+        private void onComplete(BiConsumer<? super ListOffsetResult, ? super Throwable> action) {
+            resultFuture.whenComplete(action);
+        }
+
+        private void addPartialResult(ListOffsetResult partialResult) {
+            try {
+                fetchedTimestampOffsets.putAll(partialResult.fetchedOffsets);
+                partitionsToRetry.addAll(partialResult.partitionsToRetry);
+
+                if (expectedResponses.decrementAndGet() == 0) {
+                    ListOffsetResult result =
+                            new ListOffsetResult(fetchedTimestampOffsets,
+                                    partitionsToRetry);
+                    resultFuture.complete(result);
+                }
+            } catch (RuntimeException e) {
+                resultFuture.completeExceptionally(e);
+            }
+        }
+    }
+
+    /**
+     * Group partitions by leader. Topic partitions from `timestampsToSearch` for which
+     * the leader is not known are kept as `remainingToSearch` in the `listOffsetsRequestState`
+     *
+     * @param timestampsToSearch      The mapping from partitions to the target timestamps
+     * @param listOffsetsRequestState Request state that will be extended by adding to its
+     *                                `remainingToSearch` map all partitions for which the
+     *                                request cannot be performed due to unknown leader (need
+     *                                metadata update).
+     */
+    private Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> groupListOffsetRequests(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        final Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> partitionDataMap = new HashMap<>();
+        for (Map.Entry<TopicPartition, Long> entry : timestampsToSearch.entrySet()) {
+            TopicPartition tp = entry.getKey();
+            Long offset = entry.getValue();
+            Metadata.LeaderAndEpoch leaderAndEpoch = metadata.currentLeader(tp);
+
+            if (!leaderAndEpoch.leader.isPresent()) {
+                log.debug("Leader for partition {} is unknown for fetching offset {}", tp, offset);
+                metadata.requestUpdate();
+                if (listOffsetsRequestState != null) {

Review Comment:
   I did a minor update to have the state as Optional and also updated the java doc to make the intention clearer.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311839169


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java:
##########
@@ -132,4 +138,12 @@ private boolean process(final AssignmentChangeApplicationEvent event) {
         manager.maybeAutoCommit(event.offsets);
         return true;
     }
+
+    private boolean process(final ListOffsetsApplicationEvent event) {
+        final CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> future =
+                requestManagers.offsetsRequestManager.fetchOffsets(event.timestampsToSearch(),
+                        event.requireTimestamps());
+        event.chain(future);

Review Comment:
   Sure, done. 
   
   Side note, `CommitApplicationEvent` will also use the `event.chain` but that requires bigger changes on the `CommitRequestManager`, so leaving it for another PR. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] kirktrue commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1310978474


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/DefaultEventHandler.java:
##########
@@ -129,6 +132,14 @@ public boolean add(final ApplicationEvent event) {
         return applicationEventQueue.add(event);
     }
 
+    @Override

Review Comment:
   Was the `addAndGet` method addition here taken from a different commit?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));

Review Comment:
   Truth be told: I still don't know what `addTransientTopics` does 🤷‍♂️ 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);

Review Comment:
   I believe it's a non-issue because the callback can only be invoked by our network thread which hasn't started executing yet. Perhaps a comment will suffice here?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target

Review Comment:
   Nitpicky/style: the comment for the `@return` annotation is great. Perhaps move it up to the main method-level documentation so it's not tucked away in the `@return` documentation?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);

Review Comment:
   It isn't good practice to pass a reference to `this` to another object in its constructor. It's possible that the `ClusterResourceListener` callback could get invoked before the object has finished initialization.
   
   I don't have any good suggestions just yet, but I'll noodle on it.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());

Review Comment:
   I really want an idiomatic way for the `poll()` method of returning a non-op. Maybe we should change the signature of `poll()` to return an `Optional`?
   
   Anyway, that's a change we'd need to make elsewhere, so no need to deal with that here.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));

Review Comment:
   Truth be told: I still don't know what `addTransientTopics` does 🤷‍♂️ 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309068577


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();

Review Comment:
   I wonder what would happen if the request never get a response.  My main concern is retrying.  If we clear the requestsToSend collection, how do we retry if the request failed to get a response or getting sent out?



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1310633377


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(

Review Comment:
   yeah this is probably my fault - I started using "send" in the context of request manager. What it really means is handing these requests to the networkclient to get send out.  I think i've tried to use "enqueue" before.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311863608


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/DefaultEventHandler.java:
##########
@@ -129,6 +132,14 @@ public boolean add(final ApplicationEvent event) {
         return applicationEventQueue.add(event);
     }
 
+    @Override

Review Comment:
   Yes, to avoid a cyclic dependency between our changes (integration branch nightmare). This `addAndGet` was included in the PR for [KAFKA-15188](https://issues.apache.org/jira/browse/KAFKA-15188) with more implementation for the PrototypeAsyncConsumer API, that you noted depends on this one. 
   
   Should be the cleanest way to unblock, without having to manually revert changes here as an intermediate step. Let me know if there are any concerns.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311916054


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());

Review Comment:
   I would probably go with simplifying the empty poll result creation used in all managers with something like `NetworkClientDelegate.PollResult.empty()` but your comment makes me note that this "if" is redundant here. It is enough to just create the pollResult with the `requestsToSend`, and if empty, that is already checked and properly handled in the defaultBackgroundThread for all managers in the `handlePollResult`. Removing the "if" section.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311692598


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(
+            Node node,
+            Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> targetTimes,
+            boolean requireTimestamps,
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests) {
+        ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder
+                .forConsumer(requireTimestamps, isolationLevel, false)
+                .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(targetTimes));
+
+        log.debug("Creating ListOffsetRequest {} for broker {} to reset positions", builder,
+                node);
+
+        NetworkClientDelegate.UnsentRequest unsentRequest = new NetworkClientDelegate.UnsentRequest(
+                builder,
+                Optional.ofNullable(node));
+        unsentRequests.add(unsentRequest);
+        CompletableFuture<ListOffsetResult> result = new CompletableFuture<>();
+        unsentRequest.future().whenComplete((response, error) -> {
+            if (error != null) {
+                log.error("Sending ListOffsetRequest {} to broker {} failed",

Review Comment:
   These 2 are not for the same case, that's why I introduced it differently, but totally agree with your point. I updated the log levels to align with the OffsetFetch approach, so sticking to debug level for all these internal flows.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311879131


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target

Review Comment:
   Done.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309145935


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();

Review Comment:
   There is a retry logic based on the `requestsToRetry`. Requests are retried if:
   - the leader to get partition offsets from is not available (stale metadata case [here](https://github.com/apache/kafka/blob/34afb96b6c52617957d39ffba8fdf24f1e75bc06/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L175))
   - offsets were not found for a partition after trying all the known leaders, see [here](https://github.com/apache/kafka/blob/34afb96b6c52617957d39ffba8fdf24f1e75bc06/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L231)
   
   Requests are retried once the manager is notified about a cluster metadata update. 
   
   Other than that, the request will fail and won't be retried:
   -  fail with error, if any, after completing requests to known leaders, [here](https://github.com/apache/kafka/blob/34afb96b6c52617957d39ffba8fdf24f1e75bc06/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L235)
   - timeout if no responses received (based on the ListOffsetsApplicationEvent future timeout)
   
   This covers the retry logic of the current implementation, but let me know if you think we might be missing something. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313192482


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));

Review Comment:
   Yes, it does wait for a metadata update that will never happen so very good point. Reduced time to 5 ms in both tests.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] junrao commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1312321020


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));

Review Comment:
   Does that actually wait for 100ms for the test to complete? If so, we probably want to use a smaller number. Ditto in some other tests.



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,

Review Comment:
   Why is the test named `UnknownOffset`? Also, how is this test different from `testListOffsetsRequest_Success`?



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+    }
+
+    @Test
+    public void testListOffsetsRequestMultiplePartitions() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_1);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequestEmpty() throws ExecutionException, InterruptedException {
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                Collections.emptyMap(),
+                false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        NetworkClientDelegate.PollResult pollResult = requestManager.poll(time.milliseconds());
+        assertTrue(pollResult.unsentRequests.isEmpty());
+
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        assertTrue(result.isDone());
+        assertFalse(result.isCompletedExceptionally());
+        assertTrue(result.get().isEmpty());
+    }
+
+    @Test
+    public void testListOffsetsRequestUnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        List<ListOffsetsResponseData.ListOffsetsTopicResponse> topicResponses = Collections.singletonList(
+                mockUnknownOffsetResponse(TEST_PARTITION_1));
+
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest, topicResponses);
+        clientResponse.onComplete();
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets =
+                Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(result, expectedOffsets);
+
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_RetrySucceeds() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch,
+                        false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Cluster metadata update. Previously failed attempt to build the request should be retried
+        // and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(
+                TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @ParameterizedTest
+    @MethodSource("retriableErrors")
+    public void testRequestFailsWithRetriableError_RetrySucceeds(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestNotSupportedErrorReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT);
+    }
+
+    @Test
+    public void testRequestWithUnknownOffsetInResponseReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.NONE);

Review Comment:
   This works, but is a bit unintuitive since Errors.NONE doesn't represent an error.



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/PrototypeAsyncConsumerTest.java:
##########
@@ -220,6 +225,95 @@ public void testAssignOnEmptyTopicInPartition() {
     }
 
     @Test
+    public void testBeginningOffsetsFailsIfNullPartitions() {
+        consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        assertThrows(NullPointerException.class, () -> consumer.beginningOffsets(null,
+                Duration.ofMillis(1)));
+    }
+
+    @Test
+    public void testBeginningOffsets() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsetsAndTimestamp =
+                mockOffsetAndTimestamp();
+        Set<TopicPartition> partitions = expectedOffsetsAndTimestamp.keySet();
+        doReturn(expectedOffsetsAndTimestamp).when(eventHandler).addAndGet(any(), any());
+        Map<TopicPartition, Long> result =
+                assertDoesNotThrow(() -> consumer.beginningOffsets(partitions,
+                        Duration.ofMillis(1)));
+        Map<TopicPartition, Long> expectedOffsets = expectedOffsetsAndTimestamp.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().offset()));
+        assertEquals(expectedOffsets, result);
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }
+
+    @Test
+    public void testBeginningOffsetsThrowsKafkaExceptionForUnderlyingExecutionFailure() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        Set<TopicPartition> partitions = mockTopicPartitionOffset().keySet();
+        Throwable eventProcessingFailure = new KafkaException("Unexpected failure " +
+                "processing List Offsets event");
+        doThrow(eventProcessingFailure).when(eventHandler).addAndGet(any(), any());
+        Throwable consumerError = assertThrows(KafkaException.class,
+                () -> consumer.beginningOffsets(partitions,
+                        Duration.ofMillis(1)));
+        assertEquals(eventProcessingFailure, consumerError);
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class), ArgumentMatchers.isA(Timer.class));
+    }
+
+    @Test
+    public void testBeginningOffsetsTimeoutOnEventProcessingTimeout() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        doThrow(new TimeoutException()).when(eventHandler).addAndGet(any(), any());
+        assertThrows(TimeoutException.class,
+                () -> consumer.beginningOffsets(
+                        Collections.singletonList(new TopicPartition("t1", 0)),
+                        Duration.ofMillis(1)));
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }
+
+    @Test
+    public void testOffsetsForTimesOnNullPartitions() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        assertThrows(NullPointerException.class, () -> consumer.offsetsForTimes(null,
+                Duration.ofMillis(1)));
+    }
+
+    @Test
+    public void testOffsetsForTimes() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        Map<TopicPartition, OffsetAndTimestamp> expectedResult = mockOffsetAndTimestamp();
+        Map<TopicPartition, Long> timestampToSearch = mockTimestampToSearch();
+
+        doReturn(expectedResult).when(eventHandler).addAndGet(any(), any());
+        Map<TopicPartition, OffsetAndTimestamp> result =
+                assertDoesNotThrow(() -> consumer.offsetsForTimes(timestampToSearch, Duration.ofMillis(1)));
+        assertEquals(expectedResult, result);
+        verify(eventHandler).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }
+
+    // This test ensures same behaviour as the current consumer when offsetsForTimes is called
+    // with 0 timeout. It should return map with all requested partitions as keys, with null
+    // OffsetAndTimestamp as value.
+    @Test
+    public void testOffsetsForTimesWithZeroTimeout() {
+        PrototypeAsyncConsumer<?, ?> consumer = newConsumer(time, new StringDeserializer(), new StringDeserializer());
+        TopicPartition tp = new TopicPartition("topic1", 0);
+        Map<TopicPartition, OffsetAndTimestamp> expectedResult =
+                Collections.singletonMap(tp, null);
+        Map<TopicPartition, Long> timestampToSearch = Collections.singletonMap(tp, 5L);
+
+        Map<TopicPartition, OffsetAndTimestamp> result =
+                assertDoesNotThrow(() -> consumer.offsetsForTimes(timestampToSearch,
+                        Duration.ofMillis(0)));
+        assertEquals(expectedResult, result);
+        verify(eventHandler, never()).addAndGet(ArgumentMatchers.isA(ListOffsetsApplicationEvent.class),
+                ArgumentMatchers.isA(Timer.class));
+    }

Review Comment:
   This is an existing issue. `testWakeup_commitSync` and `clientId` seem unused?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/DefaultBackgroundThread.java:
##########
@@ -42,6 +42,7 @@
 import static java.util.Objects.requireNonNull;
 import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.CONSUMER_MAX_INFLIGHT_REQUESTS_PER_CONNECTION;
 import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.CONSUMER_METRIC_GROUP_PREFIX;
+import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.configuredIsolationLevel;

Review Comment:
   This can be done in a separate PR. The logic in DefaultBackgroundThread is a bit involved. It would be useful to add a comment to document the life cycle of how an event is handled through ApplicationEventProcessor and NetworkClientDelegate.



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+    }
+
+    @Test
+    public void testListOffsetsRequestMultiplePartitions() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_1);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequestEmpty() throws ExecutionException, InterruptedException {
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                Collections.emptyMap(),
+                false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        NetworkClientDelegate.PollResult pollResult = requestManager.poll(time.milliseconds());
+        assertTrue(pollResult.unsentRequests.isEmpty());
+
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        assertTrue(result.isDone());
+        assertFalse(result.isCompletedExceptionally());
+        assertTrue(result.get().isEmpty());
+    }
+
+    @Test
+    public void testListOffsetsRequestUnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        List<ListOffsetsResponseData.ListOffsetsTopicResponse> topicResponses = Collections.singletonList(
+                mockUnknownOffsetResponse(TEST_PARTITION_1));
+
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest, topicResponses);
+        clientResponse.onComplete();
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets =
+                Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(result, expectedOffsets);
+
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_RetrySucceeds() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch,
+                        false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Cluster metadata update. Previously failed attempt to build the request should be retried
+        // and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(
+                TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @ParameterizedTest
+    @MethodSource("retriableErrors")
+    public void testRequestFailsWithRetriableError_RetrySucceeds(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestNotSupportedErrorReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT);
+    }
+
+    @Test
+    public void testRequestWithUnknownOffsetInResponseReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.NONE);
+    }
+
+    private void testResponseWithErrorAndUnknownOffsets(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+
+        // Null offsets should be returned for each partition
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestPartiallyFailsWithRetriableError_RetrySucceeds() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+
+        // List offsets request to 2 brokers successfully built
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_2);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(2, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Requests successfully sent to both brokers
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res, 2);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Mixed response with failures and successes. Offsets successfully fetched from one
+        // broker but retriable UNKNOWN_LEADER_EPOCH received from second broker.
+        NetworkClientDelegate.UnsentRequest unsentRequest1 = res.unsentRequests.get(0);
+        ClientResponse clientResponse1 = buildClientResponse(
+                unsentRequest1,
+                Collections.singletonMap(TEST_PARTITION_1, expectedOffsets.get(TEST_PARTITION_1)));
+        clientResponse1.onComplete();
+        NetworkClientDelegate.UnsentRequest unsentRequest2 = res.unsentRequests.get(1);
+        ClientResponse clientResponse2 = buildClientResponseWithErrors(
+                unsentRequest2,
+                Collections.singletonMap(TEST_PARTITION_2, Errors.UNKNOWN_LEADER_EPOCH));
+        clientResponse2.onComplete();
+
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried
+        expectSuccessfulRequest(partitionLeaders);
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        // Following poll should send the request and get a successful response
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_2, expectedOffsets.get(TEST_PARTITION_2)));
+        clientResponse.onComplete();
+
+        // Verify global result with the offset initially retrieved, and the offset that
+        // initially failed but succeeded after a metadata update
+        verifyRequestSuccessfullyCompleted(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestFailedResponse_NonRetriableAuthError() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received with non-retriable auth error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest, Collections.singletonMap(TEST_PARTITION_2, Errors.TOPIC_AUTHORIZATION_FAILED));
+        clientResponse.onComplete();
+
+        verifyRequestCompletedWithErrorResponse(fetchOffsetsFuture, TopicAuthorizationException.class);
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    @Test
+    public void testRequestFailedResponse_NonRetriableErrorTimeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest, Collections.singletonMap(TEST_PARTITION_2, Errors.BROKER_NOT_AVAILABLE));
+        clientResponse.onComplete();
+
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+
+        // Request completed with error. Nothing pending to be sent or retried
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    @Test
+    public void testRequestFails_AuthenticationException() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received with auth error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse =
+                buildClientResponseWithAuthenticationException(unsentRequest);
+        clientResponse.onComplete();
+
+        // Request completed with error. Nothing pending to be sent or retried
+        verifyRequestCompletedWithErrorResponse(fetchOffsetsFuture, AuthenticationException.class);
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    private ListOffsetsResponseData.ListOffsetsTopicResponse mockUnknownOffsetResponse(
+            TopicPartition tp) {
+        return new ListOffsetsResponseData.ListOffsetsTopicResponse()
+                .setName(tp.topic())
+                .setPartitions(Collections.singletonList(new ListOffsetsResponseData.ListOffsetsPartitionResponse()
+                        .setPartitionIndex(tp.partition())
+                        .setErrorCode(Errors.NONE.code())
+                        .setTimestamp(ListOffsetsResponse.UNKNOWN_TIMESTAMP)
+                        .setOffset(ListOffsetsResponse.UNKNOWN_OFFSET)));
+    }
+
+    private static Stream<Arguments> retriableErrors() {
+        return Stream.of(
+                Arguments.of(Errors.NOT_LEADER_OR_FOLLOWER),
+                Arguments.of(Errors.REPLICA_NOT_AVAILABLE),
+                Arguments.of(Errors.KAFKA_STORAGE_ERROR),
+                Arguments.of(Errors.OFFSET_NOT_AVAILABLE),
+                Arguments.of(Errors.LEADER_NOT_AVAILABLE),
+                Arguments.of(Errors.FENCED_LEADER_EPOCH),
+                Arguments.of(Errors.BROKER_NOT_AVAILABLE),
+                Arguments.of(Errors.INVALID_REQUEST),
+                Arguments.of(Errors.UNKNOWN_LEADER_EPOCH),
+                Arguments.of(Errors.UNKNOWN_TOPIC_OR_PARTITION));
+    }
+
+    private void verifySuccessfulPollAndResponseReceived(
+            CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> actualResult,
+            Map<TopicPartition, OffsetAndTimestamp> expectedResult) throws ExecutionException,
+            InterruptedException {
+        // Following poll should send the request and get a response
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest,
+                expectedResult);
+        clientResponse.onComplete();
+        verifyRequestSuccessfullyCompleted(actualResult, expectedResult);
+    }
+
+    private void expectSuccessfulRequest(Map<TopicPartition, Node> partitionLeaders) {
+        partitionLeaders.forEach((tp, broker) -> {
+            when(metadata.currentLeader(tp)).thenReturn(testLeaderEpoch(broker));
+            when(subscriptionState.isAssigned(tp)).thenReturn(true);
+        });
+        when(metadata.fetch()).thenReturn(testClusterMetadata(partitionLeaders));
+    }
+
+    private void expectFailedRequest_MissingLeader() {
+        when(metadata.currentLeader(any(TopicPartition.class))).thenReturn(
+                new Metadata.LeaderAndEpoch(Optional.empty(), Optional.of(1)));

Review Comment:
   If the leader is missing, typically there won't be an epoch, right?



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1313096461


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManagerTest.java:
##########
@@ -0,0 +1,675 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.message.ListOffsetsResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class OffsetsRequestManagerTest {
+
+    private OffsetsRequestManager requestManager;
+    private ConsumerMetadata metadata;
+    private SubscriptionState subscriptionState;
+    private MockTime time;
+    private static final String TEST_TOPIC = "t1";
+    private static final TopicPartition TEST_PARTITION_1 = new TopicPartition(TEST_TOPIC, 1);
+    private static final TopicPartition TEST_PARTITION_2 = new TopicPartition(TEST_TOPIC, 2);
+    private static final Node LEADER_1 = new Node(0, "host1", 9092);
+    private static final Node LEADER_2 = new Node(0, "host2", 9092);
+    private static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_COMMITTED;
+    private static final int RETRY_BACKOFF_MS = 500;
+
+    @BeforeEach
+    public void setup() {
+        metadata = mock(ConsumerMetadata.class);
+        subscriptionState = mock(SubscriptionState.class);
+        this.time = new MockTime(0);
+        ApiVersions apiVersions = mock(ApiVersions.class);
+        requestManager = new OffsetsRequestManager(subscriptionState, metadata,
+                DEFAULT_ISOLATION_LEVEL, time, RETRY_BACKOFF_MS,
+                apiVersions, new LogContext());
+    }
+
+    @Test
+    public void testListOffsetsRequest_Success() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequest_UnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_Timeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch, false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        // Metadata update not happening within the time boundaries of the request future, so
+        // future should time out.
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+    }
+
+    @Test
+    public void testListOffsetsRequestMultiplePartitions() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_1);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+        verifySuccessfulPollAndResponseReceived(result, expectedOffsets);
+    }
+
+    @Test
+    public void testListOffsetsRequestEmpty() throws ExecutionException, InterruptedException {
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                Collections.emptyMap(),
+                false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        NetworkClientDelegate.PollResult pollResult = requestManager.poll(time.milliseconds());
+        assertTrue(pollResult.unsentRequests.isEmpty());
+
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        assertTrue(result.isDone());
+        assertFalse(result.isCompletedExceptionally());
+        assertTrue(result.get().isEmpty());
+    }
+
+    @Test
+    public void testListOffsetsRequestUnknownOffset() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> result = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        List<ListOffsetsResponseData.ListOffsetsTopicResponse> topicResponses = Collections.singletonList(
+                mockUnknownOffsetResponse(TEST_PARTITION_1));
+
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest, topicResponses);
+        clientResponse.onComplete();
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets =
+                Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(result, expectedOffsets);
+
+    }
+
+    @Test
+    public void testListOffsetsWaitingForMetadataUpdate_RetrySucceeds() throws ExecutionException,
+            InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // Building list offsets request fails with unknown leader
+        expectFailedRequest_MissingLeader();
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(timestampsToSearch,
+                        false);
+        assertEquals(0, requestManager.requestsToSend());
+        assertEquals(1, requestManager.requestsToRetry());
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        assertEquals(0, res.unsentRequests.size());
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Cluster metadata update. Previously failed attempt to build the request should be retried
+        // and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(
+                TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @ParameterizedTest
+    @MethodSource("retriableErrors")
+    public void testRequestFailsWithRetriableError_RetrySucceeds(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried and succeed
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, new OffsetAndTimestamp(5L, 1L));
+        verifySuccessfulPollAndResponseReceived(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestNotSupportedErrorReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT);
+    }
+
+    @Test
+    public void testRequestWithUnknownOffsetInResponseReturnsNullOffset() throws ExecutionException,
+            InterruptedException {
+        testResponseWithErrorAndUnknownOffsets(Errors.NONE);
+    }
+
+    private void testResponseWithErrorAndUnknownOffsets(Errors error) throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent to single broker
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Response received with error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_1, error));
+        clientResponse.onComplete();
+
+        // Null offsets should be returned for each partition
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = Collections.singletonMap(TEST_PARTITION_1, null);
+        verifyRequestSuccessfullyCompleted(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestPartiallyFailsWithRetriableError_RetrySucceeds() throws ExecutionException, InterruptedException {
+        Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
+        timestampsToSearch.put(TEST_PARTITION_1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        timestampsToSearch.put(TEST_PARTITION_2, ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        Map<TopicPartition, OffsetAndTimestamp> expectedOffsets = timestampsToSearch.entrySet().stream()
+                .collect(Collectors.toMap(e -> e.getKey(), e -> new OffsetAndTimestamp(5L, 1L)));
+
+        // List offsets request to 2 brokers successfully built
+        Map<TopicPartition, Node> partitionLeaders = new HashMap<>();
+        partitionLeaders.put(TEST_PARTITION_1, LEADER_1);
+        partitionLeaders.put(TEST_PARTITION_2, LEADER_2);
+        expectSuccessfulRequest(partitionLeaders);
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture = requestManager.fetchOffsets(
+                timestampsToSearch,
+                false);
+        assertEquals(2, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Requests successfully sent to both brokers
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res, 2);
+        assertFalse(fetchOffsetsFuture.isDone());
+
+        // Mixed response with failures and successes. Offsets successfully fetched from one
+        // broker but retriable UNKNOWN_LEADER_EPOCH received from second broker.
+        NetworkClientDelegate.UnsentRequest unsentRequest1 = res.unsentRequests.get(0);
+        ClientResponse clientResponse1 = buildClientResponse(
+                unsentRequest1,
+                Collections.singletonMap(TEST_PARTITION_1, expectedOffsets.get(TEST_PARTITION_1)));
+        clientResponse1.onComplete();
+        NetworkClientDelegate.UnsentRequest unsentRequest2 = res.unsentRequests.get(1);
+        ClientResponse clientResponse2 = buildClientResponseWithErrors(
+                unsentRequest2,
+                Collections.singletonMap(TEST_PARTITION_2, Errors.UNKNOWN_LEADER_EPOCH));
+        clientResponse2.onComplete();
+
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertEquals(1, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+
+        // Cluster metadata update. Failed requests should be retried
+        expectSuccessfulRequest(partitionLeaders);
+        requestManager.onUpdate(new ClusterResource(""));
+        assertEquals(1, requestManager.requestsToSend());
+
+        // Following poll should send the request and get a successful response
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest,
+                Collections.singletonMap(TEST_PARTITION_2, expectedOffsets.get(TEST_PARTITION_2)));
+        clientResponse.onComplete();
+
+        // Verify global result with the offset initially retrieved, and the offset that
+        // initially failed but succeeded after a metadata update
+        verifyRequestSuccessfullyCompleted(fetchOffsetsFuture, expectedOffsets);
+    }
+
+    @Test
+    public void testRequestFailedResponse_NonRetriableAuthError() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received with non-retriable auth error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest, Collections.singletonMap(TEST_PARTITION_2, Errors.TOPIC_AUTHORIZATION_FAILED));
+        clientResponse.onComplete();
+
+        verifyRequestCompletedWithErrorResponse(fetchOffsetsFuture, TopicAuthorizationException.class);
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    @Test
+    public void testRequestFailedResponse_NonRetriableErrorTimeout() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponseWithErrors(
+                unsentRequest, Collections.singletonMap(TEST_PARTITION_2, Errors.BROKER_NOT_AVAILABLE));
+        clientResponse.onComplete();
+
+        assertFalse(fetchOffsetsFuture.isDone());
+        assertThrows(TimeoutException.class, () -> fetchOffsetsFuture.get(100L, TimeUnit.MILLISECONDS));
+
+        // Request completed with error. Nothing pending to be sent or retried
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    @Test
+    public void testRequestFails_AuthenticationException() {
+        Map<TopicPartition, Long> timestampsToSearch = Collections.singletonMap(TEST_PARTITION_1,
+                ListOffsetsRequest.EARLIEST_TIMESTAMP);
+
+        // List offsets request successfully built
+        expectSuccessfulRequest(Collections.singletonMap(TEST_PARTITION_1, LEADER_1));
+        CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsetsFuture =
+                requestManager.fetchOffsets(
+                        timestampsToSearch,
+                        false);
+        assertEquals(1, requestManager.requestsToSend());
+        assertEquals(0, requestManager.requestsToRetry());
+
+        // Request successfully sent
+        NetworkClientDelegate.PollResult res = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(res);
+
+        // Response received with auth error
+        NetworkClientDelegate.UnsentRequest unsentRequest = res.unsentRequests.get(0);
+        ClientResponse clientResponse =
+                buildClientResponseWithAuthenticationException(unsentRequest);
+        clientResponse.onComplete();
+
+        // Request completed with error. Nothing pending to be sent or retried
+        verifyRequestCompletedWithErrorResponse(fetchOffsetsFuture, AuthenticationException.class);
+        assertEquals(0, requestManager.requestsToRetry());
+        assertEquals(0, requestManager.requestsToSend());
+    }
+
+    private ListOffsetsResponseData.ListOffsetsTopicResponse mockUnknownOffsetResponse(
+            TopicPartition tp) {
+        return new ListOffsetsResponseData.ListOffsetsTopicResponse()
+                .setName(tp.topic())
+                .setPartitions(Collections.singletonList(new ListOffsetsResponseData.ListOffsetsPartitionResponse()
+                        .setPartitionIndex(tp.partition())
+                        .setErrorCode(Errors.NONE.code())
+                        .setTimestamp(ListOffsetsResponse.UNKNOWN_TIMESTAMP)
+                        .setOffset(ListOffsetsResponse.UNKNOWN_OFFSET)));
+    }
+
+    private static Stream<Arguments> retriableErrors() {
+        return Stream.of(
+                Arguments.of(Errors.NOT_LEADER_OR_FOLLOWER),
+                Arguments.of(Errors.REPLICA_NOT_AVAILABLE),
+                Arguments.of(Errors.KAFKA_STORAGE_ERROR),
+                Arguments.of(Errors.OFFSET_NOT_AVAILABLE),
+                Arguments.of(Errors.LEADER_NOT_AVAILABLE),
+                Arguments.of(Errors.FENCED_LEADER_EPOCH),
+                Arguments.of(Errors.BROKER_NOT_AVAILABLE),
+                Arguments.of(Errors.INVALID_REQUEST),
+                Arguments.of(Errors.UNKNOWN_LEADER_EPOCH),
+                Arguments.of(Errors.UNKNOWN_TOPIC_OR_PARTITION));
+    }
+
+    private void verifySuccessfulPollAndResponseReceived(
+            CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> actualResult,
+            Map<TopicPartition, OffsetAndTimestamp> expectedResult) throws ExecutionException,
+            InterruptedException {
+        // Following poll should send the request and get a response
+        NetworkClientDelegate.PollResult retriedPoll = requestManager.poll(time.milliseconds());
+        verifySuccessfulPollAwaitingResponse(retriedPoll);
+        NetworkClientDelegate.UnsentRequest unsentRequest = retriedPoll.unsentRequests.get(0);
+        ClientResponse clientResponse = buildClientResponse(unsentRequest,
+                expectedResult);
+        clientResponse.onComplete();
+        verifyRequestSuccessfullyCompleted(actualResult, expectedResult);
+    }
+
+    private void expectSuccessfulRequest(Map<TopicPartition, Node> partitionLeaders) {
+        partitionLeaders.forEach((tp, broker) -> {
+            when(metadata.currentLeader(tp)).thenReturn(testLeaderEpoch(broker));
+            when(subscriptionState.isAssigned(tp)).thenReturn(true);
+        });
+        when(metadata.fetch()).thenReturn(testClusterMetadata(partitionLeaders));
+    }
+
+    private void expectFailedRequest_MissingLeader() {
+        when(metadata.currentLeader(any(TopicPartition.class))).thenReturn(
+                new Metadata.LeaderAndEpoch(Optional.empty(), Optional.of(1)));

Review Comment:
   Well this is seeing it from the stand point that there is a last known epoch of 1. 
   
   If the leader is missing at any point in time, or even if there were errors in the partition metadata received, epochs are still updated on the client side when received in a metadata response ([here](https://github.com/apache/kafka/blob/6391c6603582a4e4b5bb670233c345e53f82a77b/clients/src/main/java/org/apache/kafka/clients/Metadata.java#L352)).  So the `currentLeader` used here will always return an empty leader but with the last seen epoch. I will add a comment to clarify  but surely using an emtpy epoch here would also be ok.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309322217


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(
+            Node node,
+            Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> targetTimes,
+            boolean requireTimestamps,
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests) {
+        ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder
+                .forConsumer(requireTimestamps, isolationLevel, false)
+                .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(targetTimes));
+
+        log.debug("Creating ListOffsetRequest {} for broker {} to reset positions", builder,
+                node);
+
+        NetworkClientDelegate.UnsentRequest unsentRequest = new NetworkClientDelegate.UnsentRequest(
+                builder,
+                Optional.ofNullable(node));
+        unsentRequests.add(unsentRequest);
+        CompletableFuture<ListOffsetResult> result = new CompletableFuture<>();
+        unsentRequest.future().whenComplete((response, error) -> {
+            if (error != null) {
+                log.error("Sending ListOffsetRequest {} to broker {} failed",

Review Comment:
   I see the offsetFetcher uses debug level for this message: mind double check?



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311848058


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));

Review Comment:
   it is pretty ambiguous to me too, from the following test it seems like these are the topics that are added inbetween metadata updates. if a new topic is detected, then a subsequent metadata update will be requested
   
   ```@Test
       public void testTransientTopics() {
           Map<String, Uuid> topicIds = new HashMap<>();
           topicIds.put("foo", Uuid.randomUuid());
           subscription.subscribe(singleton("foo"), new NoOpConsumerRebalanceListener());
           ConsumerMetadata metadata = newConsumerMetadata(false);
           metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWithIds(1, singletonMap("foo", 1), topicIds), false, time.milliseconds());
           assertEquals(topicIds.get("foo"), metadata.topicIds().get("foo"));
           assertFalse(metadata.updateRequested());
   
           metadata.addTransientTopics(singleton("foo"));
           assertFalse(metadata.updateRequested());
   
           metadata.addTransientTopics(singleton("bar"));
           assertTrue(metadata.updateRequested());
   
           Map<String, Integer> topicPartitionCounts = new HashMap<>();
           topicPartitionCounts.put("foo", 1);
           topicPartitionCounts.put("bar", 1);
           topicIds.put("bar", Uuid.randomUuid());
           metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWithIds(1, topicPartitionCounts, topicIds), false, time.milliseconds());
           Map<String, Uuid> metadataTopicIds = metadata.topicIds();
           topicIds.forEach((topicName, topicId) -> assertEquals(topicId, metadataTopicIds.get(topicName)));
           assertFalse(metadata.updateRequested());
   
           assertEquals(Utils.mkSet("foo", "bar"), new HashSet<>(metadata.fetch().topics()));
   
           metadata.clearTransientTopics();
           topicIds.remove("bar");
           metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWithIds(1, topicPartitionCounts, topicIds), false, time.milliseconds());
           assertEquals(singleton("foo"), new HashSet<>(metadata.fetch().topics()));
           assertEquals(topicIds.get("foo"), metadata.topicIds().get("foo"));
           assertNull(topicIds.get("bar"));
       }```
   
   



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] philipnee commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "philipnee (via GitHub)" <gi...@apache.org>.
philipnee commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311835924


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());

Review Comment:
   i can't remember the reason i didn't do that at the beginning - i believe it was discussed at some point.  however i agree with you that it does feel unergonomic. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311736231


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(
+            Node node,
+            Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> targetTimes,
+            boolean requireTimestamps,
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests) {
+        ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder
+                .forConsumer(requireTimestamps, isolationLevel, false)
+                .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(targetTimes));
+
+        log.debug("Creating ListOffsetRequest {} for broker {} to reset positions", builder,
+                node);
+
+        NetworkClientDelegate.UnsentRequest unsentRequest = new NetworkClientDelegate.UnsentRequest(
+                builder,
+                Optional.ofNullable(node));
+        unsentRequests.add(unsentRequest);
+        CompletableFuture<ListOffsetResult> result = new CompletableFuture<>();
+        unsentRequest.future().whenComplete((response, error) -> {
+            if (error != null) {
+                log.error("Sending ListOffsetRequest {} to broker {} failed",
+                        builder,
+                        node,
+                        error);
+                result.completeExceptionally(error);
+            } else {
+                ListOffsetsResponse lor = (ListOffsetsResponse) response.responseBody();
+                log.trace("Received ListOffsetResponse {} from broker {}", lor, node);
+                try {
+                    ListOffsetResult listOffsetResult =
+                            offsetFetcherUtils.handleListOffsetResponse(lor);
+                    result.complete(listOffsetResult);
+                } catch (RuntimeException e) {
+                    result.completeExceptionally(e);
+                }
+            }
+        });
+        return result;
+    }
+
+    private static class ListOffsetsRequestState {
+
+        private final Map<TopicPartition, Long> timestampsToSearch;
+        private final Map<TopicPartition, ListOffsetData> fetchedOffsets;
+        private final Map<TopicPartition, Long> remainingToSearch;
+        private final CompletableFuture<ListOffsetResult> globalResult;
+        final boolean requireTimestamps;
+        final OffsetFetcherUtils offsetFetcherUtils;
+        final IsolationLevel isolationLevel;
+
+        private ListOffsetsRequestState(Map<TopicPartition, Long> timestampsToSearch,
+                                        boolean requireTimestamps,
+                                        OffsetFetcherUtils offsetFetcherUtils,
+                                        IsolationLevel isolationLevel) {
+            remainingToSearch = new HashMap<>();
+            fetchedOffsets = new HashMap<>();
+            globalResult = new CompletableFuture<>();
+
+            this.timestampsToSearch = timestampsToSearch;
+            this.requireTimestamps = requireTimestamps;
+            this.offsetFetcherUtils = offsetFetcherUtils;
+            this.isolationLevel = isolationLevel;
+        }
+
+        private void addPartitionsToRetry(Set<TopicPartition> partitionsToRetry) {
+            remainingToSearch.putAll(partitionsToRetry.stream()
+                    .collect(Collectors.toMap(tp -> tp, timestampsToSearch::get)));
+        }
+    }
+
+    private static class MultiNodeRequest {
+        final Map<TopicPartition, ListOffsetData> fetchedTimestampOffsets;
+        final Set<TopicPartition> partitionsToRetry;
+        final AtomicInteger expectedResponses;
+        final CompletableFuture<ListOffsetResult> resultFuture;
+
+        private MultiNodeRequest(int nodeCount) {
+            fetchedTimestampOffsets = new HashMap<>();
+            partitionsToRetry = new HashSet<>();
+            expectedResponses = new AtomicInteger(nodeCount);
+            resultFuture = new CompletableFuture<>();
+        }
+
+        private void onComplete(BiConsumer<? super ListOffsetResult, ? super Throwable> action) {
+            resultFuture.whenComplete(action);
+        }
+
+        private void addPartialResult(ListOffsetResult partialResult) {
+            try {
+                fetchedTimestampOffsets.putAll(partialResult.fetchedOffsets);
+                partitionsToRetry.addAll(partialResult.partitionsToRetry);
+
+                if (expectedResponses.decrementAndGet() == 0) {
+                    ListOffsetResult result =
+                            new ListOffsetResult(fetchedTimestampOffsets,
+                                    partitionsToRetry);
+                    resultFuture.complete(result);
+                }
+            } catch (RuntimeException e) {
+                resultFuture.completeExceptionally(e);
+            }
+        }
+    }
+
+    /**
+     * Group partitions by leader. Topic partitions from `timestampsToSearch` for which
+     * the leader is not known are kept as `remainingToSearch` in the `listOffsetsRequestState`
+     *
+     * @param timestampsToSearch      The mapping from partitions to the target timestamps
+     * @param listOffsetsRequestState Request state that will be extended by adding to its
+     *                                `remainingToSearch` map all partitions for which the
+     *                                request cannot be performed due to unknown leader (need
+     *                                metadata update).
+     */
+    private Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> groupListOffsetRequests(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        final Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> partitionDataMap = new HashMap<>();
+        for (Map.Entry<TopicPartition, Long> entry : timestampsToSearch.entrySet()) {
+            TopicPartition tp = entry.getKey();
+            Long offset = entry.getValue();
+            Metadata.LeaderAndEpoch leaderAndEpoch = metadata.currentLeader(tp);
+
+            if (!leaderAndEpoch.leader.isPresent()) {
+                log.debug("Leader for partition {} is unknown for fetching offset {}", tp, offset);
+                metadata.requestUpdate();
+                if (listOffsetsRequestState != null) {

Review Comment:
   It won't be null with the code included in this PR, but it will once we add the logic for resetting positions (already implemented, that's why this check ended up here). I intentionally left reset/validate positions out of this first PR, to keep the size under control, but it will follow right after.
   
   Reset position logic reuses the same `groupListOffsetRequests` functionality. It does not require to keep a state though, because it does not retry requests in the same way the `fetchOffsetsByTimes` does. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311939026


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));

Review Comment:
   Those are topics that get a special treatment regarding consumer metadata lifecycle: always included in metadata requests and retained. Given that the offsets fetch requests heavily rely on metadata to get the leader to get offsets from, topics involved in the request are marked as transient for the duration of the request.
   
   This is used in all the 3 functions related to retrieving partition offsets in the the current consumer (ex. beginningOffsets [here](https://github.com/apache/kafka/blob/c2bb8eb875d94568d1ad19bf207ec69c182405d4/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetFetcher.java#L200)), and it was added in the same way for those 3 funcs here, on this `fetchOffsets`
   
   Please let me know if there something I might be missing regarding how that logic applies into the new consumer. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1701431659

   Thanks @junrao , @philipnee and @kirktrue for all the helpful comments. All addressed!


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309145935


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();

Review Comment:
   There is a retry logic based on the `requestsToRetry`. Requests are retried if:
   - the leader to get partition offsets from is not available (stale metadata case [here](https://github.com/apache/kafka/blob/34afb96b6c52617957d39ffba8fdf24f1e75bc06/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L175))
   - offsets were not found for a partition after trying all the known leaders, see [here](https://github.com/apache/kafka/blob/34afb96b6c52617957d39ffba8fdf24f1e75bc06/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L231)
   
   Other than that, the request will fail and won't be retried:
   -  fail with error, if any, after completing requests to known leaders, [here](https://github.com/apache/kafka/blob/34afb96b6c52617957d39ffba8fdf24f1e75bc06/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L235)
   - timeout if no responses received (based on the ListOffsetsApplicationEvent future timeout)
   
   This covers the retry logic of the current implementation, but let me know if you think we might be missing something. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311693255


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",

Review Comment:
   Agree with the debug as commented above, code updated. Thanks!



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311707449


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,

Review Comment:
   My mistake with the name, this is the map of timestamps per partition to look offsets for (`timestampsToSearch`). Fixed.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311778993


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(

Review Comment:
   Renamed it to `buildListOffsetsRequests` and updated the comments too. Not using "enqueue" in the func name here as it is on the `fetchOffsetsByTimes` where the requests built here are actually added to the `requestsToSend` queue)



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311895574


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);

Review Comment:
   Agree that it is not a risk here because of the nature of how it is used. Just for clarity I moved it to the end (after the `requestsToRetry` initialization, which is the only one used in the callback), and added a comment.



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1311939026


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));

Review Comment:
   Those are topics that get a special treatment regarding consumer metadata lifecycle: always included in metadata requests and retained (even if they are not part of the subscription, for ex). Given that the offsets fetch requests heavily rely on metadata to get the leader to get offsets from, topics involved in the request are marked as transient for the duration of the request.
   
   This is used in all the 3 functions related to retrieving partition offsets in the the current consumer (ex. beginningOffsets [here](https://github.com/apache/kafka/blob/c2bb8eb875d94568d1ad19bf207ec69c182405d4/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetFetcher.java#L200)), and it was added in the same way for those 3 funcs here, on this `fetchOffsets`
   
   Please let me know if there something I might be missing regarding how that logic applies into the new consumer. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] junrao commented on a diff in pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #14308:
URL: https://github.com/apache/kafka/pull/14308#discussion_r1309440032


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,

Review Comment:
   Hmm, why is it called ResetTimestamps?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(
+            Node node,
+            Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> targetTimes,
+            boolean requireTimestamps,
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests) {
+        ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder
+                .forConsumer(requireTimestamps, isolationLevel, false)
+                .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(targetTimes));
+
+        log.debug("Creating ListOffsetRequest {} for broker {} to reset positions", builder,
+                node);
+
+        NetworkClientDelegate.UnsentRequest unsentRequest = new NetworkClientDelegate.UnsentRequest(
+                builder,
+                Optional.ofNullable(node));
+        unsentRequests.add(unsentRequest);
+        CompletableFuture<ListOffsetResult> result = new CompletableFuture<>();
+        unsentRequest.future().whenComplete((response, error) -> {
+            if (error != null) {
+                log.error("Sending ListOffsetRequest {} to broker {} failed",
+                        builder,
+                        node,
+                        error);
+                result.completeExceptionally(error);
+            } else {
+                ListOffsetsResponse lor = (ListOffsetsResponse) response.responseBody();
+                log.trace("Received ListOffsetResponse {} from broker {}", lor, node);
+                try {
+                    ListOffsetResult listOffsetResult =
+                            offsetFetcherUtils.handleListOffsetResponse(lor);
+                    result.complete(listOffsetResult);
+                } catch (RuntimeException e) {
+                    result.completeExceptionally(e);
+                }
+            }
+        });
+        return result;
+    }
+
+    private static class ListOffsetsRequestState {
+
+        private final Map<TopicPartition, Long> timestampsToSearch;
+        private final Map<TopicPartition, ListOffsetData> fetchedOffsets;
+        private final Map<TopicPartition, Long> remainingToSearch;
+        private final CompletableFuture<ListOffsetResult> globalResult;
+        final boolean requireTimestamps;
+        final OffsetFetcherUtils offsetFetcherUtils;
+        final IsolationLevel isolationLevel;
+
+        private ListOffsetsRequestState(Map<TopicPartition, Long> timestampsToSearch,
+                                        boolean requireTimestamps,
+                                        OffsetFetcherUtils offsetFetcherUtils,
+                                        IsolationLevel isolationLevel) {
+            remainingToSearch = new HashMap<>();
+            fetchedOffsets = new HashMap<>();
+            globalResult = new CompletableFuture<>();
+
+            this.timestampsToSearch = timestampsToSearch;
+            this.requireTimestamps = requireTimestamps;
+            this.offsetFetcherUtils = offsetFetcherUtils;
+            this.isolationLevel = isolationLevel;
+        }
+
+        private void addPartitionsToRetry(Set<TopicPartition> partitionsToRetry) {
+            remainingToSearch.putAll(partitionsToRetry.stream()
+                    .collect(Collectors.toMap(tp -> tp, timestampsToSearch::get)));
+        }
+    }
+
+    private static class MultiNodeRequest {
+        final Map<TopicPartition, ListOffsetData> fetchedTimestampOffsets;
+        final Set<TopicPartition> partitionsToRetry;
+        final AtomicInteger expectedResponses;
+        final CompletableFuture<ListOffsetResult> resultFuture;
+
+        private MultiNodeRequest(int nodeCount) {
+            fetchedTimestampOffsets = new HashMap<>();
+            partitionsToRetry = new HashSet<>();
+            expectedResponses = new AtomicInteger(nodeCount);
+            resultFuture = new CompletableFuture<>();
+        }
+
+        private void onComplete(BiConsumer<? super ListOffsetResult, ? super Throwable> action) {
+            resultFuture.whenComplete(action);
+        }
+
+        private void addPartialResult(ListOffsetResult partialResult) {
+            try {
+                fetchedTimestampOffsets.putAll(partialResult.fetchedOffsets);
+                partitionsToRetry.addAll(partialResult.partitionsToRetry);
+
+                if (expectedResponses.decrementAndGet() == 0) {
+                    ListOffsetResult result =
+                            new ListOffsetResult(fetchedTimestampOffsets,
+                                    partitionsToRetry);
+                    resultFuture.complete(result);
+                }
+            } catch (RuntimeException e) {
+                resultFuture.completeExceptionally(e);
+            }
+        }
+    }
+
+    /**
+     * Group partitions by leader. Topic partitions from `timestampsToSearch` for which
+     * the leader is not known are kept as `remainingToSearch` in the `listOffsetsRequestState`
+     *
+     * @param timestampsToSearch      The mapping from partitions to the target timestamps
+     * @param listOffsetsRequestState Request state that will be extended by adding to its
+     *                                `remainingToSearch` map all partitions for which the
+     *                                request cannot be performed due to unknown leader (need
+     *                                metadata update).
+     */
+    private Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> groupListOffsetRequests(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        final Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> partitionDataMap = new HashMap<>();
+        for (Map.Entry<TopicPartition, Long> entry : timestampsToSearch.entrySet()) {
+            TopicPartition tp = entry.getKey();
+            Long offset = entry.getValue();
+            Metadata.LeaderAndEpoch leaderAndEpoch = metadata.currentLeader(tp);
+
+            if (!leaderAndEpoch.leader.isPresent()) {
+                log.debug("Leader for partition {} is unknown for fetching offset {}", tp, offset);
+                metadata.requestUpdate();
+                if (listOffsetsRequestState != null) {

Review Comment:
   Will `listOffsetsRequestState` ever be null?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult}
+     * containing it.
+     */
+    @Override
+    public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
+        if (requestsToSend.isEmpty()) {
+            return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, Collections.emptyList());
+        }
+
+        NetworkClientDelegate.PollResult pollResult =
+                new NetworkClientDelegate.PollResult(Long.MAX_VALUE, new ArrayList<>(requestsToSend));
+        this.requestsToSend.clear();
+
+        return pollResult;
+    }
+
+    /**
+     * Retrieve offsets for the given partitions and timestamp.
+     *
+     * @param timestampsToSearch Partitions and target timestamps to get offsets for
+     * @param requireTimestamps  True if this should fail with an UnsupportedVersionException if the
+     *                           broker does not support fetching precise timestamps for offsets
+     * @return Future containing the map of {@link TopicPartition} and {@link OffsetAndTimestamp}
+     * found (offset of the first message whose timestamp is greater than or equals to the target
+     * timestamp).The future will complete when the requests responses are received and
+     * processed, following a call to {@link #poll(long)}
+     */
+    public CompletableFuture<Map<TopicPartition, OffsetAndTimestamp>> fetchOffsets(
+            final Map<TopicPartition, Long> timestampsToSearch,
+            final boolean requireTimestamps) {
+        if (timestampsToSearch.isEmpty()) {
+            return CompletableFuture.completedFuture(Collections.emptyMap());
+        }
+        metadata.addTransientTopics(OffsetFetcherUtils.topicsForPartitions(timestampsToSearch.keySet()));
+
+        ListOffsetsRequestState listOffsetsRequestState = new ListOffsetsRequestState(
+                timestampsToSearch,
+                requireTimestamps,
+                offsetFetcherUtils,
+                isolationLevel);
+        listOffsetsRequestState.globalResult.whenComplete((result, error) -> {
+            metadata.clearTransientTopics();
+            if (error != null) {
+                log.error("Fetch offsets completed with error for partitions and timestamps {}.",
+                        timestampsToSearch, error);
+            } else {
+                log.debug("Fetch offsets completed successfully for partitions and timestamps {}." +
+                        " Result {}", timestampsToSearch, result);
+            }
+        });
+
+        fetchOffsetsByTimes(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+
+        return listOffsetsRequestState.globalResult.thenApply(result ->
+                OffsetFetcherUtils.buildOffsetsForTimesResult(timestampsToSearch, result.fetchedOffsets));
+    }
+
+    /**
+     * Generate requests for partitions with known leaders. Update the listOffsetsRequestState by adding
+     * partitions with unknown leader to the listOffsetsRequestState.remainingToSearch
+     */
+    private void fetchOffsetsByTimes(final Map<TopicPartition, Long> timestampsToSearch,
+                                     final boolean requireTimestamps,
+                                     final ListOffsetsRequestState listOffsetsRequestState) {
+        if (timestampsToSearch.isEmpty()) {
+            // Early return if empty map to avoid wrongfully raising StaleMetadataException on
+            // empty grouping
+            return;
+        }
+        try {
+            List<NetworkClientDelegate.UnsentRequest> unsentRequests = sendListOffsetsRequests(
+                    timestampsToSearch, requireTimestamps, listOffsetsRequestState);
+            requestsToSend.addAll(unsentRequests);
+        } catch (StaleMetadataException e) {
+            requestsToRetry.add(listOffsetsRequestState);
+        }
+    }
+
+    @Override
+    public void onUpdate(ClusterResource clusterResource) {
+        // Retry requests that were awaiting a metadata update. Process a copy of the list to
+        // avoid errors, given that the list of requestsToRetry may be modified from the
+        // fetchOffsetsByTimes call if any of the requests being retried fails
+        List<ListOffsetsRequestState> requestsToProcess = new ArrayList<>(requestsToRetry);
+        requestsToRetry.clear();
+        requestsToProcess.forEach(requestState -> {
+            Map<TopicPartition, Long> timestampsToSearch =
+                    new HashMap<>(requestState.remainingToSearch);
+            requestState.remainingToSearch.clear();
+            fetchOffsetsByTimes(timestampsToSearch, requestState.requireTimestamps, requestState);
+        });
+    }
+
+    /**
+     * Search the offsets by target times for the specified partitions.
+     *
+     * @param partitionResetTimestamps the mapping between partitions and target time
+     * @param requireTimestamps        true if we should fail with an UnsupportedVersionException if the broker does
+     *                                 not support fetching precise timestamps for offsets
+     * @return A list of
+     * {@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
+     * that can be polled to obtain the corresponding timestamps and offsets.
+     */
+    private List<NetworkClientDelegate.UnsentRequest> sendListOffsetsRequests(
+            final Map<TopicPartition, Long> partitionResetTimestamps,
+            final boolean requireTimestamps,
+            final ListOffsetsRequestState listOffsetsRequestState) {
+        log.debug("Building ListOffsets request for partitions {}", partitionResetTimestamps);
+        Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> partitionResetTimestampsByNode =
+                groupListOffsetRequests(partitionResetTimestamps, listOffsetsRequestState);
+        if (partitionResetTimestampsByNode.isEmpty()) {
+            throw new StaleMetadataException();
+        }
+
+        final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
+        MultiNodeRequest multiNodeRequest = new MultiNodeRequest(partitionResetTimestampsByNode.size());
+        multiNodeRequest.onComplete((multiNodeResult, error) -> {
+            // Done sending request to a set of known leaders
+            if (error == null) {
+                listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
+                listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
+                offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
+                        isolationLevel);
+
+                if (listOffsetsRequestState.remainingToSearch.size() == 0) {
+                    ListOffsetResult listOffsetResult =
+                            new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
+                                    listOffsetsRequestState.remainingToSearch.keySet());
+                    listOffsetsRequestState.globalResult.complete(listOffsetResult);
+                } else {
+                    requestsToRetry.add(listOffsetsRequestState);
+                }
+            } else {
+                log.debug("ListOffsets request failed with error", error);
+                listOffsetsRequestState.globalResult.completeExceptionally(error);
+            }
+        });
+
+        for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : partitionResetTimestampsByNode.entrySet()) {
+            Node node = entry.getKey();
+
+            CompletableFuture<ListOffsetResult> partialResult = sendListOffsetRequestToNode(
+                    node,
+                    entry.getValue(),
+                    requireTimestamps,
+                    unsentRequests);
+
+            partialResult.whenComplete((result, error) -> {
+                if (error != null) {
+                    multiNodeRequest.resultFuture.completeExceptionally(error);
+                } else {
+                    multiNodeRequest.addPartialResult(result);
+                }
+            });
+        }
+        return unsentRequests;
+    }
+
+    /**
+     * Build ListOffsetRequest to send to a specific broker for the partitions and
+     * target timestamps. This also adds the request to the list of unsentRequests.
+     **/
+    private CompletableFuture<ListOffsetResult> sendListOffsetRequestToNode(

Review Comment:
   `sendListOffsetRequestToNode` is a bit confusing since the method only creates a request to be sent.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * 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.clients.consumer.internals;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.Metadata;
+import org.apache.kafka.clients.StaleMetadataException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetData;
+import org.apache.kafka.clients.consumer.internals.OffsetFetcherUtils.ListOffsetResult;
+import org.apache.kafka.common.ClusterResource;
+import org.apache.kafka.common.ClusterResourceListener;
+import org.apache.kafka.common.IsolationLevel;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.ListOffsetsRequestData;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.requests.ListOffsetsResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Manager responsible for building the following requests to retrieve partition offsets, and
+ * processing its responses.
+ * <ul>
+ *      <li>ListOffset request</li>
+ *      <li>OffsetForLeaderEpoch request</li>
+ * </ul>
+ * Requests are kept in-memory ready to be sent on the next call to {@link #poll(long)}.
+ * <br>
+ * Partition leadership information required to build ListOffset requests is retrieved from the
+ * {@link ConsumerMetadata}, so this implements {@link ClusterResourceListener} to get notified
+ * when the cluster metadata is updated.
+ */
+public class OffsetsRequestManager implements RequestManager, ClusterResourceListener {
+
+    private final ConsumerMetadata metadata;
+    private final IsolationLevel isolationLevel;
+    private final Logger log;
+    private final OffsetFetcherUtils offsetFetcherUtils;
+
+    private final Set<ListOffsetsRequestState> requestsToRetry;
+    private final List<NetworkClientDelegate.UnsentRequest> requestsToSend;
+
+    public OffsetsRequestManager(final SubscriptionState subscriptionState,
+                                 final ConsumerMetadata metadata,
+                                 final IsolationLevel isolationLevel,
+                                 final Time time,
+                                 final long retryBackoffMs,
+                                 final ApiVersions apiVersions,
+                                 final LogContext logContext) {
+        requireNonNull(subscriptionState);
+        requireNonNull(metadata);
+        requireNonNull(isolationLevel);
+        requireNonNull(time);
+        requireNonNull(apiVersions);
+        requireNonNull(logContext);
+
+        this.metadata = metadata;
+        this.metadata.addClusterUpdateListener(this);
+        this.isolationLevel = isolationLevel;
+        this.log = logContext.logger(getClass());
+        this.requestsToRetry = new HashSet<>();
+        this.requestsToSend = new ArrayList<>();
+        this.offsetFetcherUtils = new OffsetFetcherUtils(logContext, metadata, subscriptionState,
+                time, retryBackoffMs, apiVersions);
+    }
+
+    /**
+     * Determine if a there are pending fetch offsets requests to be sent and build a

Review Comment:
   a there are => there are



-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] lianetm commented on pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #14308:
URL: https://github.com/apache/kafka/pull/14308#issuecomment-1703178243

   Build completed with 10 unrelated test failures (mainly due to unexpected threads found before running them & timeouts):
   
   Build / JDK 20 and Scala 2.13 / initializationError – org.apache.kafka.tiered.storage.integration.OffloadAndConsumeFromLeaderTest
   Build / JDK 17 and Scala 2.13 / testLegacyAlterConfigs() – kafka.server.KRaftClusterTest
   Build / JDK 17 and Scala 2.13 / testBalancePartitionLeaders() – org.apache.kafka.controller.QuorumControllerTest
   Build / JDK 17 and Scala 2.13 / initializationError – org.apache.kafka.tiered.storage.integration.OffloadAndConsumeFromLeaderTest
   Build / JDK 8 and Scala 2.12 / testReplicateSourceDefault() – org.apache.kafka.connect.mirror.integration.MirrorConnectorsIntegrationExactlyOnceTest
   Build / JDK 8 and Scala 2.12 / testBalancePartitionLeaders() – org.apache.kafka.controller.QuorumControllerTest
   Build / JDK 8 and Scala 2.12 / initializationError – org.apache.kafka.tiered.storage.integration.OffloadAndConsumeFromLeaderTest
   Build / JDK 11 and Scala 2.13 / testBalancePartitionLeaders() – org.apache.kafka.controller.QuorumControllerTest
   Build / JDK 11 and Scala 2.13 / initializationError – org.apache.kafka.tiered.storage.integration.OffloadAndConsumeFromLeaderTest
   Build / JDK 11 and Scala 2.13 / testTaskRequestWithOldStartMsGetsUpdated() – org.apache.kafka.trogdor.coordinator.CoordinatorTest


-- 
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: jira-unsubscribe@kafka.apache.org

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


[GitHub] [kafka] junrao merged pull request #14308: KAFKA-14965 - OffsetsRequestsManager implementation & API integration

Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao merged PR #14308:
URL: https://github.com/apache/kafka/pull/14308


-- 
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: jira-unsubscribe@kafka.apache.org

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