Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 namespace Aws;
4
5 use Aws\Credentials\CredentialsInterface;
6 use Aws\Credentials\CredentialSources;
7 use Aws\Token;
8 use Aws\Token\TokenInterface;
9
10 /**
11 * A placeholder for gathering metrics in a request.
12 *
13 * @internal
14 */
15 final class MetricsBuilder
16 {
17 const WAITER = "B";
18 const PAGINATOR = "C";
19 const RETRY_MODE_LEGACY = "D";
20 const RETRY_MODE_STANDARD = "E";
21 const RETRY_MODE_ADAPTIVE = "F";
22 const S3_TRANSFER = "G";
23 const S3_CRYPTO_V1N = "H";
24 const S3_CRYPTO_V2 = "I";
25 const S3_CRYPTO_V3 = "AE";
26 const S3_EXPRESS_BUCKET = "J";
27 const GZIP_REQUEST_COMPRESSION = "L";
28 const ENDPOINT_OVERRIDE = "N";
29 const ACCOUNT_ID_ENDPOINT = "O";
30 const ACCOUNT_ID_MODE_PREFERRED = "P";
31 const ACCOUNT_ID_MODE_DISABLED = "Q";
32 const ACCOUNT_ID_MODE_REQUIRED = "R";
33 const BEARER_SERVICE_ENV_VARS = "3";
34 const SIGV4A_SIGNING = "S";
35 const RESOLVED_ACCOUNT_ID = "T";
36 const FLEXIBLE_CHECKSUMS_REQ_CRC32 = "U";
37 const FLEXIBLE_CHECKSUMS_REQ_CRC32C = "V";
38 const FLEXIBLE_CHECKSUMS_REQ_CRC64 = "W";
39 const FLEXIBLE_CHECKSUMS_REQ_SHA1 = "X";
40 const FLEXIBLE_CHECKSUMS_REQ_SHA256 = "Y";
41 const FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED = "Z";
42 const FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED = "a";
43 const FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED = "b";
44 const FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED = "c";
45 const CREDENTIALS_CODE = "e";
46 const CREDENTIALS_ENV_VARS = "g";
47 const CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN = "h";
48 const CREDENTIALS_STS_ASSUME_ROLE = "i";
49 const CREDENTIALS_STS_ASSUME_ROLE_WEB_ID = "k";
50 const CREDENTIALS_PROFILE = "n";
51 const CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN = "q";
52 const CREDENTIALS_HTTP = "z";
53 const CREDENTIALS_IMDS = "0";
54 const CREDENTIALS_PROFILE_PROCESS = "v";
55 const CREDENTIALS_PROFILE_SSO = "r";
56 const CREDENTIALS_PROFILE_SSO_LEGACY = "t";
57 const S3_TRANSFER_UPLOAD_DIRECTORY = "9";
58 const S3_TRANSFER_DOWNLOAD_DIRECTORY = "+";
59 const CREDENTIALS_PROFILE_LOGIN = "AC";
60
61 /** @var int */
62 private static $MAX_METRICS_SIZE = 1024; // 1KB or 1024 B
63
64 /** @var string */
65 private static $METRIC_SEPARATOR = ",";
66
67 /** @var array $metrics */
68 private $metrics;
69
70 /** @var int $metricsSize */
71 private $metricsSize;
72
73 public function __construct()
74 {
75 $this->metrics = [];
76 // The first metrics does not include the separator
77 // therefore it is reduced by default.
78 $this->metricsSize = -(strlen(self::$METRIC_SEPARATOR));
79 }
80
81 /**
82 * Build the metrics string value.
83 *
84 * @return string
85 */
86 public function build(): string
87 {
88 if (empty($this->metrics)) {
89 return "";
90 }
91
92 return $this->encode();
93 }
94
95 /**
96 * Encodes the metrics by separating each metric
97 * with a comma. Example: for the metrics[A,B,C] then
98 * the output would be "A,B,C".
99 *
100 * @return string
101 */
102 private function encode(): string
103 {
104 return implode(self::$METRIC_SEPARATOR, array_keys($this->metrics));
105 }
106
107 /**
108 * Appends a metric to the internal metrics holder after validating it.
109 * Increases the current metrics size by the length of the new metric
110 * plus the length of the encoding separator.
111 * Example: $currentSize = $currentSize + len($newMetric) + len($separator)
112 *
113 * @param string $metric The metric to append.
114 *
115 * @return void
116 */
117 public function append(string $metric): void
118 {
119 if (!$this->canMetricBeAppended($metric)) {
120 return;
121 }
122
123 $this->metrics[$metric] = true;
124 $this->metricsSize += strlen($metric) + strlen(self::$METRIC_SEPARATOR);
125 }
126
127 /**
128 * Receives a feature group and a value to identify which one is the metric.
129 * For example, a group could be `signature` and a value could be `v4a`,
130 * then the metric will be `SIGV4A_SIGNING`.
131 *
132 * @param string $featureGroup the feature group such as `signature`.
133 * @param mixed $value the value for identifying the metric.
134 *
135 * @return void
136 */
137 public function identifyMetricByValueAndAppend(
138 string $featureGroup,
139 mixed $value
140 ): void
141 {
142 if (empty($value)) {
143 return;
144 }
145
146 static $appendMetricFns = [
147 'signature' => 'appendSignatureMetric',
148 'request_compression' => 'appendRequestCompressionMetric',
149 'request_checksum' => 'appendRequestChecksumMetric',
150 'credentials' => 'appendCredentialsMetric',
151 'account_id_endpoint_mode' => 'appendAccountIdEndpointMode',
152 'account_id_endpoint' => 'appendAccountIdEndpoint',
153 'request_checksum_calculation' => 'appendRequestChecksumCalculationMetric',
154 'token' => 'appendTokenMetric'
155 ];
156
157 $fn = $appendMetricFns[$featureGroup];
158 $this->{$fn}($value);
159 }
160
161 /**
162 * Appends the signature metric based on the signature value.
163 *
164 * @param string $signature
165 *
166 * @return void
167 */
168 private function appendSignatureMetric(string $signature): void
169 {
170 if ($signature === 'v4-s3express') {
171 $this->append(self::S3_EXPRESS_BUCKET);
172 } elseif ($signature === 'v4a') {
173 $this->append(self::SIGV4A_SIGNING);
174 }
175 }
176
177 /**
178 * Appends the request compression metric based on the format resolved.
179 *
180 * @param string $format
181 *
182 * @return void
183 */
184 private function appendRequestCompressionMetric(string $format): void
185 {
186 if ($format === 'gzip') {
187 $this->append(self::GZIP_REQUEST_COMPRESSION);
188 }
189 }
190
191 /**
192 * Appends the request checksum metric based on the algorithm.
193 *
194 * @param string $algorithm
195 *
196 * @return void
197 */
198 private function appendRequestChecksumMetric(string $algorithm): void
199 {
200 if ($algorithm === 'crc32') {
201 $this->append(self::FLEXIBLE_CHECKSUMS_REQ_CRC32);
202 } elseif ($algorithm === 'crc32c') {
203 $this->append(self::FLEXIBLE_CHECKSUMS_REQ_CRC32C);
204 } elseif ($algorithm === 'crc64') {
205 $this->append(self::FLEXIBLE_CHECKSUMS_REQ_CRC64);
206 } elseif ($algorithm === 'sha1') {
207 $this->append(self::FLEXIBLE_CHECKSUMS_REQ_SHA1);
208 } elseif ($algorithm === 'sha256') {
209 $this->append(self::FLEXIBLE_CHECKSUMS_REQ_SHA256);
210 }
211 }
212
213
214 /**
215 * Appends the credentials metric based on the type of credentials
216 * resolved.
217 *
218 * @param CredentialsInterface $credentials
219 *
220 * @return void
221 */
222 private function appendCredentialsMetric(
223 CredentialsInterface $credentials
224 ): void
225 {
226 $source = $credentials->toArray()['source'] ?? null;
227 if (empty($source)) {
228 return;
229 }
230
231 static $credentialsMetricMapping = [
232 CredentialSources::STATIC =>
233 self::CREDENTIALS_CODE,
234 CredentialSources::ENVIRONMENT =>
235 self::CREDENTIALS_ENV_VARS,
236 CredentialSources::ENVIRONMENT_STS_WEB_ID_TOKEN =>
237 self::CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN,
238 CredentialSources::STS_ASSUME_ROLE =>
239 self::CREDENTIALS_STS_ASSUME_ROLE,
240 CredentialSources::STS_WEB_ID_TOKEN =>
241 self::CREDENTIALS_STS_ASSUME_ROLE_WEB_ID,
242 CredentialSources::PROFILE =>
243 self::CREDENTIALS_PROFILE,
244 CredentialSources::IMDS =>
245 self::CREDENTIALS_IMDS,
246 CredentialSources::ECS =>
247 self::CREDENTIALS_HTTP,
248 CredentialSources::PROFILE_STS_WEB_ID_TOKEN =>
249 self::CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN,
250 CredentialSources::PROFILE_PROCESS =>
251 self::CREDENTIALS_PROFILE_PROCESS,
252 CredentialSources::PROFILE_SSO =>
253 self::CREDENTIALS_PROFILE_SSO,
254 CredentialSources::PROFILE_SSO_LEGACY =>
255 self::CREDENTIALS_PROFILE_SSO_LEGACY,
256 CredentialSources::PROFILE_LOGIN =>
257 self::CREDENTIALS_PROFILE_LOGIN
258 ];
259 if (isset($credentialsMetricMapping[$source])) {
260 $this->append($credentialsMetricMapping[$source]);
261 }
262 }
263
264 private function appendTokenMetric(TokenInterface $token): void
265 {
266 $source = $token->getSource();
267 if (empty($source)) {
268 return;
269 }
270
271 static $tokenMetricMapping = [
272 'bearer_service_env_vars' => self::BEARER_SERVICE_ENV_VARS
273 ];
274
275 if (isset($tokenMetricMapping[$source])) {
276 $this->append($tokenMetricMapping[$source]);
277 }
278 }
279
280 private function appendRequestChecksumCalculationMetric(
281 string $checkSumCalculation
282 ): void
283 {
284 static $checksumCalculationMetricMapping = [
285 'when_supported' => self::FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED,
286 'when_required' => self::FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED,
287 ];
288
289 if (isset($checksumCalculationMetricMapping[$checkSumCalculation])) {
290 $this->append($checksumCalculationMetricMapping[$checkSumCalculation]);
291 }
292 }
293
294 /**
295 * Appends the account_id_endpoint_mode metrics based on
296 * the value resolved.
297 *
298 * @param string $accountIdEndpointMode
299 *
300 * @return void
301 */
302 private function appendAccountIdEndpointMode(
303 string $accountIdEndpointMode
304 ): void
305 {
306 if (empty($accountIdEndpointMode)) {
307 return;
308 }
309
310 if ($accountIdEndpointMode === 'preferred') {
311 $this->append(self::ACCOUNT_ID_MODE_PREFERRED);
312 } elseif ($accountIdEndpointMode === 'disabled') {
313 $this->append(self::ACCOUNT_ID_MODE_DISABLED);
314 } elseif ($accountIdEndpointMode === 'required') {
315 $this->append(self::ACCOUNT_ID_MODE_REQUIRED);
316 }
317 }
318
319 /**
320 * Appends the account_id_endpoint metric whenever a resolved endpoint
321 * matches an account_id endpoint pattern which also defined here.
322 *
323 * @param string $endpoint
324 *
325 * @return void
326 */
327 private function appendAccountIdEndpoint(string $endpoint): void
328 {
329 static $pattern = "/(https|http):\\/\\/\\d{12}\\.ddb/";
330 if (preg_match($pattern, $endpoint)) {
331 $this->append(self::ACCOUNT_ID_ENDPOINT);
332 }
333 }
334
335 /**
336 * Resolves metrics from client arguments.
337 *
338 * @param array $args
339 *
340 * @return void
341 */
342 public function resolveAndAppendFromArgs(array $args = []): void
343 {
344 static $metricsFnList = [
345 'appendEndpointMetric',
346 'appendRetryConfigMetric',
347 'appendResponseChecksumValidationMetric',
348 ];
349 foreach ($metricsFnList as $metricFn) {
350 $this->{$metricFn}($args);
351 }
352 }
353
354 /**
355 * Appends the endpoint metric into the metrics builder,
356 * just if a custom endpoint was provided at client construction.
357 *
358 * @param array $args
359 *
360 * @return void
361 */
362 private function appendEndpointMetric(array $args): void
363 {
364 if (!empty($args['endpoint_override'])) {
365 $this->append(MetricsBuilder::ENDPOINT_OVERRIDE);
366 }
367 }
368
369 /**
370 * Appends the retry mode metric into the metrics builder,
371 * based on the resolved retry config mode.
372 *
373 * @param array $args
374 *
375 * @return void
376 */
377 private function appendRetryConfigMetric(array $args): void
378 {
379 $retries = $args['retries'] ?? null;
380 if ($retries === null) {
381 return;
382 }
383
384 $retryMode = '';
385 if ($retries instanceof \Aws\Retry\Configuration) {
386 $retryMode = $retries->getMode();
387 } elseif (is_array($retries)
388 && isset($retries["mode"])
389 ) {
390 $retryMode = $retries["mode"];
391 }
392
393 if ($retryMode === 'legacy') {
394 $this->append(
395 MetricsBuilder::RETRY_MODE_LEGACY
396 );
397 } elseif ($retryMode === 'standard') {
398 $this->append(
399 MetricsBuilder::RETRY_MODE_STANDARD
400 );
401 } elseif ($retryMode === 'adaptive') {
402 $this->append(
403 MetricsBuilder::RETRY_MODE_ADAPTIVE
404 );
405 }
406 }
407
408 /**
409 * Appends the provided/resolved response checksum validation mode.
410 *
411 * @param array $args
412 *
413 * @return void
414 */
415 private function appendResponseChecksumValidationMetric(array $args): void
416 {
417 if (empty($args['response_checksum_validation'])) {
418 return;
419 }
420
421 $checksumValidation = $args['response_checksum_validation'];
422 static $checksumValidationMetricMapping = [
423 'when_supported' => MetricsBuilder::FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED,
424 'when_required' => MetricsBuilder::FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED,
425 ];
426
427 if (isset($checksumValidationMetricMapping[$checksumValidation])) {
428 $this->append($checksumValidationMetricMapping[$checksumValidation]);
429 }
430 }
431
432 /**
433 * Validates if a metric can be appended by ensuring the total size,
434 * including the new metric and separator, does not exceed the limit.
435 * Also checks that the metric does not already exist.
436 * Example: Appendable if:
437 * $currentSize + len($newMetric) + len($separator) <= MAX_SIZE
438 * and:
439 * $newMetric not in $existingMetrics
440 *
441 * @param string $newMetric The metric to validate.
442 *
443 * @return bool True if the metric can be appended, false otherwise.
444 */
445 private function canMetricBeAppended(string $newMetric): bool
446 {
447 if ($newMetric === "") {
448 return false;
449 }
450
451 if ($this->metricsSize
452 + (strlen($newMetric) + strlen(self::$METRIC_SEPARATOR))
453 > self::$MAX_METRICS_SIZE
454 ) {
455 return false;
456 }
457
458 if (isset($this->metrics[$newMetric])) {
459 return false;
460 }
461
462 return true;
463 }
464
465 /**
466 * Returns the metrics builder from the property @context of a command.
467 *
468 * @param Command $command
469 *
470 * @return MetricsBuilder
471 */
472 public static function fromCommand(CommandInterface $command): MetricsBuilder
473 {
474 return $command->getMetricsBuilder();
475 }
476
477 /**
478 * Helper method for appending a metrics capture middleware into a
479 * handler stack given. The middleware appended here is on top of the
480 * build step.
481 *
482 * @param HandlerList $handlerList
483 * @param $metric
484 *
485 * @return void
486 */
487 public static function appendMetricsCaptureMiddleware(
488 HandlerList $handlerList,
489 $metric
490 ): void
491 {
492 $middlewareName = 'metrics-capture-'.$metric;
493 if (!$handlerList->hasMiddleware($middlewareName)) {
494 $handlerList->appendBuild(
495 Middleware::tap(
496 function (CommandInterface $command) use ($metric) {
497 self::fromCommand($command)->append(
498 $metric
499 );
500 }
501 ),
502 $middlewareName
503 );
504 }
505 }
506 }