Middleware.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. namespace Aws;
  3. use Aws\Api\Service;
  4. use Aws\Api\Validator;
  5. use Aws\Credentials\CredentialsInterface;
  6. use Aws\Exception\AwsException;
  7. use GuzzleHttp\Promise;
  8. use GuzzleHttp\Psr7;
  9. use GuzzleHttp\Psr7\LazyOpenStream;
  10. use Psr\Http\Message\RequestInterface;
  11. use Psr\Http\Message\ResponseInterface;
  12. final class Middleware
  13. {
  14. /**
  15. * Middleware used to allow a command parameter (e.g., "SourceFile") to
  16. * be used to specify the source of data for an upload operation.
  17. *
  18. * @param Service $api
  19. * @param string $bodyParameter
  20. * @param string $sourceParameter
  21. *
  22. * @return callable
  23. */
  24. public static function sourceFile(
  25. Service $api,
  26. $bodyParameter = 'Body',
  27. $sourceParameter = 'SourceFile'
  28. ) {
  29. return function (callable $handler) use (
  30. $api,
  31. $bodyParameter,
  32. $sourceParameter
  33. ) {
  34. return function (
  35. CommandInterface $command,
  36. RequestInterface $request = null)
  37. use (
  38. $handler,
  39. $api,
  40. $bodyParameter,
  41. $sourceParameter
  42. ) {
  43. $operation = $api->getOperation($command->getName());
  44. $source = $command[$sourceParameter];
  45. if ($source !== null
  46. && $operation->getInput()->hasMember($bodyParameter)
  47. ) {
  48. $command[$bodyParameter] = new LazyOpenStream($source, 'r');
  49. unset($command[$sourceParameter]);
  50. }
  51. return $handler($command, $request);
  52. };
  53. };
  54. }
  55. /**
  56. * Adds a middleware that uses client-side validation.
  57. *
  58. * @param Service $api API being accessed.
  59. *
  60. * @return callable
  61. */
  62. public static function validation(Service $api, Validator $validator = null)
  63. {
  64. $validator = $validator ?: new Validator();
  65. return function (callable $handler) use ($api, $validator) {
  66. return function (
  67. CommandInterface $command,
  68. RequestInterface $request = null
  69. ) use ($api, $validator, $handler) {
  70. $operation = $api->getOperation($command->getName());
  71. $validator->validate(
  72. $command->getName(),
  73. $operation->getInput(),
  74. $command->toArray()
  75. );
  76. return $handler($command, $request);
  77. };
  78. };
  79. }
  80. /**
  81. * Builds an HTTP request for a command.
  82. *
  83. * @param callable $serializer Function used to serialize a request for a
  84. * command.
  85. * @return callable
  86. */
  87. public static function requestBuilder(callable $serializer)
  88. {
  89. return function (callable $handler) use ($serializer) {
  90. return function (CommandInterface $command) use ($serializer, $handler) {
  91. return $handler($command, $serializer($command));
  92. };
  93. };
  94. }
  95. /**
  96. * Creates a middleware that signs requests for a command.
  97. *
  98. * @param callable $credProvider Credentials provider function that
  99. * returns a promise that is resolved
  100. * with a CredentialsInterface object.
  101. * @param callable $signatureFunction Function that accepts a Command
  102. * object and returns a
  103. * SignatureInterface.
  104. *
  105. * @return callable
  106. */
  107. public static function signer(callable $credProvider, callable $signatureFunction)
  108. {
  109. return function (callable $handler) use ($signatureFunction, $credProvider) {
  110. return function (
  111. CommandInterface $command,
  112. RequestInterface $request
  113. ) use ($handler, $signatureFunction, $credProvider) {
  114. $signer = $signatureFunction($command);
  115. return $credProvider()->then(
  116. function (CredentialsInterface $creds)
  117. use ($handler, $command, $signer, $request) {
  118. return $handler(
  119. $command,
  120. $signer->signRequest($request, $creds)
  121. );
  122. }
  123. );
  124. };
  125. };
  126. }
  127. /**
  128. * Creates a middleware that invokes a callback at a given step.
  129. *
  130. * The tap callback accepts a CommandInterface and RequestInterface as
  131. * arguments but is not expected to return a new value or proxy to
  132. * downstream middleware. It's simply a way to "tap" into the handler chain
  133. * to debug or get an intermediate value.
  134. *
  135. * @param callable $fn Tap function
  136. *
  137. * @return callable
  138. */
  139. public static function tap(callable $fn)
  140. {
  141. return function (callable $handler) use ($fn) {
  142. return function (
  143. CommandInterface $command,
  144. RequestInterface $request = null
  145. ) use ($handler, $fn) {
  146. $fn($command, $request);
  147. return $handler($command, $request);
  148. };
  149. };
  150. }
  151. /**
  152. * Middleware wrapper function that retries requests based on the boolean
  153. * result of invoking the provided "decider" function.
  154. *
  155. * If no delay function is provided, a simple implementation of exponential
  156. * backoff will be utilized.
  157. *
  158. * @param callable $decider Function that accepts the number of retries,
  159. * a request, [result], and [exception] and
  160. * returns true if the command is to be retried.
  161. * @param callable $delay Function that accepts the number of retries and
  162. * returns the number of milliseconds to delay.
  163. * @param bool $stats Whether to collect statistics on retries and the
  164. * associated delay.
  165. *
  166. * @return callable
  167. */
  168. public static function retry(
  169. callable $decider = null,
  170. callable $delay = null,
  171. $stats = false
  172. ) {
  173. $decider = $decider ?: RetryMiddleware::createDefaultDecider();
  174. $delay = $delay ?: [RetryMiddleware::class, 'exponentialDelay'];
  175. return function (callable $handler) use ($decider, $delay, $stats) {
  176. return new RetryMiddleware($decider, $delay, $handler, $stats);
  177. };
  178. }
  179. /**
  180. * Middleware wrapper function that adds an invocation id header to
  181. * requests, which is only applied after the build step.
  182. *
  183. * This is a uniquely generated UUID to identify initial and subsequent
  184. * retries as part of a complete request lifecycle.
  185. *
  186. * @return callable
  187. */
  188. public static function invocationId()
  189. {
  190. return function (callable $handler) {
  191. return function (
  192. CommandInterface $command,
  193. RequestInterface $request
  194. ) use ($handler){
  195. return $handler($command, $request->withHeader(
  196. 'aws-sdk-invocation-id',
  197. md5(uniqid(gethostname(), true))
  198. ));
  199. };
  200. };
  201. }
  202. /**
  203. * Middleware wrapper function that adds a Content-Type header to requests.
  204. * This is only done when the Content-Type has not already been set, and the
  205. * request body's URI is available. It then checks the file extension of the
  206. * URI to determine the mime-type.
  207. *
  208. * @param array $operations Operations that Content-Type should be added to.
  209. *
  210. * @return callable
  211. */
  212. public static function contentType(array $operations)
  213. {
  214. return function (callable $handler) use ($operations) {
  215. return function (
  216. CommandInterface $command,
  217. RequestInterface $request = null
  218. ) use ($handler, $operations) {
  219. if (!$request->hasHeader('Content-Type')
  220. && in_array($command->getName(), $operations, true)
  221. && ($uri = $request->getBody()->getMetadata('uri'))
  222. ) {
  223. $request = $request->withHeader(
  224. 'Content-Type',
  225. Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream'
  226. );
  227. }
  228. return $handler($command, $request);
  229. };
  230. };
  231. }
  232. /**
  233. * Tracks command and request history using a history container.
  234. *
  235. * This is useful for testing.
  236. *
  237. * @param History $history History container to store entries.
  238. *
  239. * @return callable
  240. */
  241. public static function history(History $history)
  242. {
  243. return function (callable $handler) use ($history) {
  244. return function (
  245. CommandInterface $command,
  246. RequestInterface $request = null
  247. ) use ($handler, $history) {
  248. $ticket = $history->start($command, $request);
  249. return $handler($command, $request)
  250. ->then(
  251. function ($result) use ($history, $ticket) {
  252. $history->finish($ticket, $result);
  253. return $result;
  254. },
  255. function ($reason) use ($history, $ticket) {
  256. $history->finish($ticket, $reason);
  257. return Promise\rejection_for($reason);
  258. }
  259. );
  260. };
  261. };
  262. }
  263. /**
  264. * Creates a middleware that applies a map function to requests as they
  265. * pass through the middleware.
  266. *
  267. * @param callable $f Map function that accepts a RequestInterface and
  268. * returns a RequestInterface.
  269. *
  270. * @return callable
  271. */
  272. public static function mapRequest(callable $f)
  273. {
  274. return function (callable $handler) use ($f) {
  275. return function (
  276. CommandInterface $command,
  277. RequestInterface $request = null
  278. ) use ($handler, $f) {
  279. return $handler($command, $f($request));
  280. };
  281. };
  282. }
  283. /**
  284. * Creates a middleware that applies a map function to commands as they
  285. * pass through the middleware.
  286. *
  287. * @param callable $f Map function that accepts a command and returns a
  288. * command.
  289. *
  290. * @return callable
  291. */
  292. public static function mapCommand(callable $f)
  293. {
  294. return function (callable $handler) use ($f) {
  295. return function (
  296. CommandInterface $command,
  297. RequestInterface $request = null
  298. ) use ($handler, $f) {
  299. return $handler($f($command), $request);
  300. };
  301. };
  302. }
  303. /**
  304. * Creates a middleware that applies a map function to results.
  305. *
  306. * @param callable $f Map function that accepts an Aws\ResultInterface and
  307. * returns an Aws\ResultInterface.
  308. *
  309. * @return callable
  310. */
  311. public static function mapResult(callable $f)
  312. {
  313. return function (callable $handler) use ($f) {
  314. return function (
  315. CommandInterface $command,
  316. RequestInterface $request = null
  317. ) use ($handler, $f) {
  318. return $handler($command, $request)->then($f);
  319. };
  320. };
  321. }
  322. public static function timer()
  323. {
  324. return function (callable $handler) {
  325. return function (
  326. CommandInterface $command,
  327. RequestInterface $request = null
  328. ) use ($handler) {
  329. $start = microtime(true);
  330. return $handler($command, $request)
  331. ->then(
  332. function (ResultInterface $res) use ($start) {
  333. if (!isset($res['@metadata'])) {
  334. $res['@metadata'] = [];
  335. }
  336. if (!isset($res['@metadata']['transferStats'])) {
  337. $res['@metadata']['transferStats'] = [];
  338. }
  339. $res['@metadata']['transferStats']['total_time']
  340. = microtime(true) - $start;
  341. return $res;
  342. },
  343. function ($err) use ($start) {
  344. if ($err instanceof AwsException) {
  345. $err->setTransferInfo([
  346. 'total_time' => microtime(true) - $start,
  347. ] + $err->getTransferInfo());
  348. }
  349. return Promise\rejection_for($err);
  350. }
  351. );
  352. };
  353. };
  354. }
  355. }