Created
September 17, 2020 15:48
-
-
Save wryk/65a2ccf298ec282209e30d55126aece5 to your computer and use it in GitHub Desktop.
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
<?php | |
// util | |
$constant = function ($value) { | |
return function ($_) use ($value) { | |
return $value; | |
}; | |
}; | |
$lessThan = function ($right) { | |
return function ($left) use ($right) { | |
return $left < $right; | |
}; | |
}; | |
$linear = function ($ms) { | |
return function ($n) use ($ms) { | |
return $n * $ms; | |
}; | |
}; | |
$exponential = function ($ms) { | |
return function ($n) use ($ms) { | |
return pow(2, $n - 1) * $ms; | |
}; | |
}; | |
// implementation | |
$retry = function ($allowAttempt, $backoff, $supportsException, $fn) { | |
$attempt = 0; | |
while (true) { | |
if ($attempt > 0) { | |
usleep($backoff($attempt) * 1000); | |
} | |
try { | |
return $fn(); | |
} catch (\Exception $exception) { | |
if (!$supportsException($exception)) { | |
throw $exception; | |
} | |
if (!$allowAttempt(++$attempt)) { | |
throw new \Exception('Max attempts'); | |
} | |
} | |
} | |
}; | |
// test | |
$result = $retry( | |
$lessThan(5), | |
$linear(2000), | |
$constant(true), | |
function () { | |
if (rand(0, 2)) { | |
var_dump('has exception'); | |
throw new \Exception('random error'); | |
} else { | |
var_dump('has result'); | |
return 'hello world'; | |
} | |
} | |
); | |
var_dump($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment