public function setUp() { $this->client = $this->getServiceBuilder()->get('s3'); $this->client->getEventDispatcher()->removeSubscriber(BackoffPlugin::getExponentialBackoff()); // disable retry $this->bucket = randBucket(); }
public function testBuildAlternate() { $client = ClientBuilder::factory('Aws\\DynamoDb')->setConfigDefaults(array('scheme' => 'https', 'region' => 'us-west-1', 'service' => 'dynamodb', 'service.description' => $this->dynamoDbDescription))->setCredentialsResolver(new CredentialsOptionResolver(function (Collection $config) { return Credentials::factory($config->getAll(array_keys(Credentials::getConfigDefaults()))); }))->addClientResolver(new BackoffOptionResolver(function () { return BackoffPlugin::getExponentialBackoff(); }))->build(); $this->assertInstanceOf('Aws\\DynamoDb\\DynamoDbClient', $client); }
/** * Public constructor. * * Enables backoff support. * * @param string $baseUrl Base URL of the web service. * @param string $backoffRegex Optional error pattern to * search for in response bodies. */ public function __construct($baseUrl = '', $backoffRegex = null) { if (is_string($backoffRegex)) { $backoffPlugin = new BackoffPlugin(new ResponseMatchesBackoffStrategy($backoffRegex)); } else { $backoffPlugin = BackoffPlugin::getExponentialBackoff(); } $config = array('request.options' => array('plugins' => array($backoffPlugin))); parent::__construct($baseUrl, $config); }
/** * Constructs a new instance of the {@see GitHub} class. * * @param string $user Your GitHub username. * @param string $pass Your GitHub password. */ public function __construct($user, $pass) { $this->user = $user; $this->pass = $pass; $this->client = new Client('https://api.github.com', array('params.cache.override_ttl' => 3600)); // Caching $this->client->addSubscriber(new CachePlugin(new DoctrineCacheAdapter(new PhpFileCache(VANITY_CACHE_DIR . '/github')), true)); // Exponential backoff $this->client->addSubscriber(BackoffPlugin::getExponentialBackoff()); }
/** * Creates the GuzzleTeleporter * * @return GuzzleTeleporter */ public static function create() { $client = new Client(); $client->getEventDispatcher()->addListener('request.error', function (Event $event) { // override guzzle default behavior of throwing exceptions // when 4xx & 5xx responses are encountered $event->stopPropagation(); }, -254); $client->addSubscriber(BackoffPlugin::getExponentialBackoff(5, array(500, 502, 503, 408))); return new static($client); }
public function __construct(ClientInterface $client = null) { $this->client = $client; if (!$this->client) { $this->client = new Client(); $this->client->getEventDispatcher()->addListener('request.error', function (Event $event) { // override guzzle default behavior of throwing exceptions // when 4xx & 5xx responses are encountered $event->stopPropagation(); }, -254); $this->client->addSubscriber(BackoffPlugin::getExponentialBackoff(5, array(500, 502, 503, 408))); } }
protected function getGuzzle(InputInterface $input) { if (null !== $this->guzzle) { return $this->guzzle; } if (!in_array($input->getArgument('es-scheme'), array('http', 'https'))) { throw new InvalidArgumentException("Elastic search scheme must be http or https"); } $uri = sprintf('%s://%s:%s/%s', $input->getArgument('es-scheme'), rtrim($input->getArgument('es-host'), '/'), $input->getArgument('es-port'), $input->getArgument('es-index')); $this->guzzle = new Guzzle($uri); $this->guzzle->addSubscriber(BackoffPlugin::getExponentialBackoff()); return $this->guzzle; }
public function testConstructorCallsResolvers() { $config = new Collection(array(Options::ENDPOINT_PROVIDER => $this->getMock('Aws\\Common\\Region\\EndpointProviderInterface'))); $signature = new SignatureV4(); $credentials = new Credentials('test', '123'); $config->set('client.resolvers', array(new BackoffOptionResolver(function () { return BackoffPlugin::getExponentialBackoff(); }))); $client = $this->getMockBuilder('Aws\\Common\\Client\\AbstractClient')->setConstructorArgs(array($credentials, $signature, $config))->getMockForAbstractClass(); // Ensure that lazy resolvers were triggered $this->assertInstanceOf('Guzzle\\Plugin\\Backoff\\BackoffPlugin', $client->getConfig(Options::BACKOFF)); // Ensure that the client removed the option $this->assertNull($config->get('client.resolvers')); }
/** * Add the exponential backoff logger to the backoff plugin * * @param BackoffPlugin $plugin Plugin to attach a logger to * @param mixed $logger Logger to use with the plugin * @param string $format Logger format option * * @throws InvalidArgumentException if the logger is not valid */ private function addLogger(BackoffPlugin $plugin, $logger, $format = null) { if ($logger === 'debug') { $logger = new ClosureLogAdapter(function ($message) { trigger_error($message . "\n"); }); } elseif (!$logger instanceof LogAdapterInterface) { throw new InvalidArgumentException(Options::BACKOFF_LOGGER . ' must be set to `debug` or an instance of ' . 'Guzzle\\Common\\Log\\LogAdapterInterface'); } // Create the plugin responsible for logging exponential backoff retries $logPlugin = new BackoffLogger($logger); // You can specify a custom format or use the default if ($format) { $logPlugin->setTemplate($format); } $plugin->addSubscriber($logPlugin); }
/** * @param array $config * @return Client */ public static function factory($config = array()) { $default = array('url' => self::DEFAULT_API_URL); $required = array('token'); $config = Collection::fromConfig($config, $default, $required); $config['curl.options'] = array(CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0); $config['request.options'] = array('headers' => array('X-StorageApi-Token' => $config->get('token'))); $client = new self($config->get('url'), $config); // Attach a service description to the client $description = ServiceDescription::factory(__DIR__ . '/service.json'); $client->setDescription($description); $client->setBaseUrl($config->get('url')); // Setup exponential backoff $backoffPlugin = BackoffPlugin::getExponentialBackoff(); $client->addSubscriber($backoffPlugin); return $client; }
/** * Create Securepass client using Guzzle * * @param array $config Client Configuration options * */ public function __construct($config = array()) { $default = array('base_url' => self::BASE_URL); // The following values are required when creating the client $required = array('base_url', 'app_id', 'app_secret'); $config = Collection::fromConfig($config, $default, $required); // Create a new Securepass client $this->client = new Client($config->get('base_url'), $config); // set Securepass deafult headers $this->client->setDefaultOption('headers/X-SecurePass-App-ID', $config->get('app_id')); $this->client->setDefaultOption('headers/X-SecurePass-App-Secret', $config->get('app_secret')); $this->client->setDefaultOption('headers/Content-type', 'application/json'); // set Useragent $this->client->setUserAgent('SecurePass-PHP/1.0"'); // load services description $this->setServiceDescription(); // Use a static factory method to get a backoff plugin using the exponential backoff strategy $backoffPlugin = BackoffPlugin::getExponentialBackoff(); // Add the backoff plugin to the client object $this->client->addSubscriber($backoffPlugin); }
protected function execute(InputInterface $input, OutputInterface $output) { $repositoryName = $this->parseRepositoryName($input->getOption('repository')); $client = new Client($input->getOption('api-url') . '{?access_token}', array('access_token' => $input->getOption('access-token'), 'request.options' => array('Content-Type' => 'application/json'))); $client->addSubscriber(BackoffPlugin::getExponentialBackoff()); $postData = $this->generatePostData($input); if (!isset($postData['coverage'])) { $output->write(sprintf('Notifying that no code coverage data is available for repository "%s" and revision "%s"... ', $repositoryName, $postData['revision'])); } else { $output->write(sprintf('Uploading code coverage for repository "%s" and revision "%s"... ', $repositoryName, $postData['revision'])); } try { $client->post('repositories/' . $repositoryName . '/data/code-coverage{?access_token}', null, json_encode($postData))->send(); $output->writeln('Done'); return 0; } catch (BadResponseException $ex) { $output->writeln("<error>Failed</error>"); if ($ex instanceof ClientErrorResponseException) { $output->writeln('<error>' . $ex->getResponse()->getBody(true) . '</error>'); return 1; } throw $ex; } }
/** * Register the default subscribers for Guzzle * * @param array $options */ public function registerGuzzleSubscribers(array $options) { $acceptJsonHeaderPlugin = new AcceptJsonHeaderPlugin(); $this->addSubscriber($acceptJsonHeaderPlugin); $backoffPlugin = BackoffPlugin::getExponentialBackoff(5); $this->addSubscriber($backoffPlugin); if (array_key_exists('token', $options) && $options['token'] instanceof ApiToken) { $apiTokenPlugin = new ApiTokenPlugin($options['token']); $this->addSubscriber($apiTokenPlugin); } }
/** * Construct the Guzzle Http Client with the exponential retry plugin * * @access protected * @return \Guzzle|Http\Client */ protected function getClient() { $retries = 5; $httpCodes = null; $curlCodes = null; $plugin = BackoffPlugin::getExponentialBackoff($retries, $httpCodes, $curlCodes); $client = new Client($this->baseUrl); $client->addSubscriber($plugin); return $client; }
public function testDoesNotSeekOnRequestsWithNoBodyWhenRetrying() { // Create a request with a body $request = new EntityEnclosingRequest('PUT', 'http://www.example.com'); $request->getParams()->set(BackoffPlugin::DELAY_PARAM, 2); $plugin = new BackoffPlugin(new ConstantBackoffStrategy(0)); $plugin->onRequestPoll($this->getMockEvent($request)); }
public function testAddsDefaultBackoffPluginIfNeeded() { $config = array('service' => 'dynamodb', 'region' => 'us-east-1', 'service.description' => array('signatureVersion' => 'v2', 'regions' => array('us-east-1' => array('https' => true, 'hostname' => 'foo.com')))); // Ensure that a default plugin is set $client = ClientBuilder::factory('Aws\\DynamoDb')->setConfig($config)->build(); $this->assertInstanceOf('Guzzle\\Plugin\\Backoff\\BackoffPlugin', $client->getConfig(Options::BACKOFF)); // Ensure that the plugin is set $this->assertTrue($this->hasSubscriber($client, $client->getConfig(Options::BACKOFF))); // Ensure that a specific plugin can be used $plugin = BackoffPlugin::getExponentialBackoff(); $config[Options::BACKOFF] = $plugin; $client = ClientBuilder::factory('Aws\\DynamoDb')->setConfig($config)->build(); $this->assertSame($plugin, $client->getConfig(Options::BACKOFF)); // Ensure that the plugin is set $this->assertTrue($this->hasSubscriber($client, $plugin)); }
/** * Returns the default exponential backoff plugin for a client * * @return BackoffOptionResolver */ protected function getDefaultBackoffResolver() { return new BackoffOptionResolver(function () { return BackoffPlugin::getExponentialBackoff(); }); }
private function getMocks() { $config = new Collection(); $plugin = BackoffPlugin::getExponentialBackoff(); $resolver = new BackoffOptionResolver(function ($config, $client = null) use($plugin) { return $plugin; }); return array($config, $plugin, $resolver); }
/** * Add backoff logging to the backoff plugin if needed * * @param BackoffPlugin $plugin Backoff plugin * @param Collection $config Configuration settings * * @throws InvalidArgumentException */ protected function addBackoffLogger(BackoffPlugin $plugin, Collection $config) { // The log option can be set to `debug` or an instance of a LogAdapterInterface if ($logger = $config->get(Options::BACKOFF_LOGGER)) { $format = $config->get(Options::BACKOFF_LOGGER_TEMPLATE); if ($logger === 'debug') { $logger = new ClosureLogAdapter(function ($message) { trigger_error($message . "\n"); }); } elseif (!$logger instanceof LogAdapterInterface) { throw new InvalidArgumentException(Options::BACKOFF_LOGGER . ' must be set to `debug` or an instance of ' . 'Guzzle\\Common\\Log\\LogAdapterInterface'); } // Create the plugin responsible for logging exponential backoff retries $logPlugin = new BackoffLogger($logger); // You can specify a custom format or use the default if ($format) { $logPlugin->setTemplate($format); } $plugin->addSubscriber($logPlugin); } }
public function __construct() { parent::__construct(new DeskRateLimitStrategy()); }