Skip to content

Commit

Permalink
fix: ensure randomizationFactor is always between 0 and 1
Browse files Browse the repository at this point in the history
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

Backported from 0cbf01e
  • Loading branch information
darrachequesne committed Jul 10, 2022
1 parent 8664499 commit cb966d5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/main/java/io/socket/backo/Backoff.java
Expand Up @@ -3,6 +3,9 @@
import java.math.BigDecimal;
import java.math.BigInteger;

/**
* Imported from https://github.com/mokesmokes/backo
*/
public class Backoff {

private long ms = 100;
Expand All @@ -23,7 +26,10 @@ public long duration() {
.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() {
Expand All @@ -46,6 +52,10 @@ public Backoff setFactor(int factor) {
}

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;
}
Expand Down
6 changes: 6 additions & 0 deletions src/test/java/io/socket/backo/BackoffTest.java
Expand Up @@ -44,4 +44,10 @@ public void durationOverflow() {
}
}
}

@Test(expected = IllegalArgumentException.class)
public void ensureJitterIsValid() {
Backoff b = new Backoff();
b.setJitter(2);
}
}

0 comments on commit cb966d5

Please sign in to comment.