diff --git a/composer.json b/composer.json index 2c95b22145ee..e947486ee221 100644 --- a/composer.json +++ b/composer.json @@ -48,8 +48,8 @@ "monolog/monolog": "~1", "psr/http-message": "1.0.*", "ramsey/uuid": "~3", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "require-dev": { "phpunit/phpunit": "4.8.*", @@ -117,4 +117,4 @@ ] } } -} \ No newline at end of file +} diff --git a/src/Core/GrpcRequestWrapper.php b/src/Core/GrpcRequestWrapper.php index d1c56349ce63..ddac1112ef39 100644 --- a/src/Core/GrpcRequestWrapper.php +++ b/src/Core/GrpcRequestWrapper.php @@ -131,11 +131,13 @@ public function send(callable $request, array $args, array $options = []) }); if (!isset($grpcOptions['retrySettings'])) { - $grpcOptions['retrySettings'] = new RetrySettings(null, null); - } - - if ($timeout && !array_key_exists('timeoutMs', $grpcOptions)) { - $grpcOptions['timeoutMs'] = $timeout * 1000; + $retrySettings = [ + 'retriesEnabled' => false + ]; + if ($timeout) { + $retrySettings['noRetriesRpcTimeoutMillis'] = $timeout * 1000; + } + $grpcOptions['retrySettings'] = $retrySettings; } $optionalArgs = &$args[count($args) - 1]; diff --git a/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php b/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php index e3fb6df64c17..ee0fc733829b 100644 --- a/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php +++ b/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php @@ -30,14 +30,15 @@ namespace Google\Cloud\Dlp\V2beta1\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Privacy\Dlp\V2beta1\ContentItem; use Google\Privacy\Dlp\V2beta1\CreateInspectOperationRequest; use Google\Privacy\Dlp\V2beta1\DlpServiceGrpcClient; @@ -91,8 +92,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -108,11 +109,6 @@ class DlpServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -124,6 +120,9 @@ class DlpServiceGapicClient const CODEGEN_VERSION = '0.0.5'; private static $resultNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $dlpServiceStub; @@ -132,6 +131,50 @@ class DlpServiceGapicClient private $descriptors; private $operationsClient; + private static function getResultNameTemplate() + { + if (self::$resultNameTemplate == null) { + self::$resultNameTemplate = new PathTemplate('inspect/results/{result}'); + } + + return self::$resultNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'result' => self::getResultNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + + private static function getLongRunningDescriptors() + { + return [ + 'createInspectOperation' => [ + 'operationReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationResult', + 'metadataReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationMetadata', + ], + ]; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a result resource. @@ -141,7 +184,7 @@ class DlpServiceGapicClient * @return string The formatted result resource. * @experimental */ - public static function formatResultName($result) + public static function resultName($result) { return self::getResultNameTemplate()->render([ 'result' => $result, @@ -149,47 +192,44 @@ public static function formatResultName($result) } /** - * Parses the result from the given fully-qualified path which - * represents a result resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - result: inspect/results/{result}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @param string $resultName The fully-qualified result resource. + * @return array An associative array from name component IDs to component values. * - * @return string The extracted result value. + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseResultFromResultName($resultName) + public static function parseName($formattedName, $template = null) { - return self::getResultNameTemplate()->match($resultName)['result']; - } + $templateMap = self::getPathTemplateMap(); - private static function getResultNameTemplate() - { - if (self::$resultNameTemplate == null) { - self::$resultNameTemplate = new PathTemplate('inspect/results/{result}'); - } - - return self::$resultNameTemplate; - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - private static function getLongRunningDescriptors() - { - return [ - 'createInspectOperation' => [ - 'operationReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationResult', - 'metadataReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationMetadata', - ], - ]; - } + return $templateMap[$template]->match($formattedName); + } - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -254,15 +294,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the DLP API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -275,9 +320,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/dlp_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -285,8 +330,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -312,15 +357,13 @@ public function __construct($options = []) $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/dlp_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.privacy.dlp.v2beta1.DlpService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -373,12 +416,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Privacy\Dlp\V2beta1\InspectContentResponse @@ -392,9 +434,13 @@ public function inspectContent($inspectConfig, $items, $optionalArgs = []) $request->setInspectConfig($inspectConfig); $request->setItems($items); - $mergedSettings = $this->defaultCallSettings['inspectContent']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['inspectContent']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->dlpServiceStub, 'InspectContent', @@ -451,12 +497,11 @@ public function inspectContent($inspectConfig, $items, $optionalArgs = []) * * @type ImageRedactionConfig[] $imageRedactionConfigs * The configuration for specifying what content to redact from images. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Privacy\Dlp\V2beta1\RedactContentResponse @@ -474,9 +519,13 @@ public function redactContent($inspectConfig, $items, $replaceConfigs, $optional $request->setImageRedactionConfigs($optionalArgs['imageRedactionConfigs']); } - $mergedSettings = $this->defaultCallSettings['redactContent']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['redactContent']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->dlpServiceStub, 'RedactContent', @@ -566,12 +615,11 @@ public function redactContent($inspectConfig, $items, $replaceConfigs, $optional * * @type OperationConfig $operationConfig * Additional configuration settings for long running operations. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -589,9 +637,13 @@ public function createInspectOperation($inspectConfig, $storageConfig, $outputCo $request->setOperationConfig($optionalArgs['operationConfig']); } - $mergedSettings = $this->defaultCallSettings['createInspectOperation']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createInspectOperation']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->dlpServiceStub, 'CreateInspectOperation', @@ -612,7 +664,7 @@ public function createInspectOperation($inspectConfig, $storageConfig, $outputCo * ``` * try { * $dlpServiceClient = new DlpServiceClient(); - * $formattedName = DlpServiceClient::formatResultName("[RESULT]"); + * $formattedName = $dlpServiceClient->resultName("[RESULT]"); * $response = $dlpServiceClient->listInspectFindings($formattedName); * } finally { * $dlpServiceClient->close(); @@ -640,12 +692,11 @@ public function createInspectOperation($inspectConfig, $storageConfig, $outputCo *
  • likelihood=VERY_LIKELY *
  • likelihood=VERY_LIKELY,LIKELY *
  • info_type=EMAIL_ADDRESS,likelihood=VERY_LIKELY,LIKELY - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Privacy\Dlp\V2beta1\ListInspectFindingsResponse @@ -667,9 +718,13 @@ public function listInspectFindings($name, $optionalArgs = []) $request->setFilter($optionalArgs['filter']); } - $mergedSettings = $this->defaultCallSettings['listInspectFindings']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listInspectFindings']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->dlpServiceStub, 'ListInspectFindings', @@ -705,12 +760,11 @@ public function listInspectFindings($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Privacy\Dlp\V2beta1\ListInfoTypesResponse @@ -724,9 +778,13 @@ public function listInfoTypes($category, $languageCode, $optionalArgs = []) $request->setCategory($category); $request->setLanguageCode($languageCode); - $mergedSettings = $this->defaultCallSettings['listInfoTypes']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listInfoTypes']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->dlpServiceStub, 'ListInfoTypes', @@ -760,12 +818,11 @@ public function listInfoTypes($category, $languageCode, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Privacy\Dlp\V2beta1\ListRootCategoriesResponse @@ -778,9 +835,13 @@ public function listRootCategories($languageCode, $optionalArgs = []) $request = new ListRootCategoriesRequest(); $request->setLanguageCode($languageCode); - $mergedSettings = $this->defaultCallSettings['listRootCategories']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listRootCategories']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->dlpServiceStub, 'ListRootCategories', diff --git a/src/Dlp/composer.json b/src/Dlp/composer.json index 2517284eeac5..9ca671c40c2e 100644 --- a/src/Dlp/composer.json +++ b/src/Dlp/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "ext-grpc": "*", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "extra": { "component": { diff --git a/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php index a024985cdbc5..191a4091a666 100644 --- a/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php +++ b/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php @@ -30,6 +30,7 @@ namespace Google\Cloud\ErrorReporting\V1beta1\Gapic; +use Google\Cloud\Version; use Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup; use Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroupServiceGrpcClient; use Google\Devtools\Clouderrorreporting\V1beta1\GetGroupRequest; @@ -37,9 +38,9 @@ use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; /** * Service Description: Service for retrieving and updating individual error groups. @@ -54,7 +55,7 @@ * ``` * try { * $errorGroupServiceClient = new ErrorGroupServiceClient(); - * $formattedGroupName = ErrorGroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $formattedGroupName = $errorGroupServiceClient->groupName("[PROJECT]", "[GROUP]"); * $response = $errorGroupServiceClient->getGroup($formattedGroupName); * } finally { * $errorGroupServiceClient->close(); @@ -63,8 +64,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -80,11 +81,6 @@ class ErrorGroupServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -96,6 +92,9 @@ class ErrorGroupServiceGapicClient const CODEGEN_VERSION = '0.0.5'; private static $groupNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $errorGroupServiceStub; @@ -103,6 +102,40 @@ class ErrorGroupServiceGapicClient private $defaultCallSettings; private $descriptors; + private static function getGroupNameTemplate() + { + if (self::$groupNameTemplate == null) { + self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); + } + + return self::$groupNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'group' => self::getGroupNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a group resource. @@ -113,7 +146,7 @@ class ErrorGroupServiceGapicClient * @return string The formatted group resource. * @experimental */ - public static function formatGroupName($project, $group) + public static function groupName($project, $group) { return self::getGroupNameTemplate()->render([ 'project' => $project, @@ -122,51 +155,44 @@ public static function formatGroupName($project, $group) } /** - * Parses the project from the given fully-qualified path which - * represents a group resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - group: projects/{project}/groups/{group}. * - * @param string $groupName The fully-qualified group resource. + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromGroupName($groupName) - { - return self::getGroupNameTemplate()->match($groupName)['project']; - } - - /** - * Parses the group from the given fully-qualified path which - * represents a group resource. + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @param string $groupName The fully-qualified group resource. + * @return array An associative array from name component IDs to component values. * - * @return string The extracted group value. + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseGroupFromGroupName($groupName) + public static function parseName($formattedName, $template = null) { - return self::getGroupNameTemplate()->match($groupName)['group']; - } + $templateMap = self::getPathTemplateMap(); - private static function getGroupNameTemplate() - { - if (self::$groupNameTemplate == null) { - self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - return self::$groupNameTemplate; - } + return $templateMap[$template]->match($formattedName); + } - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -193,15 +219,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Error Reporting API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -214,9 +245,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/error_group_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -234,15 +265,13 @@ public function __construct($options = []) 'updateGroup' => $defaultDescriptors, ]; - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/error_group_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -269,7 +298,7 @@ public function __construct($options = []) * ``` * try { * $errorGroupServiceClient = new ErrorGroupServiceClient(); - * $formattedGroupName = ErrorGroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $formattedGroupName = $errorGroupServiceClient->groupName("[PROJECT]", "[GROUP]"); * $response = $errorGroupServiceClient->getGroup($formattedGroupName); * } finally { * $errorGroupServiceClient->close(); @@ -287,12 +316,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup @@ -305,9 +333,13 @@ public function getGroup($groupName, $optionalArgs = []) $request = new GetGroupRequest(); $request->setGroupName($groupName); - $mergedSettings = $this->defaultCallSettings['getGroup']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getGroup']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->errorGroupServiceStub, 'GetGroup', @@ -340,12 +372,11 @@ public function getGroup($groupName, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup @@ -358,9 +389,13 @@ public function updateGroup($group, $optionalArgs = []) $request = new UpdateGroupRequest(); $request->setGroup($group); - $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateGroup']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->errorGroupServiceStub, 'UpdateGroup', diff --git a/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php index 40ea53b5eec9..f42d6c076b8e 100644 --- a/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php +++ b/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php @@ -30,6 +30,7 @@ namespace Google\Cloud\ErrorReporting\V1beta1\Gapic; +use Google\Cloud\Version; use Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsRequest; use Google\Devtools\Clouderrorreporting\V1beta1\ErrorStatsServiceGrpcClient; use Google\Devtools\Clouderrorreporting\V1beta1\ListEventsRequest; @@ -39,10 +40,10 @@ use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Protobuf\Duration; use Google\Protobuf\Timestamp; @@ -60,7 +61,7 @@ * ``` * try { * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $formattedProjectName = $errorStatsServiceClient->projectName("[PROJECT]"); * $timeRange = new QueryTimeRange(); * // Iterate through all elements * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange); @@ -82,8 +83,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -99,11 +100,6 @@ class ErrorStatsServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -115,6 +111,9 @@ class ErrorStatsServiceGapicClient const CODEGEN_VERSION = '0.0.5'; private static $projectNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $errorStatsServiceStub; @@ -122,36 +121,6 @@ class ErrorStatsServiceGapicClient private $defaultCallSettings; private $descriptors; - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - private static function getProjectNameTemplate() { if (self::$projectNameTemplate == null) { @@ -161,6 +130,16 @@ private static function getProjectNameTemplate() return self::$projectNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listGroupStatsPageStreamingDescriptor = @@ -192,13 +171,73 @@ private static function getPageStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function projectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } + } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -225,15 +264,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Error Reporting API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -246,9 +290,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/error_stats_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -271,15 +315,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/error_stats_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -306,7 +348,7 @@ public function __construct($options = []) * ``` * try { * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $formattedProjectName = $errorStatsServiceClient->projectName("[PROJECT]"); * $timeRange = new QueryTimeRange(); * // Iterate through all elements * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange); @@ -371,12 +413,11 @@ public function __construct($options = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -414,9 +455,13 @@ public function listGroupStats($projectName, $timeRange, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listGroupStats']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listGroupStats']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->errorStatsServiceStub, 'ListGroupStats', @@ -437,7 +482,7 @@ public function listGroupStats($projectName, $timeRange, $optionalArgs = []) * ``` * try { * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $formattedProjectName = $errorStatsServiceClient->projectName("[PROJECT]"); * $groupId = ""; * // Iterate through all elements * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId); @@ -483,12 +528,11 @@ public function listGroupStats($projectName, $timeRange, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -514,9 +558,13 @@ public function listEvents($projectName, $groupId, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listEvents']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listEvents']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->errorStatsServiceStub, 'ListEvents', @@ -537,7 +585,7 @@ public function listEvents($projectName, $groupId, $optionalArgs = []) * ``` * try { * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $formattedProjectName = $errorStatsServiceClient->projectName("[PROJECT]"); * $response = $errorStatsServiceClient->deleteEvents($formattedProjectName); * } finally { * $errorStatsServiceClient->close(); @@ -552,12 +600,11 @@ public function listEvents($projectName, $groupId, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsResponse @@ -570,9 +617,13 @@ public function deleteEvents($projectName, $optionalArgs = []) $request = new DeleteEventsRequest(); $request->setProjectName($projectName); - $mergedSettings = $this->defaultCallSettings['deleteEvents']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteEvents']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->errorStatsServiceStub, 'DeleteEvents', diff --git a/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php index 6872418f026b..871d95617f8b 100644 --- a/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php +++ b/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php @@ -30,15 +30,16 @@ namespace Google\Cloud\ErrorReporting\V1beta1\Gapic; +use Google\Cloud\Version; use Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventRequest; use Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorsServiceGrpcClient; use Google\Devtools\Clouderrorreporting\V1beta1\ReportedErrorEvent; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; /** * Service Description: An API for reporting error events. @@ -53,7 +54,7 @@ * ``` * try { * $reportErrorsServiceClient = new ReportErrorsServiceClient(); - * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); + * $formattedProjectName = $reportErrorsServiceClient->projectName("[PROJECT]"); * $event = new ReportedErrorEvent(); * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); * } finally { @@ -63,8 +64,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -80,11 +81,6 @@ class ReportErrorsServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -96,6 +92,9 @@ class ReportErrorsServiceGapicClient const CODEGEN_VERSION = '0.0.5'; private static $projectNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $reportErrorsServiceStub; @@ -103,6 +102,40 @@ class ReportErrorsServiceGapicClient private $defaultCallSettings; private $descriptors; + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a project resource. @@ -112,7 +145,7 @@ class ReportErrorsServiceGapicClient * @return string The formatted project resource. * @experimental */ - public static function formatProjectName($project) + public static function projectName($project) { return self::getProjectNameTemplate()->render([ 'project' => $project, @@ -120,37 +153,44 @@ public static function formatProjectName($project) } /** - * Parses the project from the given fully-qualified path which - * represents a project resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. * - * @param string $projectName The fully-qualified project resource. + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @return string The extracted project value. + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseProjectFromProjectName($projectName) + public static function parseName($formattedName, $template = null) { - return self::getProjectNameTemplate()->match($projectName)['project']; - } + $templateMap = self::getPathTemplateMap(); - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - return self::$projectNameTemplate; - } + return $templateMap[$template]->match($formattedName); + } - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -177,15 +217,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Error Reporting API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -198,9 +243,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/report_errors_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -217,15 +262,13 @@ public function __construct($options = []) 'reportErrorEvent' => $defaultDescriptors, ]; - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/report_errors_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -259,7 +302,7 @@ public function __construct($options = []) * ``` * try { * $reportErrorsServiceClient = new ReportErrorsServiceClient(); - * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); + * $formattedProjectName = $reportErrorsServiceClient->projectName("[PROJECT]"); * $event = new ReportedErrorEvent(); * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); * } finally { @@ -275,12 +318,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventResponse @@ -294,9 +336,13 @@ public function reportErrorEvent($projectName, $event, $optionalArgs = []) $request->setProjectName($projectName); $request->setEvent($event); - $mergedSettings = $this->defaultCallSettings['reportErrorEvent']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['reportErrorEvent']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->reportErrorsServiceStub, 'ReportErrorEvent', diff --git a/src/ErrorReporting/composer.json b/src/ErrorReporting/composer.json index 49995e53f507..79f9eb403124 100644 --- a/src/ErrorReporting/composer.json +++ b/src/ErrorReporting/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "ext-grpc": "*", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "extra": { "component": { diff --git a/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php b/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php index 64833f1ccf7b..cac6b6dca6f6 100644 --- a/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php +++ b/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php @@ -40,10 +40,10 @@ use Google\Cloud\Language\V1beta2\Document; use Google\Cloud\Language\V1beta2\EncodingType; use Google\Cloud\Language\V1beta2\LanguageServiceGrpcClient; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; /** @@ -81,11 +81,6 @@ class LanguageServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -96,6 +91,9 @@ class LanguageServiceGapicClient */ const CODEGEN_VERSION = '0.0.5'; + private static $gapicVersion; + private static $gapicVersionLoaded = false; + protected $grpcCredentialsHelper; protected $languageServiceStub; private $scopes; @@ -104,13 +102,16 @@ class LanguageServiceGapicClient private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; } /** @@ -137,15 +138,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Natural Language API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -158,9 +164,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/language_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -182,15 +188,13 @@ public function __construct($options = []) 'annotateText' => $defaultDescriptors, ]; - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/language_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.cloud.language.v1beta2.LanguageService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -232,12 +236,11 @@ public function __construct($options = []) * The encoding type used by the API to calculate sentence offsets for the * sentence sentiment. * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Language\V1beta2\AnalyzeSentimentResponse @@ -253,9 +256,13 @@ public function analyzeSentiment($document, $optionalArgs = []) $request->setEncodingType($optionalArgs['encodingType']); } - $mergedSettings = $this->defaultCallSettings['analyzeSentiment']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['analyzeSentiment']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->languageServiceStub, 'AnalyzeSentiment', @@ -292,12 +299,11 @@ public function analyzeSentiment($document, $optionalArgs = []) * @type int $encodingType * The encoding type used by the API to calculate offsets. * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitiesResponse @@ -313,9 +319,13 @@ public function analyzeEntities($document, $optionalArgs = []) $request->setEncodingType($optionalArgs['encodingType']); } - $mergedSettings = $this->defaultCallSettings['analyzeEntities']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['analyzeEntities']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->languageServiceStub, 'AnalyzeEntities', @@ -351,12 +361,11 @@ public function analyzeEntities($document, $optionalArgs = []) * @type int $encodingType * The encoding type used by the API to calculate offsets. * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitySentimentResponse @@ -372,9 +381,13 @@ public function analyzeEntitySentiment($document, $optionalArgs = []) $request->setEncodingType($optionalArgs['encodingType']); } - $mergedSettings = $this->defaultCallSettings['analyzeEntitySentiment']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['analyzeEntitySentiment']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->languageServiceStub, 'AnalyzeEntitySentiment', @@ -411,12 +424,11 @@ public function analyzeEntitySentiment($document, $optionalArgs = []) * @type int $encodingType * The encoding type used by the API to calculate offsets. * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Language\V1beta2\AnalyzeSyntaxResponse @@ -432,9 +444,13 @@ public function analyzeSyntax($document, $optionalArgs = []) $request->setEncodingType($optionalArgs['encodingType']); } - $mergedSettings = $this->defaultCallSettings['analyzeSyntax']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['analyzeSyntax']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->languageServiceStub, 'AnalyzeSyntax', @@ -466,12 +482,11 @@ public function analyzeSyntax($document, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Language\V1beta2\ClassifyTextResponse @@ -484,9 +499,13 @@ public function classifyText($document, $optionalArgs = []) $request = new ClassifyTextRequest(); $request->setDocument($document); - $mergedSettings = $this->defaultCallSettings['classifyText']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['classifyText']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->languageServiceStub, 'ClassifyText', @@ -524,12 +543,11 @@ public function classifyText($document, $optionalArgs = []) * @type int $encodingType * The encoding type used by the API to calculate offsets. * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Language\V1beta2\AnnotateTextResponse @@ -546,9 +564,13 @@ public function annotateText($document, $features, $optionalArgs = []) $request->setEncodingType($optionalArgs['encodingType']); } - $mergedSettings = $this->defaultCallSettings['annotateText']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['annotateText']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->languageServiceStub, 'AnnotateText', diff --git a/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php b/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php index 9098371ccea9..a8c746994d56 100644 --- a/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php +++ b/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php @@ -30,13 +30,14 @@ namespace Google\Cloud\Logging\V2\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Logging\V2\ConfigServiceV2GrpcClient; use Google\Logging\V2\CreateSinkRequest; use Google\Logging\V2\DeleteSinkRequest; @@ -59,7 +60,7 @@ * ``` * try { * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $configServiceV2Client->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -80,8 +81,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -97,11 +98,6 @@ class ConfigServiceV2GapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -114,6 +110,9 @@ class ConfigServiceV2GapicClient private static $projectNameTemplate; private static $sinkNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $configServiceV2Stub; @@ -121,6 +120,68 @@ class ConfigServiceV2GapicClient private $defaultCallSettings; private $descriptors; + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getSinkNameTemplate() + { + if (self::$sinkNameTemplate == null) { + self::$sinkNameTemplate = new PathTemplate('projects/{project}/sinks/{sink}'); + } + + return self::$sinkNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'sink' => self::getSinkNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + private static function getPageStreamingDescriptors() + { + $listSinksPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSinks', + ]); + + $pageStreamingDescriptors = [ + 'listSinks' => $listSinksPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a project resource. @@ -130,7 +191,7 @@ class ConfigServiceV2GapicClient * @return string The formatted project resource. * @experimental */ - public static function formatProjectName($project) + public static function projectName($project) { return self::getProjectNameTemplate()->render([ 'project' => $project, @@ -147,7 +208,7 @@ public static function formatProjectName($project) * @return string The formatted sink resource. * @experimental */ - public static function formatSinkName($project, $sink) + public static function sinkName($project, $sink) { return self::getSinkNameTemplate()->render([ 'project' => $project, @@ -156,93 +217,45 @@ public static function formatSinkName($project, $sink) } /** - * Parses the project from the given fully-qualified path which - * represents a project resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - sink: projects/{project}/sinks/{sink}. * - * @param string $projectName The fully-qualified project resource. + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a sink resource. + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @param string $sinkName The fully-qualified sink resource. + * @return array An associative array from name component IDs to component values. * - * @return string The extracted project value. + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseProjectFromSinkName($sinkName) + public static function parseName($formattedName, $template = null) { - return self::getSinkNameTemplate()->match($sinkName)['project']; - } + $templateMap = self::getPathTemplateMap(); - /** - * Parses the sink from the given fully-qualified path which - * represents a sink resource. - * - * @param string $sinkName The fully-qualified sink resource. - * - * @return string The extracted sink value. - * @experimental - */ - public static function parseSinkFromSinkName($sinkName) - { - return self::getSinkNameTemplate()->match($sinkName)['sink']; - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); + return $templateMap[$template]->match($formattedName); } - return self::$projectNameTemplate; - } - - private static function getSinkNameTemplate() - { - if (self::$sinkNameTemplate == null) { - self::$sinkNameTemplate = new PathTemplate('projects/{project}/sinks/{sink}'); - } - - return self::$sinkNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listSinksPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSinks', - ]); - - $pageStreamingDescriptors = [ - 'listSinks' => $listSinksPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -269,15 +282,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Logging API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -294,9 +312,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/logging.write', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/config_service_v2_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -321,15 +339,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/config_service_v2_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.logging.v2.ConfigServiceV2', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -356,7 +372,7 @@ public function __construct($options = []) * ``` * try { * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $configServiceV2Client->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -393,12 +409,11 @@ public function __construct($options = []) * The maximum number of resources contained in the underlying API * response. The API may return fewer values in a page, even if * there are additional values to be retrieved. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -417,9 +432,13 @@ public function listSinks($parent, $optionalArgs = []) $request->setPageSize($optionalArgs['pageSize']); } - $mergedSettings = $this->defaultCallSettings['listSinks']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listSinks']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->configServiceV2Stub, 'ListSinks', @@ -440,7 +459,7 @@ public function listSinks($parent, $optionalArgs = []) * ``` * try { * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $formattedSinkName = $configServiceV2Client->sinkName("[PROJECT]", "[SINK]"); * $response = $configServiceV2Client->getSink($formattedSinkName); * } finally { * $configServiceV2Client->close(); @@ -458,12 +477,11 @@ public function listSinks($parent, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\LogSink @@ -476,9 +494,13 @@ public function getSink($sinkName, $optionalArgs = []) $request = new GetSinkRequest(); $request->setSinkName($sinkName); - $mergedSettings = $this->defaultCallSettings['getSink']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getSink']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->configServiceV2Stub, 'GetSink', @@ -503,7 +525,7 @@ public function getSink($sinkName, $optionalArgs = []) * ``` * try { * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $configServiceV2Client->projectName("[PROJECT]"); * $sink = new LogSink(); * $response = $configServiceV2Client->createSink($formattedParent, $sink); * } finally { @@ -536,12 +558,11 @@ public function getSink($sinkName, $optionalArgs = []) * resource such as an organization, then the value of `writer_identity` will * be a unique service account used only for exports from the new sink. For * more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink]. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\LogSink @@ -558,9 +579,13 @@ public function createSink($parent, $sink, $optionalArgs = []) $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); } - $mergedSettings = $this->defaultCallSettings['createSink']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createSink']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->configServiceV2Stub, 'CreateSink', @@ -585,7 +610,7 @@ public function createSink($parent, $sink, $optionalArgs = []) * ``` * try { * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $formattedSinkName = $configServiceV2Client->sinkName("[PROJECT]", "[SINK]"); * $sink = new LogSink(); * $response = $configServiceV2Client->updateSink($formattedSinkName, $sink); * } finally { @@ -620,12 +645,11 @@ public function createSink($parent, $sink, $optionalArgs = []) * `writer_identity` is changed to a unique service account. * + It is an error if the old value is true and the new value is * set to false or defaulted to false. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\LogSink @@ -642,9 +666,13 @@ public function updateSink($sinkName, $sink, $optionalArgs = []) $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); } - $mergedSettings = $this->defaultCallSettings['updateSink']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateSink']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->configServiceV2Stub, 'UpdateSink', @@ -666,7 +694,7 @@ public function updateSink($sinkName, $sink, $optionalArgs = []) * ``` * try { * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $formattedSinkName = $configServiceV2Client->sinkName("[PROJECT]", "[SINK]"); * $configServiceV2Client->deleteSink($formattedSinkName); * } finally { * $configServiceV2Client->close(); @@ -685,12 +713,11 @@ public function updateSink($sinkName, $sink, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -701,9 +728,13 @@ public function deleteSink($sinkName, $optionalArgs = []) $request = new DeleteSinkRequest(); $request->setSinkName($sinkName); - $mergedSettings = $this->defaultCallSettings['deleteSink']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteSink']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->configServiceV2Stub, 'DeleteSink', diff --git a/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php b/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php index 96beea321d21..afcc13483bdc 100644 --- a/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php +++ b/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php @@ -31,13 +31,14 @@ namespace Google\Cloud\Logging\V2\Gapic; use Google\Api\MonitoredResource; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Logging\V2\DeleteLogRequest; use Google\Logging\V2\ListLogEntriesRequest; use Google\Logging\V2\ListLogsRequest; @@ -59,7 +60,7 @@ * ``` * try { * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); + * $formattedLogName = $loggingServiceV2Client->logName("[PROJECT]", "[LOG]"); * $loggingServiceV2Client->deleteLog($formattedLogName); * } finally { * $loggingServiceV2Client->close(); @@ -68,8 +69,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -85,11 +86,6 @@ class LoggingServiceV2GapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -102,6 +98,9 @@ class LoggingServiceV2GapicClient private static $projectNameTemplate; private static $logNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $loggingServiceV2Stub; @@ -109,82 +108,6 @@ class LoggingServiceV2GapicClient private $defaultCallSettings; private $descriptors; - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a log resource. - * - * @param string $project - * @param string $log - * - * @return string The formatted log resource. - * @experimental - */ - public static function formatLogName($project, $log) - { - return self::getLogNameTemplate()->render([ - 'project' => $project, - 'log' => $log, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a log resource. - * - * @param string $logName The fully-qualified log resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromLogName($logName) - { - return self::getLogNameTemplate()->match($logName)['project']; - } - - /** - * Parses the log from the given fully-qualified path which - * represents a log resource. - * - * @param string $logName The fully-qualified log resource. - * - * @return string The extracted log value. - * @experimental - */ - public static function parseLogFromLogName($logName) - { - return self::getLogNameTemplate()->match($logName)['log']; - } - private static function getProjectNameTemplate() { if (self::$projectNameTemplate == null) { @@ -203,6 +126,17 @@ private static function getLogNameTemplate() return self::$logNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'log' => self::getLogNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listLogEntriesPageStreamingDescriptor = @@ -244,13 +178,92 @@ private static function getPageStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function projectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a log resource. + * + * @param string $project + * @param string $log + * + * @return string The formatted log resource. + * @experimental + */ + public static function logName($project, $log) + { + return self::getLogNameTemplate()->render([ + 'project' => $project, + 'log' => $log, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - log: projects/{project}/logs/{log}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -277,15 +290,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Logging API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -302,9 +320,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/logging.write', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/logging_service_v2_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -329,15 +347,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/logging_service_v2_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.logging.v2.LoggingServiceV2', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -367,7 +383,7 @@ public function __construct($options = []) * ``` * try { * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); + * $formattedLogName = $loggingServiceV2Client->logName("[PROJECT]", "[LOG]"); * $loggingServiceV2Client->deleteLog($formattedLogName); * } finally { * $loggingServiceV2Client->close(); @@ -389,12 +405,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -405,9 +420,13 @@ public function deleteLog($logName, $optionalArgs = []) $request = new DeleteLogRequest(); $request->setLogName($logName); - $mergedSettings = $this->defaultCallSettings['deleteLog']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteLog']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->loggingServiceV2Stub, 'DeleteLog', @@ -499,12 +518,11 @@ public function deleteLog($logName, $optionalArgs = []) * entry is not written, then the response status is the error associated * with one of the failed entries and the response includes error details * keyed by the entries' zero-based index in the `entries.write` method. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\WriteLogEntriesResponse @@ -529,9 +547,13 @@ public function writeLogEntries($entries, $optionalArgs = []) $request->setPartialSuccess($optionalArgs['partialSuccess']); } - $mergedSettings = $this->defaultCallSettings['writeLogEntries']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['writeLogEntries']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->loggingServiceV2Stub, 'WriteLogEntries', @@ -615,12 +637,11 @@ public function writeLogEntries($entries, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -648,9 +669,13 @@ public function listLogEntries($resourceNames, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listLogEntries']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listLogEntries']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->loggingServiceV2Stub, 'ListLogEntries', @@ -703,12 +728,11 @@ public function listLogEntries($resourceNames, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -726,9 +750,13 @@ public function listMonitoredResourceDescriptors($optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->loggingServiceV2Stub, 'ListMonitoredResourceDescriptors', @@ -750,7 +778,7 @@ public function listMonitoredResourceDescriptors($optionalArgs = []) * ``` * try { * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedParent = LoggingServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $loggingServiceV2Client->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -787,12 +815,11 @@ public function listMonitoredResourceDescriptors($optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -811,9 +838,13 @@ public function listLogs($parent, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listLogs']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listLogs']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->loggingServiceV2Stub, 'ListLogs', diff --git a/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php b/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php index f60547ee7165..f1ccaf9d5667 100644 --- a/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php +++ b/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php @@ -30,13 +30,14 @@ namespace Google\Cloud\Logging\V2\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Logging\V2\CreateLogMetricRequest; use Google\Logging\V2\DeleteLogMetricRequest; use Google\Logging\V2\GetLogMetricRequest; @@ -58,7 +59,7 @@ * ``` * try { * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $metricsServiceV2Client->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -79,8 +80,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -96,11 +97,6 @@ class MetricsServiceV2GapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -113,6 +109,9 @@ class MetricsServiceV2GapicClient private static $projectNameTemplate; private static $metricNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $metricsServiceV2Stub; @@ -120,6 +119,68 @@ class MetricsServiceV2GapicClient private $defaultCallSettings; private $descriptors; + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getMetricNameTemplate() + { + if (self::$metricNameTemplate == null) { + self::$metricNameTemplate = new PathTemplate('projects/{project}/metrics/{metric}'); + } + + return self::$metricNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'metric' => self::getMetricNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + private static function getPageStreamingDescriptors() + { + $listLogMetricsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getMetrics', + ]); + + $pageStreamingDescriptors = [ + 'listLogMetrics' => $listLogMetricsPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a project resource. @@ -129,7 +190,7 @@ class MetricsServiceV2GapicClient * @return string The formatted project resource. * @experimental */ - public static function formatProjectName($project) + public static function projectName($project) { return self::getProjectNameTemplate()->render([ 'project' => $project, @@ -146,7 +207,7 @@ public static function formatProjectName($project) * @return string The formatted metric resource. * @experimental */ - public static function formatMetricName($project, $metric) + public static function metricName($project, $metric) { return self::getMetricNameTemplate()->render([ 'project' => $project, @@ -155,93 +216,45 @@ public static function formatMetricName($project, $metric) } /** - * Parses the project from the given fully-qualified path which - * represents a project resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - metric: projects/{project}/metrics/{metric}. * - * @param string $projectName The fully-qualified project resource. + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a metric resource. + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @param string $metricName The fully-qualified metric resource. + * @return array An associative array from name component IDs to component values. * - * @return string The extracted project value. + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseProjectFromMetricName($metricName) + public static function parseName($formattedName, $template = null) { - return self::getMetricNameTemplate()->match($metricName)['project']; - } + $templateMap = self::getPathTemplateMap(); - /** - * Parses the metric from the given fully-qualified path which - * represents a metric resource. - * - * @param string $metricName The fully-qualified metric resource. - * - * @return string The extracted metric value. - * @experimental - */ - public static function parseMetricFromMetricName($metricName) - { - return self::getMetricNameTemplate()->match($metricName)['metric']; - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); + return $templateMap[$template]->match($formattedName); } - return self::$projectNameTemplate; - } - - private static function getMetricNameTemplate() - { - if (self::$metricNameTemplate == null) { - self::$metricNameTemplate = new PathTemplate('projects/{project}/metrics/{metric}'); - } - - return self::$metricNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listLogMetricsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getMetrics', - ]); - - $pageStreamingDescriptors = [ - 'listLogMetrics' => $listLogMetricsPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -268,15 +281,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Logging API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -293,9 +311,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/logging.write', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/metrics_service_v2_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -320,15 +338,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/metrics_service_v2_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.logging.v2.MetricsServiceV2', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -355,7 +371,7 @@ public function __construct($options = []) * ``` * try { * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $metricsServiceV2Client->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -389,12 +405,11 @@ public function __construct($options = []) * The maximum number of resources contained in the underlying API * response. The API may return fewer values in a page, even if * there are additional values to be retrieved. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -413,9 +428,13 @@ public function listLogMetrics($parent, $optionalArgs = []) $request->setPageSize($optionalArgs['pageSize']); } - $mergedSettings = $this->defaultCallSettings['listLogMetrics']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listLogMetrics']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricsServiceV2Stub, 'ListLogMetrics', @@ -436,7 +455,7 @@ public function listLogMetrics($parent, $optionalArgs = []) * ``` * try { * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $formattedMetricName = $metricsServiceV2Client->metricName("[PROJECT]", "[METRIC]"); * $response = $metricsServiceV2Client->getLogMetric($formattedMetricName); * } finally { * $metricsServiceV2Client->close(); @@ -449,12 +468,11 @@ public function listLogMetrics($parent, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\LogMetric @@ -467,9 +485,13 @@ public function getLogMetric($metricName, $optionalArgs = []) $request = new GetLogMetricRequest(); $request->setMetricName($metricName); - $mergedSettings = $this->defaultCallSettings['getLogMetric']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getLogMetric']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricsServiceV2Stub, 'GetLogMetric', @@ -490,7 +512,7 @@ public function getLogMetric($metricName, $optionalArgs = []) * ``` * try { * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * $formattedParent = $metricsServiceV2Client->projectName("[PROJECT]"); * $metric = new LogMetric(); * $response = $metricsServiceV2Client->createLogMetric($formattedParent, $metric); * } finally { @@ -508,12 +530,11 @@ public function getLogMetric($metricName, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\LogMetric @@ -527,9 +548,13 @@ public function createLogMetric($parent, $metric, $optionalArgs = []) $request->setParent($parent); $request->setMetric($metric); - $mergedSettings = $this->defaultCallSettings['createLogMetric']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createLogMetric']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricsServiceV2Stub, 'CreateLogMetric', @@ -550,7 +575,7 @@ public function createLogMetric($parent, $metric, $optionalArgs = []) * ``` * try { * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $formattedMetricName = $metricsServiceV2Client->metricName("[PROJECT]", "[METRIC]"); * $metric = new LogMetric(); * $response = $metricsServiceV2Client->updateLogMetric($formattedMetricName, $metric); * } finally { @@ -569,12 +594,11 @@ public function createLogMetric($parent, $metric, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Logging\V2\LogMetric @@ -588,9 +612,13 @@ public function updateLogMetric($metricName, $metric, $optionalArgs = []) $request->setMetricName($metricName); $request->setMetric($metric); - $mergedSettings = $this->defaultCallSettings['updateLogMetric']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateLogMetric']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricsServiceV2Stub, 'UpdateLogMetric', @@ -611,7 +639,7 @@ public function updateLogMetric($metricName, $metric, $optionalArgs = []) * ``` * try { * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $formattedMetricName = $metricsServiceV2Client->metricName("[PROJECT]", "[METRIC]"); * $metricsServiceV2Client->deleteLogMetric($formattedMetricName); * } finally { * $metricsServiceV2Client->close(); @@ -624,12 +652,11 @@ public function updateLogMetric($metricName, $metric, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -640,9 +667,13 @@ public function deleteLogMetric($metricName, $optionalArgs = []) $request = new DeleteLogMetricRequest(); $request->setMetricName($metricName); - $mergedSettings = $this->defaultCallSettings['deleteLogMetric']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteLogMetric']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricsServiceV2Stub, 'DeleteLogMetric', diff --git a/src/Logging/composer.json b/src/Logging/composer.json index 45139b96972e..765a167bb149 100644 --- a/src/Logging/composer.json +++ b/src/Logging/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "google/cloud-core": "^1.0", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "extra": { "component": { diff --git a/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php b/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php index 05475a813410..df660abb679b 100644 --- a/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php +++ b/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php @@ -30,13 +30,14 @@ namespace Google\Cloud\Monitoring\V3\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Monitoring\V3\CreateGroupRequest; use Google\Monitoring\V3\DeleteGroupRequest; use Google\Monitoring\V3\GetGroupRequest; @@ -71,7 +72,7 @@ * ``` * try { * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $groupServiceClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $groupServiceClient->listGroups($formattedName); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -92,8 +93,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -109,11 +110,6 @@ class GroupServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -126,6 +122,9 @@ class GroupServiceGapicClient private static $projectNameTemplate; private static $groupNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $groupServiceStub; @@ -133,82 +132,6 @@ class GroupServiceGapicClient private $defaultCallSettings; private $descriptors; - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a group resource. - * - * @param string $project - * @param string $group - * - * @return string The formatted group resource. - * @experimental - */ - public static function formatGroupName($project, $group) - { - return self::getGroupNameTemplate()->render([ - 'project' => $project, - 'group' => $group, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a group resource. - * - * @param string $groupName The fully-qualified group resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromGroupName($groupName) - { - return self::getGroupNameTemplate()->match($groupName)['project']; - } - - /** - * Parses the group from the given fully-qualified path which - * represents a group resource. - * - * @param string $groupName The fully-qualified group resource. - * - * @return string The extracted group value. - * @experimental - */ - public static function parseGroupFromGroupName($groupName) - { - return self::getGroupNameTemplate()->match($groupName)['group']; - } - private static function getProjectNameTemplate() { if (self::$projectNameTemplate == null) { @@ -227,6 +150,17 @@ private static function getGroupNameTemplate() return self::$groupNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'group' => self::getGroupNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listGroupsPageStreamingDescriptor = @@ -258,13 +192,92 @@ private static function getPageStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function projectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a group resource. + * + * @param string $project + * @param string $group + * + * @return string The formatted group resource. + * @experimental + */ + public static function groupName($project, $group) + { + return self::getGroupNameTemplate()->render([ + 'project' => $project, + 'group' => $group, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - group: projects/{project}/groups/{group}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } + } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -291,15 +304,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Monitoring API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -315,9 +333,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/monitoring.write', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/group_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -343,15 +361,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/group_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.monitoring.v3.GroupService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -378,7 +394,7 @@ public function __construct($options = []) * ``` * try { * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $groupServiceClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $groupServiceClient->listGroups($formattedName); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -426,12 +442,11 @@ public function __construct($options = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -459,9 +474,13 @@ public function listGroups($name, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listGroups']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listGroups']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->groupServiceStub, 'ListGroups', @@ -482,7 +501,7 @@ public function listGroups($name, $optionalArgs = []) * ``` * try { * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $formattedName = $groupServiceClient->groupName("[PROJECT]", "[GROUP]"); * $response = $groupServiceClient->getGroup($formattedName); * } finally { * $groupServiceClient->close(); @@ -494,12 +513,11 @@ public function listGroups($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Monitoring\V3\Group @@ -512,9 +530,13 @@ public function getGroup($name, $optionalArgs = []) $request = new GetGroupRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getGroup']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getGroup']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->groupServiceStub, 'GetGroup', @@ -535,7 +557,7 @@ public function getGroup($name, $optionalArgs = []) * ``` * try { * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $groupServiceClient->projectName("[PROJECT]"); * $group = new Group(); * $response = $groupServiceClient->createGroup($formattedName, $group); * } finally { @@ -552,12 +574,11 @@ public function getGroup($name, $optionalArgs = []) * * @type bool $validateOnly * If true, validate this request but do not create the group. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Monitoring\V3\Group @@ -574,9 +595,13 @@ public function createGroup($name, $group, $optionalArgs = []) $request->setValidateOnly($optionalArgs['validateOnly']); } - $mergedSettings = $this->defaultCallSettings['createGroup']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createGroup']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->groupServiceStub, 'CreateGroup', @@ -612,12 +637,11 @@ public function createGroup($name, $group, $optionalArgs = []) * * @type bool $validateOnly * If true, validate this request but do not update the existing group. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Monitoring\V3\Group @@ -633,9 +657,13 @@ public function updateGroup($group, $optionalArgs = []) $request->setValidateOnly($optionalArgs['validateOnly']); } - $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateGroup']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->groupServiceStub, 'UpdateGroup', @@ -656,7 +684,7 @@ public function updateGroup($group, $optionalArgs = []) * ``` * try { * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $formattedName = $groupServiceClient->groupName("[PROJECT]", "[GROUP]"); * $groupServiceClient->deleteGroup($formattedName); * } finally { * $groupServiceClient->close(); @@ -668,12 +696,11 @@ public function updateGroup($group, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -684,9 +711,13 @@ public function deleteGroup($name, $optionalArgs = []) $request = new DeleteGroupRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['deleteGroup']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteGroup']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->groupServiceStub, 'DeleteGroup', @@ -707,7 +738,7 @@ public function deleteGroup($name, $optionalArgs = []) * ``` * try { * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $formattedName = $groupServiceClient->groupName("[PROJECT]", "[GROUP]"); * // Iterate through all elements * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -753,12 +784,11 @@ public function deleteGroup($name, $optionalArgs = []) * members that were part of the group during the specified interval are * included in the response. If no interval is provided then the group * membership over the last minute is returned. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -783,9 +813,13 @@ public function listGroupMembers($name, $optionalArgs = []) $request->setInterval($optionalArgs['interval']); } - $mergedSettings = $this->defaultCallSettings['listGroupMembers']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listGroupMembers']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->groupServiceStub, 'ListGroupMembers', diff --git a/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php b/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php index b50d330297fa..c0f82ad77984 100644 --- a/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php +++ b/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php @@ -31,13 +31,14 @@ namespace Google\Cloud\Monitoring\V3\Gapic; use Google\Api\MetricDescriptor; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Monitoring\V3\Aggregation; use Google\Monitoring\V3\CreateMetricDescriptorRequest; use Google\Monitoring\V3\CreateTimeSeriesRequest; @@ -66,7 +67,7 @@ * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $metricServiceClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -87,8 +88,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -104,11 +105,6 @@ class MetricServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -122,6 +118,9 @@ class MetricServiceGapicClient private static $projectNameTemplate; private static $metricDescriptorNameTemplate; private static $monitoredResourceDescriptorNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $metricServiceStub; @@ -129,128 +128,6 @@ class MetricServiceGapicClient private $defaultCallSettings; private $descriptors; - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a metric_descriptor resource. - * - * @param string $project - * @param string $metricDescriptor - * - * @return string The formatted metric_descriptor resource. - * @experimental - */ - public static function formatMetricDescriptorName($project, $metricDescriptor) - { - return self::getMetricDescriptorNameTemplate()->render([ - 'project' => $project, - 'metric_descriptor' => $metricDescriptor, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a monitored_resource_descriptor resource. - * - * @param string $project - * @param string $monitoredResourceDescriptor - * - * @return string The formatted monitored_resource_descriptor resource. - * @experimental - */ - public static function formatMonitoredResourceDescriptorName($project, $monitoredResourceDescriptor) - { - return self::getMonitoredResourceDescriptorNameTemplate()->render([ - 'project' => $project, - 'monitored_resource_descriptor' => $monitoredResourceDescriptor, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a metric_descriptor resource. - * - * @param string $metricDescriptorName The fully-qualified metric_descriptor resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromMetricDescriptorName($metricDescriptorName) - { - return self::getMetricDescriptorNameTemplate()->match($metricDescriptorName)['project']; - } - - /** - * Parses the metric_descriptor from the given fully-qualified path which - * represents a metric_descriptor resource. - * - * @param string $metricDescriptorName The fully-qualified metric_descriptor resource. - * - * @return string The extracted metric_descriptor value. - * @experimental - */ - public static function parseMetricDescriptorFromMetricDescriptorName($metricDescriptorName) - { - return self::getMetricDescriptorNameTemplate()->match($metricDescriptorName)['metric_descriptor']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a monitored_resource_descriptor resource. - * - * @param string $monitoredResourceDescriptorName The fully-qualified monitored_resource_descriptor resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromMonitoredResourceDescriptorName($monitoredResourceDescriptorName) - { - return self::getMonitoredResourceDescriptorNameTemplate()->match($monitoredResourceDescriptorName)['project']; - } - - /** - * Parses the monitored_resource_descriptor from the given fully-qualified path which - * represents a monitored_resource_descriptor resource. - * - * @param string $monitoredResourceDescriptorName The fully-qualified monitored_resource_descriptor resource. - * - * @return string The extracted monitored_resource_descriptor value. - * @experimental - */ - public static function parseMonitoredResourceDescriptorFromMonitoredResourceDescriptorName($monitoredResourceDescriptorName) - { - return self::getMonitoredResourceDescriptorNameTemplate()->match($monitoredResourceDescriptorName)['monitored_resource_descriptor']; - } - private static function getProjectNameTemplate() { if (self::$projectNameTemplate == null) { @@ -278,6 +155,18 @@ private static function getMonitoredResourceDescriptorNameTemplate() return self::$monitoredResourceDescriptorNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'metricDescriptor' => self::getMetricDescriptorNameTemplate(), + 'monitoredResourceDescriptor' => self::getMonitoredResourceDescriptorNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listMonitoredResourceDescriptorsPageStreamingDescriptor = @@ -319,13 +208,111 @@ private static function getPageStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function projectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a metric_descriptor resource. + * + * @param string $project + * @param string $metricDescriptor + * + * @return string The formatted metric_descriptor resource. + * @experimental + */ + public static function metricDescriptorName($project, $metricDescriptor) + { + return self::getMetricDescriptorNameTemplate()->render([ + 'project' => $project, + 'metric_descriptor' => $metricDescriptor, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a monitored_resource_descriptor resource. + * + * @param string $project + * @param string $monitoredResourceDescriptor + * + * @return string The formatted monitored_resource_descriptor resource. + * @experimental + */ + public static function monitoredResourceDescriptorName($project, $monitoredResourceDescriptor) + { + return self::getMonitoredResourceDescriptorNameTemplate()->render([ + 'project' => $project, + 'monitored_resource_descriptor' => $monitoredResourceDescriptor, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - metricDescriptor: projects/{project}/metricDescriptors/{metric_descriptor=**} + * - monitoredResourceDescriptor: projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -352,15 +339,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Stackdriver Monitoring API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -376,9 +368,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/monitoring.write', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/metric_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -406,15 +398,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/metric_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.monitoring.v3.MetricService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -441,7 +431,7 @@ public function __construct($options = []) * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $metricServiceClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -482,12 +472,11 @@ public function __construct($options = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -509,9 +498,13 @@ public function listMonitoredResourceDescriptors($name, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'ListMonitoredResourceDescriptors', @@ -532,7 +525,7 @@ public function listMonitoredResourceDescriptors($name, $optionalArgs = []) * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); + * $formattedName = $metricServiceClient->monitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); * $response = $metricServiceClient->getMonitoredResourceDescriptor($formattedName); * } finally { * $metricServiceClient->close(); @@ -546,12 +539,11 @@ public function listMonitoredResourceDescriptors($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Api\MonitoredResourceDescriptor @@ -564,9 +556,13 @@ public function getMonitoredResourceDescriptor($name, $optionalArgs = []) $request = new GetMonitoredResourceDescriptorRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getMonitoredResourceDescriptor']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getMonitoredResourceDescriptor']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'GetMonitoredResourceDescriptor', @@ -587,7 +583,7 @@ public function getMonitoredResourceDescriptor($name, $optionalArgs = []) * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $metricServiceClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -629,12 +625,11 @@ public function getMonitoredResourceDescriptor($name, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -656,9 +651,13 @@ public function listMetricDescriptors($name, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listMetricDescriptors']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listMetricDescriptors']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'ListMetricDescriptors', @@ -679,7 +678,7 @@ public function listMetricDescriptors($name, $optionalArgs = []) * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); + * $formattedName = $metricServiceClient->metricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); * $response = $metricServiceClient->getMetricDescriptor($formattedName); * } finally { * $metricServiceClient->close(); @@ -693,12 +692,11 @@ public function listMetricDescriptors($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Api\MetricDescriptor @@ -711,9 +709,13 @@ public function getMetricDescriptor($name, $optionalArgs = []) $request = new GetMetricDescriptorRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getMetricDescriptor']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'GetMetricDescriptor', @@ -736,7 +738,7 @@ public function getMetricDescriptor($name, $optionalArgs = []) * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $metricServiceClient->projectName("[PROJECT]"); * $metricDescriptor = new MetricDescriptor(); * $response = $metricServiceClient->createMetricDescriptor($formattedName, $metricDescriptor); * } finally { @@ -751,12 +753,11 @@ public function getMetricDescriptor($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Api\MetricDescriptor @@ -770,9 +771,13 @@ public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = $request->setName($name); $request->setMetricDescriptor($metricDescriptor); - $mergedSettings = $this->defaultCallSettings['createMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createMetricDescriptor']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'CreateMetricDescriptor', @@ -794,7 +799,7 @@ public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); + * $formattedName = $metricServiceClient->metricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); * $metricServiceClient->deleteMetricDescriptor($formattedName); * } finally { * $metricServiceClient->close(); @@ -808,12 +813,11 @@ public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -824,9 +828,13 @@ public function deleteMetricDescriptor($name, $optionalArgs = []) $request = new DeleteMetricDescriptorRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['deleteMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteMetricDescriptor']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'DeleteMetricDescriptor', @@ -847,7 +855,7 @@ public function deleteMetricDescriptor($name, $optionalArgs = []) * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $metricServiceClient->projectName("[PROJECT]"); * $filter = ""; * $interval = new TimeInterval(); * $view = TimeSeriesView::FULL; @@ -903,12 +911,11 @@ public function deleteMetricDescriptor($name, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -936,9 +943,13 @@ public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listTimeSeries']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listTimeSeries']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'ListTimeSeries', @@ -962,7 +973,7 @@ public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = * ``` * try { * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $formattedName = $metricServiceClient->projectName("[PROJECT]"); * $timeSeries = []; * $metricServiceClient->createTimeSeries($formattedName, $timeSeries); * } finally { @@ -980,12 +991,11 @@ public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -997,9 +1007,13 @@ public function createTimeSeries($name, $timeSeries, $optionalArgs = []) $request->setName($name); $request->setTimeSeries($timeSeries); - $mergedSettings = $this->defaultCallSettings['createTimeSeries']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createTimeSeries']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->metricServiceStub, 'CreateTimeSeries', diff --git a/src/Monitoring/composer.json b/src/Monitoring/composer.json index af65f34c43ae..a645c0c3d240 100644 --- a/src/Monitoring/composer.json +++ b/src/Monitoring/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "ext-grpc": "*", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "extra": { "component": { diff --git a/src/PubSub/V1/Gapic/PublisherGapicClient.php b/src/PubSub/V1/Gapic/PublisherGapicClient.php index 5add6e38230c..7a079f9540e1 100644 --- a/src/PubSub/V1/Gapic/PublisherGapicClient.php +++ b/src/PubSub/V1/Gapic/PublisherGapicClient.php @@ -30,18 +30,20 @@ namespace Google\Cloud\PubSub\V1\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Iam\V1\GetIamPolicyRequest; use Google\Iam\V1\IAMPolicyGrpcClient; use Google\Iam\V1\Policy; use Google\Iam\V1\SetIamPolicyRequest; use Google\Iam\V1\TestIamPermissionsRequest; +use Google\Protobuf\FieldMask; use Google\Pubsub\V1\DeleteTopicRequest; use Google\Pubsub\V1\GetTopicRequest; use Google\Pubsub\V1\ListTopicSubscriptionsRequest; @@ -50,6 +52,7 @@ use Google\Pubsub\V1\PublisherGrpcClient; use Google\Pubsub\V1\PubsubMessage; use Google\Pubsub\V1\Topic; +use Google\Pubsub\V1\UpdateTopicRequest; /** * Service Description: The service that an application uses to manipulate topics, and to send @@ -65,7 +68,7 @@ * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedName = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $response = $publisherClient->createTopic($formattedName); * } finally { * $publisherClient->close(); @@ -74,8 +77,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -91,11 +94,6 @@ class PublisherGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -108,6 +106,9 @@ class PublisherGapicClient private static $projectNameTemplate; private static $topicNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $iamPolicyStub; @@ -116,82 +117,6 @@ class PublisherGapicClient private $defaultCallSettings; private $descriptors; - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a topic resource. - * - * @param string $project - * @param string $topic - * - * @return string The formatted topic resource. - * @experimental - */ - public static function formatTopicName($project, $topic) - { - return self::getTopicNameTemplate()->render([ - 'project' => $project, - 'topic' => $topic, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['project']; - } - - /** - * Parses the topic from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted topic value. - * @experimental - */ - public static function parseTopicFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['topic']; - } - private static function getProjectNameTemplate() { if (self::$projectNameTemplate == null) { @@ -210,6 +135,17 @@ private static function getTopicNameTemplate() return self::$topicNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'topic' => self::getTopicNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listTopicsPageStreamingDescriptor = @@ -241,13 +177,92 @@ private static function getPageStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function projectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a topic resource. + * + * @param string $project + * @param string $topic + * + * @return string The formatted topic resource. + * @experimental + */ + public static function topicName($project, $topic) + { + return self::getTopicNameTemplate()->render([ + 'project' => $project, + 'topic' => $topic, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - topic: projects/{project}/topics/{topic}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } + } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -274,15 +289,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Pub/Sub API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -296,9 +316,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/pubsub', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/publisher_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -313,6 +333,7 @@ public function __construct($options = []) $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; $this->descriptors = [ 'createTopic' => $defaultDescriptors, + 'updateTopic' => $defaultDescriptors, 'publish' => $defaultDescriptors, 'getTopic' => $defaultDescriptors, 'listTopics' => $defaultDescriptors, @@ -327,15 +348,13 @@ public function __construct($options = []) $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/publisher_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.pubsub.v1.Publisher', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -369,7 +388,7 @@ public function __construct($options = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedName = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $response = $publisherClient->createTopic($formattedName); * } finally { * $publisherClient->close(); @@ -387,12 +406,11 @@ public function __construct($options = []) * * @type array $labels * User labels. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\Topic @@ -408,9 +426,13 @@ public function createTopic($name, $optionalArgs = []) $request->setLabels($optionalArgs['labels']); } - $mergedSettings = $this->defaultCallSettings['createTopic']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createTopic']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->publisherStub, 'CreateTopic', @@ -424,6 +446,70 @@ public function createTopic($name, $optionalArgs = []) ['call_credentials_callback' => $this->createCredentialsCallback()]); } + /** + * Updates an existing topic. Note that certain properties of a topic are not + * modifiable. Options settings follow the style guide: + * NOTE: The style guide requires body: "topic" instead of body: "*". + * Keeping the latter for internal consistency in V1, however it should be + * corrected in V2. See + * https://cloud.google.com/apis/design/standard_methods#update for details. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $topic = new Topic(); + * $updateMask = new FieldMask(); + * $response = $publisherClient->updateTopic($topic, $updateMask); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param Topic $topic The topic to update. + * @param FieldMask $updateMask Indicates which fields in the provided topic to update. + * Must be specified and non-empty. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. + * } + * + * @return \Google\Pubsub\V1\Topic + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateTopic($topic, $updateMask, $optionalArgs = []) + { + $request = new UpdateTopicRequest(); + $request->setTopic($topic); + $request->setUpdateMask($updateMask); + + $defaultCallSettings = $this->defaultCallSettings['updateTopic']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'UpdateTopic', + $mergedSettings, + $this->descriptors['updateTopic'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + /** * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic * does not exist. The message payload must not be empty; it must contain @@ -433,7 +519,7 @@ public function createTopic($name, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedTopic = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $data = ""; * $messagesElement = new PubsubMessage(); * $messagesElement->setData($data); @@ -450,12 +536,11 @@ public function createTopic($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\PublishResponse @@ -469,9 +554,13 @@ public function publish($topic, $messages, $optionalArgs = []) $request->setTopic($topic); $request->setMessages($messages); - $mergedSettings = $this->defaultCallSettings['publish']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['publish']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->publisherStub, 'Publish', @@ -492,7 +581,7 @@ public function publish($topic, $messages, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedTopic = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $response = $publisherClient->getTopic($formattedTopic); * } finally { * $publisherClient->close(); @@ -504,12 +593,11 @@ public function publish($topic, $messages, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\Topic @@ -522,9 +610,13 @@ public function getTopic($topic, $optionalArgs = []) $request = new GetTopicRequest(); $request->setTopic($topic); - $mergedSettings = $this->defaultCallSettings['getTopic']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getTopic']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->publisherStub, 'GetTopic', @@ -545,7 +637,7 @@ public function getTopic($topic, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedProject = PublisherClient::formatProjectName("[PROJECT]"); + * $formattedProject = $publisherClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $publisherClient->listTopics($formattedProject); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -578,12 +670,11 @@ public function getTopic($topic, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -602,9 +693,13 @@ public function listTopics($project, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listTopics']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listTopics']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->publisherStub, 'ListTopics', @@ -625,7 +720,7 @@ public function listTopics($project, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedTopic = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * // Iterate through all elements * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -658,12 +753,11 @@ public function listTopics($project, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -682,9 +776,13 @@ public function listTopicSubscriptions($topic, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listTopicSubscriptions']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listTopicSubscriptions']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->publisherStub, 'ListTopicSubscriptions', @@ -709,7 +807,7 @@ public function listTopicSubscriptions($topic, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedTopic = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $publisherClient->deleteTopic($formattedTopic); * } finally { * $publisherClient->close(); @@ -721,12 +819,11 @@ public function listTopicSubscriptions($topic, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -737,9 +834,13 @@ public function deleteTopic($topic, $optionalArgs = []) $request = new DeleteTopicRequest(); $request->setTopic($topic); - $mergedSettings = $this->defaultCallSettings['deleteTopic']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteTopic']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->publisherStub, 'DeleteTopic', @@ -761,7 +862,7 @@ public function deleteTopic($topic, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedResource = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $policy = new Policy(); * $response = $publisherClient->setIamPolicy($formattedResource, $policy); * } finally { @@ -779,12 +880,11 @@ public function deleteTopic($topic, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -798,9 +898,13 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) $request->setResource($resource); $request->setPolicy($policy); - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['setIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->iamPolicyStub, 'SetIamPolicy', @@ -823,7 +927,7 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedResource = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $response = $publisherClient->getIamPolicy($formattedResource); * } finally { * $publisherClient->close(); @@ -836,12 +940,11 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -854,9 +957,13 @@ public function getIamPolicy($resource, $optionalArgs = []) $request = new GetIamPolicyRequest(); $request->setResource($resource); - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->iamPolicyStub, 'GetIamPolicy', @@ -879,7 +986,7 @@ public function getIamPolicy($resource, $optionalArgs = []) * ``` * try { * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedResource = $publisherClient->topicName("[PROJECT]", "[TOPIC]"); * $permissions = []; * $response = $publisherClient->testIamPermissions($formattedResource, $permissions); * } finally { @@ -897,12 +1004,11 @@ public function getIamPolicy($resource, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\TestIamPermissionsResponse @@ -916,9 +1022,13 @@ public function testIamPermissions($resource, $permissions, $optionalArgs = []) $request->setResource($resource); $request->setPermissions($permissions); - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['testIamPermissions']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->iamPolicyStub, 'TestIamPermissions', diff --git a/src/PubSub/V1/Gapic/SubscriberGapicClient.php b/src/PubSub/V1/Gapic/SubscriberGapicClient.php index 52181dca86ea..4570c1ada8da 100644 --- a/src/PubSub/V1/Gapic/SubscriberGapicClient.php +++ b/src/PubSub/V1/Gapic/SubscriberGapicClient.php @@ -30,13 +30,14 @@ namespace Google\Cloud\PubSub\V1\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Iam\V1\GetIamPolicyRequest; use Google\Iam\V1\IAMPolicyGrpcClient; use Google\Iam\V1\Policy; @@ -57,9 +58,11 @@ use Google\Pubsub\V1\PullRequest; use Google\Pubsub\V1\PushConfig; use Google\Pubsub\V1\SeekRequest; +use Google\Pubsub\V1\Snapshot; use Google\Pubsub\V1\StreamingPullRequest; use Google\Pubsub\V1\SubscriberGrpcClient; use Google\Pubsub\V1\Subscription; +use Google\Pubsub\V1\UpdateSnapshotRequest; use Google\Pubsub\V1\UpdateSubscriptionRequest; /** @@ -76,8 +79,8 @@ * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedName = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedTopic = $subscriberClient->topicName("[PROJECT]", "[TOPIC]"); * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); * } finally { * $subscriberClient->close(); @@ -86,8 +89,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -103,11 +106,6 @@ class SubscriberGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -122,6 +120,9 @@ class SubscriberGapicClient private static $snapshotNameTemplate; private static $subscriptionNameTemplate; private static $topicNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $iamPolicyStub; @@ -130,6 +131,108 @@ class SubscriberGapicClient private $defaultCallSettings; private $descriptors; + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getSnapshotNameTemplate() + { + if (self::$snapshotNameTemplate == null) { + self::$snapshotNameTemplate = new PathTemplate('projects/{project}/snapshots/{snapshot}'); + } + + return self::$snapshotNameTemplate; + } + + private static function getSubscriptionNameTemplate() + { + if (self::$subscriptionNameTemplate == null) { + self::$subscriptionNameTemplate = new PathTemplate('projects/{project}/subscriptions/{subscription}'); + } + + return self::$subscriptionNameTemplate; + } + + private static function getTopicNameTemplate() + { + if (self::$topicNameTemplate == null) { + self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); + } + + return self::$topicNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'snapshot' => self::getSnapshotNameTemplate(), + 'subscription' => self::getSubscriptionNameTemplate(), + 'topic' => self::getTopicNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + private static function getPageStreamingDescriptors() + { + $listSubscriptionsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSubscriptions', + ]); + $listSnapshotsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSnapshots', + ]); + + $pageStreamingDescriptors = [ + 'listSubscriptions' => $listSubscriptionsPageStreamingDescriptor, + 'listSnapshots' => $listSnapshotsPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGrpcStreamingDescriptors() + { + return [ + 'streamingPull' => [ + 'grpcStreamingType' => 'BidiStreaming', + 'resourcesGetMethod' => 'getReceivedMessages', + ], + ]; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a project resource. @@ -139,7 +242,7 @@ class SubscriberGapicClient * @return string The formatted project resource. * @experimental */ - public static function formatProjectName($project) + public static function projectName($project) { return self::getProjectNameTemplate()->render([ 'project' => $project, @@ -156,7 +259,7 @@ public static function formatProjectName($project) * @return string The formatted snapshot resource. * @experimental */ - public static function formatSnapshotName($project, $snapshot) + public static function snapshotName($project, $snapshot) { return self::getSnapshotNameTemplate()->render([ 'project' => $project, @@ -174,7 +277,7 @@ public static function formatSnapshotName($project, $snapshot) * @return string The formatted subscription resource. * @experimental */ - public static function formatSubscriptionName($project, $subscription) + public static function subscriptionName($project, $subscription) { return self::getSubscriptionNameTemplate()->render([ 'project' => $project, @@ -192,7 +295,7 @@ public static function formatSubscriptionName($project, $subscription) * @return string The formatted topic resource. * @experimental */ - public static function formatTopicName($project, $topic) + public static function topicName($project, $topic) { return self::getTopicNameTemplate()->render([ 'project' => $project, @@ -201,187 +304,47 @@ public static function formatTopicName($project, $topic) } /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a snapshot resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - snapshot: projects/{project}/snapshots/{snapshot} + * - subscription: projects/{project}/subscriptions/{subscription} + * - topic: projects/{project}/topics/{topic}. * - * @param string $snapshotName The fully-qualified snapshot resource. + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSnapshotName($snapshotName) - { - return self::getSnapshotNameTemplate()->match($snapshotName)['project']; - } - - /** - * Parses the snapshot from the given fully-qualified path which - * represents a snapshot resource. + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @param string $snapshotName The fully-qualified snapshot resource. + * @return array An associative array from name component IDs to component values. * - * @return string The extracted snapshot value. + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseSnapshotFromSnapshotName($snapshotName) + public static function parseName($formattedName, $template = null) { - return self::getSnapshotNameTemplate()->match($snapshotName)['snapshot']; - } + $templateMap = self::getPathTemplateMap(); - /** - * Parses the project from the given fully-qualified path which - * represents a subscription resource. - * - * @param string $subscriptionName The fully-qualified subscription resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSubscriptionName($subscriptionName) - { - return self::getSubscriptionNameTemplate()->match($subscriptionName)['project']; - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - /** - * Parses the subscription from the given fully-qualified path which - * represents a subscription resource. - * - * @param string $subscriptionName The fully-qualified subscription resource. - * - * @return string The extracted subscription value. - * @experimental - */ - public static function parseSubscriptionFromSubscriptionName($subscriptionName) - { - return self::getSubscriptionNameTemplate()->match($subscriptionName)['subscription']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['project']; - } - - /** - * Parses the topic from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted topic value. - * @experimental - */ - public static function parseTopicFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['topic']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); + return $templateMap[$template]->match($formattedName); } - return self::$projectNameTemplate; - } - - private static function getSnapshotNameTemplate() - { - if (self::$snapshotNameTemplate == null) { - self::$snapshotNameTemplate = new PathTemplate('projects/{project}/snapshots/{snapshot}'); - } - - return self::$snapshotNameTemplate; - } - - private static function getSubscriptionNameTemplate() - { - if (self::$subscriptionNameTemplate == null) { - self::$subscriptionNameTemplate = new PathTemplate('projects/{project}/subscriptions/{subscription}'); - } - - return self::$subscriptionNameTemplate; - } - - private static function getTopicNameTemplate() - { - if (self::$topicNameTemplate == null) { - self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); - } - - return self::$topicNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listSubscriptionsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSubscriptions', - ]); - $listSnapshotsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSnapshots', - ]); - - $pageStreamingDescriptors = [ - 'listSubscriptions' => $listSubscriptionsPageStreamingDescriptor, - 'listSnapshots' => $listSnapshotsPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGrpcStreamingDescriptors() - { - return [ - 'streamingPull' => [ - 'grpcStreamingType' => 'BidiStreaming', - 'resourcesGetMethod' => 'getReceivedMessages', - ], - ]; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -408,15 +371,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Pub/Sub API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -430,9 +398,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/pubsub', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/subscriber_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -458,6 +426,7 @@ public function __construct($options = []) 'modifyPushConfig' => $defaultDescriptors, 'listSnapshots' => $defaultDescriptors, 'createSnapshot' => $defaultDescriptors, + 'updateSnapshot' => $defaultDescriptors, 'deleteSnapshot' => $defaultDescriptors, 'seek' => $defaultDescriptors, 'setIamPolicy' => $defaultDescriptors, @@ -473,15 +442,13 @@ public function __construct($options = []) $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/subscriber_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.pubsub.v1.Subscriber', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -524,8 +491,8 @@ public function __construct($options = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $formattedName = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedTopic = $subscriberClient->topicName("[PROJECT]", "[TOPIC]"); * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); * } finally { * $subscriberClient->close(); @@ -583,12 +550,11 @@ public function __construct($options = []) * minutes. * @type array $labels * User labels. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\Subscription @@ -617,9 +583,13 @@ public function createSubscription($name, $topic, $optionalArgs = []) $request->setLabels($optionalArgs['labels']); } - $mergedSettings = $this->defaultCallSettings['createSubscription']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createSubscription']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'CreateSubscription', @@ -640,7 +610,7 @@ public function createSubscription($name, $topic, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $response = $subscriberClient->getSubscription($formattedSubscription); * } finally { * $subscriberClient->close(); @@ -652,12 +622,11 @@ public function createSubscription($name, $topic, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\Subscription @@ -670,9 +639,13 @@ public function getSubscription($subscription, $optionalArgs = []) $request = new GetSubscriptionRequest(); $request->setSubscription($subscription); - $mergedSettings = $this->defaultCallSettings['getSubscription']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getSubscription']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'GetSubscription', @@ -712,12 +685,11 @@ public function getSubscription($subscription, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\Subscription @@ -731,9 +703,13 @@ public function updateSubscription($subscription, $updateMask, $optionalArgs = [ $request->setSubscription($subscription); $request->setUpdateMask($updateMask); - $mergedSettings = $this->defaultCallSettings['updateSubscription']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateSubscription']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'UpdateSubscription', @@ -754,7 +730,7 @@ public function updateSubscription($subscription, $updateMask, $optionalArgs = [ * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); + * $formattedProject = $subscriberClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -787,12 +763,11 @@ public function updateSubscription($subscription, $updateMask, $optionalArgs = [ * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -811,9 +786,13 @@ public function listSubscriptions($project, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listSubscriptions']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listSubscriptions']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'ListSubscriptions', @@ -838,7 +817,7 @@ public function listSubscriptions($project, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $subscriberClient->deleteSubscription($formattedSubscription); * } finally { * $subscriberClient->close(); @@ -850,12 +829,11 @@ public function listSubscriptions($project, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -866,9 +844,13 @@ public function deleteSubscription($subscription, $optionalArgs = []) $request = new DeleteSubscriptionRequest(); $request->setSubscription($subscription); - $mergedSettings = $this->defaultCallSettings['deleteSubscription']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteSubscription']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'DeleteSubscription', @@ -893,7 +875,7 @@ public function deleteSubscription($subscription, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $ackIds = []; * $ackDeadlineSeconds = 0; * $subscriberClient->modifyAckDeadline($formattedSubscription, $ackIds, $ackDeadlineSeconds); @@ -915,12 +897,11 @@ public function deleteSubscription($subscription, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -933,9 +914,13 @@ public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $ $request->setAckIds($ackIds); $request->setAckDeadlineSeconds($ackDeadlineSeconds); - $mergedSettings = $this->defaultCallSettings['modifyAckDeadline']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['modifyAckDeadline']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'ModifyAckDeadline', @@ -962,7 +947,7 @@ public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $ * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $ackIds = []; * $subscriberClient->acknowledge($formattedSubscription, $ackIds); * } finally { @@ -977,12 +962,11 @@ public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $ * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -994,9 +978,13 @@ public function acknowledge($subscription, $ackIds, $optionalArgs = []) $request->setSubscription($subscription); $request->setAckIds($ackIds); - $mergedSettings = $this->defaultCallSettings['acknowledge']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['acknowledge']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'Acknowledge', @@ -1020,7 +1008,7 @@ public function acknowledge($subscription, $ackIds, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $maxMessages = 0; * $response = $subscriberClient->pull($formattedSubscription, $maxMessages); * } finally { @@ -1042,12 +1030,11 @@ public function acknowledge($subscription, $ackIds, $optionalArgs = []) * least one message is available, rather than returning no messages. The * client may cancel the request if it does not wish to wait any longer for * the response. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\PullResponse @@ -1064,9 +1051,13 @@ public function pull($subscription, $maxMessages, $optionalArgs = []) $request->setReturnImmediately($optionalArgs['returnImmediately']); } - $mergedSettings = $this->defaultCallSettings['pull']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['pull']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'Pull', @@ -1098,7 +1089,7 @@ public function pull($subscription, $maxMessages, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $streamAckDeadlineSeconds = 0; * $request = new StreamingPullRequest(); * $request->setSubscription($formattedSubscription); @@ -1148,9 +1139,20 @@ public function pull($subscription, $maxMessages, $optionalArgs = []) */ public function streamingPull($optionalArgs = []) { - $mergedSettings = $this->defaultCallSettings['streamingPull']->merge( - new CallSettings($optionalArgs) - ); + if (array_key_exists('timeoutMillis', $optionalArgs)) { + $optionalArgs['retrySettings'] = [ + 'retriesEnabled' => false, + 'noRetriesRpcTimeoutMillis' => $optionalArgs['timeoutMillis'], + ]; + } + + $defaultCallSettings = $this->defaultCallSettings['streamingPull']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'StreamingPull', @@ -1176,7 +1178,7 @@ public function streamingPull($optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $pushConfig = new PushConfig(); * $subscriberClient->modifyPushConfig($formattedSubscription, $pushConfig); * } finally { @@ -1195,12 +1197,11 @@ public function streamingPull($optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -1212,9 +1213,13 @@ public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) $request->setSubscription($subscription); $request->setPushConfig($pushConfig); - $mergedSettings = $this->defaultCallSettings['modifyPushConfig']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['modifyPushConfig']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'ModifyPushConfig', @@ -1235,7 +1240,7 @@ public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); + * $formattedProject = $subscriberClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $subscriberClient->listSnapshots($formattedProject); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -1268,12 +1273,11 @@ public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -1292,9 +1296,13 @@ public function listSnapshots($project, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listSnapshots']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listSnapshots']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'ListSnapshots', @@ -1324,8 +1332,8 @@ public function listSnapshots($project, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedName = $subscriberClient->snapshotName("[PROJECT]", "[SNAPSHOT]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $response = $subscriberClient->createSnapshot($formattedName, $formattedSubscription); * } finally { * $subscriberClient->close(); @@ -1349,12 +1357,11 @@ public function listSnapshots($project, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\Snapshot @@ -1368,9 +1375,13 @@ public function createSnapshot($name, $subscription, $optionalArgs = []) $request->setName($name); $request->setSubscription($subscription); - $mergedSettings = $this->defaultCallSettings['createSnapshot']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createSnapshot']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'CreateSnapshot', @@ -1384,6 +1395,70 @@ public function createSnapshot($name, $subscription, $optionalArgs = []) ['call_credentials_callback' => $this->createCredentialsCallback()]); } + /** + * Updates an existing snapshot. Note that certain properties of a snapshot + * are not modifiable. + * NOTE: The style guide requires body: "snapshot" instead of body: "*". + * Keeping the latter for internal consistency in V1, however it should be + * corrected in V2. See + * https://cloud.google.com/apis/design/standard_methods#update for details. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $snapshot = new Snapshot(); + * $updateMask = new FieldMask(); + * $response = $subscriberClient->updateSnapshot($snapshot, $updateMask); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param Snapshot $snapshot The updated snpashot object. + * @param FieldMask $updateMask Indicates which fields in the provided snapshot to update. + * Must be specified and non-empty. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. + * } + * + * @return \Google\Pubsub\V1\Snapshot + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateSnapshot($snapshot, $updateMask, $optionalArgs = []) + { + $request = new UpdateSnapshotRequest(); + $request->setSnapshot($snapshot); + $request->setUpdateMask($updateMask); + + $defaultCallSettings = $this->defaultCallSettings['updateSnapshot']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'UpdateSnapshot', + $mergedSettings, + $this->descriptors['updateSnapshot'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + /** * Removes an existing snapshot. All messages retained in the snapshot * are immediately dropped. After a snapshot is deleted, a new one may be @@ -1394,7 +1469,7 @@ public function createSnapshot($name, $subscription, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSnapshot = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); + * $formattedSnapshot = $subscriberClient->snapshotName("[PROJECT]", "[SNAPSHOT]"); * $subscriberClient->deleteSnapshot($formattedSnapshot); * } finally { * $subscriberClient->close(); @@ -1406,12 +1481,11 @@ public function createSnapshot($name, $subscription, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -1422,9 +1496,13 @@ public function deleteSnapshot($snapshot, $optionalArgs = []) $request = new DeleteSnapshotRequest(); $request->setSnapshot($snapshot); - $mergedSettings = $this->defaultCallSettings['deleteSnapshot']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteSnapshot']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'DeleteSnapshot', @@ -1446,7 +1524,7 @@ public function deleteSnapshot($snapshot, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedSubscription = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $response = $subscriberClient->seek($formattedSubscription); * } finally { * $subscriberClient->close(); @@ -1473,12 +1551,11 @@ public function deleteSnapshot($snapshot, $optionalArgs = []) * The snapshot to seek to. The snapshot's topic must be the same as that of * the provided subscription. * Format is `projects/{project}/snapshots/{snap}`. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Pubsub\V1\SeekResponse @@ -1497,9 +1574,13 @@ public function seek($subscription, $optionalArgs = []) $request->setSnapshot($optionalArgs['snapshot']); } - $mergedSettings = $this->defaultCallSettings['seek']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['seek']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->subscriberStub, 'Seek', @@ -1521,7 +1602,7 @@ public function seek($subscription, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedResource = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $policy = new Policy(); * $response = $subscriberClient->setIamPolicy($formattedResource, $policy); * } finally { @@ -1539,12 +1620,11 @@ public function seek($subscription, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -1558,9 +1638,13 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) $request->setResource($resource); $request->setPolicy($policy); - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['setIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->iamPolicyStub, 'SetIamPolicy', @@ -1583,7 +1667,7 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedResource = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $response = $subscriberClient->getIamPolicy($formattedResource); * } finally { * $subscriberClient->close(); @@ -1596,12 +1680,11 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -1614,9 +1697,13 @@ public function getIamPolicy($resource, $optionalArgs = []) $request = new GetIamPolicyRequest(); $request->setResource($resource); - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->iamPolicyStub, 'GetIamPolicy', @@ -1639,7 +1726,7 @@ public function getIamPolicy($resource, $optionalArgs = []) * ``` * try { * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedResource = $subscriberClient->subscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * $permissions = []; * $response = $subscriberClient->testIamPermissions($formattedResource, $permissions); * } finally { @@ -1657,12 +1744,11 @@ public function getIamPolicy($resource, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\TestIamPermissionsResponse @@ -1676,9 +1762,13 @@ public function testIamPermissions($resource, $permissions, $optionalArgs = []) $request->setResource($resource); $request->setPermissions($permissions); - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['testIamPermissions']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->iamPolicyStub, 'TestIamPermissions', diff --git a/src/PubSub/V1/resources/publisher_client_config.json b/src/PubSub/V1/resources/publisher_client_config.json index 9fb679cbad27..b1e3be747fd0 100644 --- a/src/PubSub/V1/resources/publisher_client_config.json +++ b/src/PubSub/V1/resources/publisher_client_config.json @@ -43,6 +43,11 @@ "retry_codes_name": "idempotent", "retry_params_name": "default" }, + "UpdateTopic": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, "Publish": { "timeout_millis": 60000, "retry_codes_name": "one_plus_delivery", diff --git a/src/PubSub/V1/resources/subscriber_client_config.json b/src/PubSub/V1/resources/subscriber_client_config.json index 413a57aed9f2..37a5f16fe8f7 100644 --- a/src/PubSub/V1/resources/subscriber_client_config.json +++ b/src/PubSub/V1/resources/subscriber_client_config.json @@ -103,6 +103,11 @@ "retry_codes_name": "idempotent", "retry_params_name": "default" }, + "UpdateSnapshot": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, "DeleteSnapshot": { "timeout_millis": 60000, "retry_codes_name": "idempotent", diff --git a/src/PubSub/composer.json b/src/PubSub/composer.json index 2905183aceb6..141239d288f4 100644 --- a/src/PubSub/composer.json +++ b/src/PubSub/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "google/cloud-core": "^1.0", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "extra": { "component": { diff --git a/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php b/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php index 1faacf3af681..38c4f0603ea9 100644 --- a/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php +++ b/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php @@ -30,15 +30,16 @@ namespace Google\Cloud\Spanner\Admin\Database\V1\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Iam\V1\GetIamPolicyRequest; use Google\Iam\V1\Policy; use Google\Iam\V1\SetIamPolicyRequest; @@ -71,7 +72,7 @@ * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedParent = $databaseAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * // Iterate through all elements * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -92,8 +93,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -109,11 +110,6 @@ class DatabaseAdminGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -126,6 +122,9 @@ class DatabaseAdminGapicClient private static $instanceNameTemplate; private static $databaseNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $databaseAdminStub; @@ -134,114 +133,6 @@ class DatabaseAdminGapicClient private $descriptors; private $operationsClient; - /** - * Formats a string containing the fully-qualified path to represent - * a instance resource. - * - * @param string $project - * @param string $instance - * - * @return string The formatted instance resource. - * @experimental - */ - public static function formatInstanceName($project, $instance) - { - return self::getInstanceNameTemplate()->render([ - 'project' => $project, - 'instance' => $instance, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a database resource. - * - * @param string $project - * @param string $instance - * @param string $database - * - * @return string The formatted database resource. - * @experimental - */ - public static function formatDatabaseName($project, $instance, $database) - { - return self::getDatabaseNameTemplate()->render([ - 'project' => $project, - 'instance' => $instance, - 'database' => $database, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a instance resource. - * - * @param string $instanceName The fully-qualified instance resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromInstanceName($instanceName) - { - return self::getInstanceNameTemplate()->match($instanceName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a instance resource. - * - * @param string $instanceName The fully-qualified instance resource. - * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromInstanceName($instanceName) - { - return self::getInstanceNameTemplate()->match($instanceName)['instance']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['instance']; - } - - /** - * Parses the database from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted database value. - * @experimental - */ - public static function parseDatabaseFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['database']; - } - private static function getInstanceNameTemplate() { if (self::$instanceNameTemplate == null) { @@ -260,6 +151,17 @@ private static function getDatabaseNameTemplate() return self::$databaseNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'instance' => self::getInstanceNameTemplate(), + 'database' => self::getDatabaseNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listDatabasesPageStreamingDescriptor = @@ -295,13 +197,96 @@ private static function getLongRunningDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a instance resource. + * + * @param string $project + * @param string $instance + * + * @return string The formatted instance resource. + * @experimental + */ + public static function instanceName($project, $instance) + { + return self::getInstanceNameTemplate()->render([ + 'project' => $project, + 'instance' => $instance, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a database resource. + * + * @param string $project + * @param string $instance + * @param string $database + * + * @return string The formatted database resource. + * @experimental + */ + public static function databaseName($project, $instance, $database) + { + return self::getDatabaseNameTemplate()->render([ + 'project' => $project, + 'instance' => $instance, + 'database' => $database, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - instance: projects/{project}/instances/{instance} + * - database: projects/{project}/instances/{instance}/databases/{database}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } + } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -366,15 +351,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Cloud Spanner Database Admin API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -388,9 +378,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/spanner.admin', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/database_admin_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -398,8 +388,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -432,15 +422,13 @@ public function __construct($options = []) $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/database_admin_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.spanner.admin.database.v1.DatabaseAdmin', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -467,7 +455,7 @@ public function __construct($options = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedParent = $databaseAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * // Iterate through all elements * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -500,12 +488,11 @@ public function __construct($options = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -524,9 +511,13 @@ public function listDatabases($parent, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listDatabases']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listDatabases']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'ListDatabases', @@ -554,7 +545,7 @@ public function listDatabases($parent, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedParent = $databaseAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * $createStatement = ""; * $operationResponse = $databaseAdminClient->createDatabase($formattedParent, $createStatement); * $operationResponse->pollUntilComplete(); @@ -600,12 +591,11 @@ public function listDatabases($parent, $optionalArgs = []) * database. Statements can create tables, indexes, etc. These * statements execute atomically with the creation of the database: * if there is an error in any statement, the database is not created. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -622,9 +612,13 @@ public function createDatabase($parent, $createStatement, $optionalArgs = []) $request->setExtraStatements($optionalArgs['extraStatements']); } - $mergedSettings = $this->defaultCallSettings['createDatabase']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createDatabase']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'CreateDatabase', @@ -645,7 +639,7 @@ public function createDatabase($parent, $createStatement, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedName = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedName = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $response = $databaseAdminClient->getDatabase($formattedName); * } finally { * $databaseAdminClient->close(); @@ -657,12 +651,11 @@ public function createDatabase($parent, $createStatement, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\Admin\Database\V1\Database @@ -675,9 +668,13 @@ public function getDatabase($name, $optionalArgs = []) $request = new GetDatabaseRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getDatabase']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getDatabase']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'GetDatabase', @@ -704,7 +701,7 @@ public function getDatabase($name, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedDatabase = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $statements = []; * $operationResponse = $databaseAdminClient->updateDatabaseDdl($formattedDatabase, $statements); * $operationResponse->pollUntilComplete(); @@ -760,12 +757,11 @@ public function getDatabase($name, $optionalArgs = []) * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -782,9 +778,13 @@ public function updateDatabaseDdl($database, $statements, $optionalArgs = []) $request->setOperationId($optionalArgs['operationId']); } - $mergedSettings = $this->defaultCallSettings['updateDatabaseDdl']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateDatabaseDdl']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'UpdateDatabaseDdl', @@ -805,7 +805,7 @@ public function updateDatabaseDdl($database, $statements, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedDatabase = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $databaseAdminClient->dropDatabase($formattedDatabase); * } finally { * $databaseAdminClient->close(); @@ -816,12 +816,11 @@ public function updateDatabaseDdl($database, $statements, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -832,9 +831,13 @@ public function dropDatabase($database, $optionalArgs = []) $request = new DropDatabaseRequest(); $request->setDatabase($database); - $mergedSettings = $this->defaultCallSettings['dropDatabase']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['dropDatabase']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'DropDatabase', @@ -857,7 +860,7 @@ public function dropDatabase($database, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedDatabase = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $response = $databaseAdminClient->getDatabaseDdl($formattedDatabase); * } finally { * $databaseAdminClient->close(); @@ -868,12 +871,11 @@ public function dropDatabase($database, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\Admin\Database\V1\GetDatabaseDdlResponse @@ -886,9 +888,13 @@ public function getDatabaseDdl($database, $optionalArgs = []) $request = new GetDatabaseDdlRequest(); $request->setDatabase($database); - $mergedSettings = $this->defaultCallSettings['getDatabaseDdl']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getDatabaseDdl']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'GetDatabaseDdl', @@ -913,7 +919,7 @@ public function getDatabaseDdl($database, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedResource = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $policy = new Policy(); * $response = $databaseAdminClient->setIamPolicy($formattedResource, $policy); * } finally { @@ -931,12 +937,11 @@ public function getDatabaseDdl($database, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -950,9 +955,13 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) $request->setResource($resource); $request->setPolicy($policy); - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['setIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'SetIamPolicy', @@ -977,7 +986,7 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedResource = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $response = $databaseAdminClient->getIamPolicy($formattedResource); * } finally { * $databaseAdminClient->close(); @@ -990,12 +999,11 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -1008,9 +1016,13 @@ public function getIamPolicy($resource, $optionalArgs = []) $request = new GetIamPolicyRequest(); $request->setResource($resource); - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'GetIamPolicy', @@ -1036,7 +1048,7 @@ public function getIamPolicy($resource, $optionalArgs = []) * ``` * try { * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedResource = $databaseAdminClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $permissions = []; * $response = $databaseAdminClient->testIamPermissions($formattedResource, $permissions); * } finally { @@ -1054,12 +1066,11 @@ public function getIamPolicy($resource, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\TestIamPermissionsResponse @@ -1073,9 +1084,13 @@ public function testIamPermissions($resource, $permissions, $optionalArgs = []) $request->setResource($resource); $request->setPermissions($permissions); - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['testIamPermissions']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->databaseAdminStub, 'TestIamPermissions', diff --git a/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php b/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php index 6582d937ab09..3160533a1b7f 100644 --- a/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php +++ b/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php @@ -30,15 +30,16 @@ namespace Google\Cloud\Spanner\Admin\Instance\V1\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; use Google\GAX\PageStreamingDescriptor; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Iam\V1\GetIamPolicyRequest; use Google\Iam\V1\Policy; use Google\Iam\V1\SetIamPolicyRequest; @@ -89,7 +90,7 @@ * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * $formattedParent = $instanceAdminClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -110,8 +111,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -127,11 +128,6 @@ class InstanceAdminGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -145,6 +141,9 @@ class InstanceAdminGapicClient private static $projectNameTemplate; private static $instanceConfigNameTemplate; private static $instanceNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $instanceAdminStub; @@ -153,128 +152,6 @@ class InstanceAdminGapicClient private $descriptors; private $operationsClient; - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a instance_config resource. - * - * @param string $project - * @param string $instanceConfig - * - * @return string The formatted instance_config resource. - * @experimental - */ - public static function formatInstanceConfigName($project, $instanceConfig) - { - return self::getInstanceConfigNameTemplate()->render([ - 'project' => $project, - 'instance_config' => $instanceConfig, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a instance resource. - * - * @param string $project - * @param string $instance - * - * @return string The formatted instance resource. - * @experimental - */ - public static function formatInstanceName($project, $instance) - { - return self::getInstanceNameTemplate()->render([ - 'project' => $project, - 'instance' => $instance, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a instance_config resource. - * - * @param string $instanceConfigName The fully-qualified instance_config resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromInstanceConfigName($instanceConfigName) - { - return self::getInstanceConfigNameTemplate()->match($instanceConfigName)['project']; - } - - /** - * Parses the instance_config from the given fully-qualified path which - * represents a instance_config resource. - * - * @param string $instanceConfigName The fully-qualified instance_config resource. - * - * @return string The extracted instance_config value. - * @experimental - */ - public static function parseInstanceConfigFromInstanceConfigName($instanceConfigName) - { - return self::getInstanceConfigNameTemplate()->match($instanceConfigName)['instance_config']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a instance resource. - * - * @param string $instanceName The fully-qualified instance resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromInstanceName($instanceName) - { - return self::getInstanceNameTemplate()->match($instanceName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a instance resource. - * - * @param string $instanceName The fully-qualified instance resource. - * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromInstanceName($instanceName) - { - return self::getInstanceNameTemplate()->match($instanceName)['instance']; - } - private static function getProjectNameTemplate() { if (self::$projectNameTemplate == null) { @@ -302,6 +179,18 @@ private static function getInstanceNameTemplate() return self::$instanceNameTemplate; } + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'project' => self::getProjectNameTemplate(), + 'instanceConfig' => self::getInstanceConfigNameTemplate(), + 'instance' => self::getInstanceNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } private static function getPageStreamingDescriptors() { $listInstanceConfigsPageStreamingDescriptor = @@ -347,13 +236,111 @@ private static function getLongRunningDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; + } + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function projectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a instance_config resource. + * + * @param string $project + * @param string $instanceConfig + * + * @return string The formatted instance_config resource. + * @experimental + */ + public static function instanceConfigName($project, $instanceConfig) + { + return self::getInstanceConfigNameTemplate()->render([ + 'project' => $project, + 'instance_config' => $instanceConfig, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a instance resource. + * + * @param string $project + * @param string $instance + * + * @return string The formatted instance resource. + * @experimental + */ + public static function instanceName($project, $instance) + { + return self::getInstanceNameTemplate()->render([ + 'project' => $project, + 'instance' => $instance, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * - instanceConfig: projects/{project}/instanceConfigs/{instance_config} + * - instance: projects/{project}/instances/{instance}. + * + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * @experimental + */ + public static function parseName($formattedName, $template = null) + { + $templateMap = self::getPathTemplateMap(); + + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } + + return $templateMap[$template]->match($formattedName); + } + + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } + } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -418,15 +405,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Cloud Spanner Instance Admin API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -440,9 +432,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/spanner.admin', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/instance_admin_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -450,8 +442,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -485,15 +477,13 @@ public function __construct($options = []) $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/instance_admin_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.spanner.admin.instance.v1.InstanceAdmin', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -520,7 +510,7 @@ public function __construct($options = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * $formattedParent = $instanceAdminClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -554,12 +544,11 @@ public function __construct($options = []) * If no page token is specified (the default), the first page * of values will be returned. Any page token used here must have * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -578,9 +567,13 @@ public function listInstanceConfigs($parent, $optionalArgs = []) $request->setPageToken($optionalArgs['pageToken']); } - $mergedSettings = $this->defaultCallSettings['listInstanceConfigs']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listInstanceConfigs']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'ListInstanceConfigs', @@ -601,7 +594,7 @@ public function listInstanceConfigs($parent, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedName = InstanceAdminClient::formatInstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"); + * $formattedName = $instanceAdminClient->instanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"); * $response = $instanceAdminClient->getInstanceConfig($formattedName); * } finally { * $instanceAdminClient->close(); @@ -613,12 +606,11 @@ public function listInstanceConfigs($parent, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\Admin\Instance\V1\InstanceConfig @@ -631,9 +623,13 @@ public function getInstanceConfig($name, $optionalArgs = []) $request = new GetInstanceConfigRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getInstanceConfig']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getInstanceConfig']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'GetInstanceConfig', @@ -654,7 +650,7 @@ public function getInstanceConfig($name, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * $formattedParent = $instanceAdminClient->projectName("[PROJECT]"); * // Iterate through all elements * $pagedResponse = $instanceAdminClient->listInstances($formattedParent); * foreach ($pagedResponse->iterateAllElements() as $element) { @@ -707,12 +703,11 @@ public function getInstanceConfig($name, $optionalArgs = []) * * name:howl labels.env:dev --> The instance's name contains "howl" and * it has the label "env" with its value * containing "dev". - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\PagedListResponse @@ -734,9 +729,13 @@ public function listInstances($parent, $optionalArgs = []) $request->setFilter($optionalArgs['filter']); } - $mergedSettings = $this->defaultCallSettings['listInstances']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['listInstances']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'ListInstances', @@ -757,7 +756,7 @@ public function listInstances($parent, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedName = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedName = $instanceAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * $response = $instanceAdminClient->getInstance($formattedName); * } finally { * $instanceAdminClient->close(); @@ -769,12 +768,11 @@ public function listInstances($parent, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\Admin\Instance\V1\Instance @@ -787,9 +785,13 @@ public function getInstance($name, $optionalArgs = []) $request = new GetInstanceRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getInstance']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getInstance']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'GetInstance', @@ -843,7 +845,7 @@ public function getInstance($name, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * $formattedParent = $instanceAdminClient->projectName("[PROJECT]"); * $instanceId = ""; * $instance = new Instance(); * $operationResponse = $instanceAdminClient->createInstance($formattedParent, $instanceId, $instance); @@ -887,12 +889,11 @@ public function getInstance($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -907,9 +908,13 @@ public function createInstance($parent, $instanceId, $instance, $optionalArgs = $request->setInstanceId($instanceId); $request->setInstance($instance); - $mergedSettings = $this->defaultCallSettings['createInstance']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createInstance']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'CreateInstance', @@ -1011,12 +1016,11 @@ public function createInstance($parent, $instanceId, $instance, $optionalArgs = * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -1030,9 +1034,13 @@ public function updateInstance($instance, $fieldMask, $optionalArgs = []) $request->setInstance($instance); $request->setFieldMask($fieldMask); - $mergedSettings = $this->defaultCallSettings['updateInstance']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['updateInstance']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'UpdateInstance', @@ -1063,7 +1071,7 @@ public function updateInstance($instance, $fieldMask, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedName = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedName = $instanceAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * $instanceAdminClient->deleteInstance($formattedName); * } finally { * $instanceAdminClient->close(); @@ -1075,12 +1083,11 @@ public function updateInstance($instance, $fieldMask, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -1091,9 +1098,13 @@ public function deleteInstance($name, $optionalArgs = []) $request = new DeleteInstanceRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['deleteInstance']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteInstance']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'DeleteInstance', @@ -1118,7 +1129,7 @@ public function deleteInstance($name, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedResource = $instanceAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * $policy = new Policy(); * $response = $instanceAdminClient->setIamPolicy($formattedResource, $policy); * } finally { @@ -1136,12 +1147,11 @@ public function deleteInstance($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -1155,9 +1165,13 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) $request->setResource($resource); $request->setPolicy($policy); - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['setIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'SetIamPolicy', @@ -1182,7 +1196,7 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedResource = $instanceAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * $response = $instanceAdminClient->getIamPolicy($formattedResource); * } finally { * $instanceAdminClient->close(); @@ -1195,12 +1209,11 @@ public function setIamPolicy($resource, $policy, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\Policy @@ -1213,9 +1226,13 @@ public function getIamPolicy($resource, $optionalArgs = []) $request = new GetIamPolicyRequest(); $request->setResource($resource); - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getIamPolicy']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'GetIamPolicy', @@ -1241,7 +1258,7 @@ public function getIamPolicy($resource, $optionalArgs = []) * ``` * try { * $instanceAdminClient = new InstanceAdminClient(); - * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $formattedResource = $instanceAdminClient->instanceName("[PROJECT]", "[INSTANCE]"); * $permissions = []; * $response = $instanceAdminClient->testIamPermissions($formattedResource, $permissions); * } finally { @@ -1259,12 +1276,11 @@ public function getIamPolicy($resource, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Iam\V1\TestIamPermissionsResponse @@ -1278,9 +1294,13 @@ public function testIamPermissions($resource, $permissions, $optionalArgs = []) $request->setResource($resource); $request->setPermissions($permissions); - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['testIamPermissions']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->instanceAdminStub, 'TestIamPermissions', diff --git a/src/Spanner/Database.php b/src/Spanner/Database.php index 27fb931b3d78..5ac65974bdf5 100644 --- a/src/Spanner/Database.php +++ b/src/Spanner/Database.php @@ -309,7 +309,8 @@ public function create(array $options = []) 'statements' => [], ]; - $statement = sprintf('CREATE DATABASE `%s`', DatabaseAdminClient::parseDatabaseFromDatabaseName($this->name)); + $databaseName = DatabaseAdminClient::parseName($this->name())['database']; + $statement = sprintf('CREATE DATABASE `%s`', $databaseName); $operation = $this->connection->createDatabase([ 'instance' => $this->instance->name(), @@ -1430,12 +1431,13 @@ public function createSession(array $options = []) */ public function session($name) { + $sessionNameComponents = GapicSpannerClient::parseName($name); return new Session( $this->connection, $this->projectId, - GapicSpannerClient::parseInstanceFromSessionName($name), - GapicSpannerClient::parseDatabaseFromSessionName($name), - GapicSpannerClient::parseSessionFromSessionName($name) + $sessionNameComponents['instance'], + $sessionNameComponents['database'], + $sessionNameComponents['session'] ); } @@ -1526,10 +1528,10 @@ private function commitInSingleUseTransaction(array $mutations, array $options = */ private function fullyQualifiedDatabaseName($name) { - $instance = InstanceAdminClient::parseInstanceFromInstanceName($this->instance->name()); + $instance = InstanceAdminClient::parseName($this->instance->name())['instance']; try { - return GapicSpannerClient::formatDatabaseName( + return GapicSpannerClient::databaseName( $this->projectId, $instance, $name diff --git a/src/Spanner/Instance.php b/src/Spanner/Instance.php index 2fd7187f2759..56f8f34499a9 100644 --- a/src/Spanner/Instance.php +++ b/src/Spanner/Instance.php @@ -268,7 +268,7 @@ public function reload(array $options = []) */ public function create(InstanceConfiguration $config, array $options = []) { - $instanceId = InstanceAdminClient::parseInstanceFromInstanceName($this->name); + $instanceId = InstanceAdminClient::parseName($this->name)['instance']; $options += [ 'displayName' => $instanceId, 'nodeCount' => self::DEFAULT_NODE_COUNT, @@ -281,7 +281,7 @@ public function create(InstanceConfiguration $config, array $options = []) $operation = $this->connection->createInstance([ 'instanceId' => $instanceId, 'name' => $this->name, - 'projectId' => InstanceAdminClient::formatProjectName($this->projectId), + 'projectId' => InstanceAdminClient::projectName($this->projectId), 'config' => $config->name() ] + $options); @@ -508,7 +508,7 @@ public function iam() private function fullyQualifiedInstanceName($name, $project) { // try { - return InstanceAdminClient::formatInstanceName( + return InstanceAdminClient::instanceName( $project, $name ); diff --git a/src/Spanner/InstanceConfiguration.php b/src/Spanner/InstanceConfiguration.php index ffa08fb62363..59ba5ba53d1d 100644 --- a/src/Spanner/InstanceConfiguration.php +++ b/src/Spanner/InstanceConfiguration.php @@ -202,7 +202,7 @@ public function __debugInfo() private function fullyQualifiedConfigName($name, $projectId) { try { - return InstanceAdminClient::formatInstanceConfigName( + return InstanceAdminClient::instanceConfigName( $projectId, $name ); diff --git a/src/Spanner/Session/Session.php b/src/Spanner/Session/Session.php index b0c8218b4d7b..9ec566b5eab2 100644 --- a/src/Spanner/Session/Session.php +++ b/src/Spanner/Session/Session.php @@ -133,7 +133,7 @@ public function delete(array $options = []) */ public function name() { - return SpannerClient::formatSessionName( + return SpannerClient::sessionName( $this->projectId, $this->instance, $this->database, diff --git a/src/Spanner/SpannerClient.php b/src/Spanner/SpannerClient.php index 68af4c122dfd..0453fc26f395 100644 --- a/src/Spanner/SpannerClient.php +++ b/src/Spanner/SpannerClient.php @@ -127,14 +127,15 @@ public function __construct(array $config = []) [ 'typeUrl' => 'type.googleapis.com/google.spanner.admin.instance.v1.UpdateInstanceMetadata', 'callable' => function ($instance) { - $name = InstanceAdminClient::parseInstanceFromInstanceName($instance['name']); + $name = InstanceAdminClient::parseName($instance['name'])['instance']; return $this->instance($name, $instance); } ], [ 'typeUrl' => 'type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata', 'callable' => function ($database) { - $instanceName = DatabaseAdminClient::parseInstanceFromDatabaseName($database['name']); - $databaseName = DatabaseAdminClient::parseDatabaseFromDatabaseName($database['name']); + $databaseNameComponents = DatabaseAdminClient::parseName($database['name']); + $instanceName = $databaseNameComponents['instance']; + $databaseName = $databaseNameComponents['database']; $instance = $this->instance($instanceName); return $instance->database($databaseName); @@ -142,7 +143,7 @@ public function __construct(array $config = []) ], [ 'typeUrl' => 'type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceMetadata', 'callable' => function ($instance) { - $name = InstanceAdminClient::parseInstanceFromInstanceName($instance['name']); + $name = InstanceAdminClient::parseName($instance['name'])['instance']; return $this->instance($name, $instance); } ] @@ -183,7 +184,7 @@ function (array $config) { return $this->instanceConfiguration($config['name'], $config); }, [$this->connection, 'listInstanceConfigs'], - ['projectId' => InstanceAdminClient::formatProjectName($this->projectId)] + $options, + ['projectId' => InstanceAdminClient::projectName($this->projectId)] + $options, [ 'itemsKey' => 'instanceConfigs', 'resultLimit' => $resultLimit @@ -309,11 +310,11 @@ public function instances(array $options = []) return new ItemIterator( new PageIterator( function (array $instance) { - $name = InstanceAdminClient::parseInstanceFromInstanceName($instance['name']); + $name = InstanceAdminClient::parseName($instance['name'])['instance']; return $this->instance($name, $instance); }, [$this->connection, 'listInstances'], - ['projectId' => InstanceAdminClient::formatProjectName($this->projectId)] + $options, + ['projectId' => InstanceAdminClient::projectName($this->projectId)] + $options, [ 'itemsKey' => 'instances', 'resultLimit' => $resultLimit diff --git a/src/Spanner/V1/Gapic/SpannerGapicClient.php b/src/Spanner/V1/Gapic/SpannerGapicClient.php index eabdc3d93e86..c10f47559dd6 100644 --- a/src/Spanner/V1/Gapic/SpannerGapicClient.php +++ b/src/Spanner/V1/Gapic/SpannerGapicClient.php @@ -30,12 +30,13 @@ namespace Google\Cloud\Spanner\V1\Gapic; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\PathTemplate; +use Google\GAX\ValidationException; use Google\Protobuf\Struct; use Google\Spanner\V1\BeginTransactionRequest; use Google\Spanner\V1\CommitRequest; @@ -68,7 +69,7 @@ * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedDatabase = SpannerClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedDatabase = $spannerClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $response = $spannerClient->createSession($formattedDatabase); * } finally { * $spannerClient->close(); @@ -77,8 +78,8 @@ * * Many parameters require resource names to be formatted in a particular way. To assist * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + * a parseName method to extract the individual identifiers contained within formatted names + * that are returned by the API. * * @experimental */ @@ -94,11 +95,6 @@ class SpannerGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -111,6 +107,9 @@ class SpannerGapicClient private static $databaseNameTemplate; private static $sessionNameTemplate; + private static $pathTemplateMap; + private static $gapicVersion; + private static $gapicVersionLoaded = false; protected $grpcCredentialsHelper; protected $spannerStub; @@ -118,6 +117,62 @@ class SpannerGapicClient private $defaultCallSettings; private $descriptors; + private static function getDatabaseNameTemplate() + { + if (self::$databaseNameTemplate == null) { + self::$databaseNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}'); + } + + return self::$databaseNameTemplate; + } + + private static function getSessionNameTemplate() + { + if (self::$sessionNameTemplate == null) { + self::$sessionNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}/sessions/{session}'); + } + + return self::$sessionNameTemplate; + } + + private static function getPathTemplateMap() + { + if (self::$pathTemplateMap == null) { + self::$pathTemplateMap = [ + 'database' => self::getDatabaseNameTemplate(), + 'session' => self::getSessionNameTemplate(), + ]; + } + + return self::$pathTemplateMap; + } + + private static function getGrpcStreamingDescriptors() + { + return [ + 'executeStreamingSql' => [ + 'grpcStreamingType' => 'ServerStreaming', + ], + 'streamingRead' => [ + 'grpcStreamingType' => 'ServerStreaming', + ], + ]; + } + + private static function getGapicVersion() + { + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; + } + + return self::$gapicVersion; + } + /** * Formats a string containing the fully-qualified path to represent * a database resource. @@ -129,7 +184,7 @@ class SpannerGapicClient * @return string The formatted database resource. * @experimental */ - public static function formatDatabaseName($project, $instance, $database) + public static function databaseName($project, $instance, $database) { return self::getDatabaseNameTemplate()->render([ 'project' => $project, @@ -150,7 +205,7 @@ public static function formatDatabaseName($project, $instance, $database) * @return string The formatted session resource. * @experimental */ - public static function formatSessionName($project, $instance, $database, $session) + public static function sessionName($project, $instance, $database, $session) { return self::getSessionNameTemplate()->render([ 'project' => $project, @@ -161,142 +216,45 @@ public static function formatSessionName($project, $instance, $database, $sessio } /** - * Parses the project from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['instance']; - } - - /** - * Parses the database from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted database value. - * @experimental - */ - public static function parseDatabaseFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['database']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a session resource. - * - * @param string $sessionName The fully-qualified session resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSessionName($sessionName) - { - return self::getSessionNameTemplate()->match($sessionName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a session resource. + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - database: projects/{project}/instances/{instance}/databases/{database} + * - session: projects/{project}/instances/{instance}/databases/{database}/sessions/{session}. * - * @param string $sessionName The fully-qualified session resource. + * The optional $template argument can be supplied to specify a particular pattern, and must + * match one of the templates listed above. If no $template argument is provided, or if the + * $template argument does not match one of the templates listed, then parseName will check + * each of the supported templates, and return the first match. * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromSessionName($sessionName) - { - return self::getSessionNameTemplate()->match($sessionName)['instance']; - } - - /** - * Parses the database from the given fully-qualified path which - * represents a session resource. + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match * - * @param string $sessionName The fully-qualified session resource. + * @return array An associative array from name component IDs to component values. * - * @return string The extracted database value. + * @throws ValidationException If $formattedName could not be matched. * @experimental */ - public static function parseDatabaseFromSessionName($sessionName) + public static function parseName($formattedName, $template = null) { - return self::getSessionNameTemplate()->match($sessionName)['database']; - } - - /** - * Parses the session from the given fully-qualified path which - * represents a session resource. - * - * @param string $sessionName The fully-qualified session resource. - * - * @return string The extracted session value. - * @experimental - */ - public static function parseSessionFromSessionName($sessionName) - { - return self::getSessionNameTemplate()->match($sessionName)['session']; - } - - private static function getDatabaseNameTemplate() - { - if (self::$databaseNameTemplate == null) { - self::$databaseNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}'); - } + $templateMap = self::getPathTemplateMap(); - return self::$databaseNameTemplate; - } + if ($template) { + if (!isset($templateMap[$template])) { + throw new ValidationException("Template name $template does not exist"); + } - private static function getSessionNameTemplate() - { - if (self::$sessionNameTemplate == null) { - self::$sessionNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}/sessions/{session}'); + return $templateMap[$template]->match($formattedName); } - return self::$sessionNameTemplate; - } - - private static function getGrpcStreamingDescriptors() - { - return [ - 'executeStreamingSql' => [ - 'grpcStreamingType' => 'ServerStreaming', - ], - 'streamingRead' => [ - 'grpcStreamingType' => 'ServerStreaming', - ], - ]; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + foreach ($templateMap as $templateName => $pathTemplate) { + try { + return $pathTemplate->match($formattedName); + } catch (ValidationException $ex) { + // Swallow the exception to continue trying other path templates + } } + throw new ValidationException("Input did not match any known format. Input: $formattedName"); } /** @@ -323,15 +281,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Cloud Spanner API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -345,9 +308,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/spanner.data', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/spanner_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -377,15 +340,13 @@ public function __construct($options = []) $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/spanner_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.spanner.v1.Spanner', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -430,7 +391,7 @@ public function __construct($options = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedDatabase = SpannerClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $formattedDatabase = $spannerClient->databaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); * $response = $spannerClient->createSession($formattedDatabase); * } finally { * $spannerClient->close(); @@ -441,12 +402,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\V1\Session @@ -459,9 +419,13 @@ public function createSession($database, $optionalArgs = []) $request = new CreateSessionRequest(); $request->setDatabase($database); - $mergedSettings = $this->defaultCallSettings['createSession']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['createSession']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'CreateSession', @@ -484,7 +448,7 @@ public function createSession($database, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedName = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedName = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $response = $spannerClient->getSession($formattedName); * } finally { * $spannerClient->close(); @@ -495,12 +459,11 @@ public function createSession($database, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\V1\Session @@ -513,9 +476,13 @@ public function getSession($name, $optionalArgs = []) $request = new GetSessionRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['getSession']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['getSession']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'GetSession', @@ -536,7 +503,7 @@ public function getSession($name, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedName = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedName = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $spannerClient->deleteSession($formattedName); * } finally { * $spannerClient->close(); @@ -547,12 +514,11 @@ public function getSession($name, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -563,9 +529,13 @@ public function deleteSession($name, $optionalArgs = []) $request = new DeleteSessionRequest(); $request->setName($name); - $mergedSettings = $this->defaultCallSettings['deleteSession']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['deleteSession']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'DeleteSession', @@ -596,7 +566,7 @@ public function deleteSession($name, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $sql = ""; * $response = $spannerClient->executeSql($formattedSession, $sql); * } finally { @@ -647,12 +617,11 @@ public function deleteSession($name, $optionalArgs = []) * Used to control the amount of debugging information returned in * [ResultSetStats][google.spanner.v1.ResultSetStats]. * For allowed values, use constants defined on {@see \Google\Spanner\V1\ExecuteSqlRequest_QueryMode} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\V1\ResultSet @@ -681,9 +650,13 @@ public function executeSql($session, $sql, $optionalArgs = []) $request->setQueryMode($optionalArgs['queryMode']); } - $mergedSettings = $this->defaultCallSettings['executeSql']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['executeSql']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'ExecuteSql', @@ -708,7 +681,7 @@ public function executeSql($session, $sql, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $sql = ""; * // Read all responses until the stream is complete * $stream = $spannerClient->executeStreamingSql($formattedSession, $sql); @@ -793,9 +766,20 @@ public function executeStreamingSql($session, $sql, $optionalArgs = []) $request->setQueryMode($optionalArgs['queryMode']); } - $mergedSettings = $this->defaultCallSettings['executeStreamingSql']->merge( - new CallSettings($optionalArgs) - ); + if (array_key_exists('timeoutMillis', $optionalArgs)) { + $optionalArgs['retrySettings'] = [ + 'retriesEnabled' => false, + 'noRetriesRpcTimeoutMillis' => $optionalArgs['timeoutMillis'], + ]; + } + + $defaultCallSettings = $this->defaultCallSettings['executeStreamingSql']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'ExecuteStreamingSql', @@ -828,7 +812,7 @@ public function executeStreamingSql($session, $sql, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $table = ""; * $columns = []; * $keySet = new KeySet(); @@ -872,12 +856,11 @@ public function executeStreamingSql($session, $sql, $optionalArgs = []) * enables the new read to resume where the last read left off. The * rest of the request parameters must exactly match the request * that yielded this token. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\V1\ResultSet @@ -905,9 +888,13 @@ public function read($session, $table, $columns, $keySet, $optionalArgs = []) $request->setResumeToken($optionalArgs['resumeToken']); } - $mergedSettings = $this->defaultCallSettings['read']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['read']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'Read', @@ -932,7 +919,7 @@ public function read($session, $table, $columns, $keySet, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $table = ""; * $columns = []; * $keySet = new KeySet(); @@ -1009,9 +996,20 @@ public function streamingRead($session, $table, $columns, $keySet, $optionalArgs $request->setResumeToken($optionalArgs['resumeToken']); } - $mergedSettings = $this->defaultCallSettings['streamingRead']->merge( - new CallSettings($optionalArgs) - ); + if (array_key_exists('timeoutMillis', $optionalArgs)) { + $optionalArgs['retrySettings'] = [ + 'retriesEnabled' => false, + 'noRetriesRpcTimeoutMillis' => $optionalArgs['timeoutMillis'], + ]; + } + + $defaultCallSettings = $this->defaultCallSettings['streamingRead']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'StreamingRead', @@ -1035,7 +1033,7 @@ public function streamingRead($session, $table, $columns, $keySet, $optionalArgs * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $options = new TransactionOptions(); * $response = $spannerClient->beginTransaction($formattedSession, $options); * } finally { @@ -1048,12 +1046,11 @@ public function streamingRead($session, $table, $columns, $keySet, $optionalArgs * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\V1\Transaction @@ -1067,9 +1064,13 @@ public function beginTransaction($session, $options, $optionalArgs = []) $request->setSession($session); $request->setOptions($options); - $mergedSettings = $this->defaultCallSettings['beginTransaction']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['beginTransaction']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'BeginTransaction', @@ -1097,7 +1098,7 @@ public function beginTransaction($session, $options, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $mutations = []; * $response = $spannerClient->commit($formattedSession, $mutations); * } finally { @@ -1124,12 +1125,11 @@ public function beginTransaction($session, $options, $optionalArgs = []) * executed more than once. If this is undesirable, use * [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] and * [Commit][google.spanner.v1.Spanner.Commit] instead. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Spanner\V1\CommitResponse @@ -1149,9 +1149,13 @@ public function commit($session, $mutations, $optionalArgs = []) $request->setSingleUseTransaction($optionalArgs['singleUseTransaction']); } - $mergedSettings = $this->defaultCallSettings['commit']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['commit']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'Commit', @@ -1179,7 +1183,7 @@ public function commit($session, $mutations, $optionalArgs = []) * ``` * try { * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $formattedSession = $spannerClient->sessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); * $transactionId = ""; * $spannerClient->rollback($formattedSession, $transactionId); * } finally { @@ -1192,12 +1196,11 @@ public function commit($session, $mutations, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @throws \Google\GAX\ApiException if the remote call fails @@ -1209,9 +1212,13 @@ public function rollback($session, $transactionId, $optionalArgs = []) $request->setSession($session); $request->setTransactionId($transactionId); - $mergedSettings = $this->defaultCallSettings['rollback']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['rollback']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->spannerStub, 'Rollback', diff --git a/src/Spanner/composer.json b/src/Spanner/composer.json index 7feb40e19026..91449ee85829 100644 --- a/src/Spanner/composer.json +++ b/src/Spanner/composer.json @@ -6,8 +6,8 @@ "require": { "ext-grpc": "*", "google/cloud-core": "^1.5", - "google/gax": "^0.23", - "google/proto-client": "^0.23" + "google/gax": "^0.24", + "google/proto-client": "^0.24" }, "extra": { "component": { diff --git a/src/Speech/V1/Gapic/SpeechGapicClient.php b/src/Speech/V1/Gapic/SpeechGapicClient.php index 601f316b69db..6151aaa71b6a 100644 --- a/src/Speech/V1/Gapic/SpeechGapicClient.php +++ b/src/Speech/V1/Gapic/SpeechGapicClient.php @@ -37,10 +37,10 @@ use Google\Cloud\Speech\V1\RecognizeRequest; use Google\Cloud\Speech\V1\SpeechGrpcClient; use Google\Cloud\Speech\V1\StreamingRecognizeRequest; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; @@ -88,11 +88,6 @@ class SpeechGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -103,6 +98,9 @@ class SpeechGapicClient */ const CODEGEN_VERSION = '0.0.5'; + private static $gapicVersion; + private static $gapicVersionLoaded = false; + protected $grpcCredentialsHelper; protected $speechStub; private $scopes; @@ -131,13 +129,16 @@ private static function getGrpcStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; } /** @@ -202,15 +203,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Speech API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -223,9 +229,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/speech_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -233,8 +239,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -261,15 +267,13 @@ public function __construct($options = []) $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/speech_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.cloud.speech.v1.Speech', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -319,12 +323,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Speech\V1\RecognizeResponse @@ -338,9 +341,13 @@ public function recognize($config, $audio, $optionalArgs = []) $request->setConfig($config); $request->setAudio($audio); - $mergedSettings = $this->defaultCallSettings['recognize']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['recognize']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->speechStub, 'Recognize', @@ -411,12 +418,11 @@ public function recognize($config, $audio, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -430,9 +436,13 @@ public function longRunningRecognize($config, $audio, $optionalArgs = []) $request->setConfig($config); $request->setAudio($audio); - $mergedSettings = $this->defaultCallSettings['longRunningRecognize']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['longRunningRecognize']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->speechStub, 'LongRunningRecognize', @@ -500,9 +510,20 @@ public function longRunningRecognize($config, $audio, $optionalArgs = []) */ public function streamingRecognize($optionalArgs = []) { - $mergedSettings = $this->defaultCallSettings['streamingRecognize']->merge( - new CallSettings($optionalArgs) - ); + if (array_key_exists('timeoutMillis', $optionalArgs)) { + $optionalArgs['retrySettings'] = [ + 'retriesEnabled' => false, + 'noRetriesRpcTimeoutMillis' => $optionalArgs['timeoutMillis'], + ]; + } + + $defaultCallSettings = $this->defaultCallSettings['streamingRecognize']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->speechStub, 'StreamingRecognize', diff --git a/src/Speech/V1beta1/Gapic/SpeechGapicClient.php b/src/Speech/V1beta1/Gapic/SpeechGapicClient.php index 5111253a5503..9d3071a1a5ae 100644 --- a/src/Speech/V1beta1/Gapic/SpeechGapicClient.php +++ b/src/Speech/V1beta1/Gapic/SpeechGapicClient.php @@ -37,10 +37,10 @@ use Google\Cloud\Speech\V1beta1\SpeechGrpcClient; use Google\Cloud\Speech\V1beta1\StreamingRecognizeRequest; use Google\Cloud\Speech\V1beta1\SyncRecognizeRequest; +use Google\Cloud\Version; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; @@ -86,11 +86,6 @@ class SpeechGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -101,6 +96,9 @@ class SpeechGapicClient */ const CODEGEN_VERSION = '0.0.5'; + private static $gapicVersion; + private static $gapicVersionLoaded = false; + protected $grpcCredentialsHelper; protected $speechStub; private $scopes; @@ -129,13 +127,16 @@ private static function getGrpcStreamingDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; } /** @@ -200,15 +201,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Speech API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -221,9 +227,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/speech_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -231,8 +237,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -259,15 +265,13 @@ public function __construct($options = []) $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/speech_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.cloud.speech.v1beta1.Speech', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -315,12 +319,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Speech\V1beta1\SyncRecognizeResponse @@ -334,9 +337,13 @@ public function syncRecognize($config, $audio, $optionalArgs = []) $request->setConfig($config); $request->setAudio($audio); - $mergedSettings = $this->defaultCallSettings['syncRecognize']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['syncRecognize']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->speechStub, 'SyncRecognize', @@ -407,12 +414,11 @@ public function syncRecognize($config, $audio, $optionalArgs = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -426,9 +432,13 @@ public function asyncRecognize($config, $audio, $optionalArgs = []) $request->setConfig($config); $request->setAudio($audio); - $mergedSettings = $this->defaultCallSettings['asyncRecognize']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['asyncRecognize']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->speechStub, 'AsyncRecognize', @@ -496,9 +506,20 @@ public function asyncRecognize($config, $audio, $optionalArgs = []) */ public function streamingRecognize($optionalArgs = []) { - $mergedSettings = $this->defaultCallSettings['streamingRecognize']->merge( - new CallSettings($optionalArgs) - ); + if (array_key_exists('timeoutMillis', $optionalArgs)) { + $optionalArgs['retrySettings'] = [ + 'retriesEnabled' => false, + 'noRetriesRpcTimeoutMillis' => $optionalArgs['timeoutMillis'], + ]; + } + + $defaultCallSettings = $this->defaultCallSettings['streamingRecognize']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->speechStub, 'StreamingRecognize', diff --git a/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php b/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php index 2b204a75fae7..6cb416296c74 100644 --- a/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php +++ b/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php @@ -30,6 +30,7 @@ namespace Google\Cloud\VideoIntelligence\V1beta1\Gapic; +use Google\Cloud\Version; use Google\Cloud\Videointelligence\V1beta1\AnnotateVideoProgress; use Google\Cloud\Videointelligence\V1beta1\AnnotateVideoRequest; use Google\Cloud\Videointelligence\V1beta1\AnnotateVideoResponse; @@ -39,7 +40,6 @@ use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; @@ -104,11 +104,6 @@ class VideoIntelligenceServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -119,6 +114,9 @@ class VideoIntelligenceServiceGapicClient */ const CODEGEN_VERSION = '0.0.5'; + private static $gapicVersion; + private static $gapicVersionLoaded = false; + protected $grpcCredentialsHelper; protected $videoIntelligenceServiceStub; private $scopes; @@ -138,13 +136,16 @@ private static function getLongRunningDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; } /** @@ -209,15 +210,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Video Intelligence API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -230,9 +236,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/video_intelligence_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -240,8 +246,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -262,15 +268,13 @@ public function __construct($options = []) $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/video_intelligence_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.cloud.videointelligence.v1beta1.VideoIntelligenceService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -364,12 +368,11 @@ public function __construct($options = []) * Optional cloud region where annotation should take place. Supported cloud * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region * is specified, a region will be determined based on video file location. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -395,9 +398,13 @@ public function annotateVideo($inputUri, $features, $optionalArgs = []) $request->setLocationId($optionalArgs['locationId']); } - $mergedSettings = $this->defaultCallSettings['annotateVideo']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['annotateVideo']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->videoIntelligenceServiceStub, 'AnnotateVideo', diff --git a/src/VideoIntelligence/V1beta2/Gapic/VideoIntelligenceServiceGapicClient.php b/src/VideoIntelligence/V1beta2/Gapic/VideoIntelligenceServiceGapicClient.php index b831c93d8ca6..691ec2bf34dd 100644 --- a/src/VideoIntelligence/V1beta2/Gapic/VideoIntelligenceServiceGapicClient.php +++ b/src/VideoIntelligence/V1beta2/Gapic/VideoIntelligenceServiceGapicClient.php @@ -30,6 +30,7 @@ namespace Google\Cloud\VideoIntelligence\V1beta2\Gapic; +use Google\Cloud\Version; use Google\Cloud\Videointelligence\V1beta2\AnnotateVideoProgress; use Google\Cloud\Videointelligence\V1beta2\AnnotateVideoRequest; use Google\Cloud\Videointelligence\V1beta2\AnnotateVideoResponse; @@ -39,7 +40,6 @@ use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; use Google\GAX\LongRunning\OperationsClient; use Google\GAX\OperationResponse; @@ -104,11 +104,6 @@ class VideoIntelligenceServiceGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -119,6 +114,9 @@ class VideoIntelligenceServiceGapicClient */ const CODEGEN_VERSION = '0.0.5'; + private static $gapicVersion; + private static $gapicVersionLoaded = false; + protected $grpcCredentialsHelper; protected $videoIntelligenceServiceStub; private $scopes; @@ -138,13 +136,16 @@ private static function getLongRunningDescriptors() private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; } /** @@ -209,15 +210,20 @@ public function resumeOperation($operationName, $methodName = null) * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Video Intelligence API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -230,9 +236,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/video_intelligence_service_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -240,8 +246,8 @@ public function __construct($options = []) $this->operationsClient = $options['operationsClient']; } else { $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); unset($operationsClientOptions['retryingOverride']); + unset($operationsClientOptions['clientConfigPath']); $this->operationsClient = new OperationsClient($operationsClientOptions); } @@ -262,15 +268,13 @@ public function __construct($options = []) $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; } - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/video_intelligence_service_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.cloud.videointelligence.v1beta2.VideoIntelligenceService', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -364,12 +368,11 @@ public function __construct($options = []) * Optional cloud region where annotation should take place. Supported cloud * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region * is specified, a region will be determined based on video file location. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\GAX\OperationResponse @@ -395,9 +398,13 @@ public function annotateVideo($inputUri, $features, $optionalArgs = []) $request->setLocationId($optionalArgs['locationId']); } - $mergedSettings = $this->defaultCallSettings['annotateVideo']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['annotateVideo']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->videoIntelligenceServiceStub, 'AnnotateVideo', diff --git a/src/VideoIntelligence/composer.json b/src/VideoIntelligence/composer.json index 848c1328da1c..b6b1568b362b 100644 --- a/src/VideoIntelligence/composer.json +++ b/src/VideoIntelligence/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "ext-grpc": "*", - "google/proto-client": "^0.23", - "google/gax": "^0.23" + "google/proto-client": "^0.24", + "google/gax": "^0.24" }, "extra": { "component": { diff --git a/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php b/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php index fbf97a0214dd..c98e572bdee9 100644 --- a/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php +++ b/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php @@ -30,13 +30,13 @@ namespace Google\Cloud\Vision\V1\Gapic; +use Google\Cloud\Version; use Google\Cloud\Vision\V1\AnnotateImageRequest; use Google\Cloud\Vision\V1\BatchAnnotateImagesRequest; use Google\Cloud\Vision\V1\ImageAnnotatorGrpcClient; use Google\GAX\AgentHeaderDescriptor; use Google\GAX\ApiCallable; use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; use Google\GAX\GrpcCredentialsHelper; /** @@ -75,11 +75,6 @@ class ImageAnnotatorGapicClient */ const DEFAULT_SERVICE_PORT = 443; - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - /** * The name of the code generator, to be included in the agent header. */ @@ -90,6 +85,9 @@ class ImageAnnotatorGapicClient */ const CODEGEN_VERSION = '0.0.5'; + private static $gapicVersion; + private static $gapicVersionLoaded = false; + protected $grpcCredentialsHelper; protected $imageAnnotatorStub; private $scopes; @@ -98,13 +96,16 @@ class ImageAnnotatorGapicClient private static function getGapicVersion() { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; + if (!self::$gapicVersionLoaded) { + if (file_exists(__DIR__.'/../VERSION')) { + self::$gapicVersion = trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists(Version::class)) { + self::$gapicVersion = Version::VERSION; + } + self::$gapicVersionLoaded = true; } + + return self::$gapicVersion; } /** @@ -131,15 +132,20 @@ private static function getGapicVersion() * A CredentialsLoader object created using the Google\Auth library. * @type array $scopes A string array of scopes to use when acquiring credentials. * Defaults to the scopes for the Google Cloud Vision API. + * @type string $clientConfigPath + * Path to a JSON file containing client method configuration, including retry settings. + * Specify this setting to specify the retry behavior of all methods on the client. + * By default this settings points to the default client config file, which is provided + * in the resources folder. The retry settings provided in this option can be overridden + * by settings in $retryingOverride * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) + * An associative array in which the keys are method names (e.g. 'createFoo'), and + * the values are retry settings to use for that method. The retry settings for each + * method can be a {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on {@see Google\GAX\RetrySettings} + * for example usage. Passing a value of null is equivalent to a value of + * ['retriesEnabled' => false]. Retry settings provided in this setting override the + * settings in $clientConfigPath. * } * @experimental */ @@ -152,9 +158,9 @@ public function __construct($options = []) 'https://www.googleapis.com/auth/cloud-platform', ], 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, 'libName' => null, 'libVersion' => null, + 'clientConfigPath' => __DIR__.'/../resources/image_annotator_client_config.json', ]; $options = array_merge($defaultOptions, $options); @@ -171,15 +177,13 @@ public function __construct($options = []) 'batchAnnotateImages' => $defaultDescriptors, ]; - $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/image_annotator_client_config.json'); + $clientConfigJsonString = file_get_contents($options['clientConfigPath']); $clientConfig = json_decode($clientConfigJsonString, true); $this->defaultCallSettings = CallSettings::load( 'google.cloud.vision.v1.ImageAnnotator', $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] + $options['retryingOverride'] ); $this->scopes = $options['scopes']; @@ -217,12 +221,11 @@ public function __construct($options = []) * @param array $optionalArgs { * Optional. * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. + * @type \Google\GAX\RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a + * {@see Google\GAX\RetrySettings} object, or an associative array + * of retry settings parameters. See the documentation on + * {@see Google\GAX\RetrySettings} for example usage. * } * * @return \Google\Cloud\Vision\V1\BatchAnnotateImagesResponse @@ -235,9 +238,13 @@ public function batchAnnotateImages($requests, $optionalArgs = []) $request = new BatchAnnotateImagesRequest(); $request->setRequests($requests); - $mergedSettings = $this->defaultCallSettings['batchAnnotateImages']->merge( - new CallSettings($optionalArgs) - ); + $defaultCallSettings = $this->defaultCallSettings['batchAnnotateImages']; + if (isset($optionalArgs['retrySettings']) && is_array($optionalArgs['retrySettings'])) { + $optionalArgs['retrySettings'] = $defaultCallSettings->getRetrySettings()->with( + $optionalArgs['retrySettings'] + ); + } + $mergedSettings = $defaultCallSettings->merge(new CallSettings($optionalArgs)); $callable = ApiCallable::createApiCall( $this->imageAnnotatorStub, 'BatchAnnotateImages', diff --git a/tests/snippets/Spanner/DatabaseTest.php b/tests/snippets/Spanner/DatabaseTest.php index dfb0c98b643f..5218e566b56f 100644 --- a/tests/snippets/Spanner/DatabaseTest.php +++ b/tests/snippets/Spanner/DatabaseTest.php @@ -59,7 +59,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $instance = $this->prophesize(Instance::class); - $instance->name()->willReturn(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE)); + $instance->name()->willReturn(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)); $session = $this->prophesize(Session::class); @@ -95,7 +95,7 @@ public function testClass() $snippet = $this->snippetFromClass(Database::class); $res = $snippet->invoke('database'); $this->assertInstanceOf(Database::class, $res->returnVal()); - $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseDatabaseFromDatabaseName($res->returnVal()->name())); + $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseName($res->returnVal()->name())['database']); } public function testClassViaInstance() @@ -107,7 +107,7 @@ public function testClassViaInstance() $snippet = $this->snippetFromClass(Database::class, 1); $res = $snippet->invoke('database'); $this->assertInstanceOf(Database::class, $res->returnVal()); - $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseDatabaseFromDatabaseName($res->returnVal()->name())); + $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseName($res->returnVal()->name())['database']); } public function testName() @@ -115,7 +115,7 @@ public function testName() $snippet = $this->snippetFromMethod(Database::class, 'name'); $snippet->addLocal('database', $this->database); $res = $snippet->invoke('name'); - $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseDatabaseFromDatabaseName($res->returnVal())); + $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseName($res->returnVal())['database']); } /** diff --git a/tests/snippets/Spanner/InstanceConfigurationTest.php b/tests/snippets/Spanner/InstanceConfigurationTest.php index a11c9c35e7a2..fb32afff0131 100644 --- a/tests/snippets/Spanner/InstanceConfigurationTest.php +++ b/tests/snippets/Spanner/InstanceConfigurationTest.php @@ -56,7 +56,7 @@ public function testClass() $res = $snippet->invoke('configuration'); $this->assertInstanceOf(InstanceConfiguration::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), $res->returnVal()->name()); + $this->assertEquals(InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), $res->returnVal()->name()); } public function testName() @@ -65,7 +65,7 @@ public function testName() $snippet->addLocal('configuration', $this->config); $res = $snippet->invoke('name'); - $this->assertEquals(InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), $res->returnVal()); + $this->assertEquals(InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), $res->returnVal()); } public function testInfo() @@ -74,7 +74,7 @@ public function testInfo() $snippet->addLocal('configuration', $this->config); $info = [ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), 'displayName' => self::CONFIG ]; @@ -96,7 +96,7 @@ public function testExists() $this->connection->getInstanceConfig(Argument::any()) ->shouldBeCalled() ->willReturn([ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), 'displayName' => self::CONFIG ]); @@ -109,7 +109,7 @@ public function testExists() public function testReload() { $info = [ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), 'displayName' => self::CONFIG ]; diff --git a/tests/snippets/Spanner/InstanceTest.php b/tests/snippets/Spanner/InstanceTest.php index 76717b19a253..06c6fe9b74e8 100644 --- a/tests/snippets/Spanner/InstanceTest.php +++ b/tests/snippets/Spanner/InstanceTest.php @@ -65,7 +65,7 @@ public function testClass() $snippet = $this->snippetFromClass(Instance::class); $res = $snippet->invoke('instance'); $this->assertInstanceOf(Instance::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->name()); + $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->name()); } /** @@ -74,7 +74,7 @@ public function testClass() public function testCreate() { $config = $this->prophesize(InstanceConfiguration::class); - $config->name()->willReturn(InstanceAdminClient::formatInstanceConfigName(self::PROJECT, 'foo')); + $config->name()->willReturn(InstanceAdminClient::instanceConfigName(self::PROJECT, 'foo')); $snippet = $this->snippetFromMethod(Instance::class, 'create'); $snippet->addLocal('configuration', $config->reveal()); @@ -96,7 +96,7 @@ public function testName() $snippet->addLocal('instance', $this->instance); $res = $snippet->invoke('name'); - $this->assertEquals(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE), $res->returnVal()); + $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()); } public function testInfo() @@ -212,7 +212,7 @@ public function testDatabase() $res = $snippet->invoke('database'); $this->assertInstanceOf(Database::class, $res->returnVal()); - $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseDatabaseFromDatabaseName($res->returnVal()->name())); + $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseName($res->returnVal()->name())['database']); } public function testDatabases() @@ -225,7 +225,7 @@ public function testDatabases() ->willReturn([ 'databases' => [ [ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE) + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) ] ] ]); diff --git a/tests/snippets/Spanner/SpannerClientTest.php b/tests/snippets/Spanner/SpannerClientTest.php index 44af7775e945..aace5adfb41b 100644 --- a/tests/snippets/Spanner/SpannerClientTest.php +++ b/tests/snippets/Spanner/SpannerClientTest.php @@ -105,7 +105,7 @@ public function testInstanceConfiguration() $res = $snippet->invoke('configuration'); $this->assertInstanceOf(InstanceConfiguration::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::formatInstanceConfigName(self::PROJECT, $configName), $res->returnVal()->name()); + $this->assertEquals(InstanceAdminClient::instanceConfigName(self::PROJECT, $configName), $res->returnVal()->name()); } /** @@ -137,7 +137,7 @@ public function testInstance() $res = $snippet->invoke('instance'); $this->assertInstanceOf(Instance::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->name()); + $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->name()); } /** @@ -152,8 +152,8 @@ public function testInstances() ->shouldBeCalled() ->willReturn([ 'instances' => [ - ['name' => InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE)], - ['name' => InstanceAdminClient::formatInstanceName(self::PROJECT, 'bar')] + ['name' => InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)], + ['name' => InstanceAdminClient::instanceName(self::PROJECT, 'bar')] ] ]); @@ -162,7 +162,7 @@ public function testInstances() $res = $snippet->invoke('instances'); $this->assertInstanceOf(ItemIterator::class, $res->returnVal()); $this->assertInstanceOf(Instance::class, $res->returnVal()->current()); - $this->assertEquals(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->current()->name()); + $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->current()->name()); } public function testConnect() diff --git a/tests/system/Spanner/AdminTest.php b/tests/system/Spanner/AdminTest.php index 8a5f8e473e75..c699721c12b4 100644 --- a/tests/system/Spanner/AdminTest.php +++ b/tests/system/Spanner/AdminTest.php @@ -125,11 +125,11 @@ public function testConfigurations() private function parseName($name) { - return InstanceAdminClient::parseInstanceFromInstanceName($name); + return InstanceAdminClient::parseName($name)['instance']; } private function parseDbName($name) { - return DatabaseAdminClient::parseDatabaseFromDatabaseName($name); + return DatabaseAdminClient::parseName($name)['database']; } } diff --git a/tests/unit/Core/GrpcRequestWrapperTest.php b/tests/unit/Core/GrpcRequestWrapperTest.php index eff18c2fdd5a..3069d76cff63 100644 --- a/tests/unit/Core/GrpcRequestWrapperTest.php +++ b/tests/unit/Core/GrpcRequestWrapperTest.php @@ -24,6 +24,7 @@ use Google\Cloud\Tests\GrpcTestTrait; use Google\Cloud\Core\GrpcRequestWrapper; use Google\GAX\ApiException; +use Google\GAX\ApiStatus; use Google\GAX\Page; use Google\GAX\PagedListResponse; use Google\GAX\Serializer; @@ -65,7 +66,7 @@ public function testSuccessfullySendsRequest($response, $expectedMessage, $seria $actualResponse = $requestWrapper->send( function ($test, $options) use ($response, $requestOptions) { - $this->assertEquals($requestOptions['requestTimeout'] * 1000, $options['timeoutMs']); + $this->assertEquals($requestOptions['requestTimeout'] * 1000, $options['retrySettings']['noRetriesRpcTimeoutMillis']); return $response; }, ['test', []], @@ -104,7 +105,10 @@ public function testThrowsExceptionWhenRequestFails() $requestWrapper = new GrpcRequestWrapper(); $requestWrapper->send(function () { - throw new ApiException('message', 5); + throw new ApiException('message', + \Google\Rpc\Code::NOT_FOUND, + \Google\GAX\ApiStatus::NOT_FOUND + ); }, [[]]); } @@ -180,7 +184,8 @@ public function testCastsToProperException($code, $expectedException) try { $requestWrapper->send(function () use ($code) { - throw new ApiException('message', $code); + $status = ApiStatus::statusFromRpcCode($code); + throw new ApiException('message', $code, $status); }, [[]], ['retries' => 0]); } catch (\Exception $ex) { $this->assertInstanceOf($expectedException, $ex); diff --git a/tests/unit/PubSub/Connection/GrpcTest.php b/tests/unit/PubSub/Connection/GrpcTest.php index 994a35c00810..c7b28a2cfab0 100644 --- a/tests/unit/PubSub/Connection/GrpcTest.php +++ b/tests/unit/PubSub/Connection/GrpcTest.php @@ -114,11 +114,6 @@ public function methodProvider() $timestamp = $serializer->decodeMessage(new Timestamp(), $this->formatTimestampForApi($time)); return [ - [ - 'updateSubscription', - ['name' => 'projects/foo/subscriptions/bar', 'retainAckedMessages' => true], - [$subscription, $fieldMask, []] - ], [ 'listSnapshots', ['project' => 'projectId'], diff --git a/tests/unit/PubSub/Connection/RestTest.php b/tests/unit/PubSub/Connection/RestTest.php index 49af5829bd68..5f1643ed4343 100644 --- a/tests/unit/PubSub/Connection/RestTest.php +++ b/tests/unit/PubSub/Connection/RestTest.php @@ -84,7 +84,6 @@ public function methodProvider() ['setTopicIamPolicy'], ['testTopicIamPermissions'], ['createSubscription'], - ['updateSubscription'], ['getSubscription'], ['listSubscriptions'], ['deleteSubscription'], diff --git a/tests/unit/PubSub/SubscriptionTest.php b/tests/unit/PubSub/SubscriptionTest.php index 85ea771796d0..1d67ebc52c1f 100644 --- a/tests/unit/PubSub/SubscriptionTest.php +++ b/tests/unit/PubSub/SubscriptionTest.php @@ -86,28 +86,6 @@ public function testCreateWithoutTopicName() $sub = $subscription->create(); } - public function testUpdate() - { - $args = [ - 'foo' => 'bar' - ]; - - $argsWithName = $args + [ - 'name' => $this->subscription->name() - ]; - - $this->connection->updateSubscription($argsWithName) - ->shouldBeCalled() - ->willReturn($argsWithName); - - $this->subscription->setConnection($this->connection->reveal()); - - $res = $this->subscription->update($args); - - $this->assertEquals($res, $argsWithName); - $this->assertEquals($this->subscription->info(), $argsWithName); - } - public function testDelete() { $this->connection->deleteSubscription(Argument::withEntry('foo', 'bar')) diff --git a/tests/unit/Spanner/DatabaseTest.php b/tests/unit/Spanner/DatabaseTest.php index 9b479a088daa..4c4944a0aaa6 100644 --- a/tests/unit/Spanner/DatabaseTest.php +++ b/tests/unit/Spanner/DatabaseTest.php @@ -82,7 +82,7 @@ public function setUp() $this->sessionPool->release(Argument::type(Session::class)) ->willReturn(null); - $this->instance->name()->willReturn(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE)); + $this->instance->name()->willReturn(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)); $args = [ $this->connection->reveal(), @@ -103,7 +103,7 @@ public function setUp() public function testName() { - $this->assertEquals($this->database->name(), DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE)); + $this->assertEquals($this->database->name(), DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE)); } public function testInfo() @@ -148,7 +148,7 @@ public function testReload() public function testExists() { $this->connection->getDatabase(Argument::withEntry( - 'name', DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE) + 'name', DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) )) ->shouldBeCalled() ->willReturn([]); @@ -179,7 +179,7 @@ public function testUpdateDdl() { $statement = 'foo'; $this->connection->updateDatabaseDdl([ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE), + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE), 'statements' => [$statement] ])->willReturn([ 'name' => 'my-operation' @@ -197,7 +197,7 @@ public function testUpdateDdlBatch() { $statements = ['foo', 'bar']; $this->connection->updateDatabaseDdl([ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE), + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE), 'statements' => $statements ])->willReturn([ 'name' => 'my-operation' @@ -215,7 +215,7 @@ public function testUpdateWithSingleStatement() { $statement = 'foo'; $this->connection->updateDatabaseDdl([ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE), + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE), 'statements' => ['foo'] ])->shouldBeCalled()->willReturn(['name' => 'operations/foo']); @@ -231,7 +231,7 @@ public function testUpdateWithSingleStatement() public function testDrop() { $this->connection->dropDatabase([ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE) + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) ])->shouldBeCalled(); $this->database->___setProperty('connection', $this->connection->reveal()); @@ -246,7 +246,7 @@ public function testDdl() { $ddl = ['create table users', 'create table posts']; $this->connection->getDatabaseDDL([ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE) + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) ])->willReturn(['statements' => $ddl]); $this->database->___setProperty('connection', $this->connection->reveal()); @@ -260,7 +260,7 @@ public function testDdl() public function testDdlNoResult() { $this->connection->getDatabaseDDL([ - 'name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT, self::INSTANCE, self::DATABASE) + 'name' => DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) ])->willReturn([]); $this->database->___setProperty('connection', $this->connection->reveal()); diff --git a/tests/unit/Spanner/InstanceConfigurationTest.php b/tests/unit/Spanner/InstanceConfigurationTest.php index e654d9687439..87a6fabaedbb 100644 --- a/tests/unit/Spanner/InstanceConfigurationTest.php +++ b/tests/unit/Spanner/InstanceConfigurationTest.php @@ -52,7 +52,7 @@ public function setUp() public function testName() { - $this->assertEquals(self::NAME, InstanceAdminClient::parseInstanceConfigFromInstanceConfigName($this->configuration->name())); + $this->assertEquals(self::NAME, InstanceAdminClient::parseName($this->configuration->name())['instance_config']); } public function testInfo() @@ -76,7 +76,7 @@ public function testInfoWithReload() $info = ['foo' => 'bar']; $this->connection->getInstanceConfig([ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT_ID, self::NAME), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT_ID, self::NAME), 'projectId' => self::PROJECT_ID ])->shouldBeCalled()->willReturn($info); @@ -106,7 +106,7 @@ public function testReload() $info = ['foo' => 'bar']; $this->connection->getInstanceConfig([ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT_ID, self::NAME), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT_ID, self::NAME), 'projectId' => self::PROJECT_ID ])->shouldBeCalledTimes(1)->willReturn($info); diff --git a/tests/unit/Spanner/InstanceTest.php b/tests/unit/Spanner/InstanceTest.php index e313e4dbc95b..34d2c9b52e6e 100644 --- a/tests/unit/Spanner/InstanceTest.php +++ b/tests/unit/Spanner/InstanceTest.php @@ -65,7 +65,7 @@ public function setUp() public function testName() { - $this->assertEquals(self::NAME, InstanceAdminClient::parseInstanceFromInstanceName($this->instance->name())); + $this->assertEquals(self::NAME, InstanceAdminClient::parseName($this->instance->name())['instance']); } public function testInfo() @@ -213,7 +213,7 @@ public function testUpdateWithChanges() public function testDelete() { $this->connection->deleteInstance([ - 'name' => InstanceAdminClient::formatInstanceName(self::PROJECT_ID, self::NAME) + 'name' => InstanceAdminClient::instanceName(self::PROJECT_ID, self::NAME) ])->shouldBeCalled(); $this->instance->___setProperty('connection', $this->connection->reveal()); @@ -226,7 +226,7 @@ public function testCreateDatabase() $extra = ['foo', 'bar']; $this->connection->createDatabase([ - 'instance' => InstanceAdminClient::formatInstanceName(self::PROJECT_ID, self::NAME), + 'instance' => InstanceAdminClient::instanceName(self::PROJECT_ID, self::NAME), 'createStatement' => 'CREATE DATABASE `test-database`', 'extraStatements' => $extra ]) @@ -246,14 +246,14 @@ public function testDatabase() { $database = $this->instance->database('test-database'); $this->assertInstanceOf(Database::class, $database); - $this->assertEquals('test-database', DatabaseAdminClient::parseDatabaseFromDatabaseName($database->name())); + $this->assertEquals('test-database', DatabaseAdminClient::parseName($database->name())['database']); } public function testDatabases() { $databases = [ - ['name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT_ID, self::NAME, 'database1')], - ['name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT_ID, self::NAME, 'database2')] + ['name' => DatabaseAdminClient::databaseName(self::PROJECT_ID, self::NAME, 'database1')], + ['name' => DatabaseAdminClient::databaseName(self::PROJECT_ID, self::NAME, 'database2')] ]; $this->connection->listDatabases(Argument::any()) @@ -269,15 +269,15 @@ public function testDatabases() $dbs = iterator_to_array($dbs); $this->assertEquals(2, count($dbs)); - $this->assertEquals('database1', DatabaseAdminClient::parseDatabaseFromDatabaseName($dbs[0]->name())); - $this->assertEquals('database2', DatabaseAdminClient::parseDatabaseFromDatabaseName($dbs[1]->name())); + $this->assertEquals('database1', DatabaseAdminClient::parseName($dbs[0]->name())['database']); + $this->assertEquals('database2', DatabaseAdminClient::parseName($dbs[1]->name())['database']); } public function testDatabasesPaged() { $databases = [ - ['name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT_ID, self::NAME, 'database1')], - ['name' => DatabaseAdminClient::formatDatabaseName(self::PROJECT_ID, self::NAME, 'database2')] + ['name' => DatabaseAdminClient::databaseName(self::PROJECT_ID, self::NAME, 'database1')], + ['name' => DatabaseAdminClient::databaseName(self::PROJECT_ID, self::NAME, 'database2')] ]; $iteration = 0; @@ -294,8 +294,8 @@ public function testDatabasesPaged() $dbs = iterator_to_array($dbs); $this->assertEquals(2, count($dbs)); - $this->assertEquals('database1', DatabaseAdminClient::parseDatabaseFromDatabaseName($dbs[0]->name())); - $this->assertEquals('database2', DatabaseAdminClient::parseDatabaseFromDatabaseName($dbs[1]->name())); + $this->assertEquals('database1', DatabaseAdminClient::parseName($dbs[0]->name())['database']); + $this->assertEquals('database2', DatabaseAdminClient::parseName($dbs[1]->name())['database']); } public function testIam() diff --git a/tests/unit/Spanner/SpannerClientTest.php b/tests/unit/Spanner/SpannerClientTest.php index a58d762443bd..3ed469241990 100644 --- a/tests/unit/Spanner/SpannerClientTest.php +++ b/tests/unit/Spanner/SpannerClientTest.php @@ -70,10 +70,10 @@ public function testInstanceConfigurations() ->willReturn([ 'instanceConfigs' => [ [ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), 'displayName' => 'Bar' ], [ - 'name' => InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG), + 'name' => InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), 'displayName' => 'Bat' ] ] @@ -139,7 +139,7 @@ public function testInstanceConfiguration() $config = $this->client->instanceConfiguration('bar'); $this->assertInstanceOf(InstanceConfiguration::class, $config); - $this->assertEquals('bar', InstanceAdminClient::parseInstanceConfigFromInstanceConfigName($config->name())); + $this->assertEquals('bar', InstanceAdminClient::parseName($config->name())['instance_config']); } /** @@ -148,8 +148,8 @@ public function testInstanceConfiguration() public function testCreateInstance() { $this->connection->createInstance(Argument::that(function ($arg) { - if ($arg['name'] !== InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE)) return false; - if ($arg['config'] !== InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG)) return false; + if ($arg['name'] !== InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)) return false; + if ($arg['config'] !== InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG)) return false; return true; })) @@ -161,7 +161,7 @@ public function testCreateInstance() $this->client->___setProperty('connection', $this->connection->reveal()); $config = $this->prophesize(InstanceConfiguration::class); - $config->name()->willReturn(InstanceAdminClient::formatInstanceConfigName(self::PROJECT, self::CONFIG)); + $config->name()->willReturn(InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG)); $operation = $this->client->createInstance($config->reveal(), self::INSTANCE); @@ -175,7 +175,7 @@ public function testInstance() { $i = $this->client->instance('foo'); $this->assertInstanceOf(Instance::class, $i); - $this->assertEquals('foo', InstanceAdminClient::parseInstanceFromInstanceName($i->name())); + $this->assertEquals('foo', InstanceAdminClient::parseName($i->name())['instance']); } /** @@ -208,8 +208,8 @@ public function testInstances() $instances = iterator_to_array($instances); $this->assertEquals(2, count($instances)); - $this->assertEquals('foo', InstanceAdminClient::parseInstanceFromInstanceName($instances[0]->name())); - $this->assertEquals('bar', InstanceAdminClient::parseInstanceFromInstanceName($instances[1]->name())); + $this->assertEquals('foo', InstanceAdminClient::parseName($instances[0]->name())['instance']); + $this->assertEquals('bar', InstanceAdminClient::parseName($instances[1]->name())['instance']); } /** @@ -228,7 +228,7 @@ public function testConnect() { $database = $this->client->connect(self::INSTANCE, self::DATABASE); $this->assertInstanceOf(Database::class, $database); - $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseDatabaseFromDatabaseName($database->name())); + $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseName($database->name())['database']); } public function testConnectWithInstance() @@ -236,7 +236,7 @@ public function testConnectWithInstance() $inst = $this->client->instance(self::INSTANCE); $database = $this->client->connect($inst, self::DATABASE); $this->assertInstanceOf(Database::class, $database); - $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseDatabaseFromDatabaseName($database->name())); + $this->assertEquals(self::DATABASE, DatabaseAdminClient::parseName($database->name())['database']); } public function testKeyset() diff --git a/tests/unit/Spanner/TransactionTypeTest.php b/tests/unit/Spanner/TransactionTypeTest.php index 5c947c558bfd..b551c938e533 100644 --- a/tests/unit/Spanner/TransactionTypeTest.php +++ b/tests/unit/Spanner/TransactionTypeTest.php @@ -61,7 +61,7 @@ public function setUp() $this->connection = $this->prophesize(ConnectionInterface::class); $this->connection->createSession(Argument::any()) - ->willReturn(['name' => SpannerClient::formatSessionName( + ->willReturn(['name' => SpannerClient::sessionName( self::PROJECT, self::INSTANCE, self::DATABASE, @@ -732,7 +732,7 @@ public function testTransactionPreAllocatedRollback() $this->connection->rollback(Argument::that(function ($arg) { if ($arg['transactionId'] !== self::TRANSACTION) return false; - if ($arg['session'] !== SpannerClient::formatSessionName( + if ($arg['session'] !== SpannerClient::sessionName( self::PROJECT, self::INSTANCE, self::DATABASE, @@ -764,7 +764,7 @@ private function database(ConnectionInterface $connection) { $operation = new Operation($connection, false); $instance = $this->prophesize(Instance::class); - $instance->name()->willReturn(InstanceAdminClient::formatInstanceName(self::PROJECT, self::INSTANCE)); + $instance->name()->willReturn(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)); $database = \Google\Cloud\Dev\stub(Database::class, [ $connection,