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:
@@ -3,6 +3,9 @@ package io.socket.backo;
|
|||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Imported from https://github.com/mokesmokes/backo
|
||||||
|
*/
|
||||||
public class Backoff {
|
public class Backoff {
|
||||||
|
|
||||||
private long ms = 100;
|
private long ms = 100;
|
||||||
@@ -23,7 +26,10 @@ public class Backoff {
|
|||||||
.multiply(new BigDecimal(ms)).toBigInteger();
|
.multiply(new BigDecimal(ms)).toBigInteger();
|
||||||
ms = (((int) Math.floor(rand * 10)) & 1) == 0 ? ms.subtract(deviation) : ms.add(deviation);
|
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() {
|
public void reset() {
|
||||||
@@ -46,6 +52,10 @@ public class Backoff {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Backoff setJitter(double jitter) {
|
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;
|
this.jitter = jitter;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,4 +44,10 @@ public class BackoffTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void ensureJitterIsValid() {
|
||||||
|
Backoff b = new Backoff();
|
||||||
|
b.setJitter(2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user