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
This commit is contained in:
Damien Arrachequesne
2022-07-02 09:02:48 +02:00
parent fd0c733822
commit 0cbf01eb25
2 changed files with 17 additions and 1 deletions

View File

@@ -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;
}