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