AbstractUploadManager.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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' => 'Aws\Exception\MultipartUploadException',
  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()
  80. {
  81. if ($this->promise) {
  82. return $this->promise;
  83. }
  84. return $this->promise = Promise\coroutine(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. * @return PromiseInterface A `Promise` that resolves to an `UploadState`.
  196. */
  197. private function determineState()
  198. {
  199. // If the state was provided via config, then just use it.
  200. if ($this->config['state'] instanceof UploadState) {
  201. return $this->config['state'];
  202. }
  203. // Otherwise, construct a new state from the provided identifiers.
  204. $required = $this->info['id'];
  205. $id = [$required['upload_id'] => null];
  206. unset($required['upload_id']);
  207. foreach ($required as $key => $param) {
  208. if (!$this->config[$key]) {
  209. throw new IAE('You must provide a value for "' . $key . '" in '
  210. . 'your config for the MultipartUploader for '
  211. . $this->client->getApi()->getServiceFullName() . '.');
  212. }
  213. $id[$param] = $this->config[$key];
  214. }
  215. $state = new UploadState($id);
  216. $state->setPartSize($this->determinePartSize());
  217. return $state;
  218. }
  219. /**
  220. * Executes a MUP command with all of the parameters for the operation.
  221. *
  222. * @param string $operation Name of the operation.
  223. * @param array $params Service-specific params for the operation.
  224. *
  225. * @return PromiseInterface
  226. */
  227. protected function execCommand($operation, array $params)
  228. {
  229. // Create the command.
  230. $command = $this->client->getCommand(
  231. $this->info['command'][$operation],
  232. $params + $this->state->getId()
  233. );
  234. // Execute the before callback.
  235. if (is_callable($this->config["before_{$operation}"])) {
  236. $this->config["before_{$operation}"]($command);
  237. }
  238. // Execute the command asynchronously and return the promise.
  239. return $this->client->executeAsync($command);
  240. }
  241. /**
  242. * Returns a middleware for processing responses of part upload operations.
  243. *
  244. * - Adds an onFulfilled callback that calls the service-specific
  245. * handleResult method on the Result of the operation.
  246. * - Adds an onRejected callback that adds the error to an array of errors.
  247. * - Has a passedByRef $errors arg that the exceptions get added to. The
  248. * caller should use that &$errors array to do error handling.
  249. *
  250. * @param array $errors Errors from upload operations are added to this.
  251. *
  252. * @return callable
  253. */
  254. protected function getResultHandler(&$errors = [])
  255. {
  256. return function (callable $handler) use (&$errors) {
  257. return function (
  258. CommandInterface $command,
  259. RequestInterface $request = null
  260. ) use ($handler, &$errors) {
  261. return $handler($command, $request)->then(
  262. function (ResultInterface $result) use ($command) {
  263. $this->handleResult($command, $result);
  264. return $result;
  265. },
  266. function (AwsException $e) use (&$errors) {
  267. $errors[$e->getCommand()[$this->info['part_num']]] = $e;
  268. return new Result();
  269. }
  270. );
  271. };
  272. };
  273. }
  274. /**
  275. * Creates a generator that yields part data for the upload's source.
  276. *
  277. * Yields associative arrays of parameters that are ultimately merged in
  278. * with others to form the complete parameters of a command. This can
  279. * include the Body parameter, which is a limited stream (i.e., a Stream
  280. * object, decorated with a LimitStream).
  281. *
  282. * @param callable $resultHandler
  283. *
  284. * @return \Generator
  285. */
  286. abstract protected function getUploadCommands(callable $resultHandler);
  287. }