vendor/google/apiclient/src/Task/Runner.php line 187

Open in your IDE?
  1. <?php
  2. /*
  3.  * Copyright 2014 Google Inc.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. namespace Google\Task;
  18. use Google\Service\Exception as GoogleServiceException;
  19. use Google\Task\Exception as GoogleTaskException;
  20. /**
  21.  * A task runner with exponential backoff support.
  22.  *
  23.  * @see https://developers.google.com/drive/web/handle-errors#implementing_exponential_backoff
  24.  */
  25. class Runner
  26. {
  27.     const TASK_RETRY_NEVER 0;
  28.     const TASK_RETRY_ONCE 1;
  29.     const TASK_RETRY_ALWAYS = -1;
  30.     /**
  31.      * @var integer $maxDelay The max time (in seconds) to wait before a retry.
  32.      */
  33.     private $maxDelay 60;
  34.     /**
  35.      * @var integer $delay The previous delay from which the next is calculated.
  36.      */
  37.     private $delay 1;
  38.     /**
  39.      * @var integer $factor The base number for the exponential back off.
  40.      */
  41.     private $factor 2;
  42.     /**
  43.      * @var float $jitter A random number between -$jitter and $jitter will be
  44.      * added to $factor on each iteration to allow for a better distribution of
  45.      * retries.
  46.      */
  47.     private $jitter 0.5;
  48.     /**
  49.      * @var integer $attempts The number of attempts that have been tried so far.
  50.      */
  51.     private $attempts 0;
  52.     /**
  53.      * @var integer $maxAttempts The max number of attempts allowed.
  54.      */
  55.     private $maxAttempts 1;
  56.     /**
  57.      * @var callable $action The task to run and possibly retry.
  58.      */
  59.     private $action;
  60.     /**
  61.      * @var array $arguments The task arguments.
  62.      */
  63.     private $arguments;
  64.     /**
  65.      * @var array $retryMap Map of errors with retry counts.
  66.      */
  67.     protected $retryMap = [
  68.         '500' => self::TASK_RETRY_ALWAYS,
  69.         '503' => self::TASK_RETRY_ALWAYS,
  70.         'rateLimitExceeded' => self::TASK_RETRY_ALWAYS,
  71.         'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS,
  72.         6  => self::TASK_RETRY_ALWAYS,  // CURLE_COULDNT_RESOLVE_HOST
  73.         7  => self::TASK_RETRY_ALWAYS,  // CURLE_COULDNT_CONNECT
  74.         28 => self::TASK_RETRY_ALWAYS,  // CURLE_OPERATION_TIMEOUTED
  75.         35 => self::TASK_RETRY_ALWAYS,  // CURLE_SSL_CONNECT_ERROR
  76.         52 => self::TASK_RETRY_ALWAYS,  // CURLE_GOT_NOTHING
  77.         'lighthouseError' => self::TASK_RETRY_NEVER
  78.     ];
  79.     /**
  80.      * Creates a new task runner with exponential backoff support.
  81.      *
  82.      * @param array $config The task runner config
  83.      * @param string $name The name of the current task (used for logging)
  84.      * @param callable $action The task to run and possibly retry
  85.      * @param array $arguments The task arguments
  86.      * @throws \Google\Task\Exception when misconfigured
  87.      */
  88.     // @phpstan-ignore-next-line
  89.     public function __construct(
  90.         $config,
  91.         $name,
  92.         $action,
  93.         array $arguments = []
  94.     ) {
  95.         if (isset($config['initial_delay'])) {
  96.             if ($config['initial_delay'] < 0) {
  97.                 throw new GoogleTaskException(
  98.                     'Task configuration `initial_delay` must not be negative.'
  99.                 );
  100.             }
  101.             $this->delay $config['initial_delay'];
  102.         }
  103.         if (isset($config['max_delay'])) {
  104.             if ($config['max_delay'] <= 0) {
  105.                 throw new GoogleTaskException(
  106.                     'Task configuration `max_delay` must be greater than 0.'
  107.                 );
  108.             }
  109.             $this->maxDelay $config['max_delay'];
  110.         }
  111.         if (isset($config['factor'])) {
  112.             if ($config['factor'] <= 0) {
  113.                 throw new GoogleTaskException(
  114.                     'Task configuration `factor` must be greater than 0.'
  115.                 );
  116.             }
  117.             $this->factor $config['factor'];
  118.         }
  119.         if (isset($config['jitter'])) {
  120.             if ($config['jitter'] <= 0) {
  121.                 throw new GoogleTaskException(
  122.                     'Task configuration `jitter` must be greater than 0.'
  123.                 );
  124.             }
  125.             $this->jitter $config['jitter'];
  126.         }
  127.         if (isset($config['retries'])) {
  128.             if ($config['retries'] < 0) {
  129.                 throw new GoogleTaskException(
  130.                     'Task configuration `retries` must not be negative.'
  131.                 );
  132.             }
  133.             $this->maxAttempts += $config['retries'];
  134.         }
  135.         if (!is_callable($action)) {
  136.             throw new GoogleTaskException(
  137.                 'Task argument `$action` must be a valid callable.'
  138.             );
  139.         }
  140.         $this->action $action;
  141.         $this->arguments $arguments;
  142.     }
  143.     /**
  144.      * Checks if a retry can be attempted.
  145.      *
  146.      * @return boolean
  147.      */
  148.     public function canAttempt()
  149.     {
  150.         return $this->attempts $this->maxAttempts;
  151.     }
  152.     /**
  153.      * Runs the task and (if applicable) automatically retries when errors occur.
  154.      *
  155.      * @return mixed
  156.      * @throws \Google\Service\Exception on failure when no retries are available.
  157.      */
  158.     public function run()
  159.     {
  160.         while ($this->attempt()) {
  161.             try {
  162.                 return call_user_func_array($this->action$this->arguments);
  163.             } catch (GoogleServiceException $exception) {
  164.                 $allowedRetries $this->allowedRetries(
  165.                     $exception->getCode(),
  166.                     $exception->getErrors()
  167.                 );
  168.                 if (!$this->canAttempt() || !$allowedRetries) {
  169.                     throw $exception;
  170.                 }
  171.                 if ($allowedRetries 0) {
  172.                     $this->maxAttempts min(
  173.                         $this->maxAttempts,
  174.                         $this->attempts $allowedRetries
  175.                     );
  176.                 }
  177.             }
  178.         }
  179.     }
  180.     /**
  181.      * Runs a task once, if possible. This is useful for bypassing the `run()`
  182.      * loop.
  183.      *
  184.      * NOTE: If this is not the first attempt, this function will sleep in
  185.      * accordance to the backoff configurations before running the task.
  186.      *
  187.      * @return boolean
  188.      */
  189.     public function attempt()
  190.     {
  191.         if (!$this->canAttempt()) {
  192.             return false;
  193.         }
  194.         if ($this->attempts 0) {
  195.             $this->backOff();
  196.         }
  197.         $this->attempts++;
  198.         return true;
  199.     }
  200.     /**
  201.      * Sleeps in accordance to the backoff configurations.
  202.      */
  203.     private function backOff()
  204.     {
  205.         $delay $this->getDelay();
  206.         usleep((int) ($delay 1000000));
  207.     }
  208.     /**
  209.      * Gets the delay (in seconds) for the current backoff period.
  210.      *
  211.      * @return int
  212.      */
  213.     private function getDelay()
  214.     {
  215.         $jitter $this->getJitter();
  216.         $factor $this->attempts $this->factor $jitter abs($jitter);
  217.         return $this->delay min($this->maxDelay$this->delay $factor);
  218.     }
  219.     /**
  220.      * Gets the current jitter (random number between -$this->jitter and
  221.      * $this->jitter).
  222.      *
  223.      * @return float
  224.      */
  225.     private function getJitter()
  226.     {
  227.         return $this->jitter mt_rand() / mt_getrandmax() - $this->jitter;
  228.     }
  229.     /**
  230.      * Gets the number of times the associated task can be retried.
  231.      *
  232.      * NOTE: -1 is returned if the task can be retried indefinitely
  233.      *
  234.      * @return integer
  235.      */
  236.     public function allowedRetries($code$errors = [])
  237.     {
  238.         if (isset($this->retryMap[$code])) {
  239.             return $this->retryMap[$code];
  240.         }
  241.         if (
  242.             !empty($errors) &&
  243.             isset($errors[0]['reason'], $this->retryMap[$errors[0]['reason']])
  244.         ) {
  245.             return $this->retryMap[$errors[0]['reason']];
  246.         }
  247.         return 0;
  248.     }
  249.     public function setRetryMap($retryMap)
  250.     {
  251.         $this->retryMap $retryMap;
  252.     }
  253. }