0 ) { usleep( (int) round( $ms * 1000 ) ); } } /** * Retry a callable with exponential backoff. * * @param callable $fn Function to call. * @param array $options { * @type int $maxRetries Default NetworkConfig::MAX_RETRIES. * @type int $initialDelayMs Default NetworkConfig::INITIAL_RETRY_DELAY_MS. * @type float $backoffMultiplier Default NetworkConfig::RETRY_BACKOFF_MULTIPLIER. * @type int $maxDelayMs Default NetworkConfig::MAX_RETRY_DELAY_MS. * @type callable $shouldRetry fn(\Throwable): bool. Default: network errors only. * } * @return mixed Result of $fn. * @throws \Throwable The last error once retries are exhausted. */ public static function withExponentialBackoff( callable $fn, array $options = array() ) { $maxRetries = isset( $options['maxRetries'] ) ? (int) $options['maxRetries'] : NetworkConfig::MAX_RETRIES; $initialDelayMs = isset( $options['initialDelayMs'] ) ? (float) $options['initialDelayMs'] : NetworkConfig::INITIAL_RETRY_DELAY_MS; $backoffMultiplier = isset( $options['backoffMultiplier'] ) ? (float) $options['backoffMultiplier'] : NetworkConfig::RETRY_BACKOFF_MULTIPLIER; $maxDelayMs = isset( $options['maxDelayMs'] ) ? (float) $options['maxDelayMs'] : NetworkConfig::MAX_RETRY_DELAY_MS; $shouldRetry = isset( $options['shouldRetry'] ) && is_callable( $options['shouldRetry'] ) ? $options['shouldRetry'] : array( __CLASS__, 'isNetworkError' ); $currentDelay = $initialDelayMs; $lastError = null; for ( $attempt = 0; $attempt <= $maxRetries; $attempt++ ) { try { return $fn(); } catch ( \Throwable $error ) { $lastError = $error; if ( $attempt >= $maxRetries || ! call_user_func( $shouldRetry, $error ) ) { throw $error; } $jitter = $currentDelay * 0.25 * ( ( wp_rand( 0, 1000 ) / 1000 ) * 2 - 1 ); $waitTime = min( $currentDelay + $jitter, $maxDelayMs ); self::delay( $waitTime ); $currentDelay = min( $currentDelay * $backoffMultiplier, $maxDelayMs ); } } throw $lastError; } /** * Check if an error is a network error (connection failure). * * @param \Throwable $error Error. */ public static function isNetworkError( $error ) { return $error instanceof NetworkException; } }