From 0cbf01eb2501b3098eacd22594966a719b20c31e Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Sat, 2 Jul 2022 09:02:48 +0200 Subject: [PATCH] fix: ensure randomizationFactor is always between 0 and 1 Using a randomizationFactor value above 1 could lead to generating a negative duration, then throwing: > java.lang.IllegalArgumentException: delay < 0: -1012 > at java.util.Timer.schedule(Timer.java:454) > at io.socket.client.Manager.reconnect(Manager.java:544) This error does not seem related to a long overflow (in the BigInteger.longValue() operation), because the BigInteger.min(this.max) operation before should prevent it. Related: https://github.com/socketio/socket.io-client-java/issues/349 --- src/main/java/io/socket/backo/Backoff.java | 12 +++++++++++- src/test/java/io/socket/backo/BackoffTest.java | 6 ++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/socket/backo/Backoff.java b/src/main/java/io/socket/backo/Backoff.java index f519921..81e1ddd 100644 --- a/src/main/java/io/socket/backo/Backoff.java +++ b/src/main/java/io/socket/backo/Backoff.java @@ -3,6 +3,9 @@ package io.socket.backo; import java.math.BigDecimal; import java.math.BigInteger; +/** + * Imported from https://github.com/mokesmokes/backo + */ public class Backoff { private long ms = 100; @@ -23,7 +26,10 @@ public class Backoff { .multiply(new BigDecimal(ms)).toBigInteger(); ms = (((int) Math.floor(rand * 10)) & 1) == 0 ? ms.subtract(deviation) : ms.add(deviation); } - return ms.min(BigInteger.valueOf(this.max)).longValue(); + return ms + .min(BigInteger.valueOf(this.max)) + .max(BigInteger.valueOf(this.ms)) + .longValue(); } public void reset() { @@ -46,6 +52,10 @@ public class Backoff { } public Backoff setJitter(double jitter) { + boolean isValid = jitter >= 0 && jitter < 1; + if (!isValid) { + throw new IllegalArgumentException("jitter must be between 0 and 1"); + } this.jitter = jitter; return this; } diff --git a/src/test/java/io/socket/backo/BackoffTest.java b/src/test/java/io/socket/backo/BackoffTest.java index a268829..8ae61de 100644 --- a/src/test/java/io/socket/backo/BackoffTest.java +++ b/src/test/java/io/socket/backo/BackoffTest.java @@ -44,4 +44,10 @@ public class BackoffTest { } } } + + @Test(expected = IllegalArgumentException.class) + public void ensureJitterIsValid() { + Backoff b = new Backoff(); + b.setJitter(2); + } }