Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 namespace Aws\S3\S3Transfer;
4
5 use Aws\MetricsBuilder;
6 use Aws\ResultInterface;
7 use Aws\S3\S3Client;
8 use Aws\S3\S3ClientInterface;
9 use Aws\S3\S3Transfer\Exception\S3TransferException;
10 use Aws\S3\S3Transfer\Models\DownloadDirectoryRequest;
11 use Aws\S3\S3Transfer\Models\DownloadFileRequest;
12 use Aws\S3\S3Transfer\Models\DownloadRequest;
13 use Aws\S3\S3Transfer\Models\ResumableDownload;
14 use Aws\S3\S3Transfer\Models\AbstractResumableTransfer;
15 use Aws\S3\S3Transfer\Models\ResumableUpload;
16 use Aws\S3\S3Transfer\Models\ResumeDownloadRequest;
17 use Aws\S3\S3Transfer\Models\ResumeUploadRequest;
18 use Aws\S3\S3Transfer\Models\S3TransferManagerConfig;
19 use Aws\S3\S3Transfer\Models\UploadDirectoryRequest;
20 use Aws\S3\S3Transfer\Models\UploadRequest;
21 use Aws\S3\S3Transfer\Models\UploadResult;
22 use Aws\S3\S3Transfer\Progress\SingleProgressTracker;
23 use Aws\S3\S3Transfer\Progress\AbstractTransferListener;
24 use Aws\S3\S3Transfer\Progress\TransferListenerNotifier;
25 use Aws\S3\S3Transfer\Progress\TransferProgressSnapshot;
26 use Aws\S3\S3Transfer\Utils\AbstractDownloadHandler;
27 use Aws\S3\S3Transfer\Utils\FileDownloadHandler;
28 use GuzzleHttp\Promise\PromiseInterface;
29 use InvalidArgumentException;
30 use Psr\Http\Message\StreamInterface;
31 use Throwable;
32
33 final class S3TransferManager
34 {
35 /** @var S3Client */
36 private S3ClientInterface $s3Client;
37
38 /** @var S3TransferManagerConfig */
39 private S3TransferManagerConfig $config;
40
41 /**
42 * @param S3ClientInterface|null $s3Client If provided as null then,
43 * a default client will be created where its region will be the one
44 * resolved from either the default from the config or the provided.
45 * @param array|S3TransferManagerConfig|null $config
46 */
47 public function __construct(
48 ?S3ClientInterface $s3Client = null,
49 array|S3TransferManagerConfig|null $config = null
50 ) {
51 if ($config === null || is_array($config)) {
52 $this->config = S3TransferManagerConfig::fromArray($config ?? []);
53 } else {
54 $this->config = $config;
55 }
56
57 if ($s3Client === null) {
58 $this->s3Client = $this->defaultS3Client();
59 } else {
60 $this->s3Client = $s3Client;
61 }
62
63 MetricsBuilder::appendMetricsCaptureMiddleware(
64 $this->s3Client->getHandlerList(),
65 MetricsBuilder::S3_TRANSFER
66 );
67 }
68
69 /**
70 * @return S3ClientInterface
71 */
72 public function getS3Client(): S3ClientInterface
73 {
74 return $this->s3Client;
75 }
76
77 /**
78 * @return S3TransferManagerConfig
79 */
80 public function getConfig(): S3TransferManagerConfig
81 {
82 return $this->config;
83 }
84
85 /**
86 * @param UploadRequest $uploadRequest
87 * @param S3ClientInterface|null $s3Client
88 *
89 * @return PromiseInterface
90 */
91 public function upload(
92 UploadRequest $uploadRequest,
93 ?S3ClientInterface $s3Client = null
94 ): PromiseInterface
95 {
96 $client = $s3Client ?? $this->s3Client;
97 // Make sure it is a valid in path in case of a string
98 $uploadRequest->validateSource();
99
100 // Valid required parameters
101 $uploadRequest->validateRequiredParameters();
102
103 $uploadRequest->updateConfigWithDefaults(
104 $this->config->toArray()
105 );
106
107 $uploadRequest->validateConfig();
108
109 $config = $uploadRequest->getConfig();
110
111 // Validate progress tracker
112 $progressTracker = $uploadRequest->getProgressTracker();
113 if ($progressTracker === null
114 && ($config['track_progress']
115 ?? $this->config->isTrackProgress())) {
116 $progressTracker = new SingleProgressTracker();
117 }
118
119 // Append progress tracker to listeners if not null
120 $listeners = $uploadRequest->getListeners();
121 if ($progressTracker !== null) {
122 $listeners[] = $progressTracker;
123 }
124
125 $listenerNotifier = new TransferListenerNotifier($listeners);
126
127 // Validate multipart upload threshold
128 $mupThreshold = $config['multipart_upload_threshold_bytes']
129 ?? $this->config->getMultipartUploadThresholdBytes();
130 if ($mupThreshold < AbstractMultipartUploader::PART_MIN_SIZE) {
131 throw new InvalidArgumentException(
132 "The provided config `multipart_upload_threshold_bytes`"
133 ."must be greater than or equal to " . AbstractMultipartUploader::PART_MIN_SIZE
134 );
135 }
136
137 if ($this->requiresMultipartUpload($uploadRequest->getSource(), $mupThreshold)) {
138 return $this->tryMultipartUpload(
139 $uploadRequest,
140 $client,
141 $listenerNotifier
142 );
143 }
144
145 return $this->trySingleUpload(
146 $uploadRequest->getSource(),
147 $uploadRequest->getUploadRequestArgs(),
148 $listenerNotifier,
149 $client
150 );
151 }
152
153 /**
154 * @param UploadDirectoryRequest $uploadDirectoryRequest
155 *
156 * @return PromiseInterface
157 */
158 public function uploadDirectory(
159 UploadDirectoryRequest $uploadDirectoryRequest,
160 ): PromiseInterface
161 {
162 return (new DirectoryUploader(
163 $this->s3Client,
164 $this->config->toArray(),
165 fn(S3ClientInterface $client, UploadRequest $request): PromiseInterface => $this->upload($request, $client),
166 $uploadDirectoryRequest,
167 ))->promise();
168 }
169
170 /**
171 * @param DownloadRequest $downloadRequest
172 *
173 * @return PromiseInterface
174 */
175 public function download(DownloadRequest $downloadRequest): PromiseInterface
176 {
177 return $this->downloadInternal($downloadRequest, $this->s3Client);
178 }
179
180 /**
181 * @param DownloadRequest $downloadRequest
182 * @param S3ClientInterface $s3Client
183 *
184 * @return PromiseInterface
185 */
186 private function downloadInternal(
187 DownloadRequest $downloadRequest,
188 S3ClientInterface $s3Client
189 ): PromiseInterface {
190 $sourceArgs = $downloadRequest->normalizeSourceAsArray();
191 $getObjectRequestArgs = $downloadRequest->getObjectRequestArgs();
192
193 $downloadRequest->updateConfigWithDefaults($this->config->toArray());
194
195 $downloadRequest->validateConfig();
196
197 $config = $downloadRequest->getConfig();
198
199 $progressTracker = $downloadRequest->getProgressTracker();
200 if ($progressTracker === null && $config['track_progress']) {
201 $progressTracker = new SingleProgressTracker();
202 }
203
204 $listeners = $downloadRequest->getListeners();
205 if ($progressTracker !== null) {
206 $listeners[] = $progressTracker;
207 }
208
209 $listenerNotifier = new TransferListenerNotifier($listeners);
210
211 foreach ($sourceArgs as $key => $value) {
212 $getObjectRequestArgs[$key] = $value;
213 }
214
215 return $this->tryMultipartDownload(
216 $getObjectRequestArgs,
217 $config,
218 $downloadRequest->getDownloadHandler(),
219 $listenerNotifier,
220 $s3Client,
221 );
222 }
223
224 /**
225 * @param ResumeDownloadRequest $resumeDownloadRequest
226 *
227 * @return PromiseInterface
228 */
229 public function resumeDownload(
230 ResumeDownloadRequest $resumeDownloadRequest
231 ): PromiseInterface
232 {
233 $resumableDownload = $resumeDownloadRequest->getResumableDownload();
234 if (is_string($resumableDownload)) {
235 if (!AbstractResumableTransfer::isResumeFile($resumableDownload)) {
236 throw new S3TransferException(
237 "Resume file `$resumableDownload` is not a valid resumable file."
238 );
239 }
240
241 $resumableDownload = ResumableDownload::fromFile($resumableDownload);
242 }
243
244 // Verify that temporary file still exists
245 if (!file_exists($resumableDownload->getTemporaryFile())) {
246 throw new S3TransferException(
247 "Cannot resume download: temporary file does not exist: "
248 . $resumableDownload->getTemporaryFile()
249 );
250 }
251
252 // Verify object ETag hasn't changed
253 $headResult = $this->s3Client->headObject([
254 'Bucket' => $resumableDownload->getBucket(),
255 'Key' => $resumableDownload->getKey(),
256 ]);
257
258 $currentETag = $headResult['ETag'] ?? null;
259 $resumeETag = $resumableDownload->getETag();
260 if (empty($currentETag) || empty($resumeETag)) {
261 throw new S3TransferException(
262 "Cannot resume download: missing eTag in resumable download"
263 );
264 }
265
266 if ($currentETag !== $resumableDownload->getETag()) {
267 throw new S3TransferException(
268 "Cannot resume download: S3 object has changed (ETag mismatch). "
269 . "Expected: {$resumableDownload->getETag()}, "
270 . "Current: {$currentETag}"
271 );
272 }
273
274 // Make sure it uses a supported file download handler
275 $downloadHandlerClass = $resumeDownloadRequest->getDownloadHandlerClass();
276 if (!class_exists($downloadHandlerClass)) {
277 throw new S3TransferException(
278 "Download handler class `$downloadHandlerClass` does not exist"
279 );
280 }
281
282 if ($downloadHandlerClass !== FileDownloadHandler::class
283 && !is_subclass_of($downloadHandlerClass, FileDownloadHandler::class)) {
284 throw new S3TransferException(
285 "Download handler class `$downloadHandlerClass` must extend `FileDownloadHandler`"
286 );
287 }
288
289 $config = $resumableDownload->getConfig();
290 $downloadHandler = new $downloadHandlerClass(
291 $resumableDownload->getDestination(),
292 $config['fails_when_destination_exists'] ?? false,
293 $config['resume_enabled'] ?? false,
294 $resumableDownload->getTemporaryFile(),
295 $resumableDownload->getFixedPartSize()
296 );
297
298 $progressTracker = $resumeDownloadRequest->getProgressTracker();
299 $listeners = $resumeDownloadRequest->getListeners();
300
301 if ($progressTracker === null
302 && ($resumableDownload->getConfig()['track_progress']
303 ?? $this->config->isTrackProgress())) {
304 $progressTracker = new SingleProgressTracker();
305 $listeners[] = $progressTracker;
306 }
307
308 $listenerNotifier = new TransferListenerNotifier(
309 $listeners,
310 );
311
312 return $this->tryMultipartDownload(
313 $resumableDownload->getRequestArgs(),
314 $resumableDownload->getConfig(),
315 $downloadHandler,
316 $listenerNotifier,
317 null,
318 $resumableDownload,
319 );
320 }
321
322 /**
323 * @param ResumeUploadRequest $resumeUploadRequest
324 *
325 * @return PromiseInterface
326 */
327 public function resumeUpload(
328 ResumeUploadRequest $resumeUploadRequest
329 ): PromiseInterface
330 {
331 $resumableUpload = $resumeUploadRequest->getResumableUpload();
332 if (is_string($resumableUpload)) {
333 if (!AbstractResumableTransfer::isResumeFile($resumableUpload)) {
334 throw new S3TransferException(
335 "Resume file `$resumableUpload` is not a valid resumable file."
336 );
337 }
338
339 $resumableUpload = ResumableUpload::fromFile($resumableUpload);
340 }
341
342 // Verify that source file still exists
343 if (!file_exists($resumableUpload->getSource())) {
344 throw new S3TransferException(
345 "Cannot resume upload: source file does not exist: "
346 . $resumableUpload->getSource()
347 );
348 }
349
350 // Verify if source still matches the same size
351 $objectSizeAtFailure = $resumableUpload->getObjectSize();
352 $currentObjectSize = filesize($resumableUpload->getSource());
353 if ($objectSizeAtFailure !== $currentObjectSize) {
354 throw new S3TransferException(
355 "Cannot resume upload: source file size has changed since the upload failed. "
356 . "Size at failure: {$objectSizeAtFailure}, current size: {$currentObjectSize}."
357 );
358 }
359
360 // Verify upload still exists in S3 by checking uploadId
361 $uploads = $this->s3Client->getPaginator(
362 'ListMultipartUploads',
363 [
364 'Bucket' => $resumableUpload->getBucket(),
365 'Prefix' => $resumableUpload->getKey(),
366 ]
367 )->search('Uploads[]');
368 $uploadExists = false;
369 foreach ($uploads as $upload) {
370 if ($upload['UploadId'] === $resumableUpload->getUploadId()
371 && $upload['Key'] === $resumableUpload->getKey()) {
372 $uploadExists = true;
373 break;
374 }
375 }
376
377 if (!$uploadExists) {
378 throw new S3TransferException(
379 "Cannot resume upload: multipart upload no longer exists (UploadId: "
380 . $resumableUpload->getUploadId() . ")"
381 );
382 }
383
384 $config = $resumableUpload->getConfig();
385 $progressTracker = $resumeUploadRequest->getProgressTracker();
386 $listeners = $resumeUploadRequest->getListeners();
387
388 if ($progressTracker === null
389 && ($config['track_progress'] ?? $this->config->isTrackProgress())) {
390 $progressTracker = new SingleProgressTracker();
391 $listeners[] = $progressTracker;
392 }
393
394 $listenerNotifier = new TransferListenerNotifier($listeners);
395
396 return (new MultipartUploader(
397 $this->s3Client,
398 $resumableUpload->getRequestArgs(),
399 $resumableUpload->getSource(),
400 $config,
401 listenerNotifier: $listenerNotifier,
402 resumableUpload: $resumableUpload,
403 ))->promise();
404 }
405
406 /**
407 * @param DownloadFileRequest $downloadFileRequest
408 * @param S3ClientInterface|null $s3Client
409 *
410 * @return PromiseInterface
411 */
412 public function downloadFile(
413 DownloadFileRequest $downloadFileRequest,
414 ?S3ClientInterface $s3Client = null
415 ): PromiseInterface
416 {
417 $client = $s3Client ?? $this->s3Client;
418 return $this->downloadInternal($downloadFileRequest->getDownloadRequest(), $client);
419 }
420
421 /**
422 * @param DownloadDirectoryRequest $downloadDirectoryRequest
423 *
424 * @return PromiseInterface
425 */
426 public function downloadDirectory(
427 DownloadDirectoryRequest $downloadDirectoryRequest
428 ): PromiseInterface
429 {
430 return (new DirectoryDownloader(
431 $this->s3Client,
432 $this->config->toArray(),
433 fn(S3ClientInterface $client, DownloadFileRequest $request): PromiseInterface => $this->downloadFile($request, $client),
434 $downloadDirectoryRequest,
435 ))->promise();
436 }
437
438 /**
439 * Tries an object multipart download.
440 *
441 * @param array $getObjectRequestArgs
442 * @param array $config
443 * @param AbstractDownloadHandler $downloadHandler
444 * @param TransferListenerNotifier|null $listenerNotifier
445 * @param S3ClientInterface|null $s3Client
446 * @param ResumableDownload|null $resumableDownload
447 * @return PromiseInterface
448 */
449 private function tryMultipartDownload(
450 array $getObjectRequestArgs,
451 array $config,
452 AbstractDownloadHandler $downloadHandler,
453 ?TransferListenerNotifier $listenerNotifier = null,
454 ?S3ClientInterface $s3Client = null,
455 ?ResumableDownload $resumableDownload = null,
456 ): PromiseInterface
457 {
458 $client = $s3Client ?? $this->s3Client;
459 $downloaderClassName = AbstractMultipartDownloader::chooseDownloaderClass(
460 strtolower($config['multipart_download_type'])
461 );
462 $multipartDownloader = new $downloaderClassName(
463 $client,
464 $getObjectRequestArgs,
465 $config,
466 $downloadHandler,
467 listenerNotifier: $listenerNotifier,
468 resumableDownload: $resumableDownload,
469 );
470
471 return $multipartDownloader->promise();
472 }
473
474 /**
475 * @param string|StreamInterface $source
476 * @param array $requestArgs
477 * @param TransferListenerNotifier|null $listenerNotifier
478 * @param S3ClientInterface|null $s3Client
479 *
480 * @return PromiseInterface
481 */
482 private function trySingleUpload(
483 string|StreamInterface $source,
484 array $requestArgs,
485 ?TransferListenerNotifier $listenerNotifier = null,
486 ?S3ClientInterface $s3Client = null
487 ): PromiseInterface
488 {
489 $client = $s3Client ?? $this->s3Client;
490 if (is_string($source) && is_readable($source)) {
491 $requestArgs['SourceFile'] = $source;
492 $objectSize = filesize($source);
493 } elseif ($source instanceof StreamInterface && $source->isSeekable()) {
494 $requestArgs['Body'] = $source;
495 $objectSize = $source->getSize();
496 } else {
497 throw new S3TransferException(
498 "Unable to process upload request due to the type of the source"
499 );
500 }
501
502 if (!empty($listenerNotifier)) {
503 $listenerNotifier->transferInitiated(
504 [
505 AbstractTransferListener::REQUEST_ARGS_KEY => $requestArgs,
506 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => new TransferProgressSnapshot(
507 $requestArgs['Key'],
508 0,
509 $objectSize,
510 ),
511 ]
512 );
513
514 $command = $client->getCommand('PutObject', $requestArgs);
515 return $client->executeAsync($command)->then(
516 function (ResultInterface $result)
517 use ($objectSize, $listenerNotifier, $requestArgs) {
518 $listenerNotifier->bytesTransferred(
519 [
520 AbstractTransferListener::REQUEST_ARGS_KEY => $requestArgs,
521 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => new TransferProgressSnapshot(
522 $requestArgs['Key'],
523 $objectSize,
524 $objectSize,
525 ),
526 ]
527 );
528
529 $listenerNotifier->transferComplete(
530 [
531 AbstractTransferListener::REQUEST_ARGS_KEY => $requestArgs,
532 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => new TransferProgressSnapshot(
533 $requestArgs['Key'],
534 $objectSize,
535 $objectSize,
536 $result->toArray()
537 ),
538 ]
539 );
540
541 return new UploadResult(
542 $result->toArray()
543 );
544 }
545 )->otherwise(function (Throwable $reason)
546 use ($objectSize, $requestArgs, $listenerNotifier) {
547 $listenerNotifier->transferFail(
548 [
549 AbstractTransferListener::REQUEST_ARGS_KEY => $requestArgs,
550 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => new TransferProgressSnapshot(
551 $requestArgs['Key'],
552 0,
553 $objectSize,
554 ),
555 'reason' => $reason,
556 ]
557 );
558
559 throw $reason;
560 });
561 }
562
563 $command = $client->getCommand('PutObject', $requestArgs);
564
565 return $client->executeAsync($command)
566 ->then(function (ResultInterface $result) {
567 return new UploadResult($result->toArray());
568 });
569 }
570
571 /**
572 * @param UploadRequest $uploadRequest
573 * @param S3ClientInterface|null $s3Client
574 * @param TransferListenerNotifier|null $listenerNotifier
575 *
576 * @return PromiseInterface
577 */
578 private function tryMultipartUpload(
579 UploadRequest $uploadRequest,
580 ?S3ClientInterface $s3Client = null,
581 ?TransferListenerNotifier $listenerNotifier = null,
582 ): PromiseInterface
583 {
584 $client = $s3Client ?? $this->s3Client;
585 return (new MultipartUploader(
586 $client,
587 $uploadRequest->getUploadRequestArgs(),
588 $uploadRequest->getSource(),
589 $uploadRequest->getConfig(),
590 listenerNotifier: $listenerNotifier,
591 ))->promise();
592 }
593
594 /**
595 * @param string|StreamInterface $source
596 * @param int $mupThreshold
597 *
598 * @return bool
599 */
600 private function requiresMultipartUpload(
601 string|StreamInterface $source,
602 int $mupThreshold
603 ): bool
604 {
605 if (is_string($source) && is_readable($source)) {
606 return filesize($source) >= $mupThreshold;
607 } elseif ($source instanceof StreamInterface) {
608 // When the stream's size is unknown then we could try a multipart upload.
609 if (empty($source->getSize())) {
610 return true;
611 }
612
613 return $source->getSize() >= $mupThreshold;
614 }
615
616 throw new S3TransferException(
617 "Unable to determine if a multipart is required"
618 );
619 }
620
621 /**
622 * Returns a default instance of S3Client.
623 *
624 * @return S3Client
625 */
626 private function defaultS3Client(): S3ClientInterface
627 {
628 $defaultRegion = $this->config->getDefaultRegion();
629 if (empty($defaultRegion)) {
630 throw new S3TransferException(
631 "When using the default S3 Client you must define a default region."
632 . "\nThe config parameter is `default_region`.`"
633 );
634 }
635
636 return new S3Client([
637 'region' => $defaultRegion,
638 ]);
639 }
640
641 /**
642 * Validates a string value is a valid S3 URI.
643 * Valid S3 URI Example: S3://mybucket.dev/myobject.txt
644 *
645 * @param string $uri
646 *
647 * @return bool
648 */
649 public static function isValidS3URI(string $uri): bool
650 {
651 // in the expression `substr($uri, 5)))` the 5 belongs to the size of `s3://`.
652 return str_starts_with(strtolower($uri), 's3://')
653 && count(explode('/', substr($uri, 5))) > 1;
654 }
655
656 /**
657 * Converts a S3 URI into an array with a Bucket and Key
658 * properties set.
659 *
660 * @param string $uri: The S3 URI.
661 *
662 * @return array
663 */
664 public static function s3UriAsBucketAndKey(string $uri): array
665 {
666 $errorMessage = "Invalid URI: `$uri` provided. \nA valid S3 URI looks as `s3://bucket/key`";
667 if (!self::isValidS3URI($uri)) {
668 throw new InvalidArgumentException($errorMessage);
669 }
670
671 $path = substr($uri, 5); // without s3://
672 $parts = explode('/', $path, 2);
673
674 if (count($parts) < 2) {
675 throw new InvalidArgumentException($errorMessage);
676 }
677
678 return [
679 'Bucket' => $parts[0],
680 'Key' => $parts[1],
681 ];
682 }
683
684 }