GuzzleHttpRetryMiddleware

Middleware that retries requests based on the boolean result of invoking the provided "decider" function.

Defined (1)

The class is defined in the following location(s).

/lib/Azure/GuzzleHttp/RetryMiddleware.php  
  1. class RetryMiddleware 
  2. /** @var callable */ 
  3. private $nextHandler; 
  4.  
  5. /** @var callable */ 
  6. private $decider; 
  7.  
  8. /** 
  9. * @param callable $decider Function that accepts the number of retries,  
  10. * a request, [response], and [exception] and 
  11. * returns true if the request is to be 
  12. * retried. 
  13. * @param callable $nextHandler Next handler to invoke. 
  14. * @param callable $delay Function that accepts the number of retries 
  15. * and [response] and returns the number of 
  16. * milliseconds to delay. 
  17. */ 
  18. public function __construct( 
  19. callable $decider,  
  20. callable $nextHandler,  
  21. callable $delay = null 
  22. ) { 
  23. $this->decider = $decider; 
  24. $this->nextHandler = $nextHandler; 
  25. $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; 
  26.  
  27. /** 
  28. * Default exponential backoff delay function. 
  29. * @param $retries 
  30. * @return int 
  31. */ 
  32. public static function exponentialDelay($retries) 
  33. return (int) pow(2, $retries - 1); 
  34.  
  35. /** 
  36. * @param RequestInterface $request 
  37. * @param array $options 
  38. * @return PromiseInterface 
  39. */ 
  40. public function __invoke(RequestInterface $request, array $options) 
  41. if (!isset($options['retries'])) { 
  42. $options['retries'] = 0; 
  43.  
  44. $fn = $this->nextHandler; 
  45. return $fn($request, $options) 
  46. ->then( 
  47. $this->onFulfilled($request, $options),  
  48. $this->onRejected($request, $options) 
  49. ); 
  50.  
  51. private function onFulfilled(RequestInterface $req, array $options) 
  52. return function ($value) use ($req, $options) { 
  53. if (!call_user_func( 
  54. $this->decider,  
  55. $options['retries'],  
  56. $req,  
  57. $value,  
  58. null 
  59. )) { 
  60. return $value; 
  61. return $this->doRetry($req, $options, $value); 
  62. }; 
  63.  
  64. private function onRejected(RequestInterface $req, array $options) 
  65. return function ($reason) use ($req, $options) { 
  66. if (!call_user_func( 
  67. $this->decider,  
  68. $options['retries'],  
  69. $req,  
  70. null,  
  71. $reason 
  72. )) { 
  73. return new RejectedPromise($reason); 
  74. return $this->doRetry($req, $options); 
  75. }; 
  76.  
  77. private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null) 
  78. $options['delay'] = call_user_func($this->delay, ++$options['retries'], $response); 
  79.  
  80. return $this($request, $options);