Skip to content

Commit 0cbf01e

Browse files
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: #349
1 parent fd0c733 commit 0cbf01e

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

Diff for: src/main/java/io/socket/backo/Backoff.java

+11-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
import java.math.BigDecimal;
44
import java.math.BigInteger;
55

6+
/**
7+
* Imported from https://github.com/mokesmokes/backo
8+
*/
69
public class Backoff {
710

811
private long ms = 100;
@@ -23,7 +26,10 @@ public long duration() {
2326
.multiply(new BigDecimal(ms)).toBigInteger();
2427
ms = (((int) Math.floor(rand * 10)) & 1) == 0 ? ms.subtract(deviation) : ms.add(deviation);
2528
}
26-
return ms.min(BigInteger.valueOf(this.max)).longValue();
29+
return ms
30+
.min(BigInteger.valueOf(this.max))
31+
.max(BigInteger.valueOf(this.ms))
32+
.longValue();
2733
}
2834

2935
public void reset() {
@@ -46,6 +52,10 @@ public Backoff setFactor(int factor) {
4652
}
4753

4854
public Backoff setJitter(double jitter) {
55+
boolean isValid = jitter >= 0 && jitter < 1;
56+
if (!isValid) {
57+
throw new IllegalArgumentException("jitter must be between 0 and 1");
58+
}
4959
this.jitter = jitter;
5060
return this;
5161
}

Diff for: src/test/java/io/socket/backo/BackoffTest.java

+6
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,10 @@ public void durationOverflow() {
4444
}
4545
}
4646
}
47+
48+
@Test(expected = IllegalArgumentException.class)
49+
public void ensureJitterIsValid() {
50+
Backoff b = new Backoff();
51+
b.setJitter(2);
52+
}
4753
}

0 commit comments

Comments
 (0)