Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Multipart/AbstractUploadManager.php

raw symbols SCIP
1 <?php
2 namespace Aws\Multipart;
3
4 use Aws\AwsClientInterface as Client;
5 use Aws\CommandInterface;
6 use Aws\CommandPool;
7 use Aws\Exception\AwsException;
8 use Aws\Exception\MultipartUploadException;
9 use Aws\Result;
10 use Aws\ResultInterface;
11 use GuzzleHttp\Promise;
12 use GuzzleHttp\Promise\PromiseInterface;
13 use InvalidArgumentException as IAE;
14 use Psr\Http\Message\RequestInterface;
15
16 /**
17 * Encapsulates the execution of a multipart upload to S3 or Glacier.
18 *
19 * @internal
20 */
21 abstract class AbstractUploadManager implements Promise\PromisorInterface
22 {
23 const DEFAULT_CONCURRENCY = 5;
24
25 /** @var array Default values for base multipart configuration */
26 private static $defaultConfig = [
27 'part_size' => null,
28 'state' => null,
29 'concurrency' => self::DEFAULT_CONCURRENCY,
30 'prepare_data_source' => null,
31 'before_initiate' => null,
32 'before_upload' => null,
33 'before_complete' => null,
34 'exception_class' => MultipartUploadException::class,
35 ];
36
37 /** @var Client Client used for the upload. */
38 protected $client;
39
40 /** @var array Configuration used to perform the upload. */
41 protected $config;
42
43 /** @var array Service-specific information about the upload workflow. */
44 protected $info;
45
46 /** @var PromiseInterface Promise that represents the multipart upload. */
47 protected $promise;
48
49 /** @var UploadState State used to manage the upload. */
50 protected $state;
51
52 /** @var bool Configuration used to indicate if upload progress will be displayed. */
53 protected $displayProgress;
54
55 /**
56 * @param Client $client
57 * @param array $config
58 */
59 public function __construct(Client $client, array $config = [])
60 {
61 $this->client = $client;
62 $this->info = $this->loadUploadWorkflowInfo();
63 $this->config = $config + self::$defaultConfig;
64 $this->state = $this->determineState();
65
66 if (isset($config['display_progress'])
67 && is_bool($config['display_progress'])
68 ) {
69 $this->displayProgress = $config['display_progress'];
70 }
71 }
72
73 /**
74 * Returns the current state of the upload
75 *
76 * @return UploadState
77 */
78 public function getState()
79 {
80 return $this->state;
81 }
82
83 /**
84 * Upload the source using multipart upload operations.
85 *
86 * @return Result The result of the CompleteMultipartUpload operation.
87 * @throws \LogicException if the upload is already complete or aborted.
88 * @throws MultipartUploadException if an upload operation fails.
89 */
90 public function upload()
91 {
92 return $this->promise()->wait();
93 }
94
95 /**
96 * Upload the source asynchronously using multipart upload operations.
97 *
98 * @return PromiseInterface
99 */
100 public function promise(): PromiseInterface
101 {
102 if ($this->promise) {
103 return $this->promise;
104 }
105
106 return $this->promise = Promise\Coroutine::of(function () {
107 // Initiate the upload.
108 if ($this->state->isCompleted()) {
109 throw new \LogicException('This multipart upload has already '
110 . 'been completed or aborted.'
111 );
112 }
113
114 if (!$this->state->isInitiated()) {
115 // Execute the prepare callback.
116 if (is_callable($this->config["prepare_data_source"])) {
117 $this->config["prepare_data_source"]();
118 }
119
120 $result = (yield $this->execCommand('initiate', $this->getInitiateParams()));
121 $this->state->setUploadId(
122 $this->info['id']['upload_id'],
123 $result[$this->info['id']['upload_id']]
124 );
125 $this->state->setStatus(UploadState::INITIATED);
126 }
127
128 // Create a command pool from a generator that yields UploadPart
129 // commands for each upload part.
130 $resultHandler = $this->getResultHandler($errors);
131 $commands = new CommandPool(
132 $this->client,
133 $this->getUploadCommands($resultHandler),
134 [
135 'concurrency' => $this->config['concurrency'],
136 'before' => $this->config['before_upload'],
137 ]
138 );
139
140 // Execute the pool of commands concurrently, and process errors.
141 yield $commands->promise();
142 if ($errors) {
143 throw new $this->config['exception_class']($this->state, $errors);
144 }
145
146 // Complete the multipart upload.
147 yield $this->execCommand('complete', $this->getCompleteParams());
148 $this->state->setStatus(UploadState::COMPLETED);
149 })->otherwise($this->buildFailureCatch());
150 }
151
152 private function transformException($e)
153 {
154 // Throw errors from the operations as a specific Multipart error.
155 if ($e instanceof AwsException) {
156 $e = new $this->config['exception_class']($this->state, $e);
157 }
158 throw $e;
159 }
160
161 private function buildFailureCatch()
162 {
163 if (interface_exists("Throwable")) {
164 return function (\Throwable $e) {
165 return $this->transformException($e);
166 };
167 } else {
168 return function (\Exception $e) {
169 return $this->transformException($e);
170 };
171 }
172 }
173
174 protected function getConfig()
175 {
176 return $this->config;
177 }
178
179 /**
180 * Provides service-specific information about the multipart upload
181 * workflow.
182 *
183 * This array of data should include the keys: 'command', 'id', and 'part_num'.
184 *
185 * @return array
186 */
187 abstract protected function loadUploadWorkflowInfo();
188
189 /**
190 * Determines the part size to use for upload parts.
191 *
192 * Examines the provided partSize value and the source to determine the
193 * best possible part size.
194 *
195 * @throws \InvalidArgumentException if the part size is invalid.
196 *
197 * @return int
198 */
199 abstract protected function determinePartSize();
200
201 /**
202 * Uses information from the Command and Result to determine which part was
203 * uploaded and mark it as uploaded in the upload's state.
204 *
205 * @param CommandInterface $command
206 * @param ResultInterface $result
207 */
208 abstract protected function handleResult(
209 CommandInterface $command,
210 ResultInterface $result
211 );
212
213 /**
214 * Gets the service-specific parameters used to initiate the upload.
215 *
216 * @return array
217 */
218 abstract protected function getInitiateParams();
219
220 /**
221 * Gets the service-specific parameters used to complete the upload.
222 *
223 * @return array
224 */
225 abstract protected function getCompleteParams();
226
227 /**
228 * Based on the config and service-specific workflow info, creates a
229 * `Promise` for an `UploadState` object.
230 */
231 private function determineState(): UploadState
232 {
233 // If the state was provided via config, then just use it.
234 if ($this->config['state'] instanceof UploadState) {
235 return $this->config['state'];
236 }
237
238 // Otherwise, construct a new state from the provided identifiers.
239 $required = $this->info['id'];
240 $id = [$required['upload_id'] => null];
241 unset($required['upload_id']);
242 foreach ($required as $key => $param) {
243 if (!isset($this->config[$key]) || $this->config[$key] === '') {
244 throw new IAE('You must provide a value for "' . $key . '" in '
245 . 'your config for the MultipartUploader for '
246 . $this->client->getApi()->getServiceFullName() . '.');
247 }
248 $id[$param] = $this->config[$key];
249 }
250 $state = new UploadState($id, $this->config);
251 $state->setPartSize($this->determinePartSize());
252
253 return $state;
254 }
255
256 /**
257 * Executes a MUP command with all of the parameters for the operation.
258 *
259 * @param string $operation Name of the operation.
260 * @param array $params Service-specific params for the operation.
261 *
262 * @return PromiseInterface
263 */
264 protected function execCommand($operation, array $params)
265 {
266 // Create the command.
267 $command = $this->client->getCommand(
268 $this->info['command'][$operation],
269 $params + $this->state->getId()
270 );
271
272 // Execute the before callback.
273 if (is_callable($this->config["before_{$operation}"])) {
274 $this->config["before_{$operation}"]($command);
275 }
276
277 // Execute the command asynchronously and return the promise.
278 return $this->client->executeAsync($command);
279 }
280
281 /**
282 * Returns a middleware for processing responses of part upload operations.
283 *
284 * - Adds an onFulfilled callback that calls the service-specific
285 * handleResult method on the Result of the operation.
286 * - Adds an onRejected callback that adds the error to an array of errors.
287 * - Has a passedByRef $errors arg that the exceptions get added to. The
288 * caller should use that &$errors array to do error handling.
289 *
290 * @param array $errors Errors from upload operations are added to this.
291 *
292 * @return callable
293 */
294 protected function getResultHandler(&$errors = [])
295 {
296 return function (callable $handler) use (&$errors) {
297 return function (
298 CommandInterface $command,
299 ?RequestInterface $request = null
300 ) use ($handler, &$errors) {
301 return $handler($command, $request)->then(
302 function (ResultInterface $result) use ($command) {
303 $this->handleResult($command, $result);
304 return $result;
305 },
306 function (AwsException $e) use (&$errors) {
307 $errors[$e->getCommand()[$this->info['part_num']]] = $e;
308 return new Result();
309 }
310 );
311 };
312 };
313 }
314
315 /**
316 * Creates a generator that yields part data for the upload's source.
317 *
318 * Yields associative arrays of parameters that are ultimately merged in
319 * with others to form the complete parameters of a command. This can
320 * include the Body parameter, which is a limited stream (i.e., a Stream
321 * object, decorated with a LimitStream).
322 *
323 * @param callable $resultHandler
324 *
325 * @return \Generator
326 */
327 abstract protected function getUploadCommands(callable $resultHandler);
328 }