Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Middleware.php

raw symbols SCIP
1 <?php
2 namespace Aws;
3
4 use Aws\Api\Service;
5 use Aws\Api\Validator;
6 use Aws\Credentials\CredentialsInterface;
7 use Aws\EndpointV2\EndpointProviderV2;
8 use Aws\Exception\AwsException;
9 use Aws\Signature\DpopSignature;
10 use Aws\Signature\S3ExpressSignature;
11 use Aws\Token\TokenAuthorization;
12 use Aws\Token\TokenInterface;
13 use GuzzleHttp\Promise;
14 use GuzzleHttp\Psr7;
15 use GuzzleHttp\Psr7\LazyOpenStream;
16 use Psr\Http\Message\RequestInterface;
17
18 final class Middleware
19 {
20 /**
21 * Middleware used to allow a command parameter (e.g., "SourceFile") to
22 * be used to specify the source of data for an upload operation.
23 *
24 * @param Service $api
25 * @param string $bodyParameter
26 * @param string $sourceParameter
27 *
28 * @return callable
29 */
30 public static function sourceFile(
31 Service $api,
32 $bodyParameter = 'Body',
33 $sourceParameter = 'SourceFile'
34 ) {
35 return function (callable $handler) use (
36 $api,
37 $bodyParameter,
38 $sourceParameter
39 ) {
40 return function (
41 CommandInterface $command,
42 ?RequestInterface $request = null)
43 use (
44 $handler,
45 $api,
46 $bodyParameter,
47 $sourceParameter
48 ) {
49 $operation = $api->getOperation($command->getName());
50 $source = $command[$sourceParameter];
51
52 if ($source !== null
53 && $operation->getInput()->hasMember($bodyParameter)
54 ) {
55 $lazyOpenStream = new LazyOpenStream($source, 'r');
56 $command[$bodyParameter] = $lazyOpenStream;
57 unset($command[$sourceParameter]);
58
59 $next = $handler($command, $request);
60 // To avoid failures in some tests cases
61 if ($next !== null && method_exists($next, 'then')) {
62 return $next->then(
63 function ($result) use ($lazyOpenStream) {
64 // To make sure the resource is closed.
65 $lazyOpenStream->close();
66
67 return $result;
68 }
69 )->otherwise(function (\Throwable $e) use ($lazyOpenStream) {
70 $lazyOpenStream->close();
71
72 throw $e;
73 });
74 }
75
76 return $next;
77 }
78
79 return $handler($command, $request);
80 };
81 };
82 }
83
84 /**
85 * Adds a middleware that uses client-side validation.
86 *
87 * @param Service $api API being accessed.
88 *
89 * @return callable
90 */
91 public static function validation(Service $api, ?Validator $validator = null)
92 {
93 $validator = $validator ?: new Validator();
94 if ($api->isModifiedModel()) {
95 $api = new Service(
96 $api->getDefinition(),
97 $api->getProvider()
98 );
99 }
100 return function (callable $handler) use ($api, $validator) {
101 return function (
102 CommandInterface $command,
103 ?RequestInterface $request = null
104 ) use ($api, $validator, $handler) {
105 $operation = $api->getOperation($command->getName());
106 $validator->validate(
107 $command->getName(),
108 $operation->getInput(),
109 $command->toArray()
110 );
111 return $handler($command, $request);
112 };
113 };
114 }
115
116 /**
117 * Builds an HTTP request for a command.
118 *
119 * @param callable $serializer Function used to serialize a request for a
120 * command.
121 * @param EndpointProviderV2 | null $endpointProvider
122 * @param array $providerArgs
123 * @return callable
124 */
125 public static function requestBuilder($serializer)
126 {
127 return function (callable $handler) use ($serializer) {
128 return function (CommandInterface $command, $endpoint = null) use ($serializer, $handler) {
129 return $handler($command, $serializer($command, $endpoint));
130 };
131 };
132 }
133
134 /**
135 * Creates a middleware that signs requests for a command.
136 *
137 * @param callable $credProvider Credentials provider function that
138 * returns a promise that is resolved
139 * with a CredentialsInterface object.
140 * @param callable $signatureFunction Function that accepts a Command
141 * object and returns a
142 * SignatureInterface.
143 *
144 * @return callable
145 */
146 public static function signer(
147 callable $credProvider,
148 callable $signatureFunction,
149 $tokenProvider = null,
150 $config = []
151 ) {
152 return function (callable $handler) use ($signatureFunction, $credProvider, $tokenProvider, $config) {
153 return function (
154 CommandInterface $command,
155 RequestInterface $request
156 ) use ($handler, $signatureFunction, $credProvider, $tokenProvider, $config) {
157 $signer = $signatureFunction($command);
158
159 // Token authorization path
160 if ($signer instanceof TokenAuthorization) {
161 return $tokenProvider()->then(function (TokenInterface $token) use ($handler, $command, $signer, $request) {
162 $command->getMetricsBuilder()->identifyMetricByValueAndAppend('token', $token);
163 return $handler($command, $signer->authorizeRequest($request, $token));
164 });
165 }
166
167 // DPoP path
168 if ($signer instanceof DpopSignature) {
169 if (empty($key = $command['dpopKey'])
170 || !($key instanceof \OpenSSLAsymmetricKey)
171 ) {
172 throw new \RuntimeException(
173 'A valid DPoP key must be present for DPoP signatures'
174 );
175 }
176
177 return $handler($command, $signer->signRequest($request, $key));
178 }
179
180 // Credential signing path
181 $credentialPromise = ($signer instanceof S3ExpressSignature)
182 ? $config['s3_express_identity_provider']($command)
183 : $credProvider();
184
185 return $credentialPromise->then(function (CredentialsInterface $creds) use ($handler,
186 $command,
187 $signer,
188 $request
189 ) {
190 $command->getMetricsBuilder()->identifyMetricByValueAndAppend('credentials', $creds);
191 return $handler($command, $signer->signRequest($request, $creds));
192 });
193 };
194 };
195 }
196
197 /**
198 * Creates a middleware that invokes a callback at a given step.
199 *
200 * The tap callback accepts a CommandInterface and RequestInterface as
201 * arguments but is not expected to return a new value or proxy to
202 * downstream middleware. It's simply a way to "tap" into the handler chain
203 * to debug or get an intermediate value.
204 *
205 * @param callable $fn Tap function
206 *
207 * @return callable
208 */
209 public static function tap(callable $fn)
210 {
211 return function (callable $handler) use ($fn) {
212 return function (
213 CommandInterface $command,
214 ?RequestInterface $request = null
215 ) use ($handler, $fn) {
216 $fn($command, $request);
217 return $handler($command, $request);
218 };
219 };
220 }
221
222 /**
223 * Middleware wrapper function that retries requests based on the boolean
224 * result of invoking the provided "decider" function.
225 *
226 * If no delay function is provided, a simple implementation of exponential
227 * backoff will be utilized.
228 *
229 * @param callable $decider Function that accepts the number of retries,
230 * a request, [result], and [exception] and
231 * returns true if the command is to be retried.
232 * @param callable $delay Function that accepts the number of retries and
233 * returns the number of milliseconds to delay.
234 * @param bool $stats Whether to collect statistics on retries and the
235 * associated delay.
236 *
237 * @return callable
238 */
239 public static function retry(
240 ?callable $decider = null,
241 ?callable $delay = null,
242 $stats = false
243 ) {
244 $decider = $decider ?: RetryMiddleware::createDefaultDecider();
245 $delay = $delay ?: [RetryMiddleware::class, 'exponentialDelay'];
246
247 return function (callable $handler) use ($decider, $delay, $stats) {
248 return new RetryMiddleware($decider, $delay, $handler, $stats);
249 };
250 }
251 /**
252 * Middleware wrapper function that adds an invocation id header to
253 * requests, which is only applied after the build step.
254 *
255 * This is a uniquely generated UUID to identify initial and subsequent
256 * retries as part of a complete request lifecycle.
257 *
258 * @return callable
259 */
260 public static function invocationId()
261 {
262 return function (callable $handler) {
263 return function (
264 CommandInterface $command,
265 RequestInterface $request
266 ) use ($handler){
267 return $handler($command, $request->withHeader(
268 'aws-sdk-invocation-id',
269 md5(uniqid(gethostname(), true))
270 ));
271 };
272 };
273 }
274 /**
275 * Middleware wrapper function that adds a Content-Type header to requests.
276 * This is only done when the Content-Type has not already been set, and the
277 * request body's URI is available. It then checks the file extension of the
278 * URI to determine the mime-type.
279 *
280 * @param array $operations Operations that Content-Type should be added to.
281 *
282 * @return callable
283 */
284 public static function contentType(array $operations)
285 {
286 return function (callable $handler) use ($operations) {
287 return function (
288 CommandInterface $command,
289 ?RequestInterface $request = null
290 ) use ($handler, $operations) {
291 if (!$request->hasHeader('Content-Type')
292 && in_array($command->getName(), $operations, true)
293 && ($uri = $request->getBody()->getMetadata('uri'))
294 ) {
295 $request = $request->withHeader(
296 'Content-Type',
297 Psr7\MimeType::fromFilename($uri) ?: 'application/octet-stream'
298 );
299 }
300
301 return $handler($command, $request);
302 };
303 };
304 }
305 /**
306 * Middleware wrapper function that adds a trace id header to requests
307 * from clients instantiated in supported Lambda runtime environments.
308 *
309 * The purpose for this header is to track and stop Lambda functions
310 * from being recursively invoked due to misconfigured resources.
311 *
312 * @return callable
313 */
314 public static function recursionDetection()
315 {
316 return function (callable $handler) {
317 return function (
318 CommandInterface $command,
319 RequestInterface $request
320 ) use ($handler){
321 $isLambda = getenv('AWS_LAMBDA_FUNCTION_NAME');
322 $traceId = str_replace('\e', '\x1b', getenv('_X_AMZN_TRACE_ID'));
323
324 if ($isLambda && $traceId) {
325 if (!$request->hasHeader('X-Amzn-Trace-Id')) {
326 $ignoreChars = ['=', ';', ':', '+', '&', '[', ']', '{', '}', '"', '\'', ','];
327 $traceIdEncoded = rawurlencode(stripcslashes($traceId));
328
329 foreach($ignoreChars as $char) {
330 $encodedChar = rawurlencode($char);
331 $traceIdEncoded = str_replace($encodedChar, $char, $traceIdEncoded);
332 }
333
334 return $handler($command, $request->withHeader(
335 'X-Amzn-Trace-Id',
336 $traceIdEncoded
337 ));
338 }
339 }
340 return $handler($command, $request);
341 };
342 };
343 }
344 /**
345 * Tracks command and request history using a history container.
346 *
347 * This is useful for testing.
348 *
349 * @param History $history History container to store entries.
350 *
351 * @return callable
352 */
353 public static function history(History $history)
354 {
355 return function (callable $handler) use ($history) {
356 return function (
357 CommandInterface $command,
358 ?RequestInterface $request = null
359 ) use ($handler, $history) {
360 $ticket = $history->start($command, $request);
361 return $handler($command, $request)
362 ->then(
363 function ($result) use ($history, $ticket) {
364 $history->finish($ticket, $result);
365 return $result;
366 },
367 function ($reason) use ($history, $ticket) {
368 $history->finish($ticket, $reason);
369 return Promise\Create::rejectionFor($reason);
370 }
371 );
372 };
373 };
374 }
375
376 /**
377 * Creates a middleware that applies a map function to requests as they
378 * pass through the middleware.
379 *
380 * @param callable $f Map function that accepts a RequestInterface and
381 * returns a RequestInterface.
382 *
383 * @return callable
384 */
385 public static function mapRequest(callable $f)
386 {
387 return static function (callable $handler) use ($f) {
388 return static function (
389 CommandInterface $command,
390 ?RequestInterface $request = null
391 ) use ($handler, $f) {
392 return $handler($command, $f($request));
393 };
394 };
395 }
396
397 /**
398 * Creates a middleware that applies a map function to commands as they
399 * pass through the middleware.
400 *
401 * @param callable $f Map function that accepts a command and returns a
402 * command.
403 *
404 * @return callable
405 */
406 public static function mapCommand(callable $f)
407 {
408 return function (callable $handler) use ($f) {
409 return function (
410 CommandInterface $command,
411 ?RequestInterface $request = null
412 ) use ($handler, $f) {
413 return $handler($f($command), $request);
414 };
415 };
416 }
417
418 /**
419 * Creates a middleware that applies a map function to results.
420 *
421 * @param callable $f Map function that accepts an Aws\ResultInterface and
422 * returns an Aws\ResultInterface.
423 *
424 * @return callable
425 */
426 public static function mapResult(callable $f)
427 {
428 return function (callable $handler) use ($f) {
429 return function (
430 CommandInterface $command,
431 ?RequestInterface $request = null
432 ) use ($handler, $f) {
433 return $handler($command, $request)->then($f);
434 };
435 };
436 }
437
438 public static function timer()
439 {
440 return function (callable $handler) {
441 return function (
442 CommandInterface $command,
443 ?RequestInterface $request = null
444 ) use ($handler) {
445 $start = microtime(true);
446 return $handler($command, $request)
447 ->then(
448 function (ResultInterface $res) use ($start) {
449 if (!isset($res['@metadata'])) {
450 $res['@metadata'] = [];
451 }
452 if (!isset($res['@metadata']['transferStats'])) {
453 $res['@metadata']['transferStats'] = [];
454 }
455
456 $res['@metadata']['transferStats']['total_time']
457 = microtime(true) - $start;
458
459 return $res;
460 },
461 function ($err) use ($start) {
462 if ($err instanceof AwsException) {
463 $err->setTransferInfo([
464 'total_time' => microtime(true) - $start,
465 ] + $err->getTransferInfo());
466 }
467 return Promise\Create::rejectionFor($err);
468 }
469 );
470 };
471 };
472 }
473 }