AbstractUploadManager.php 10 KB

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