AndrewJSchofield commented on code in PR #18096:
URL: https://github.com/apache/kafka/pull/18096#discussion_r1875037969


##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/ShareGroupAutoOffsetResetStrategy.java:
##########
@@ -0,0 +1,162 @@
+/*
+ * 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.coordinator.group;
+
+import org.apache.kafka.common.config.ConfigDef;
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.utils.Utils;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.Optional;
+
+public class ShareGroupAutoOffsetResetStrategy {
+    public enum StrategyType {
+        LATEST, EARLIEST, BY_DURATION;
+
+        @Override
+        public String toString() {
+            return super.toString().toLowerCase(Locale.ROOT);
+        }
+    }
+
+    public static final ShareGroupAutoOffsetResetStrategy EARLIEST = new 
ShareGroupAutoOffsetResetStrategy(StrategyType.EARLIEST);
+    public static final ShareGroupAutoOffsetResetStrategy LATEST = new 
ShareGroupAutoOffsetResetStrategy(StrategyType.LATEST);
+
+    private final StrategyType type;
+    private final Optional<Duration> duration;
+
+    private ShareGroupAutoOffsetResetStrategy(StrategyType type) {
+        this.type = type;
+        this.duration = Optional.empty();
+    }
+
+    private ShareGroupAutoOffsetResetStrategy(Duration duration) {
+        this.type = StrategyType.BY_DURATION;
+        this.duration = Optional.of(duration);
+    }
+
+    /**
+     *  Returns the AutoOffsetResetStrategy from the given string.
+     */
+    public static ShareGroupAutoOffsetResetStrategy fromString(String 
offsetStrategy) {
+        if (offsetStrategy == null) {
+            throw new IllegalArgumentException("Auto offset reset strategy is 
null");
+        }
+
+        if (StrategyType.BY_DURATION.toString().equals(offsetStrategy)) {
+            throw new IllegalArgumentException("<:duration> part is missing in 
by_duration auto offset reset strategy.");
+        }
+
+        if 
(Arrays.asList(Utils.enumOptions(StrategyType.class)).contains(offsetStrategy)) 
{
+            StrategyType type = 
StrategyType.valueOf(offsetStrategy.toUpperCase(Locale.ROOT));
+            switch (type) {
+                case EARLIEST:
+                    return EARLIEST;
+                case LATEST:
+                    return LATEST;
+                default:
+                    throw new IllegalArgumentException("Unknown auto offset 
reset strategy: " + offsetStrategy);
+            }
+        }
+
+        if (offsetStrategy.startsWith(StrategyType.BY_DURATION + ":")) {
+            String isoDuration = 
offsetStrategy.substring(StrategyType.BY_DURATION.toString().length() + 1);
+            try {
+                Duration duration = Duration.parse(isoDuration);
+                if (duration.isNegative()) {
+                    throw new IllegalArgumentException("Negative duration is 
not supported in by_duration offset reset strategy.");
+                }
+                return new ShareGroupAutoOffsetResetStrategy(duration);
+            } catch (Exception e) {
+                throw new IllegalArgumentException("Unable to parse duration 
string in by_duration offset reset strategy.", e);
+            }
+        }
+
+        throw new IllegalArgumentException("Unknown auto offset reset 
strategy: " + offsetStrategy);
+    }
+
+    /**
+     * Returns the offset reset strategy type.
+     */
+    public StrategyType type() {
+        return type;
+    }
+
+    /**
+     * Returns the name of the offset reset strategy.
+     */
+    public String name() {
+        return type.toString();
+    }
+
+    /**
+     * Return the timestamp to be used for the ListOffsetsRequest.
+     * @return the timestamp for the OffsetResetStrategy,
+     * if the strategy is EARLIEST or LATEST or duration is provided
+     * else return Optional.empty()
+     */
+    public Optional<Long> timestamp() {
+        if (type == StrategyType.EARLIEST)
+            return Optional.of(ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        else if (type == StrategyType.LATEST)
+            return Optional.of(ListOffsetsRequest.LATEST_TIMESTAMP);
+        else if (type == StrategyType.BY_DURATION && duration.isPresent()) {
+            Instant now = Instant.now();
+            return Optional.of(now.minus(duration.get()).toEpochMilli());
+        } else
+            return Optional.empty();
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        ShareGroupAutoOffsetResetStrategy that = 
(ShareGroupAutoOffsetResetStrategy) o;
+        return type == that.type && Objects.equals(duration, that.duration);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(type, duration);
+    }
+
+    @Override
+    public String toString() {
+        return "ShareGroupAutoOffsetReset{" +

Review Comment:
   `ShareGroupAutoOffsetResetStrategy` I think.



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupConfig.java:
##########
@@ -53,8 +50,14 @@ public final class GroupConfig extends AbstractConfig {
     public static final String SHARE_RECORD_LOCK_DURATION_MS_CONFIG = 
"share.record.lock.duration.ms";
 
     public static final String SHARE_AUTO_OFFSET_RESET_CONFIG = 
"share.auto.offset.reset";
-    public static final String SHARE_AUTO_OFFSET_RESET_DEFAULT = 
ShareGroupAutoOffsetReset.LATEST.toString();
-    public static final String SHARE_AUTO_OFFSET_RESET_DOC = "The strategy to 
initialize the share-partition start offset.";
+    public static final String SHARE_AUTO_OFFSET_RESET_DEFAULT = 
ShareGroupAutoOffsetResetStrategy.LATEST.name();
+    public static final String SHARE_AUTO_OFFSET_RESET_DOC = "The strategy to 
initialize the share-partition start offset. " +
+        "<ul><li>earliest: automatically reset the offset to the earliest 
offset" +
+        "<li>latest: automatically reset the offset to the latest offset</li>" 
+
+        "<li>by_duration:<duration>: automatically reset the offset to a 
configured <duration> from the current timestamp. " +
+        "<duration> must be specified in ISO8601 format (PnDTnHnMn.nS). " +
+        "Negative duration is not allowed.</li>" +
+        "<li>anything else: throw exception to the share consumer.</li></ul>";

Review Comment:
   I would remove the "anything else" part of this. It's implied, I think.



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/ShareGroupAutoOffsetResetStrategy.java:
##########
@@ -0,0 +1,162 @@
+/*
+ * 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.coordinator.group;
+
+import org.apache.kafka.common.config.ConfigDef;
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.utils.Utils;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.Optional;
+
+public class ShareGroupAutoOffsetResetStrategy {
+    public enum StrategyType {
+        LATEST, EARLIEST, BY_DURATION;
+
+        @Override
+        public String toString() {
+            return super.toString().toLowerCase(Locale.ROOT);
+        }
+    }
+
+    public static final ShareGroupAutoOffsetResetStrategy EARLIEST = new 
ShareGroupAutoOffsetResetStrategy(StrategyType.EARLIEST);
+    public static final ShareGroupAutoOffsetResetStrategy LATEST = new 
ShareGroupAutoOffsetResetStrategy(StrategyType.LATEST);
+
+    private final StrategyType type;
+    private final Optional<Duration> duration;
+
+    private ShareGroupAutoOffsetResetStrategy(StrategyType type) {
+        this.type = type;
+        this.duration = Optional.empty();
+    }
+
+    private ShareGroupAutoOffsetResetStrategy(Duration duration) {
+        this.type = StrategyType.BY_DURATION;
+        this.duration = Optional.of(duration);
+    }
+
+    /**
+     *  Returns the AutoOffsetResetStrategy from the given string.
+     */
+    public static ShareGroupAutoOffsetResetStrategy fromString(String 
offsetStrategy) {
+        if (offsetStrategy == null) {
+            throw new IllegalArgumentException("Auto offset reset strategy is 
null");
+        }
+
+        if (StrategyType.BY_DURATION.toString().equals(offsetStrategy)) {
+            throw new IllegalArgumentException("<:duration> part is missing in 
by_duration auto offset reset strategy.");
+        }
+
+        if 
(Arrays.asList(Utils.enumOptions(StrategyType.class)).contains(offsetStrategy)) 
{
+            StrategyType type = 
StrategyType.valueOf(offsetStrategy.toUpperCase(Locale.ROOT));
+            switch (type) {
+                case EARLIEST:
+                    return EARLIEST;
+                case LATEST:
+                    return LATEST;
+                default:
+                    throw new IllegalArgumentException("Unknown auto offset 
reset strategy: " + offsetStrategy);
+            }
+        }
+
+        if (offsetStrategy.startsWith(StrategyType.BY_DURATION + ":")) {
+            String isoDuration = 
offsetStrategy.substring(StrategyType.BY_DURATION.toString().length() + 1);
+            try {
+                Duration duration = Duration.parse(isoDuration);
+                if (duration.isNegative()) {
+                    throw new IllegalArgumentException("Negative duration is 
not supported in by_duration offset reset strategy.");
+                }
+                return new ShareGroupAutoOffsetResetStrategy(duration);
+            } catch (Exception e) {
+                throw new IllegalArgumentException("Unable to parse duration 
string in by_duration offset reset strategy.", e);
+            }
+        }
+
+        throw new IllegalArgumentException("Unknown auto offset reset 
strategy: " + offsetStrategy);
+    }
+
+    /**
+     * Returns the offset reset strategy type.
+     */
+    public StrategyType type() {
+        return type;
+    }
+
+    /**
+     * Returns the name of the offset reset strategy.
+     */
+    public String name() {
+        return type.toString();
+    }
+
+    /**
+     * Return the timestamp to be used for the ListOffsetsRequest.
+     * @return the timestamp for the OffsetResetStrategy,
+     * if the strategy is EARLIEST or LATEST or duration is provided
+     * else return Optional.empty()
+     */
+    public Optional<Long> timestamp() {
+        if (type == StrategyType.EARLIEST)
+            return Optional.of(ListOffsetsRequest.EARLIEST_TIMESTAMP);
+        else if (type == StrategyType.LATEST)
+            return Optional.of(ListOffsetsRequest.LATEST_TIMESTAMP);
+        else if (type == StrategyType.BY_DURATION && duration.isPresent()) {
+            Instant now = Instant.now();
+            return Optional.of(now.minus(duration.get()).toEpochMilli());
+        } else
+            return Optional.empty();
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        ShareGroupAutoOffsetResetStrategy that = 
(ShareGroupAutoOffsetResetStrategy) o;
+        return type == that.type && Objects.equals(duration, that.duration);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(type, duration);
+    }
+
+    @Override
+    public String toString() {
+        return "ShareGroupAutoOffsetReset{" +
+                "type=" + type +
+                (duration.map(value -> ", duration=" + value).orElse("")) +
+                '}';
+    }
+
+    public static class Validator implements ConfigDef.Validator {
+        @Override
+        public void ensureValid(String name, Object value) {
+            String offsetStrategy = (String) value;
+            try {
+                fromString(offsetStrategy);
+            } catch (Exception e) {
+                throw new ConfigException(name, value, "Invalid value `" + 
offsetStrategy + "` for configuration " +
+                        name + ". The value must be either 'earliest', 
'latest', 'none' or of the format 'by_duration:<PnDTnHnMn.nS.>'.");

Review Comment:
   `none` is not permitted for a share group.



##########
core/src/main/java/kafka/server/share/ShareFetchUtils.java:
##########
@@ -161,6 +161,20 @@ static long offsetForLatestTimestamp(TopicIdPartition 
topicIdPartition, ReplicaM
         return timestampAndOffset.get().offset;
     }
 
+    /**
+     * The method is used to get the offset for the given timestamp for the 
topic-partition.
+     *
+     * @return The offset for the given timestamp.
+     */
+    static long offsetForTimestamp(TopicIdPartition topicIdPartition, 
ReplicaManager replicaManager, long timestampToSearch, int leaderEpoch) {
+        Option<FileRecords.TimestampAndOffset> timestampAndOffset = 
replicaManager.fetchOffsetForTimestamp(
+            topicIdPartition.topicPartition(), timestampToSearch, 
Option.empty(), Optional.of(leaderEpoch), true).timestampAndOffsetOpt();
+        if (timestampAndOffset.isEmpty()) {
+            throw new OffsetNotAvailableException("offset for timestamp to 
search: " + timestampToSearch + " not found for topic partition: " + 
topicIdPartition);

Review Comment:
   For consistency, I would adjust the capitalisation. I suggest `"Offset for 
timestamp " + timestamptoSearch + " not found for topic partition"` instead.



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/ShareGroupAutoOffsetResetStrategyTest.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.coordinator.group;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ShareGroupAutoOffsetResetStrategyTest {
+
+    @Test
+    public void testFromString() {
+        assertEquals(ShareGroupAutoOffsetResetStrategy.EARLIEST, 
ShareGroupAutoOffsetResetStrategy.fromString("earliest"));
+        assertEquals(ShareGroupAutoOffsetResetStrategy.LATEST, 
ShareGroupAutoOffsetResetStrategy.fromString("latest"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("invalid"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:invalid"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:-PT1H"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("LATEST"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("EARLIEST"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString("NONE"));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString(""));
+        assertThrows(IllegalArgumentException.class, () -> 
ShareGroupAutoOffsetResetStrategy.fromString(null));
+
+        ShareGroupAutoOffsetResetStrategy strategy = 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:PT1H");
+        assertEquals("by_duration", strategy.name());
+    }
+
+    @Test
+    public void testValidator() {
+        ShareGroupAutoOffsetResetStrategy.Validator validator = new 
ShareGroupAutoOffsetResetStrategy.Validator();
+        assertDoesNotThrow(() -> validator.ensureValid("test", "earliest"));
+        assertDoesNotThrow(() -> validator.ensureValid("test", "latest"));
+        assertDoesNotThrow(() -> validator.ensureValid("test", 
"by_duration:PT1H"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "invalid"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "by_duration:invalid"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "by_duration:-PT1H"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "by_duration:"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "by_duration"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "LATEST"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "EARLIEST"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", "NONE"));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", ""));
+        assertThrows(ConfigException.class, () -> 
validator.ensureValid("test", null));
+    }
+
+    @Test
+    public void testEqualsAndHashCode() {
+        ShareGroupAutoOffsetResetStrategy earliest1 = 
ShareGroupAutoOffsetResetStrategy.fromString("earliest");
+        ShareGroupAutoOffsetResetStrategy earliest2 = 
ShareGroupAutoOffsetResetStrategy.fromString("earliest");
+        ShareGroupAutoOffsetResetStrategy latest1 = 
ShareGroupAutoOffsetResetStrategy.fromString("latest");
+
+        ShareGroupAutoOffsetResetStrategy duration1 = 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:P2D");
+        ShareGroupAutoOffsetResetStrategy duration2 = 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:P2D");
+
+        assertEquals(earliest1, earliest2);
+        assertNotEquals(earliest1, latest1);
+        assertEquals(earliest1.hashCode(), earliest2.hashCode());
+        assertNotEquals(earliest1.hashCode(), latest1.hashCode());
+
+        assertNotEquals(latest1, duration2);
+        assertEquals(duration1, duration2);
+    }
+
+    @Test
+    public void testTimestamp() {
+        ShareGroupAutoOffsetResetStrategy earliest1 = 
ShareGroupAutoOffsetResetStrategy.fromString("earliest");
+        ShareGroupAutoOffsetResetStrategy earliest2 = 
ShareGroupAutoOffsetResetStrategy.fromString("earliest");
+        assertEquals(Optional.of(ListOffsetsRequest.EARLIEST_TIMESTAMP), 
earliest1.timestamp());
+        assertEquals(earliest1, earliest2);
+
+        ShareGroupAutoOffsetResetStrategy latest1 = 
ShareGroupAutoOffsetResetStrategy.fromString("latest");
+        ShareGroupAutoOffsetResetStrategy latest2 = 
ShareGroupAutoOffsetResetStrategy.fromString("latest");
+        assertEquals(Optional.of(ListOffsetsRequest.LATEST_TIMESTAMP), 
latest1.timestamp());
+        assertEquals(latest1, latest2);
+
+        ShareGroupAutoOffsetResetStrategy byDuration1 = 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:PT1H");
+        Optional<Long> timestamp = byDuration1.timestamp();
+        assertTrue(timestamp.isPresent());
+        assertTrue(timestamp.get() <= Instant.now().toEpochMilli() - 
Duration.ofHours(1).toMillis());
+
+        ShareGroupAutoOffsetResetStrategy byDuration2 = 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:PT1H");
+        ShareGroupAutoOffsetResetStrategy byDuration3 = 
ShareGroupAutoOffsetResetStrategy.fromString("by_duration:PT2H");
+
+        assertEquals(byDuration1, byDuration2);
+        assertNotEquals(byDuration1, byDuration3);
+    }
+}

Review Comment:
   nit: Kafka source usually ends with a blank line.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to