@Test public void testAttemptLimited() { int attemptLimit = 5; Backoff backoff = Backoff.builder().withAttemptLimit(attemptLimit).build(); int i = 1; while (backoff.hasNext()) { ++i; backoff.nextBackoff(); } assertThat(i, equalTo(attemptLimit)); }
@Test public void testExpansion() { Backoff backoff = Backoff.builder().withExpansion(2.0).withAttemptLimit(5).build(); assertTrue(backoff.hasNext()); Duration lastBackoff = backoff.nextBackoff(); assertTrue(backoff.hasNext()); while (backoff.hasNext()) { Duration nextBackoff = backoff.nextBackoff(); assertThat(nextBackoff, equalTo(lastBackoff.plus(lastBackoff))); lastBackoff = nextBackoff; } }
@Test public void testInitialBackoff() { Backoff backoff = Backoff.builder().withInitialBackoff(Duration.ofSeconds(17)).build(); assertTrue(backoff.hasNext()); assertThat(backoff.nextBackoff(), equalTo(Duration.ofSeconds(17))); }
private boolean pollWork(UUID wItemId) { Pair<WorkStatusCode, String> response; try (ActiveSpan workStatusSpan = GlobalTracer.get().buildSpan("Waiting for work status").startActive()) { assert workStatusSpan != null; // avoid unused warning // Poll the work item until it finishes or fails. response = _workHelper.getWorkStatus(wItemId); if (response == null) { return false; } WorkStatusCode status = response.getFirst(); Backoff backoff = Backoff.builder().withMaximumBackoff(Duration.ofSeconds(1)).build(); while (!status.isTerminated() && backoff.hasNext()) { printWorkStatusResponse(response, false); try { Thread.sleep(backoff.nextBackoff().toMillis()); } catch (InterruptedException e) { throw new BatfishException("Interrupted while waiting for work item to complete", e); } response = _workHelper.getWorkStatus(wItemId); if (response == null) { return false; } status = response.getFirst(); } printWorkStatusResponse(response, false); } return true; }
@Test public void testTimeLimited() { Duration cumulativeLimit = Duration.ofMinutes(1); Backoff backoff = Backoff.builder().withCumulativeBackoffLimit(cumulativeLimit).build(); Duration totalSoFar = Duration.ZERO; while (backoff.hasNext()) { assertThat(totalSoFar, lessThan(cumulativeLimit)); totalSoFar = totalSoFar.plus(backoff.nextBackoff()); } assertThat(totalSoFar, greaterThanOrEqualTo(cumulativeLimit)); }
@Test public void testMaximumBackoffAndSeveralSteps() { Backoff backoff = Backoff.builder() .withInitialBackoff(Duration.ofSeconds(1)) .withMaximumBackoff(Duration.ofSeconds(11)) .withExpansion(2.0) .withAttemptLimit(8) .build(); int[] expected = {1, 2, 4, 8, 11, 11, 11}; for (int seconds : expected) { assertTrue(backoff.hasNext()); assertThat(backoff.nextBackoff(), equalTo(Duration.ofSeconds(seconds))); } assertFalse(backoff.hasNext()); } }