PluginProbe
Media Cloud Sync / 1.0.3
Media Cloud Sync v1.0.3
1.4.2 1.4.1 1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 All 36 releases
media-cloud-sync / includes / sdk / google / google / gax / src / OperationResponse.php

OperationResponse.php in Media Cloud Sync 1.0.3, at includes/sdk/google/google/gax/src/OperationResponse.php

415 lines 18.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /*
4 * Copyright 2016 Google LLC
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
9 * met:
10 *
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following disclaimer
15 * in the documentation and/or other materials provided with the
16 * distribution.
17 * * Neither the name of Google Inc. nor the names of its
18 * contributors may be used to endorse or promote products derived from
19 * this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 namespace Dudlewebs\WPMCS\Google\ApiCore;
34
35 use Dudlewebs\WPMCS\Google\LongRunning\Operation;
36 use Dudlewebs\WPMCS\Google\Protobuf\Any;
37 use Dudlewebs\WPMCS\Google\Protobuf\Internal\Message;
38 use Dudlewebs\WPMCS\Google\Rpc\Status;
39 use LogicException;
40 /**
41 * Response object from a long running API method.
42 *
43 * The OperationResponse object is returned by API methods that perform
44 * a long running operation. It provides methods that can be used to
45 * poll the status of the operation, retrieve the results, and cancel
46 * the operation.
47 *
48 * To support a long running operation, the server must implement the
49 * Operations API, which is used by the OperationResponse object. If
50 * more control is required, it is possible to make calls against the
51 * Operations API directly instead of via the OperationResponse object
52 * using an Operations Client instance.
53 */
54 class OperationResponse
55 {
56 use PollingTrait;
57 const DEFAULT_POLLING_INTERVAL = 1000;
58 const DEFAULT_POLLING_MULTIPLIER = 2;
59 const DEFAULT_MAX_POLLING_INTERVAL = 60000;
60 const DEFAULT_MAX_POLLING_DURATION = 0;
61 private string $operationName;
62 private ?object $operationsClient;
63 private ?string $operationReturnType;
64 private ?string $metadataReturnType;
65 private array $defaultPollSettings = ['initialPollDelayMillis' => self::DEFAULT_POLLING_INTERVAL, 'pollDelayMultiplier' => self::DEFAULT_POLLING_MULTIPLIER, 'maxPollDelayMillis' => self::DEFAULT_MAX_POLLING_INTERVAL, 'totalPollTimeoutMillis' => self::DEFAULT_MAX_POLLING_DURATION];
66 private ?object $lastProtoResponse;
67 private bool $deleted = \false;
68 private array $additionalArgs;
69 private string $getOperationMethod;
70 private ?string $cancelOperationMethod;
71 private ?string $deleteOperationMethod;
72 private string $operationStatusMethod;
73 /** @var mixed */
74 private $operationStatusDoneValue;
75 private ?string $operationErrorCodeMethod;
76 private ?string $operationErrorMessageMethod;
77 /**
78 * OperationResponse constructor.
79 *
80 * @param string $operationName
81 * @param object $operationsClient
82 * @param array $options {
83 * Optional. Options for configuring the operation response object.
84 *
85 * @type string $operationReturnType The return type of the longrunning operation.
86 * @type string $metadataReturnType The type of the metadata returned in the operation response.
87 * @type int $initialPollDelayMillis The initial polling interval to use, in milliseconds.
88 * @type int $pollDelayMultiplier Multiplier applied to the polling interval on each retry.
89 * @type int $maxPollDelayMillis The maximum polling interval to use, in milliseconds.
90 * @type int $totalPollTimeoutMillis The maximum amount of time to continue polling.
91 * @type object $lastProtoResponse A response already received from the server.
92 * @type string $getOperationMethod The method on $operationsClient to get the operation.
93 * @type string $cancelOperationMethod The method on $operationsClient to cancel the operation.
94 * @type string $deleteOperationMethod The method on $operationsClient to delete the operation.
95 * @type string $operationStatusMethod The method on the operation to get the status.
96 * @type string $operationStatusDoneValue The method on the operation to determine if the status is done.
97 * @type array $additionalOperationArguments Additional arguments to pass to $operationsClient methods.
98 * @type string $operationErrorCodeMethod The method on the operation to get the error code
99 * @type string $operationErrorMessageMethod The method on the operation to get the error status
100 * }
101 */
102 public function __construct(string $operationName, $operationsClient, array $options = [])
103 {
104 $this->operationName = $operationName;
105 $this->operationsClient = $operationsClient;
106 $options += ['operationReturnType' => null, 'metadataReturnType' => null, 'lastProtoResponse' => null, 'getOperationMethod' => 'getOperation', 'cancelOperationMethod' => 'cancelOperation', 'deleteOperationMethod' => 'deleteOperation', 'operationStatusMethod' => 'getDone', 'operationStatusDoneValue' => \true, 'additionalOperationArguments' => [], 'operationErrorCodeMethod' => null, 'operationErrorMessageMethod' => null];
107 $this->operationReturnType = $options['operationReturnType'];
108 $this->metadataReturnType = $options['metadataReturnType'];
109 $this->lastProtoResponse = $options['lastProtoResponse'];
110 $this->getOperationMethod = $options['getOperationMethod'];
111 $this->cancelOperationMethod = $options['cancelOperationMethod'];
112 $this->deleteOperationMethod = $options['deleteOperationMethod'];
113 $this->additionalArgs = $options['additionalOperationArguments'];
114 $this->operationStatusMethod = $options['operationStatusMethod'];
115 $this->operationStatusDoneValue = $options['operationStatusDoneValue'];
116 $this->operationErrorCodeMethod = $options['operationErrorCodeMethod'];
117 $this->operationErrorMessageMethod = $options['operationErrorMessageMethod'];
118 if (isset($options['initialPollDelayMillis'])) {
119 $this->defaultPollSettings['initialPollDelayMillis'] = $options['initialPollDelayMillis'];
120 }
121 if (isset($options['pollDelayMultiplier'])) {
122 $this->defaultPollSettings['pollDelayMultiplier'] = $options['pollDelayMultiplier'];
123 }
124 if (isset($options['maxPollDelayMillis'])) {
125 $this->defaultPollSettings['maxPollDelayMillis'] = $options['maxPollDelayMillis'];
126 }
127 if (isset($options['totalPollTimeoutMillis'])) {
128 $this->defaultPollSettings['totalPollTimeoutMillis'] = $options['totalPollTimeoutMillis'];
129 }
130 }
131 /**
132 * Check whether the operation has completed.
133 *
134 * @return bool
135 */
136 public function isDone()
137 {
138 if (!$this->hasProtoResponse()) {
139 return \false;
140 }
141 $status = call_user_func([$this->lastProtoResponse, $this->operationStatusMethod]);
142 if (is_null($status)) {
143 return \false;
144 }
145 return $status === $this->operationStatusDoneValue;
146 }
147 /**
148 * Check whether the operation completed successfully. If the operation is not complete, or if the operation
149 * failed, return false.
150 *
151 * @return bool
152 */
153 public function operationSucceeded()
154 {
155 if (!$this->hasProtoResponse()) {
156 return \false;
157 }
158 if (!$this->canHaveResult()) {
159 // For Operations which do not have a result, we consider a successful
160 // operation when the operation has completed without errors.
161 return $this->isDone() && !$this->hasErrors();
162 }
163 return !is_null($this->getResult());
164 }
165 /**
166 * Check whether the operation failed. If the operation is not complete, or if the operation
167 * succeeded, return false.
168 *
169 * @return bool
170 */
171 public function operationFailed()
172 {
173 return $this->hasErrors();
174 }
175 /**
176 * Get the formatted name of the operation
177 *
178 * @return string The formatted name of the operation
179 */
180 public function getName()
181 {
182 return $this->operationName;
183 }
184 /**
185 * Poll the server in a loop until the operation is complete.
186 *
187 * Return true if the operation completed, otherwise return false. If the
188 * $options['totalPollTimeoutMillis'] setting is not set (or set <= 0) then
189 * pollUntilComplete will continue polling until the operation completes,
190 * and therefore will always return true.
191 *
192 * @param array $options {
193 * Options for configuring the polling behaviour.
194 *
195 * @type int $initialPollDelayMillis The initial polling interval to use, in milliseconds.
196 * @type int $pollDelayMultiplier Multiplier applied to the polling interval on each retry.
197 * @type int $maxPollDelayMillis The maximum polling interval to use, in milliseconds.
198 * @type int $totalPollTimeoutMillis The maximum amount of time to continue polling, in milliseconds.
199 * }
200 * @throws ApiException If an API call fails.
201 * @throws ValidationException
202 * @return bool Indicates if the operation completed.
203 */
204 public function pollUntilComplete(array $options = [])
205 {
206 if ($this->isDone()) {
207 return \true;
208 }
209 $pollSettings = array_merge($this->defaultPollSettings, $options);
210 return $this->poll(function () {
211 $this->reload();
212 return $this->isDone();
213 }, $pollSettings);
214 }
215 /**
216 * Reload the status of the operation with a request to the service.
217 *
218 * @throws ApiException If the API call fails.
219 * @throws ValidationException If called on a deleted operation.
220 */
221 public function reload()
222 {
223 if ($this->deleted) {
224 throw new ValidationException("Cannot call reload() on a deleted operation");
225 }
226 $this->lastProtoResponse = $this->operationsCall($this->getOperationMethod, $this->getName(), $this->additionalArgs);
227 }
228 /**
229 * Return the result of the operation. If operationSucceeded() is false, return null.
230 *
231 * @return mixed|null The result of the operation, or null if operationSucceeded() is false
232 */
233 public function getResult()
234 {
235 if (!$this->hasProtoResponse()) {
236 return null;
237 }
238 if (!$this->canHaveResult()) {
239 return null;
240 }
241 if (!$this->isDone()) {
242 return null;
243 }
244 /** @var Any|null $anyResponse */
245 $anyResponse = $this->lastProtoResponse->getResponse();
246 if (is_null($anyResponse)) {
247 return null;
248 }
249 if (is_null($this->operationReturnType)) {
250 return $anyResponse;
251 }
252 $operationReturnType = $this->operationReturnType;
253 /** @var Message $response */
254 $response = new $operationReturnType();
255 $response->mergeFromString($anyResponse->getValue());
256 return $response;
257 }
258 /**
259 * If the operation failed, return the status. If operationFailed() is false, return null.
260 *
261 * @return Status|null The status of the operation in case of failure, or null if
262 * operationFailed() is false.
263 */
264 public function getError()
265 {
266 if (!$this->hasProtoResponse() || !$this->isDone()) {
267 return null;
268 }
269 if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) {
270 $errorCode = $this->operationErrorCodeMethod ? call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]) : null;
271 $errorMessage = $this->operationErrorMessageMethod ? call_user_func([$this->lastProtoResponse, $this->operationErrorMessageMethod]) : null;
272 return (new Status())->setCode(ApiStatus::rpcCodeFromHttpStatusCode($errorCode))->setMessage($errorMessage);
273 }
274 if (method_exists($this->lastProtoResponse, 'getError')) {
275 return $this->lastProtoResponse->getError();
276 }
277 return null;
278 }
279 /**
280 * Get an array containing the values of 'operationReturnType', 'metadataReturnType', and
281 * the polling options `initialPollDelayMillis`, `pollDelayMultiplier`, `maxPollDelayMillis`,
282 * and `totalPollTimeoutMillis`. The array can be passed as the $options argument to the
283 * constructor when creating another OperationResponse object.
284 *
285 * @return array
286 */
287 public function getDescriptorOptions()
288 {
289 return ['operationReturnType' => $this->operationReturnType, 'metadataReturnType' => $this->metadataReturnType] + $this->defaultPollSettings;
290 }
291 /**
292 * @return Operation|mixed|null The last Operation object received from the server.
293 */
294 public function getLastProtoResponse()
295 {
296 return $this->lastProtoResponse;
297 }
298 /**
299 * @return object The OperationsClient object used to make
300 * requests to the operations API.
301 */
302 public function getOperationsClient()
303 {
304 return $this->operationsClient;
305 }
306 /**
307 * Cancel the long-running operation.
308 *
309 * For operations of type Google\LongRunning\Operation, this method starts
310 * asynchronous cancellation on a long-running operation. The server
311 * makes a best effort to cancel the operation, but success is not
312 * guaranteed. If the server doesn't support this method, it will throw an
313 * ApiException with code \Google\Rpc\Code::UNIMPLEMENTED. Clients can continue
314 * to use reload and pollUntilComplete methods to check whether the cancellation
315 * succeeded or whether the operation completed despite cancellation.
316 * On successful cancellation, the operation is not deleted; instead, it becomes
317 * an operation with a getError() value with a \Google\Rpc\Status code of 1,
318 * corresponding to \Google\Rpc\Code::CANCELLED.
319 *
320 * @throws ApiException If the API call fails.
321 * @throws LogicException If the API call method has not been configured
322 */
323 public function cancel()
324 {
325 if (is_null($this->cancelOperationMethod)) {
326 throw new LogicException('The cancel operation is not supported by this API');
327 }
328 $this->operationsCall($this->cancelOperationMethod, $this->getName(), $this->additionalArgs);
329 }
330 /**
331 * Delete the long-running operation.
332 *
333 * For operations of type Google\LongRunning\Operation, this method
334 * indicates that the client is no longer interested in the operation result.
335 * It does not cancel the operation. If the server doesn't support this method,
336 * it will throw an ApiException with code \Google\Rpc\Code::UNIMPLEMENTED.
337 *
338 * @throws ApiException If the API call fails.
339 * @throws LogicException If the API call method has not been configured
340 */
341 public function delete()
342 {
343 if (is_null($this->deleteOperationMethod)) {
344 throw new LogicException('The delete operation is not supported by this API');
345 }
346 $this->operationsCall($this->deleteOperationMethod, $this->getName(), $this->additionalArgs);
347 $this->deleted = \true;
348 }
349 /**
350 * Get the metadata returned with the last proto response. If a metadata type was provided, then
351 * the return value will be of that type - otherwise, the return value will be of type Any. If
352 * no metadata object is available, returns null.
353 *
354 * @return mixed The metadata returned from the server in the last response.
355 */
356 public function getMetadata()
357 {
358 if (!$this->hasProtoResponse()) {
359 return null;
360 }
361 if (!method_exists($this->lastProtoResponse, 'getMetadata')) {
362 // The call to getMetadata is only for OnePlatform LROs, and is not
363 // supported by other LRO GAPIC clients (e.g. Compute)
364 return null;
365 }
366 /** @var Any|null $any */
367 $any = $this->lastProtoResponse->getMetadata();
368 if (is_null($this->metadataReturnType)) {
369 return $any;
370 }
371 if (is_null($any)) {
372 return null;
373 }
374 // @TODO: This is probably not doing anything and can be removed in the next release.
375 if (is_null($any->getValue())) {
376 return null;
377 }
378 $metadataReturnType = $this->metadataReturnType;
379 /** @var Message $metadata */
380 $metadata = new $metadataReturnType();
381 $metadata->mergeFromString($any->getValue());
382 return $metadata;
383 }
384 private function operationsCall($method, $name, array $additionalArgs)
385 {
386 $args = array_merge([$name], $additionalArgs);
387 return call_user_func_array([$this->operationsClient, $method], $args);
388 }
389 private function canHaveResult()
390 {
391 // The call to getResponse is only for OnePlatform LROs, and is not
392 // supported by other LRO GAPIC clients (e.g. Compute)
393 return method_exists($this->lastProtoResponse, 'getResponse');
394 }
395 private function hasErrors()
396 {
397 if (!$this->hasProtoResponse()) {
398 return \false;
399 }
400 if (method_exists($this->lastProtoResponse, 'getError')) {
401 return !empty($this->lastProtoResponse->getError());
402 }
403 if ($this->operationErrorCodeMethod) {
404 $errorCode = call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]);
405 return !empty($errorCode);
406 }
407 // This should never happen unless an API is misconfigured
408 throw new LogicException('Unable to determine operation error status for this service');
409 }
410 private function hasProtoResponse()
411 {
412 return !is_null($this->lastProtoResponse);
413 }
414 }
415