Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions src/Operation/WithTransaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
use function floor;
use function hrtime;
use function min;
use function mt_getrandmax;
use function random_int;
use function usleep;

Expand Down Expand Up @@ -212,10 +211,9 @@ private function getJitter(): float
return ($this->jitterGenerator)();
}

// Jitter is a random float from [0, 1)
// Since rand will return an int from 0 to mt_getrandmax(), we can divide the result by mt_getrandmax() + 1 to
// get a float in the range [0, 1)
return random_int(0, mt_getrandmax()) / (mt_getrandmax() + 1);
// Jitter is a random float from [0, 1]
// 2 ** 53 is the largest integer that can be represented in a float without losing precision
return random_int(0, 2 ** 53) / 2 ** 53;
}

/**
Expand Down
14 changes: 14 additions & 0 deletions tests/Operation/WithTransactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,18 @@ public function testComputeBackoffMSUsesRandom(): void

$this->assertNotSame($first, $second, 'computeBackoffMs() multiplies backoff with a random value');
}

public function testJitter(): void
{
$operation = new WithTransaction(fn () => 0);

$method = new ReflectionMethod($operation, 'getJitter');

// Test that the default jitter value is between 0 and 1
for ($i = 0; $i < 100; $i++) {
$jitter = $method->invoke($operation);
$this->assertGreaterThanOrEqual(0, $jitter);
$this->assertLessThanOrEqual(1, $jitter);
}
}
}
Loading