Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/S3Transfer/AbstractMultipartDownloader.php

raw symbols SCIP
1 <?php
2 namespace Aws\S3\S3Transfer;
3
4 use Aws\CommandInterface;
5 use Aws\ResultInterface;
6 use Aws\S3\S3ClientInterface;
7 use Aws\S3\S3Transfer\Exception\S3TransferException;
8 use Aws\S3\S3Transfer\Models\DownloadResult;
9 use Aws\S3\S3Transfer\Models\ResumableDownload;
10 use Aws\S3\S3Transfer\Models\S3TransferManagerConfig;
11 use Aws\S3\S3Transfer\Progress\AbstractTransferListener;
12 use Aws\S3\S3Transfer\Progress\TransferListenerNotifier;
13 use Aws\S3\S3Transfer\Progress\TransferProgressSnapshot;
14 use Aws\S3\S3Transfer\Utils\ResumableDownloadHandlerInterface;
15 use Aws\S3\S3Transfer\Utils\AbstractDownloadHandler;
16 use Aws\S3\S3Transfer\Utils\StreamDownloadHandler;
17 use GuzzleHttp\Promise\Coroutine;
18 use GuzzleHttp\Promise\Create;
19 use GuzzleHttp\Promise\Each;
20 use GuzzleHttp\Promise\PromiseInterface;
21 use GuzzleHttp\Promise\PromisorInterface;
22 use Throwable;
23
24 abstract class AbstractMultipartDownloader implements PromisorInterface
25 {
26 public const GET_OBJECT_COMMAND = "GetObject";
27 public const PART_GET_MULTIPART_DOWNLOADER = "part";
28 public const RANGED_GET_MULTIPART_DOWNLOADER = "ranged";
29 private const OBJECT_SIZE_REGEX = "/\/(\d+)$/";
30 private const RANGE_TO_REGEX = "/(\d+)\//";
31
32 /** @var array */
33 protected readonly array $downloadRequestArgs;
34
35 /** @var array */
36 protected readonly array $config;
37
38 /** @var AbstractDownloadHandler */
39 private AbstractDownloadHandler $downloadHandler;
40
41 /** @var int */
42 protected int $currentPartNo;
43
44 /** @var int */
45 protected int $objectPartsCount;
46
47 /** @var int */
48 protected int $objectSizeInBytes;
49
50 /** @var string|null */
51 protected ?string $eTag;
52
53 /** @var TransferListenerNotifier|null */
54 private readonly ?TransferListenerNotifier $listenerNotifier;
55
56 /** Tracking Members */
57 private ?TransferProgressSnapshot $currentSnapshot;
58
59 /** @var array */
60 private array $partsCompleted;
61
62 /** @var ResumableDownload|null */
63 private ?ResumableDownload $resumableDownload;
64
65 /** @var bool Whether this is a resumed download */
66 private readonly bool $isResuming;
67
68 /** @var array|null Initial request response for resume state */
69 private ?array $initialRequestResult = null;
70
71 /**
72 * @param S3ClientInterface $s3Client
73 * @param array $downloadRequestArgs
74 * @param array $config
75 * @param ?AbstractDownloadHandler $downloadHandler
76 * @param array $partsCompleted
77 * @param int $objectPartsCount
78 * @param int $objectSizeInBytes
79 * @param string|null $eTag
80 * @param TransferProgressSnapshot|null $currentSnapshot
81 * @param TransferListenerNotifier|null $listenerNotifier
82 * @param ResumableDownload|null $resumableDownload
83 */
84 public function __construct(
85 protected readonly S3ClientInterface $s3Client,
86 array $downloadRequestArgs,
87 array $config = [],
88 ?AbstractDownloadHandler $downloadHandler = null,
89 array $partsCompleted = [],
90 int $objectPartsCount = 0,
91 int $objectSizeInBytes = 0,
92 ?string $eTag = null,
93 ?TransferProgressSnapshot $currentSnapshot = null,
94 ?TransferListenerNotifier $listenerNotifier = null,
95 ?ResumableDownload $resumableDownload = null
96 ) {
97 $this->resumableDownload = $resumableDownload;
98 $this->isResuming = $resumableDownload !== null;
99 // Initialize from resume state if available
100 if ($this->isResuming) {
101 $this->objectPartsCount = $resumableDownload->getTotalNumberOfParts();
102 $this->objectSizeInBytes = $resumableDownload->getObjectSizeInBytes();
103 $this->eTag = $resumableDownload->getETag();
104 $this->partsCompleted = $resumableDownload->getPartsCompleted();
105 $this->initialRequestResult = $this->resumableDownload->getInitialRequestResult();
106 // Restore current snapshot
107 $snapshotData = $resumableDownload->getCurrentSnapshot();
108 if (!empty($snapshotData)) {
109 $this->currentSnapshot = TransferProgressSnapshot::fromArray(
110 $snapshotData
111 );
112 }
113 } else {
114 $this->partsCompleted = $partsCompleted;
115 $this->objectPartsCount = $objectPartsCount;
116 $this->objectSizeInBytes = $objectSizeInBytes;
117 $this->eTag = $eTag;
118 $this->currentSnapshot = $currentSnapshot;
119 }
120
121 $this->downloadRequestArgs = $downloadRequestArgs;
122 $this->validateConfig($config);
123 $this->config = $config;
124 if ($downloadHandler === null) {
125 $downloadHandler = new StreamDownloadHandler();
126 }
127 $this->downloadHandler = $downloadHandler;
128 $this->listenerNotifier = $listenerNotifier;
129 // Always starts in 1
130 $this->currentPartNo = 1;
131 }
132
133 /**
134 * Returns the next command args for fetching the next object part.
135 *
136 * @return array
137 */
138 abstract protected function getFetchCommandArgs(): array;
139
140 /**
141 * Compute the object dimensions, such as size and parts count.
142 *
143 * @param ResultInterface $result
144 *
145 * @return void
146 */
147 abstract protected function computeObjectDimensions(ResultInterface $result): void;
148
149 private function validateConfig(array &$config): void
150 {
151 if (!isset($config['target_part_size_bytes'])) {
152 $config['target_part_size_bytes'] = S3TransferManagerConfig::DEFAULT_TARGET_PART_SIZE_BYTES;
153 }
154
155 if (!isset($config['concurrency'])) {
156 $config['concurrency'] = S3TransferManagerConfig::DEFAULT_CONCURRENCY;
157 }
158
159 if (!isset($config['response_checksum_validation'])) {
160 $config['response_checksum_validation'] = S3TransferManagerConfig::DEFAULT_RESPONSE_CHECKSUM_VALIDATION;
161 }
162
163 if (!isset($config['resume_enabled'])) {
164 $config['resume_enabled'] = false;
165 }
166 }
167
168 /**
169 * @return array
170 */
171 public function getConfig(): array
172 {
173 return $this->config;
174 }
175
176 /**
177 * @return int
178 */
179 public function getCurrentPartNo(): int
180 {
181 return $this->currentPartNo;
182 }
183
184 /**
185 * @return int
186 */
187 public function getObjectPartsCount(): int
188 {
189 return $this->objectPartsCount;
190 }
191
192 /**
193 * @return int
194 */
195 public function getObjectSizeInBytes(): int
196 {
197 return $this->objectSizeInBytes;
198 }
199
200 /**
201 * @return TransferProgressSnapshot
202 */
203 public function getCurrentSnapshot(): TransferProgressSnapshot
204 {
205 return $this->currentSnapshot;
206 }
207
208 /**
209 * @return DownloadResult
210 */
211 public function download(): DownloadResult
212 {
213 return $this->promise()->wait();
214 }
215
216 /**
217 * Returns that resolves a multipart download operation,
218 * or to a rejection in case of any failures.
219 *
220 * @return PromiseInterface
221 */
222 public function promise(): PromiseInterface
223 {
224 return Coroutine::of(function () {
225 // Skip initial request if resuming (we already have object dimensions)
226 if ($this->isResuming) {
227 $this->downloadInitiated($this->downloadRequestArgs);
228 } else {
229 yield $this->initialRequest();
230 }
231
232 $partsDownloadPromises = $this->partDownloadRequests();
233
234 // When concurrency is not supported by the download handler
235 // Then the number of concurrency will be just one.
236 $concurrency = $this->downloadHandler->isConcurrencySupported()
237 ? $this->config['concurrency']
238 : 1;
239
240 yield Each::ofLimitAll(
241 $partsDownloadPromises,
242 $concurrency,
243 )->then(function () {
244 // Transfer completed
245 $this->downloadComplete();
246
247 return Create::promiseFor(new DownloadResult(
248 $this->downloadHandler->getHandlerResult(),
249 $this->initialRequestResult,
250 ));
251 })->otherwise(function (Throwable $e) {
252 $this->downloadFailed($e);
253
254 throw $e;
255 });
256 });
257 }
258
259 /**
260 * Perform the initial download request.
261 *
262 * @return PromiseInterface
263 */
264 protected function initialRequest(): PromiseInterface
265 {
266 $command = $this->getNextGetObjectCommand();
267 // Notify download initiated
268 $this->downloadInitiated($command->toArray());
269
270 return $this->s3Client->executeAsync($command)
271 ->then(function (ResultInterface $result) use ($command) {
272 // Compute object dimensions such as parts count and object size
273 $this->computeObjectDimensions($result);
274
275 // If there are more than one part then save the ETag
276 if ($this->objectPartsCount > 1) {
277 $this->eTag = $result['ETag'];
278 }
279
280 $initialRequestResult = $result->toArray();
281 // Set full object size
282 $initialRequestResult['ContentLength'] = $this->objectSizeInBytes;
283 // Set full object content range
284 $initialRequestResult['ContentRange'] = "0-"
285 . ($this->objectSizeInBytes - 1)
286 . "/"
287 . $this->objectSizeInBytes;
288
289 // Remove unnecessary fields
290 unset($initialRequestResult['Body']);
291 unset($initialRequestResult['@metadata']);
292
293 // Store initial response for resume state
294 $this->initialRequestResult = $initialRequestResult;
295
296 // Notify listeners but we pass the actual request result
297 $this->partDownloadCompleted(
298 1,
299 $result->toArray(),
300 $command->toArray()
301 );
302 })->otherwise(function ($reason) {
303 $this->partDownloadFailed($reason);
304
305 throw $reason;
306 });
307 }
308
309 /**
310 * @return \Generator
311 */
312 private function partDownloadRequests(): \Generator
313 {
314 while ($this->currentPartNo < $this->objectPartsCount) {
315 $this->currentPartNo++;
316 if ($this->partsCompleted[$this->currentPartNo] ?? false) {
317 continue;
318 }
319
320 $partNumber = $this->currentPartNo;
321 $command = $this->getNextGetObjectCommand();
322
323 yield $this->s3Client->executeAsync($command)
324 ->then(function (ResultInterface $result)
325 use ($command, $partNumber) {
326 $requestArgs = $command->toArray();
327
328 // Remove metadata
329 unset($result['@metadata']);
330
331 $this->partDownloadCompleted(
332 $partNumber,
333 $result->toArray(),
334 $requestArgs
335 );
336 });
337 }
338
339 if ($this->currentPartNo !== $this->objectPartsCount) {
340 throw new S3TransferException(
341 "Expected number of parts `$this->objectPartsCount`"
342 . " to have been transferred but got `$this->currentPartNo`."
343 );
344 }
345 }
346
347 /**
348 * @return CommandInterface
349 */
350 private function getNextGetObjectCommand(): CommandInterface
351 {
352 $nextCommandArgs = $this->getFetchCommandArgs();
353 if ($this->config['response_checksum_validation'] === 'when_supported') {
354 $nextCommandArgs['ChecksumMode'] = 'ENABLED';
355 }
356
357 if (!empty($this->eTag)) {
358 $nextCommandArgs['IfMatch'] = $this->eTag;
359 }
360
361 return $this->s3Client->getCommand(
362 self::GET_OBJECT_COMMAND,
363 $nextCommandArgs
364 );
365 }
366
367 /**
368 * Main purpose of this method is to propagate
369 * the download-initiated event to listeners, but
370 * also it does some computation regarding internal states
371 * that need to be maintained.
372 *
373 * @param array $commandArgs
374 *
375 * @return void
376 */
377 private function downloadInitiated(array $commandArgs): void
378 {
379 if ($this->currentSnapshot === null) {
380 $this->currentSnapshot = new TransferProgressSnapshot(
381 $commandArgs['Key'],
382 0,
383 $this->objectSizeInBytes
384 );
385 } else {
386 $this->currentSnapshot = new TransferProgressSnapshot(
387 $this->currentSnapshot->getIdentifier(),
388 $this->currentSnapshot->getTransferredBytes(),
389 $this->currentSnapshot->getTotalBytes(),
390 $this->currentSnapshot->getResponse()
391 );
392 }
393
394 // Prepare context
395 $context = [
396 AbstractTransferListener::REQUEST_ARGS_KEY => $commandArgs,
397 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => $this->currentSnapshot,
398 ];
399
400 // Notify download handler
401 $this->downloadHandler->transferInitiated($context);
402
403 // Notify listeners
404 $this->listenerNotifier?->transferInitiated($context);
405 }
406
407 /**
408 * Propagates download-failed event to listeners.
409 *
410 * @param \Throwable $reason
411 *
412 * @return void
413 */
414 private function downloadFailed(\Throwable $reason): void
415 {
416 // Event already propagated.
417 if ($this->currentSnapshot->getReason() !== null) {
418 return;
419 }
420
421 $this->currentSnapshot = new TransferProgressSnapshot(
422 $this->currentSnapshot->getIdentifier(),
423 $this->currentSnapshot->getTransferredBytes(),
424 $this->currentSnapshot->getTotalBytes(),
425 $this->currentSnapshot->getResponse(),
426 $reason
427 );
428
429 // Prepare context
430 $context = [
431 AbstractTransferListener::REQUEST_ARGS_KEY => $this->downloadRequestArgs,
432 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => $this->currentSnapshot,
433 AbstractTransferListener::REASON_KEY => $reason,
434 ];
435
436 // Notify download handler
437 $this->downloadHandler->transferFail($context);
438
439 // Notify listeners
440 $this->listenerNotifier?->transferFail($context);
441 }
442
443 /**
444 * Propagates part-download-completed to listeners.
445 * It also does some computation in order to maintain internal states.
446 *
447 * @param int $partNumber
448 * @param array $result
449 * @param array $requestArgs
450 *
451 * @return void
452 */
453 private function partDownloadCompleted(
454 int $partNumber,
455 array $result,
456 array $requestArgs
457 ): void
458 {
459 $partTransferredBytes = $result['ContentLength'] ?? 0;
460 // Snapshot and context for listeners
461 $newSnapshot = new TransferProgressSnapshot(
462 $this->currentSnapshot->getIdentifier(),
463 $this->currentSnapshot->getTransferredBytes() + $partTransferredBytes,
464 $this->objectSizeInBytes,
465 $this->initialRequestResult
466 );
467 $this->currentSnapshot = $newSnapshot;
468
469 // Notify download handler and evaluate if part was written
470 $downloadHandlerSnapshot = $this->currentSnapshot->withResponse(
471 $result
472 );
473 $wasPartWritten = $this->downloadHandler->bytesTransferred([
474 AbstractTransferListener::REQUEST_ARGS_KEY => $requestArgs,
475 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => $downloadHandlerSnapshot,
476 ]);
477 // If part was written to destination then we mark it as completed
478 if ($wasPartWritten) {
479 $this->partsCompleted[$partNumber] = true;
480
481 // Persist resume state just if resume is enabled
482 if ($this->config['resume_enabled'] ?? false) {
483 // Update the resume state holder
484 $this->resumableDownload?->updateCurrentSnapshot(
485 $this->currentSnapshot->toArray()
486 );
487 $this->resumableDownload?->markPartCompleted($partNumber);
488
489 // Persist the resume state
490 $this->persistResumeState();
491 }
492 }
493
494 // Notify listeners
495 $this->listenerNotifier?->bytesTransferred([
496 AbstractTransferListener::REQUEST_ARGS_KEY => $this->downloadRequestArgs,
497 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => $this->currentSnapshot,
498 ]);
499 }
500
501 /**
502 * Propagates part-download-failed event to listeners.
503 *
504 * @param \Throwable $reason
505 *
506 * @return void
507 */
508 private function partDownloadFailed(
509 \Throwable $reason,
510 ): void
511 {
512 $this->downloadFailed($reason);
513 }
514
515 /**
516 * Propagates object-download-completed event to listeners.
517 *
518 * @return void
519 */
520 private function downloadComplete(): void
521 {
522 $newSnapshot = new TransferProgressSnapshot(
523 $this->currentSnapshot->getIdentifier(),
524 $this->currentSnapshot->getTransferredBytes(),
525 $this->objectSizeInBytes,
526 $this->currentSnapshot->getResponse()
527 );
528 $this->currentSnapshot = $newSnapshot;
529 // Prepare context
530 $context = [
531 AbstractTransferListener::REQUEST_ARGS_KEY => $this->downloadRequestArgs,
532 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => $this->currentSnapshot,
533 ];
534
535 // Notify download handler
536 $this->downloadHandler->transferComplete($context);
537
538 // Notify listeners
539 $this->listenerNotifier?->transferComplete($context);
540
541 // Delete resume file on successful completion
542 if ($this->config['resume_enabled'] ?? false) {
543 $this->resumableDownload?->deleteResumeFile();
544 }
545 }
546
547 /**
548 * Persist the current download state to the resume file.
549 * This method is called after each part is downloaded.
550 *
551 * @return void
552 */
553 private function persistResumeState(): void
554 {
555 // Only persist if we have a download handler that supports resume
556 if (!($this->downloadHandler instanceof ResumableDownloadHandlerInterface)) {
557 return;
558 }
559
560 // Create ResumableDownload object
561 if ($this->resumableDownload === null) {
562 // Resume file destination
563 $resumeFilePath = $this->config['resume_file_path'] ??
564 $this->downloadHandler->getResumeFilePath();
565 // Create snapshot data
566 $snapshotData = $this->currentSnapshot->toArray();
567 // Determine multipart download type
568 $config = $this->config;
569 $this->resumableDownload = new ResumableDownload(
570 $resumeFilePath,
571 $this->downloadRequestArgs,
572 $config,
573 $snapshotData,
574 $this->initialRequestResult,
575 $this->partsCompleted,
576 $this->objectPartsCount,
577 $this->downloadHandler->getTemporaryFilePath(),
578 $this->eTag ?? '',
579 $this->objectSizeInBytes,
580 $this->downloadHandler->getFixedPartSize(),
581 $this->downloadHandler->getDestination()
582 );
583 }
584
585 try {
586 $this->resumableDownload->toFile();
587 } catch (\Exception $e) {
588 throw new S3TransferException(
589 "Unable to persist resumable download state due to: " . $e->getMessage(),
590 );
591 }
592 }
593
594 /**
595 * Calculates the object size from content range.
596 *
597 * @param string $contentRange
598 * @return int
599 */
600 public static function computeObjectSizeFromContentRange(
601 string $contentRange
602 ): int
603 {
604 if (empty($contentRange)) {
605 return 0;
606 }
607
608 // For extracting the object size from the ContentRange header value.
609 if (preg_match(self::OBJECT_SIZE_REGEX, $contentRange, $matches)) {
610 return (int) $matches[1];
611 }
612
613 throw new S3TransferException(
614 "Invalid content range \"$contentRange\""
615 );
616 }
617
618 /**
619 * @param string $range
620 *
621 * @return int
622 */
623 public static function getRangeTo(string $range): int
624 {
625 preg_match(self::RANGE_TO_REGEX, $range, $match);
626 if (empty($match)) {
627 return 0;
628 }
629
630 return (int) $match[1];
631 }
632
633 /**
634 * @param mixed $multipartDownloadType
635 *
636 * @return string
637 */
638 public static function chooseDownloaderClass(
639 string $multipartDownloadType
640 ): string
641 {
642 return match ($multipartDownloadType) {
643 AbstractMultipartDownloader::PART_GET_MULTIPART_DOWNLOADER => PartGetMultipartDownloader::class,
644 AbstractMultipartDownloader::RANGED_GET_MULTIPART_DOWNLOADER => RangeGetMultipartDownloader::class,
645 default => throw new \InvalidArgumentException(
646 "The config value for `multipart_download_type` must be one of:\n"
647 . "\t* " . AbstractMultipartDownloader::PART_GET_MULTIPART_DOWNLOADER
648 ."\n"
649 . "\t* " . AbstractMultipartDownloader::RANGED_GET_MULTIPART_DOWNLOADER
650 )
651 };
652 }
653 }