Skip to content

Commit

Permalink
Added jitter strategy that jitters after a specified threshold.
Browse files Browse the repository at this point in the history
  • Loading branch information
frankdejonge committed Sep 17, 2023
1 parent 1fe47e1 commit 5636bed
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Jitter/JitterAfterThreshold.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);

namespace EventSauce\BackOff\Jitter;

class JitterAfterThreshold implements Jitter
{
private int $threshold;
private Jitter $strategy;

public function __construct(
int $threshold,
Jitter $strategy = null
) {

$this->threshold = $threshold;
$this->strategy = $strategy ?: new FullJitter();
}

public function jitter(int $sleep): int
{
if ($sleep <= $this->threshold) {
return $sleep;
}

return $this->threshold + $this->strategy->jitter($sleep - $this->threshold);
}
}
37 changes: 37 additions & 0 deletions src/Jitter/JitterAfterThresholdTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);

namespace EventSauce\BackOff\Jitter;

use PHPUnit\Framework\TestCase;
use function array_sum;
use function count;
use function max;
use function min;

class JitterAfterThresholdTest extends TestCase
{
/**
* @test
*/
public function jitting_results_in_random_values_across_a_full_range_but_not_below_threshold(): void
{
$jitter = new JitterAfterThreshold(250);
$jittedSleeps = [];

for ($i = 0; $i < 100000; $i++) {
$jittedSleeps[] = $jitter->jitter(1000);
}

$average = (int) (array_sum($jittedSleeps) / count($jittedSleeps));
$max = max(...$jittedSleeps);
$min = min(...$jittedSleeps);

self::assertTrue($average > 525);
self::assertTrue($average < 725);
self::assertTrue($max > 900);
self::assertTrue($max <= 1000);
self::assertTrue($min < 350);
self::assertTrue($min >= 250);
}
}

0 comments on commit 5636bed

Please sign in to comment.