WrappedHttpHandler.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. <?php
  2. namespace Aws;
  3. use Aws\Api\Parser\Exception\ParserException;
  4. use GuzzleHttp\Promise;
  5. use Psr\Http\Message\RequestInterface;
  6. use Psr\Http\Message\ResponseInterface;
  7. /**
  8. * Converts an HTTP handler into a Command HTTP handler.
  9. *
  10. * HTTP handlers have the following signature:
  11. * function(RequestInterface $request, array $options) : PromiseInterface
  12. *
  13. * The promise returned form an HTTP handler must resolve to a PSR-7 response
  14. * object when fulfilled or an error array when rejected. The error array
  15. * can contain the following data:
  16. *
  17. * - exception: (required, Exception) Exception that was encountered.
  18. * - response: (ResponseInterface) PSR-7 response that was received (if a
  19. * response) was received.
  20. * - connection_error: (bool) True if the error is the result of failing to
  21. * connect.
  22. */
  23. class WrappedHttpHandler
  24. {
  25. private $httpHandler;
  26. private $parser;
  27. private $errorParser;
  28. private $exceptionClass;
  29. private $collectStats;
  30. /**
  31. * @param callable $httpHandler Function that accepts a request and array
  32. * of request options and returns a promise
  33. * that fulfills with a response or rejects
  34. * with an error array.
  35. * @param callable $parser Function that accepts a response object
  36. * and returns an AWS result object.
  37. * @param callable $errorParser Function that parses a response object
  38. * into AWS error data.
  39. * @param string $exceptionClass Exception class to throw.
  40. * @param bool $collectStats Whether to collect HTTP transfer
  41. * information.
  42. */
  43. public function __construct(
  44. callable $httpHandler,
  45. callable $parser,
  46. callable $errorParser,
  47. $exceptionClass = 'Aws\Exception\AwsException',
  48. $collectStats = false
  49. ) {
  50. $this->httpHandler = $httpHandler;
  51. $this->parser = $parser;
  52. $this->errorParser = $errorParser;
  53. $this->exceptionClass = $exceptionClass;
  54. $this->collectStats = $collectStats;
  55. }
  56. /**
  57. * Calls the simpler HTTP specific handler and wraps the returned promise
  58. * with AWS specific values (e.g., a result object or AWS exception).
  59. *
  60. * @param CommandInterface $command Command being executed.
  61. * @param RequestInterface $request Request to send.
  62. *
  63. * @return Promise\PromiseInterface
  64. */
  65. public function __invoke(
  66. CommandInterface $command,
  67. RequestInterface $request
  68. ) {
  69. $fn = $this->httpHandler;
  70. $options = $command['@http'] ?: [];
  71. $stats = [];
  72. if ($this->collectStats || !empty($options['collect_stats'])) {
  73. $options['http_stats_receiver'] = static function (
  74. array $transferStats
  75. ) use (&$stats) {
  76. $stats = $transferStats;
  77. };
  78. } elseif (isset($options['http_stats_receiver'])) {
  79. throw new \InvalidArgumentException('Providing a custom HTTP stats'
  80. . ' receiver to Aws\WrappedHttpHandler is not supported.');
  81. }
  82. return Promise\promise_for($fn($request, $options))
  83. ->then(
  84. function (
  85. ResponseInterface $res
  86. ) use ($command, $request, &$stats) {
  87. return $this->parseResponse($command, $request, $res, $stats);
  88. },
  89. function ($err) use ($request, $command, &$stats) {
  90. if (is_array($err)) {
  91. $err = $this->parseError(
  92. $err,
  93. $request,
  94. $command,
  95. $stats
  96. );
  97. }
  98. return new Promise\RejectedPromise($err);
  99. }
  100. );
  101. }
  102. /**
  103. * @param CommandInterface $command
  104. * @param RequestInterface $request
  105. * @param ResponseInterface $response
  106. * @param array $stats
  107. *
  108. * @return ResultInterface
  109. */
  110. private function parseResponse(
  111. CommandInterface $command,
  112. RequestInterface $request,
  113. ResponseInterface $response,
  114. array $stats
  115. ) {
  116. $parser = $this->parser;
  117. $status = $response->getStatusCode();
  118. $result = $status < 300
  119. ? $parser($command, $response)
  120. : new Result();
  121. $metadata = [
  122. 'statusCode' => $status,
  123. 'effectiveUri' => (string) $request->getUri(),
  124. 'headers' => [],
  125. 'transferStats' => [],
  126. ];
  127. if (!empty($stats)) {
  128. $metadata['transferStats']['http'] = [$stats];
  129. }
  130. // Bring headers into the metadata array.
  131. foreach ($response->getHeaders() as $name => $values) {
  132. $metadata['headers'][strtolower($name)] = $values[0];
  133. }
  134. $result['@metadata'] = $metadata;
  135. return $result;
  136. }
  137. /**
  138. * Parses a rejection into an AWS error.
  139. *
  140. * @param array $err Rejection error array.
  141. * @param RequestInterface $request Request that was sent.
  142. * @param CommandInterface $command Command being sent.
  143. * @param array $stats Transfer statistics
  144. *
  145. * @return \Exception
  146. */
  147. private function parseError(
  148. array $err,
  149. RequestInterface $request,
  150. CommandInterface $command,
  151. array $stats
  152. ) {
  153. if (!isset($err['exception'])) {
  154. throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.');
  155. }
  156. $serviceError = "AWS HTTP error: " . $err['exception']->getMessage();
  157. if (!isset($err['response'])) {
  158. $parts = ['response' => null];
  159. } else {
  160. try {
  161. $parts = call_user_func(
  162. $this->errorParser,
  163. $err['response'],
  164. $command
  165. );
  166. $serviceError .= " {$parts['code']} ({$parts['type']}): "
  167. . "{$parts['message']} - " . $err['response']->getBody();
  168. } catch (ParserException $e) {
  169. $parts = [];
  170. $serviceError .= ' Unable to parse error information from '
  171. . "response - {$e->getMessage()}";
  172. }
  173. $parts['response'] = $err['response'];
  174. }
  175. $parts['exception'] = $err['exception'];
  176. $parts['request'] = $request;
  177. $parts['connection_error'] = !empty($err['connection_error']);
  178. $parts['transfer_stats'] = $stats;
  179. return new $this->exceptionClass(
  180. sprintf(
  181. 'Error executing "%s" on "%s"; %s',
  182. $command->getName(),
  183. $request->getUri(),
  184. $serviceError
  185. ),
  186. $command,
  187. $parts,
  188. $err['exception']
  189. );
  190. }
  191. }