-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added jitter strategy that jitters after a specified threshold.
- Loading branch information
1 parent
1fe47e1
commit 5636bed
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |