PluginProbe
Media Cloud Sync / 1.2.11
Media Cloud Sync v1.2.11
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 / RetrySettings.php

RetrySettings.php in Media Cloud Sync 1.2.11, at includes/sdk/google/google/gax/src/RetrySettings.php

463 lines 20.9 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 Closure;
36 /**
37 * The RetrySettings class is used to configure retrying and timeouts for RPCs.
38 * This class can be passed as an optional parameter to RPC methods, or as part
39 * of an optional array in the constructor of a client object. In addition,
40 * many RPCs and API clients accept a PHP array in place of a RetrySettings
41 * object. This can be used to change particular retry parameters without
42 * needing to construct a complete RetrySettings object.
43 *
44 * Constructing a RetrySettings object
45 * -----------------------------------
46 *
47 * See the RetrySettings constructor for documentation about parameters that
48 * can be passed to RetrySettings.
49 *
50 * Example of creating a RetrySettings object using the constructor:
51 * ```
52 * $retrySettings = new RetrySettings([
53 * 'initialRetryDelayMillis' => 100,
54 * 'retryDelayMultiplier' => 1.3,
55 * 'maxRetryDelayMillis' => 60000,
56 * 'initialRpcTimeoutMillis' => 20000,
57 * 'rpcTimeoutMultiplier' => 1.0,
58 * 'maxRpcTimeoutMillis' => 20000,
59 * 'totalTimeoutMillis' => 600000,
60 * 'retryableCodes' => [ApiStatus::DEADLINE_EXCEEDED, ApiStatus::UNAVAILABLE],
61 * ]);
62 * ```
63 *
64 * It is also possible to create a new RetrySettings object from an existing
65 * object using the {@see \Google\ApiCore\RetrySettings::with()} method.
66 *
67 * Example modifying an existing RetrySettings object using `with()`:
68 * ```
69 * $newRetrySettings = $retrySettings->with([
70 * 'totalTimeoutMillis' => 700000,
71 * ]);
72 * ```
73 *
74 * Modifying the retry behavior of an RPC method
75 * ---------------------------------------------
76 *
77 * RetrySettings objects can be used to control retries for many RPC methods in
78 * [google-cloud-php](https://github.com/googleapis/google-cloud-php).
79 * The examples below make use of the
80 * [GroupServiceClient](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/monitoring/v3/groupserviceclient)
81 * from the [Monitoring V3 API](https://github.com/googleapis/google-cloud-php/tree/master/src/Monitoring/V3),
82 * but they can be applied to other APIs in the
83 * [google-cloud-php](https://github.com/googleapis/google-cloud-php) repository.
84 *
85 * It is possible to specify the retry behavior to be used by an RPC via the
86 * `retrySettings` field in the `optionalArgs` parameter. The `retrySettings`
87 * field can contain either a RetrySettings object, or a PHP array containing
88 * the particular retry parameters to be updated.
89 *
90 * Example of disabling retries for a single call to the
91 * [listGroups](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/monitoring/v3/groupserviceclient?method=listGroups)
92 * method, and setting a custom timeout:
93 * ```
94 * $result = $client->listGroups($name, [
95 * 'retrySettings' => [
96 * 'retriesEnabled' => false,
97 * 'noRetriesRpcTimeoutMillis' => 5000,
98 * ]
99 * ]);
100 * ```
101 *
102 * Example of creating a new RetrySettings object and using it to override
103 * the retry settings for a call to the
104 * [listGroups](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/monitoring/v3/groupserviceclient?method=listGroups)
105 * method:
106 * ```
107 * $customRetrySettings = new RetrySettings([
108 * 'initialRetryDelayMillis' => 100,
109 * 'retryDelayMultiplier' => 1.3,
110 * 'maxRetryDelayMillis' => 60000,
111 * 'initialRpcTimeoutMillis' => 20000,
112 * 'rpcTimeoutMultiplier' => 1.0,
113 * 'maxRpcTimeoutMillis' => 20000,
114 * 'totalTimeoutMillis' => 600000,
115 * 'retryableCodes' => [ApiStatus::DEADLINE_EXCEEDED, ApiStatus::UNAVAILABLE],
116 * ]);
117 *
118 * $result = $client->listGroups($name, [
119 * 'retrySettings' => $customRetrySettings
120 * ]);
121 * ```
122 *
123 * Modifying the default retry behavior for RPC methods on a Client object
124 * -----------------------------------------------------------------------
125 *
126 * It is also possible to specify the retry behavior for RPC methods when
127 * constructing a client object using the 'retrySettingsArray'. The examples
128 * below again make use of the
129 * [GroupServiceClient](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/monitoring/v3/groupserviceclient)
130 * from the [Monitoring V3 API](https://github.com/googleapis/google-cloud-php/tree/master/src/Monitoring/V3),
131 * but they can be applied to other APIs in the
132 * [google-cloud-php](https://github.com/googleapis/google-cloud-php) repository.
133 *
134 * The GroupServiceClient object accepts an optional `retrySettingsArray`
135 * parameter, which can be used to specify retry behavior for RPC methods
136 * on the client. The `retrySettingsArray` accepts a PHP array in which keys
137 * are the names of RPC methods on the client, and values are either a
138 * RetrySettings object or a PHP array containing the particular retry
139 * parameters to be updated.
140 *
141 * Example updating the retry settings for four methods of GroupServiceClient:
142 * ```
143 * use Google\Cloud\Monitoring\V3\GroupServiceClient;
144 *
145 * $customRetrySettings = new RetrySettings([
146 * 'initialRetryDelayMillis' => 100,
147 * 'retryDelayMultiplier' => 1.3,
148 * 'maxRetryDelayMillis' => 60000,
149 * 'initialRpcTimeoutMillis' => 20000,
150 * 'rpcTimeoutMultiplier' => 1.0,
151 * 'maxRpcTimeoutMillis' => 20000,
152 * 'totalTimeoutMillis' => 600000,
153 * 'retryableCodes' => [ApiStatus::DEADLINE_EXCEEDED, ApiStatus::UNAVAILABLE],
154 * ]);
155 *
156 * $updatedCustomRetrySettings = $customRetrySettings->with([
157 * 'totalTimeoutMillis' => 700000
158 * ]);
159 *
160 * $client = new GroupServiceClient([
161 * 'retrySettingsArray' => [
162 * 'listGroups' => ['retriesEnabled' => false],
163 * 'getGroup' => [
164 * 'initialRpcTimeoutMillis' => 10000,
165 * 'maxRpcTimeoutMillis' => 30000,
166 * 'totalTimeoutMillis' => 60000,
167 * ],
168 * 'deleteGroup' => $customRetrySettings,
169 * 'updateGroup' => $updatedCustomRetrySettings
170 * ],
171 * ]);
172 * ```
173 *
174 * Configure the use of logical timeout
175 * ------------------------------------
176 *
177 * To configure the use of a logical timeout, where a logical timeout is the
178 * duration a method is given to complete one or more RPC attempts, with each
179 * attempt using only the time remaining in the logical timeout, use
180 * {@see \Google\ApiCore\RetrySettings::logicalTimeout()} combined with
181 * {@see \Google\ApiCore\RetrySettings::with()}.
182 *
183 * ```
184 * $timeoutSettings = RetrySettings::logicalTimeout(30000);
185 *
186 * $customRetrySettings = $customRetrySettings->with($timeoutSettings);
187 *
188 * $result = $client->listGroups($name, [
189 * 'retrySettings' => $customRetrySettings
190 * ]);
191 * ```
192 *
193 * {@see \Google\ApiCore\RetrySettings::logicalTimeout()} can also be used on a
194 * method call independent of a RetrySettings instance.
195 *
196 * ```
197 * $timeoutSettings = RetrySettings::logicalTimeout(30000);
198 *
199 * $result = $client->listGroups($name, [
200 * 'retrySettings' => $timeoutSettings
201 * ]);
202 * ```
203 */
204 class RetrySettings
205 {
206 use ValidationTrait;
207 const DEFAULT_MAX_RETRIES = 0;
208 private $retriesEnabled;
209 private $retryableCodes;
210 private $initialRetryDelayMillis;
211 private $retryDelayMultiplier;
212 private $maxRetryDelayMillis;
213 private $initialRpcTimeoutMillis;
214 private $rpcTimeoutMultiplier;
215 private $maxRpcTimeoutMillis;
216 private $totalTimeoutMillis;
217 private $noRetriesRpcTimeoutMillis;
218 /**
219 * The number of maximum retries an operation can do.
220 * This doesn't include the original API call.
221 * Setting this to 0 means no limit.
222 */
223 private int $maxRetries;
224 /**
225 * When set, this function will be used to evaluate if the retry should
226 * take place or not. The callable will have the following signature:
227 * function (Exception $e, array $options): bool
228 */
229 private ?Closure $retryFunction;
230 /**
231 * Constructs an instance.
232 *
233 * @param array $settings {
234 * Required. Settings for configuring the retry behavior. All parameters are required except
235 * $retriesEnabled and $noRetriesRpcTimeoutMillis, which are optional and have defaults
236 * determined based on the other settings provided.
237 *
238 * @type bool $retriesEnabled Optional. Enables retries. If not specified, the value is
239 * determined using the $retryableCodes setting. If $retryableCodes is empty,
240 * then $retriesEnabled is set to false; otherwise, it is set to true.
241 * @type int $noRetriesRpcTimeoutMillis Optional. The timeout of the rpc call to be used
242 * if $retriesEnabled is false, in milliseconds. It not specified, the value
243 * of $initialRpcTimeoutMillis is used.
244 * @type array $retryableCodes The Status codes that are retryable. Each status should be
245 * either one of the string constants defined on {@see \Google\ApiCore\ApiStatus}
246 * or an integer constant defined on {@see \Google\Rpc\Code}.
247 * @type int $initialRetryDelayMillis The initial delay of retry in milliseconds.
248 * @type int $retryDelayMultiplier The exponential multiplier of retry delay.
249 * @type int $maxRetryDelayMillis The max delay of retry in milliseconds.
250 * @type int $initialRpcTimeoutMillis The initial timeout of rpc call in milliseconds.
251 * @type int $rpcTimeoutMultiplier The exponential multiplier of rpc timeout.
252 * @type int $maxRpcTimeoutMillis The max timeout of rpc call in milliseconds.
253 * @type int $totalTimeoutMillis The max accumulative timeout in total.
254 * @type int $maxRetries The max retries allowed for an operation.
255 * Defaults to the value of the DEFAULT_MAX_RETRIES constant.
256 * This option is experimental.
257 * @type callable $retryFunction This function will be used to decide if we should retry or not.
258 * Callable signature: `function (Exception $e, array $options): bool`
259 * This option is experimental.
260 * }
261 */
262 public function __construct(array $settings)
263 {
264 $this->validateNotNull($settings, ['initialRetryDelayMillis', 'retryDelayMultiplier', 'maxRetryDelayMillis', 'initialRpcTimeoutMillis', 'rpcTimeoutMultiplier', 'maxRpcTimeoutMillis', 'totalTimeoutMillis', 'retryableCodes']);
265 $this->initialRetryDelayMillis = $settings['initialRetryDelayMillis'];
266 $this->retryDelayMultiplier = $settings['retryDelayMultiplier'];
267 $this->maxRetryDelayMillis = $settings['maxRetryDelayMillis'];
268 $this->initialRpcTimeoutMillis = $settings['initialRpcTimeoutMillis'];
269 $this->rpcTimeoutMultiplier = $settings['rpcTimeoutMultiplier'];
270 $this->maxRpcTimeoutMillis = $settings['maxRpcTimeoutMillis'];
271 $this->totalTimeoutMillis = $settings['totalTimeoutMillis'];
272 $this->retryableCodes = $settings['retryableCodes'];
273 $this->retriesEnabled = array_key_exists('retriesEnabled', $settings) ? $settings['retriesEnabled'] : count($this->retryableCodes) > 0;
274 $this->noRetriesRpcTimeoutMillis = array_key_exists('noRetriesRpcTimeoutMillis', $settings) ? $settings['noRetriesRpcTimeoutMillis'] : $this->initialRpcTimeoutMillis;
275 $this->maxRetries = $settings['maxRetries'] ?? self::DEFAULT_MAX_RETRIES;
276 $this->retryFunction = $settings['retryFunction'] ?? null;
277 }
278 /**
279 * Constructs an array mapping method names to CallSettings.
280 *
281 * @param string $serviceName
282 * The fully-qualified name of this service, used as a key into
283 * the client config file.
284 * @param array $clientConfig
285 * An array parsed from the standard API client config file.
286 * @param bool $disableRetries
287 * Disable retries in all loaded RetrySettings objects. Defaults to false.
288 * @throws ValidationException
289 * @return RetrySettings[] $retrySettings
290 */
291 public static function load(string $serviceName, array $clientConfig, bool $disableRetries = \false)
292 {
293 $serviceRetrySettings = [];
294 $serviceConfig = $clientConfig['interfaces'][$serviceName];
295 $retryCodes = $serviceConfig['retry_codes'];
296 $retryParams = $serviceConfig['retry_params'];
297 foreach ($serviceConfig['methods'] as $methodName => $methodConfig) {
298 $timeoutMillis = $methodConfig['timeout_millis'];
299 if (empty($methodConfig['retry_codes_name']) || empty($methodConfig['retry_params_name'])) {
300 // Construct a RetrySettings object with retries disabled
301 $retrySettings = self::constructDefault()->with(['noRetriesRpcTimeoutMillis' => $timeoutMillis]);
302 } else {
303 $retryCodesName = $methodConfig['retry_codes_name'];
304 $retryParamsName = $methodConfig['retry_params_name'];
305 if (!array_key_exists($retryCodesName, $retryCodes)) {
306 throw new ValidationException("Invalid retry_codes_name setting: '{$retryCodesName}'");
307 }
308 if (!array_key_exists($retryParamsName, $retryParams)) {
309 throw new ValidationException("Invalid retry_params_name setting: '{$retryParamsName}'");
310 }
311 foreach ($retryCodes[$retryCodesName] as $status) {
312 if (!ApiStatus::isValidStatus($status)) {
313 throw new ValidationException("Invalid status code: '{$status}'");
314 }
315 }
316 $retryParameters = self::convertArrayFromSnakeCase($retryParams[$retryParamsName]) + ['retryableCodes' => $retryCodes[$retryCodesName], 'noRetriesRpcTimeoutMillis' => $timeoutMillis];
317 if ($disableRetries) {
318 $retryParameters['retriesEnabled'] = \false;
319 }
320 $retrySettings = new RetrySettings($retryParameters);
321 }
322 $serviceRetrySettings[$methodName] = $retrySettings;
323 }
324 return $serviceRetrySettings;
325 }
326 public static function constructDefault()
327 {
328 return new RetrySettings(['retriesEnabled' => \false, 'noRetriesRpcTimeoutMillis' => 30000, 'initialRetryDelayMillis' => 100, 'retryDelayMultiplier' => 1.3, 'maxRetryDelayMillis' => 60000, 'initialRpcTimeoutMillis' => 20000, 'rpcTimeoutMultiplier' => 1, 'maxRpcTimeoutMillis' => 20000, 'totalTimeoutMillis' => 600000, 'retryableCodes' => [], 'maxRetries' => self::DEFAULT_MAX_RETRIES, 'retryFunction' => null]);
329 }
330 /**
331 * Creates a new instance of RetrySettings that updates the settings in the existing instance
332 * with the settings specified in the $settings parameter.
333 *
334 * @param array $settings {
335 * Settings for configuring the retry behavior. Supports all of the options supported by
336 * the constructor; see {@see \Google\ApiCore\RetrySettings::__construct()}. All parameters
337 * are optional - all unset parameters will default to the value in the existing instance.
338 * }
339 * @return RetrySettings
340 */
341 public function with(array $settings)
342 {
343 $existingSettings = ['initialRetryDelayMillis' => $this->getInitialRetryDelayMillis(), 'retryDelayMultiplier' => $this->getRetryDelayMultiplier(), 'maxRetryDelayMillis' => $this->getMaxRetryDelayMillis(), 'initialRpcTimeoutMillis' => $this->getInitialRpcTimeoutMillis(), 'rpcTimeoutMultiplier' => $this->getRpcTimeoutMultiplier(), 'maxRpcTimeoutMillis' => $this->getMaxRpcTimeoutMillis(), 'totalTimeoutMillis' => $this->getTotalTimeoutMillis(), 'retryableCodes' => $this->getRetryableCodes(), 'retriesEnabled' => $this->retriesEnabled(), 'noRetriesRpcTimeoutMillis' => $this->getNoRetriesRpcTimeoutMillis(), 'maxRetries' => $this->getMaxRetries(), 'retryFunction' => $this->getRetryFunction()];
344 return new RetrySettings($settings + $existingSettings);
345 }
346 /**
347 * Creates an associative array of the {@see \Google\ApiCore\RetrySettings} timeout fields configured
348 * with the given timeout specified in the $timeout parameter interpreted as a logical timeout.
349 *
350 * @param int $timeout The timeout in milliseconds to be used as a logical call timeout.
351 * @return array
352 */
353 public static function logicalTimeout(int $timeout)
354 {
355 return ['initialRpcTimeoutMillis' => $timeout, 'maxRpcTimeoutMillis' => $timeout, 'totalTimeoutMillis' => $timeout, 'noRetriesRpcTimeoutMillis' => $timeout, 'rpcTimeoutMultiplier' => 1.0];
356 }
357 /**
358 * @return bool Returns true if retries are enabled, otherwise returns false.
359 */
360 public function retriesEnabled()
361 {
362 return $this->retriesEnabled;
363 }
364 /**
365 * @return int The timeout of the rpc call to be used if $retriesEnabled is false,
366 * in milliseconds.
367 */
368 public function getNoRetriesRpcTimeoutMillis()
369 {
370 return $this->noRetriesRpcTimeoutMillis;
371 }
372 /**
373 * @return int[] Status codes to retry
374 */
375 public function getRetryableCodes()
376 {
377 return $this->retryableCodes;
378 }
379 /**
380 * @return int The initial retry delay in milliseconds. If $this->retriesEnabled()
381 * is false, this setting is unused.
382 */
383 public function getInitialRetryDelayMillis()
384 {
385 return $this->initialRetryDelayMillis;
386 }
387 /**
388 * @return float The retry delay multiplier. If $this->retriesEnabled()
389 * is false, this setting is unused.
390 */
391 public function getRetryDelayMultiplier()
392 {
393 return $this->retryDelayMultiplier;
394 }
395 /**
396 * @return int The maximum retry delay in milliseconds. If $this->retriesEnabled()
397 * is false, this setting is unused.
398 */
399 public function getMaxRetryDelayMillis()
400 {
401 return $this->maxRetryDelayMillis;
402 }
403 /**
404 * @return int The initial rpc timeout in milliseconds. If $this->retriesEnabled()
405 * is false, this setting is unused - use noRetriesRpcTimeoutMillis to
406 * set the timeout in that case.
407 */
408 public function getInitialRpcTimeoutMillis()
409 {
410 return $this->initialRpcTimeoutMillis;
411 }
412 /**
413 * @return float The rpc timeout multiplier. If $this->retriesEnabled()
414 * is false, this setting is unused.
415 */
416 public function getRpcTimeoutMultiplier()
417 {
418 return $this->rpcTimeoutMultiplier;
419 }
420 /**
421 * @return int The maximum rpc timeout in milliseconds. If $this->retriesEnabled()
422 * is false, this setting is unused - use noRetriesRpcTimeoutMillis to
423 * set the timeout in that case.
424 */
425 public function getMaxRpcTimeoutMillis()
426 {
427 return $this->maxRpcTimeoutMillis;
428 }
429 /**
430 * @return int The total time in milliseconds to spend on the call, including all
431 * retry attempts and delays between attempts. If $this->retriesEnabled()
432 * is false, this setting is unused - use noRetriesRpcTimeoutMillis to
433 * set the timeout in that case.
434 */
435 public function getTotalTimeoutMillis()
436 {
437 return $this->totalTimeoutMillis;
438 }
439 /**
440 * @experimental
441 */
442 public function getMaxRetries()
443 {
444 return $this->maxRetries;
445 }
446 /**
447 * @experimental
448 */
449 public function getRetryFunction()
450 {
451 return $this->retryFunction;
452 }
453 private static function convertArrayFromSnakeCase(array $settings)
454 {
455 $camelCaseSettings = [];
456 foreach ($settings as $key => $value) {
457 $camelCaseKey = str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
458 $camelCaseSettings[lcfirst($camelCaseKey)] = $value;
459 }
460 return $camelCaseSettings;
461 }
462 }
463