Debian Codegraph @

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

raw symbols SCIP
1 <?php
2 namespace Aws\S3\S3Transfer;
3
4 use Aws\HashingStream;
5 use Aws\PhpHash;
6 use Aws\ResultInterface;
7 use Aws\S3\ApplyChecksumMiddleware;
8 use Aws\S3\S3ClientInterface;
9 use Aws\S3\S3Transfer\Exception\S3TransferException;
10 use Aws\S3\S3Transfer\Models\ResumableUpload;
11 use Aws\S3\S3Transfer\Models\S3TransferManagerConfig;
12 use Aws\S3\S3Transfer\Models\UploadResult;
13 use Aws\S3\S3Transfer\Progress\AbstractTransferListener;
14 use Aws\S3\S3Transfer\Progress\TransferListenerNotifier;
15 use Aws\S3\S3Transfer\Progress\TransferProgressSnapshot;
16 use GuzzleHttp\Promise\Create;
17 use GuzzleHttp\Promise\Each;
18 use GuzzleHttp\Promise\Promise;
19 use GuzzleHttp\Promise\PromiseInterface;
20 use GuzzleHttp\Psr7\LazyOpenStream;
21 use GuzzleHttp\Psr7\LimitStream;
22 use GuzzleHttp\Psr7\Utils;
23 use Psr\Http\Message\StreamInterface;
24 use Throwable;
25
26 /**
27 * Multipart uploader implementation.
28 */
29 final class MultipartUploader extends AbstractMultipartUploader
30 {
31 private const STREAM_WRAPPER_TYPE_PLAIN_FILE = 'plainfile';
32 public const DEFAULT_CHECKSUM_CALCULATION_ALGORITHM = 'crc32';
33 private const CHECKSUM_TYPE_FULL_OBJECT = 'FULL_OBJECT';
34
35 /** @var int */
36 protected int $calculatedObjectSize;
37
38 /** @var StreamInterface */
39 private StreamInterface $body;
40
41 /** @var StreamInterface|string */
42 private StreamInterface|string $source;
43
44 /**
45 * For custom or default checksum.
46 *
47 * @var string|null
48 */
49 protected ?string $requestChecksum;
50
51 /**
52 * This will be used for custom or default checksum.
53 *
54 * @var string|null
55 */
56 protected ?string $requestChecksumAlgorithm;
57
58 /** @var bool */
59 private bool $isFullObjectChecksum;
60
61 /** @var bool */
62 private bool $isResuming;
63
64 /** @var ResumableUpload|null */
65 private ?ResumableUpload $resumableUpload;
66
67 /**
68 * @param S3ClientInterface $s3Client
69 * @param array $requestArgs
70 * @param string|StreamInterface $source
71 * @param array $config
72 * - target_part_size_bytes: (int, optional)
73 * - request_checksum_calculation: (string, optional)
74 * - concurrency: (int, optional)
75 * @param TransferListenerNotifier|null $listenerNotifier
76 * @param ResumableUpload|null $resumableUpload
77 */
78 public function __construct(
79 S3ClientInterface $s3Client,
80 array $requestArgs,
81 string|StreamInterface $source,
82 array $config = [],
83 ?TransferListenerNotifier $listenerNotifier = null,
84 ?ResumableUpload $resumableUpload = null,
85 ) {
86 if (!isset($config['request_checksum_calculation'])) {
87 $config['request_checksum_calculation'] = S3TransferManagerConfig::DEFAULT_REQUEST_CHECKSUM_CALCULATION;
88 }
89
90 $uploadId = null;
91 $partsCompleted = [];
92 $currentSnapshot = null;
93 $calculatedObjectSize = 0;
94 $isFullObjectChecksum = false;
95 $this->resumableUpload = $resumableUpload;
96 $this->isResuming = $resumableUpload !== null;
97 if ($this->isResuming) {
98 $config = $resumableUpload->getConfig();
99 $uploadId = $resumableUpload->getUploadId();
100 $partsCompleted = $resumableUpload->getPartsCompleted();
101 $snapshotData = $resumableUpload->getCurrentSnapshot();
102 if (!empty($snapshotData)) {
103 $currentSnapshot = TransferProgressSnapshot::fromArray(
104 $snapshotData
105 );
106 }
107 $calculatedObjectSize = $resumableUpload->getObjectSize();
108 $isFullObjectChecksum = $resumableUpload->isFullObjectChecksum();
109 }
110
111 parent::__construct(
112 $s3Client,
113 $requestArgs,
114 $config,
115 $uploadId,
116 $partsCompleted,
117 $currentSnapshot,
118 $listenerNotifier
119 );
120 $this->source = $source;
121 $this->body = $this->parseBody($source);
122 $this->calculatedObjectSize = $calculatedObjectSize;
123 $this->isFullObjectChecksum = $isFullObjectChecksum;
124 $this->evaluateCustomChecksum();
125 }
126
127 /**
128 * @inheritDoc
129 *
130 * @return PromiseInterface
131 */
132 protected function createMultipartOperation(): PromiseInterface
133 {
134 $createMultipartUploadArgs = $this->requestArgs;
135 if ($this->requestChecksum !== null) {
136 $createMultipartUploadArgs['ChecksumType'] = self::CHECKSUM_TYPE_FULL_OBJECT;
137 $createMultipartUploadArgs['ChecksumAlgorithm'] = $this->requestChecksumAlgorithm;
138 $this->isFullObjectChecksum = true;
139 } elseif ($this->config['request_checksum_calculation'] === 'when_supported') {
140 $this->requestChecksumAlgorithm = $createMultipartUploadArgs['ChecksumAlgorithm']
141 ?? self::DEFAULT_CHECKSUM_CALCULATION_ALGORITHM;
142 $createMultipartUploadArgs['ChecksumAlgorithm'] = $this->requestChecksumAlgorithm;
143 }
144
145 // Make sure algorithm with full object is a supported one
146 if (($createMultipartUploadArgs['ChecksumType'] ?? '') === self::CHECKSUM_TYPE_FULL_OBJECT) {
147 if (stripos($this->requestChecksumAlgorithm, 'crc') !== 0) {
148 return Create::rejectionFor(
149 new S3TransferException(
150 "Full object checksum algorithm must be `CRC` family base."
151 )
152 );
153 }
154 }
155
156 if ($this->isResuming && $this->uploadId !== null) {
157 // Not need to initialize multipart
158 return Create::promiseFor("");
159 }
160
161 $this->operationInitiated($createMultipartUploadArgs);
162 $command = $this->s3Client->getCommand(
163 'CreateMultipartUpload',
164 $createMultipartUploadArgs
165 );
166
167 return $this->s3Client->executeAsync($command)
168 ->then(function (ResultInterface $result) {
169 $this->uploadId = $result['UploadId'];
170 });
171 }
172
173 /**
174 * Process a multipart upload operation.
175 *
176 * @return PromiseInterface
177 */
178 protected function processMultipartOperation(): PromiseInterface
179 {
180 $uploadPartCommandArgs = $this->requestArgs;
181 $this->calculatedObjectSize = 0;
182 $partSize = $this->calculatePartSize();
183 $partsCount = ceil($this->getTotalSize() / $partSize);
184 $uploadPartCommandArgs['UploadId'] = $this->uploadId;
185 // Customer provided checksum
186 if ($this->requestChecksum !== null) {
187 // To avoid default calculation for individual parts
188 $uploadPartCommandArgs['@context']['request_checksum_calculation'] = 'when_required';
189 unset($uploadPartCommandArgs['Checksum'. strtoupper($this->requestChecksumAlgorithm)]);
190 } elseif ($this->requestChecksumAlgorithm !== null) {
191 $uploadPartCommandArgs['ChecksumAlgorithm'] = $this->requestChecksumAlgorithm;
192 }
193
194 $promises = $this->createUploadPartPromises(
195 $uploadPartCommandArgs,
196 $partSize,
197 $partsCount,
198 );
199
200 return Each::ofLimitAll($promises, $this->config['concurrency']);
201 }
202
203 /**
204 * @inheritDoc
205 *
206 * @return PromiseInterface
207 */
208 protected function completeMultipartOperation(): PromiseInterface
209 {
210 $this->sortParts();
211 $completeMultipartUploadArgs = $this->requestArgs;
212 $completeMultipartUploadArgs['UploadId'] = $this->uploadId;
213 $completeMultipartUploadArgs['MultipartUpload'] = [
214 'Parts' => array_values($this->partsCompleted)
215 ];
216 $completeMultipartUploadArgs['MpuObjectSize'] = $this->getTotalSize();
217
218 if ($this->isFullObjectChecksum && $this->requestChecksum !== null) {
219 $completeMultipartUploadArgs['ChecksumType'] = self::CHECKSUM_TYPE_FULL_OBJECT;
220 $completeMultipartUploadArgs[
221 'Checksum' . strtoupper($this->requestChecksumAlgorithm)
222 ] = $this->requestChecksum;
223 }
224
225 $command = $this->s3Client->getCommand(
226 'CompleteMultipartUpload',
227 $completeMultipartUploadArgs
228 );
229
230 return $this->s3Client->executeAsync($command)
231 ->then(function (ResultInterface $result) {
232 $this->operationCompleted($result);
233
234 // Clean resume file on completion
235 if ($this->allowResume()) {
236 $this->resumableUpload?->deleteResumeFile();
237 }
238
239 return $result;
240 });
241 }
242
243 /**
244 * @return PromiseInterface
245 */
246 protected function abortMultipartOperation(): PromiseInterface
247 {
248 // When resume is enabled then we skip aborting.
249 if ($this->allowResume()) {
250 return Create::promiseFor("");
251 }
252
253 $abortMultipartUploadArgs = $this->requestArgs;
254 $abortMultipartUploadArgs['UploadId'] = $this->uploadId;
255 $command = $this->s3Client->getCommand(
256 'AbortMultipartUpload',
257 $abortMultipartUploadArgs
258 );
259
260 return $this->s3Client->executeAsync($command);
261 }
262
263 /**
264 * Sync upload method.
265 *
266 * @return UploadResult
267 */
268 public function upload(): UploadResult
269 {
270 return $this->promise()->wait();
271 }
272
273 /**
274 * Parses the source into an instance of
275 * StreamInterface to be read.
276 *
277 * @param string|StreamInterface $source
278 *
279 * @return StreamInterface
280 */
281 private function parseBody(
282 string|StreamInterface $source
283 ): StreamInterface
284 {
285 if (is_string($source)) {
286 // Make sure the files exists
287 if (!is_readable($source)) {
288 throw new \InvalidArgumentException(
289 "The source for this upload must be either a"
290 . " readable file path or a valid stream."
291 );
292 }
293 $body = new LazyOpenStream($source, 'r');
294 // To make sure the resource is closed.
295 $this->onCompletionCallbacks[] = function () use ($body) {
296 $body->close();
297 };
298 } elseif ($source instanceof StreamInterface) {
299 $body = $source;
300 } else {
301 throw new \InvalidArgumentException(
302 "The source must be a valid string file path or a StreamInterface."
303 );
304 }
305
306 return $body;
307 }
308
309 /**
310 * Evaluates if custom checksum has been provided,
311 * and if so then, the values are placed in the
312 * respective properties.
313 *
314 * @return void
315 */
316 private function evaluateCustomChecksum(): void
317 {
318 // Evaluation for custom provided checksums
319 $checksumName = ApplyChecksumMiddleware::filterChecksum(
320 $this->requestArgs
321 );
322 if ($checksumName !== null) {
323 $this->requestChecksum = $this->requestArgs[$checksumName];
324 $this->requestChecksumAlgorithm = str_replace(
325 'Checksum',
326 '',
327 $checksumName
328 );
329 $this->requestChecksumAlgorithm = strtolower(
330 $this->requestChecksumAlgorithm
331 );
332 } else {
333 $this->requestChecksum = null;
334 $this->requestChecksumAlgorithm = null;
335 }
336 }
337
338 /**
339 * @param array $uploadPartCommandArgs
340 * @param int $partSize
341 * @param int $partsCount
342 *
343 * @return \Generator
344 */
345 private function createUploadPartPromises(
346 array $uploadPartCommandArgs,
347 int $partSize,
348 int $partsCount
349 ): \Generator
350 {
351 $bytesRead = 0;
352 $isSeekable = $this->body->isSeekable()
353 && $this->body->getMetadata('wrapper_type')
354 === self::STREAM_WRAPPER_TYPE_PLAIN_FILE;
355
356 if ($isSeekable) {
357 $this->body->rewind();
358 }
359
360 $partNo = 0;
361 while (!$this->body->eof()) {
362 if ($isSeekable) {
363 $partBody = new LimitStream(
364 new LazyOpenStream(
365 $this->body->getMetadata('uri'),
366 'r'
367 ),
368 $partSize,
369 $bytesRead,
370 );
371 } else {
372 $body = new LimitStream(
373 $this->body,
374 $partSize,
375 $bytesRead,
376 );
377 $body = $this->decorateWithHashes($body, $uploadPartCommandArgs);
378 $partBody = Utils::streamFor();
379 Utils::copyToStream($body, $partBody);
380 }
381
382 $bodyLength = $partBody->getSize();
383 if ($bodyLength === 0) {
384 $partBody->close();
385 break;
386 }
387
388 $partNo++;
389 $bytesRead += $bodyLength;
390
391 $uploadPartCommandArgs['PartNumber'] = $partNo;
392 $uploadPartCommandArgs['ContentLength'] = $bodyLength;
393 // Attach body
394 if ($isSeekable) {
395 $partBody->rewind();
396 }
397 $uploadPartCommandArgs['Body'] = $partBody;
398
399 $this->calculatedObjectSize += $bodyLength;
400 if ($partNo > self::PART_MAX_NUM) {
401 return Create::rejectionFor(
402 "The max number of parts has been exceeded. " .
403 "Max = " . self::PART_MAX_NUM
404 );
405 }
406
407 if ($isSeekable && $partNo > $partsCount) {
408 return Create::rejectionFor(
409 "The current part `$partNo` is over "
410 . "the expected number of parts `$partsCount`"
411 );
412 }
413
414 $command = $this->s3Client->getCommand(
415 'UploadPart',
416 $uploadPartCommandArgs
417 );
418
419 // Advance if behind
420 if ($bytesRead < $this->body->tell()) {
421 $this->body->seek($bytesRead);
422 }
423
424 if (isset($this->partsCompleted[$partNo])) {
425 // Part already uploaded
426 continue;
427 }
428
429 yield $this->s3Client->executeAsync($command)
430 ->then(function (ResultInterface $result)
431 use ($command, $partBody) {
432 $partBody->close();
433 // To make sure we don't continue when a failure occurred
434 if ($this->currentSnapshot->getReason() !== null) {
435 throw $this->currentSnapshot->getReason();
436 }
437
438 $partData = $this->collectPart(
439 $result,
440 $command
441 );
442
443 // Part Upload Completed Event
444 $this->partCompleted(
445 $command['ContentLength'],
446 $command->toArray(),
447 $partData,
448 );
449 })->otherwise(function (Throwable $e) use ($partBody) {
450 $partBody->close();
451 $this->partFailed($e);
452
453 throw $e;
454 });
455 }
456 }
457
458 /**
459 * @param int $partSize
460 * @param array $requestArgs
461 * @param array $partData
462 *
463 * @return void
464 */
465 protected function partCompleted(
466 int $partSize,
467 array $requestArgs,
468 array $partData
469 ): void
470 {
471 $newSnapshot = new TransferProgressSnapshot(
472 $this->currentSnapshot->getIdentifier(),
473 $this->currentSnapshot->getTransferredBytes() + $partSize,
474 $this->currentSnapshot->getTotalBytes(),
475 $this->currentSnapshot->getResponse(),
476 $this->currentSnapshot->getReason(),
477 );
478
479 $this->currentSnapshot = $newSnapshot;
480
481 // Persist resume state if allowed
482 if ($this->allowResume()) {
483 $this->persistResumeState($partData);
484 }
485
486 $this->listenerNotifier?->bytesTransferred([
487 AbstractTransferListener::REQUEST_ARGS_KEY => $requestArgs,
488 AbstractTransferListener::PROGRESS_SNAPSHOT_KEY => $this->currentSnapshot
489 ]);
490 }
491
492 /**
493 * Resume works just when the source is a file path and is enabled.
494 *
495 * @return bool
496 */
497 private function allowResume(): bool
498 {
499 return ($this->config['resume_enabled'] ?? false)
500 && is_string($this->source);
501 }
502
503 /**
504 * Persist the current upload state to a resume file.
505 *
506 * @param array $partData
507 */
508 private function persistResumeState(array $partData): void
509 {
510 if ($this->resumableUpload === null) {
511 if ($this->config['resume_file_path'] ?? false) {
512 $resumeFilePath = $this->config['resume_file_path'];
513 } else {
514 $resumeFilePath = $this->source . '.resume';
515 }
516
517 $sourceSize = $this->body->getSize()
518 ?? $this->calculatedObjectSize;
519 $this->resumableUpload = new ResumableUpload(
520 $resumeFilePath,
521 $this->requestArgs,
522 $this->config,
523 $this->currentSnapshot->toArray(),
524 $this->uploadId,
525 $this->partsCompleted,
526 $this->source,
527 $sourceSize,
528 $this->calculatePartSize(),
529 $this->isFullObjectChecksum
530 );
531 }
532
533 // Update the completed parts and current snapshot
534 $this->resumableUpload->markPartCompleted(
535 $partData['PartNumber'],
536 $partData
537 );
538 $this->resumableUpload->updateCurrentSnapshot(
539 $this->currentSnapshot->toArray()
540 );
541
542 // Save to file
543 $this->resumableUpload->toFile();
544 }
545
546 /**
547 * @return int
548 */
549 protected function getTotalSize(): int
550 {
551 if ($this->calculatedObjectSize > 0) {
552 return $this->calculatedObjectSize;
553 }
554
555 return $this->body->getSize();
556 }
557
558 /**
559 * @param ResultInterface $result
560 *
561 * @return UploadResult
562 */
563 protected function createResponse(ResultInterface $result): UploadResult
564 {
565 return new UploadResult(
566 $result->toArray()
567 );
568 }
569
570 /**
571 * @param StreamInterface $stream
572 * @param array $data
573 *
574 * @return StreamInterface
575 */
576 private function decorateWithHashes(
577 StreamInterface $stream,
578 array &$data
579 ): StreamInterface
580 {
581 // Decorate source with a hashing stream
582 $hash = new PhpHash('sha256');
583 return new HashingStream($stream, $hash, function ($result) use (&$data) {
584 $data['ContentSHA256'] = bin2hex($result);
585 });
586 }
587 }