Middleware.php 13 KB

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