This is an automated email from the ASF dual-hosted git repository.

szetszwo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ratis.git


The following commit(s) were added to refs/heads/master by this push:
     new 493ce4370 RATIS-2413. Support different RetryPolicy implementations. 
(#1354)
493ce4370 is described below

commit 493ce43708b4326b51629e3c930425e73e971371
Author: slfan1989 <[email protected]>
AuthorDate: Fri Feb 20 09:29:53 2026 +0800

    RATIS-2413. Support different RetryPolicy implementations. (#1354)
---
 .../java/org/apache/ratis/retry/RetryPolicy.java   | 37 +++++++++++-
 .../apache/ratis/retry/TestRetryPolicyParse.java   | 67 ++++++++++++++++++++++
 ratis-docs/src/site/markdown/configurations.md     | 26 +++++++--
 .../apache/ratis/grpc/server/GrpcLogAppender.java  |  6 +-
 .../ratis/netty/client/NettyClientStreamRpc.java   |  5 +-
 5 files changed, 128 insertions(+), 13 deletions(-)

diff --git a/ratis-common/src/main/java/org/apache/ratis/retry/RetryPolicy.java 
b/ratis-common/src/main/java/org/apache/ratis/retry/RetryPolicy.java
index 6916858e5..0885e0a44 100644
--- a/ratis-common/src/main/java/org/apache/ratis/retry/RetryPolicy.java
+++ b/ratis-common/src/main/java/org/apache/ratis/retry/RetryPolicy.java
@@ -19,6 +19,7 @@ package org.apache.ratis.retry;
 
 import org.apache.ratis.util.TimeDuration;
 
+import java.util.Arrays;
 import java.util.Objects;
 import java.util.concurrent.TimeUnit;
 
@@ -76,12 +77,19 @@ public interface RetryPolicy {
    */
   Action handleAttemptFailure(Event event);
 
+  static RetryPolicy parse(String commaSeparated, String name) {
+    try {
+      return parse(commaSeparated);
+    } catch (Exception e) {
+      throw new IllegalArgumentException("Failed to parse " + name + ": \"" + 
commaSeparated + "\"", e);
+    }
+  }
+
   static RetryPolicy parse(String commaSeparated) {
     Objects.requireNonNull(commaSeparated, "commaSeparated == null");
     final String[] args = commaSeparated.split(",");
     if (args.length < 1) {
-      throw new IllegalArgumentException("Failed to parse RetryPolicy: 
args.length = "
-          + args.length + " < 1 for " + commaSeparated);
+      throw new IllegalArgumentException("Failed to parse RetryPolicy: empty 
comma separated string");
     }
     final String classname = args[0].trim();
     if (classname.equals(ExponentialBackoffRetry.class.getSimpleName())) {
@@ -95,7 +103,30 @@ public interface RetryPolicy {
           .setMaxAttempts(Integer.parseInt(args[3].trim()))
           .build();
     }
+    if (classname.equals(MultipleLinearRandomRetry.class.getSimpleName())) {
+      if (args.length == 1) {
+        throw new IllegalArgumentException(
+            "Failed to parse MultipleLinearRandomRetry: the parameter list is 
empty for " + commaSeparated);
+      }
+      final String params = String.join(",", Arrays.copyOfRange(args, 1, 
args.length));
+      return MultipleLinearRandomRetry.parseCommaSeparated(params);
+    }
+    // Backward compatibility: legacy config omits class name and starts with 
a duration (e.g. "1ms").
+    if (isLegacyMultipleLinearRandomRetryParams(classname)) {
+      return MultipleLinearRandomRetry.parseCommaSeparated(commaSeparated);
+    }
+    // If a class name is present but unknown, fail fast to surface config 
errors.
     throw new IllegalArgumentException("Failed to parse RetryPolicy: unknown 
class "
-        + args[0] + " for " + commaSeparated);
+        + classname + " for " + commaSeparated);
+  }
+
+  static boolean isLegacyMultipleLinearRandomRetryParams(String firstElement) {
+    // The legacy format starts with a duration token, not a class name.
+    try {
+      final TimeDuration t = TimeDuration.valueOf(firstElement, 
TimeUnit.MILLISECONDS);
+      return t.isPositive();
+    } catch (RuntimeException e) {
+      return false;
+    }
   }
 }
diff --git 
a/ratis-common/src/test/java/org/apache/ratis/retry/TestRetryPolicyParse.java 
b/ratis-common/src/test/java/org/apache/ratis/retry/TestRetryPolicyParse.java
new file mode 100644
index 000000000..17edb3868
--- /dev/null
+++ 
b/ratis-common/src/test/java/org/apache/ratis/retry/TestRetryPolicyParse.java
@@ -0,0 +1,67 @@
+/*
+ * 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.ratis.retry;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class TestRetryPolicyParse {
+  @Test
+  void testParseExponentialBackoffRetry() {
+    final RetryPolicy policy = 
RetryPolicy.parse("ExponentialBackoffRetry,100ms,5s,100");
+    assertInstanceOf(ExponentialBackoffRetry.class, policy);
+  }
+
+  @Test
+  void testParseMultipleLinearRandomRetryWithClassname() {
+    final MultipleLinearRandomRetry expected =
+        MultipleLinearRandomRetry.parseCommaSeparated("1ms,10,1s,20,5s,1000");
+    final RetryPolicy actual =
+        RetryPolicy.parse("MultipleLinearRandomRetry,1ms,10,1s,20,5s,1000");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  void testParseMultipleLinearRandomRetryWithoutClassname() {
+    final MultipleLinearRandomRetry expected =
+        MultipleLinearRandomRetry.parseCommaSeparated("1ms,10,1s,20,5s,1000");
+    final RetryPolicy actual = RetryPolicy.parse("1ms,10,1s,20,5s,1000");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  void testParseUnknownClassnameThrows() {
+    assertThrows(IllegalArgumentException.class,
+        () -> RetryPolicy.parse("UnknownRetry,1ms,10"));
+  }
+
+  @Test
+  void testParseMultipleLinearRandomRetryMissingParamsThrows() {
+    assertThrows(IllegalArgumentException.class,
+        () -> RetryPolicy.parse("MultipleLinearRandomRetry"));
+  }
+
+  @Test
+  void testParseNonLegacyUnknownFirstTokenThrows() {
+    assertThrows(IllegalArgumentException.class,
+        () -> RetryPolicy.parse("not_a_duration,1ms,10"));
+  }
+}
diff --git a/ratis-docs/src/site/markdown/configurations.md 
b/ratis-docs/src/site/markdown/configurations.md
index 52eef048f..67e988348 100644
--- a/ratis-docs/src/site/markdown/configurations.md
+++ b/ratis-docs/src/site/markdown/configurations.md
@@ -509,11 +509,27 @@ The follower's statemachine is responsible for fetching 
and installing snapshot
 | **Type**        | string                                  |
 | **Default**     | 1ms,10, 1s,20, 5s,1000                  |
 
-"1ms,10, 1s,20, 5s,1000" means
-The min wait time as 1ms (0 is not allowed) for first 10,
-(5 iteration with 2 times grpc client retry),
-next wait 1sec for next 20 retry (10 iteration with 2 times grpc client)
-further wait for 5sec for max times ((5sec*980)/2 times ~= 40min)
+Format:
+`<classname>,<params...>`
+If `<classname>` is omitted, it defaults to `MultipleLinearRandomRetry` for 
backward compatibility.
+
+Examples:
+- `MultipleLinearRandomRetry,1ms,10,1s,20,5s,1000`
+- `1ms,10,1s,20,5s,1000` (same as above)
+- `ExponentialBackoffRetry,100ms,5s,100`
+
+For `MultipleLinearRandomRetry`, the parameter "1ms,10, 1s,20, 5s,1000" means
+that the wait time is 1ms on average for the first 10 retries.
+Then, it becomes 1s on average for next 20 retries
+and 5s on average for the last 1000 retries.
+
+For `ExponentialBackoffRetry`, the parameter "100ms,5s,100" means
+that the base wait time is 100ms, the maximum wait time is 5s
+and the number of attempts is 100.
+The wait time is $\min(2^{n-1} \times 100\text{ms}, 5\text{s})$ on average for 
the n-th retry.
+In other words, the wait times are on average 100ms, 200ms, 400ms, 800ms, 
1.6s, 3.2s, 5s, 5s and so on.
+
+Note that the actual wait time is randomized by a multiplier in the range 
[0.5, 1.5) for all retry policies.
 
 
--------------------------------------------------------------------------------
 
diff --git 
a/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GrpcLogAppender.java 
b/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GrpcLogAppender.java
index 9ce45d1ab..b4d78c207 100644
--- a/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GrpcLogAppender.java
+++ b/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GrpcLogAppender.java
@@ -24,7 +24,6 @@ import org.apache.ratis.grpc.metrics.GrpcServerMetrics;
 import org.apache.ratis.metrics.Timekeeper;
 import org.apache.ratis.proto.RaftProtos.InstallSnapshotResult;
 import org.apache.ratis.protocol.RaftPeerId;
-import org.apache.ratis.retry.MultipleLinearRandomRetry;
 import org.apache.ratis.retry.RetryPolicy;
 import org.apache.ratis.server.RaftServer;
 import org.apache.ratis.server.RaftServerConfigKeys;
@@ -198,8 +197,9 @@ public class GrpcLogAppender extends LogAppenderBase {
 
     lock = new AutoCloseableReadWriteLock(this);
     caller = LOG.isTraceEnabled()? JavaUtils.getCallerStackTraceElement(): 
null;
-    errorRetryWaitPolicy = MultipleLinearRandomRetry.parseCommaSeparated(
-        RaftServerConfigKeys.Log.Appender.retryPolicy(properties));
+    errorRetryWaitPolicy = RetryPolicy.parse(
+        RaftServerConfigKeys.Log.Appender.retryPolicy(properties),
+        RaftServerConfigKeys.Log.Appender.RETRY_POLICY_KEY);
   }
 
   @Override
diff --git 
a/ratis-netty/src/main/java/org/apache/ratis/netty/client/NettyClientStreamRpc.java
 
b/ratis-netty/src/main/java/org/apache/ratis/netty/client/NettyClientStreamRpc.java
index 44e91d283..54ad8acf6 100644
--- 
a/ratis-netty/src/main/java/org/apache/ratis/netty/client/NettyClientStreamRpc.java
+++ 
b/ratis-netty/src/main/java/org/apache/ratis/netty/client/NettyClientStreamRpc.java
@@ -347,8 +347,9 @@ public class NettyClientStreamRpc implements 
DataStreamClientRpc {
 
     final InetSocketAddress address = 
NetUtils.createSocketAddr(server.getDataStreamAddress());
     final SslContext sslContext = NettyUtils.buildSslContextForClient(tlsConf);
-    final RetryPolicy reconnectPolicy =
-        
RetryPolicy.parse(NettyConfigKeys.DataStream.Client.reconnectPolicy(properties));
+    final RetryPolicy reconnectPolicy = RetryPolicy.parse(
+        NettyConfigKeys.DataStream.Client.reconnectPolicy(properties),
+        NettyConfigKeys.DataStream.Client.RECONNECT_POLICY_KEY);
     this.connection = new Connection(address, 
WorkerGroupGetter.newInstance(properties),
         () -> newChannelInitializer(address, sslContext, getClientHandler()), 
reconnectPolicy);
   }

Reply via email to