diff --git a/composer.json b/composer.json index c2f3e9c3be73..f7ff669e291d 100644 --- a/composer.json +++ b/composer.json @@ -57,8 +57,8 @@ "league/json-guard": "^0.3", "erusev/parsedown": "^1.6", "vierbergenlars/php-semver": "^3.0", - "google/proto-client": "^0.21.0", - "google/gax": "^0.21.0", + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1", "symfony/lock": "3.3.x-dev#1ba6ac9", "phpseclib/phpseclib": "^2" }, @@ -114,4 +114,4 @@ "entry": "ServiceBuilder.php" } } -} \ No newline at end of file +} diff --git a/src/Dlp/V2beta1/DlpServiceClient.php b/src/Dlp/V2beta1/DlpServiceClient.php index ad2c868b03de..eb844f8a804f 100644 --- a/src/Dlp/V2beta1/DlpServiceClient.php +++ b/src/Dlp/V2beta1/DlpServiceClient.php @@ -30,728 +30,12 @@ namespace Google\Cloud\Dlp\V2beta1; -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\Privacy\Dlp\V2beta1\ContentItem; -use Google\Privacy\Dlp\V2beta1\CreateInspectOperationRequest; -use Google\Privacy\Dlp\V2beta1\DlpServiceGrpcClient; -use Google\Privacy\Dlp\V2beta1\InspectConfig; -use Google\Privacy\Dlp\V2beta1\InspectContentRequest; -use Google\Privacy\Dlp\V2beta1\ListInfoTypesRequest; -use Google\Privacy\Dlp\V2beta1\ListInspectFindingsRequest; -use Google\Privacy\Dlp\V2beta1\ListRootCategoriesRequest; -use Google\Privacy\Dlp\V2beta1\OutputStorageConfig; -use Google\Privacy\Dlp\V2beta1\RedactContentRequest; -use Google\Privacy\Dlp\V2beta1\RedactContentRequest_ImageRedactionConfig as ImageRedactionConfig; -use Google\Privacy\Dlp\V2beta1\RedactContentRequest_ReplaceConfig as ReplaceConfig; -use Google\Privacy\Dlp\V2beta1\StorageConfig; +use Google\Cloud\Dlp\V2beta1\Gapic\DlpServiceGapicClient; /** - * Service Description: The DLP API is a service that allows clients - * to detect the presence of Personally Identifiable Information (PII) and other - * privacy-sensitive data in user-supplied, unstructured data streams, like text - * blocks or images. - * The service also includes methods for sensitive data redaction and - * scheduling of data scans on Google Cloud Platform based data sets. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $items = []; - * $response = $dlpServiceClient->inspectContent($inspectConfig, $items); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class DlpServiceClient +class DlpServiceClient extends DlpServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'dlp.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $resultNameTemplate; - - private $grpcCredentialsHelper; - private $dlpServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - private $operationsClient; - - /** - * Formats a string containing the fully-qualified path to represent - * a result resource. - * - * @param string $result - * - * @return string The formatted result resource. - * @experimental - */ - public static function formatResultName($result) - { - return self::getResultNameTemplate()->render([ - 'result' => $result, - ]); - } - - /** - * Parses the result from the given fully-qualified path which - * represents a result resource. - * - * @param string $resultName The fully-qualified result resource. - * - * @return string The extracted result value. - * @experimental - */ - public static function parseResultFromResultName($resultName) - { - return self::getResultNameTemplate()->match($resultName)['result']; - } - - private static function getResultNameTemplate() - { - if (self::$resultNameTemplate == null) { - self::$resultNameTemplate = new PathTemplate('inspect/results/{result}'); - } - - return self::$resultNameTemplate; - } - - private static function getLongRunningDescriptors() - { - return [ - 'createInspectOperation' => [ - 'operationReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationResult', - 'metadataReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationMetadata', - ], - ]; - } - - 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; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'dlp.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the DLP API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'inspectContent' => $defaultDescriptors, - 'redactContent' => $defaultDescriptors, - 'createInspectOperation' => $defaultDescriptors, - 'listInspectFindings' => $defaultDescriptors, - 'listInfoTypes' => $defaultDescriptors, - 'listRootCategories' => $defaultDescriptors, - ]; - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/dlp_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.privacy.dlp.v2beta1.DlpService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createDlpServiceStubFunction = function ($hostname, $opts) { - return new DlpServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createDlpServiceStubFunction', $options)) { - $createDlpServiceStubFunction = $options['createDlpServiceStubFunction']; - } - $this->dlpServiceStub = $this->grpcCredentialsHelper->createStub( - $createDlpServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Finds potentially sensitive info in a list of strings. - * This method has limits on input size, processing time, and output size. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $items = []; - * $response = $dlpServiceClient->inspectContent($inspectConfig, $items); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param InspectConfig $inspectConfig Configuration for the inspector. - * @param ContentItem[] $items The list of items to inspect. Items in a single request are - * considered "related" unless inspect_config.independent_inputs is true. - * Up to 100 are allowed per request. - * @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. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\InspectContentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function inspectContent($inspectConfig, $items, $optionalArgs = []) - { - $request = new InspectContentRequest(); - $request->setInspectConfig($inspectConfig); - $request->setItems($items); - - $mergedSettings = $this->defaultCallSettings['inspectContent']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'InspectContent', - $mergedSettings, - $this->descriptors['inspectContent'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Redacts potentially sensitive info from a list of strings. - * This method has limits on input size, processing time, and output size. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $items = []; - * $replaceConfigs = []; - * $response = $dlpServiceClient->redactContent($inspectConfig, $items, $replaceConfigs); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param InspectConfig $inspectConfig Configuration for the inspector. - * @param ContentItem[] $items The list of items to inspect. Up to 100 are allowed per request. - * @param ReplaceConfig[] $replaceConfigs The strings to replace findings text findings with. Must specify at least - * one of these or one ImageRedactionConfig if redacting images. - * @param array $optionalArgs { - * Optional. - * - * @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. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\RedactContentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function redactContent($inspectConfig, $items, $replaceConfigs, $optionalArgs = []) - { - $request = new RedactContentRequest(); - $request->setInspectConfig($inspectConfig); - $request->setItems($items); - $request->setReplaceConfigs($replaceConfigs); - if (isset($optionalArgs['imageRedactionConfigs'])) { - $request->setImageRedactionConfigs($optionalArgs['imageRedactionConfigs']); - } - - $mergedSettings = $this->defaultCallSettings['redactContent']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'RedactContent', - $mergedSettings, - $this->descriptors['redactContent'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Schedules a job scanning content in a Google Cloud Platform data - * repository. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $storageConfig = new StorageConfig(); - * $outputConfig = new OutputStorageConfig(); - * $operationResponse = $dlpServiceClient->createInspectOperation($inspectConfig, $storageConfig, $outputConfig); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $dlpServiceClient->createInspectOperation($inspectConfig, $storageConfig, $outputConfig); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $dlpServiceClient->resumeOperation($operationName, 'createInspectOperation'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param InspectConfig $inspectConfig Configuration for the inspector. - * @param StorageConfig $storageConfig Specification of the data set to process. - * @param OutputStorageConfig $outputConfig Optional location to store findings. The bucket must already exist and - * the Google APIs service account for DLP must have write permission to - * write to the given bucket. - *

Results are split over multiple csv files with each file name matching - * the pattern "[operation_id]_[count].csv", for example - * `3094877188788974909_1.csv`. The `operation_id` matches the - * identifier for the Operation, and the `count` is a counter used for - * tracking the number of files written.

The CSV file(s) contain the - * following columns regardless of storage type scanned:

  • id
  • info_type - *
  • likelihood
  • byte size of finding
  • quote
  • time_stamp
    - *

    For Cloud Storage the next columns are:

  • file_path - *
  • start_offset
    - *

    For Cloud Datastore the next columns are:

  • project_id - *
  • namespace_id
  • path
  • column_name
  • offset - * @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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createInspectOperation($inspectConfig, $storageConfig, $outputConfig, $optionalArgs = []) - { - $request = new CreateInspectOperationRequest(); - $request->setInspectConfig($inspectConfig); - $request->setStorageConfig($storageConfig); - $request->setOutputConfig($outputConfig); - - $mergedSettings = $this->defaultCallSettings['createInspectOperation']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'CreateInspectOperation', - $mergedSettings, - $this->descriptors['createInspectOperation'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns list of results for given inspect operation result set id. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $formattedName = DlpServiceClient::formatResultName("[RESULT]"); - * $response = $dlpServiceClient->listInspectFindings($formattedName); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param string $name Identifier of the results set returned as metadata of - * the longrunning operation created by a call to CreateInspectOperation. - * Should be in the format of `inspect/results/{id}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * Maximum number of results to return. - * If 0, the implementation selects a reasonable value. - * @type string $pageToken - * The value returned by the last `ListInspectFindingsResponse`; indicates - * that this is a continuation of a prior `ListInspectFindings` call, and that - * the system should return the next page of data. - * @type string $filter - * Restricts findings to items that match. Supports info_type and likelihood. - *

    Examples:
    - *

  • info_type=EMAIL_ADDRESS - *
  • info_type=PHONE_NUMBER,EMAIL_ADDRESS - *
  • 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. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\ListInspectFindingsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listInspectFindings($name, $optionalArgs = []) - { - $request = new ListInspectFindingsRequest(); - $request->setName($name); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - - $mergedSettings = $this->defaultCallSettings['listInspectFindings']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'ListInspectFindings', - $mergedSettings, - $this->descriptors['listInspectFindings'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns sensitive information types for given category. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $category = ""; - * $languageCode = ""; - * $response = $dlpServiceClient->listInfoTypes($category, $languageCode); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param string $category Category name as returned by ListRootCategories. - * @param string $languageCode Optional BCP-47 language code for localized info type friendly - * names. If omitted, or if localized strings are not available, - * en-US strings will be returned. - * @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. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\ListInfoTypesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listInfoTypes($category, $languageCode, $optionalArgs = []) - { - $request = new ListInfoTypesRequest(); - $request->setCategory($category); - $request->setLanguageCode($languageCode); - - $mergedSettings = $this->defaultCallSettings['listInfoTypes']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'ListInfoTypes', - $mergedSettings, - $this->descriptors['listInfoTypes'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns the list of root categories of sensitive information. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $languageCode = ""; - * $response = $dlpServiceClient->listRootCategories($languageCode); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param string $languageCode Optional language code for localized friendly category names. - * If omitted or if localized strings are not available, - * en-US strings will be returned. - * @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. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\ListRootCategoriesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listRootCategories($languageCode, $optionalArgs = []) - { - $request = new ListRootCategoriesRequest(); - $request->setLanguageCode($languageCode); - - $mergedSettings = $this->defaultCallSettings['listRootCategories']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'ListRootCategories', - $mergedSettings, - $this->descriptors['listRootCategories'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->dlpServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see DlpServiceClientImpl} class. } diff --git a/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php b/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php new file mode 100644 index 000000000000..5f7bbb5e6596 --- /dev/null +++ b/src/Dlp/V2beta1/Gapic/DlpServiceGapicClient.php @@ -0,0 +1,764 @@ +inspectContent($inspectConfig, $items); + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class DlpServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'dlp.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $resultNameTemplate; + + protected $grpcCredentialsHelper; + protected $dlpServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + private $operationsClient; + + /** + * Formats a string containing the fully-qualified path to represent + * a result resource. + * + * @param string $result + * + * @return string The formatted result resource. + * @experimental + */ + public static function formatResultName($result) + { + return self::getResultNameTemplate()->render([ + 'result' => $result, + ]); + } + + /** + * Parses the result from the given fully-qualified path which + * represents a result resource. + * + * @param string $resultName The fully-qualified result resource. + * + * @return string The extracted result value. + * @experimental + */ + public static function parseResultFromResultName($resultName) + { + return self::getResultNameTemplate()->match($resultName)['result']; + } + + private static function getResultNameTemplate() + { + if (self::$resultNameTemplate == null) { + self::$resultNameTemplate = new PathTemplate('inspect/results/{result}'); + } + + return self::$resultNameTemplate; + } + + private static function getLongRunningDescriptors() + { + return [ + 'createInspectOperation' => [ + 'operationReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationResult', + 'metadataReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationMetadata', + ], + ]; + } + + 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; + } + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return \Google\GAX\LongRunning\OperationsClient + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started + * by a long running API method. If $methodName is not provided, or does + * not match a long running API method, then the operation can still be + * resumed, but the OperationResponse object will not deserialize the + * final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return \Google\GAX\OperationResponse + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $lroDescriptors = self::getLongRunningDescriptors(); + if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { + $options = $lroDescriptors[$methodName]; + } else { + $options = []; + } + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'dlp.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + if (array_key_exists('operationsClient', $options)) { + $this->operationsClient = $options['operationsClient']; + } else { + $operationsClientOptions = $options; + unset($operationsClientOptions['timeoutMillis']); + unset($operationsClientOptions['retryingOverride']); + $this->operationsClient = new OperationsClient($operationsClientOptions); + } + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'inspectContent' => $defaultDescriptors, + 'redactContent' => $defaultDescriptors, + 'createInspectOperation' => $defaultDescriptors, + 'listInspectFindings' => $defaultDescriptors, + 'listInfoTypes' => $defaultDescriptors, + 'listRootCategories' => $defaultDescriptors, + ]; + $longRunningDescriptors = self::getLongRunningDescriptors(); + foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { + $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/dlp_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.privacy.dlp.v2beta1.DlpService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createDlpServiceStubFunction = function ($hostname, $opts, $channel) { + return new DlpServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createDlpServiceStubFunction', $options)) { + $createDlpServiceStubFunction = $options['createDlpServiceStubFunction']; + } + $this->dlpServiceStub = $this->grpcCredentialsHelper->createStub($createDlpServiceStubFunction); + } + + /** + * Finds potentially sensitive info in a list of strings. + * This method has limits on input size, processing time, and output size. + * + * Sample code: + * ``` + * try { + * $dlpServiceClient = new DlpServiceClient(); + * $inspectConfig = new InspectConfig(); + * $items = []; + * $response = $dlpServiceClient->inspectContent($inspectConfig, $items); + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * @param InspectConfig $inspectConfig Configuration for the inspector. + * @param ContentItem[] $items The list of items to inspect. Items in a single request are + * considered "related" unless inspect_config.independent_inputs is true. + * Up to 100 are allowed per request. + * @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. + * } + * + * @return \Google\Privacy\Dlp\V2beta1\InspectContentResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function inspectContent($inspectConfig, $items, $optionalArgs = []) + { + $request = new InspectContentRequest(); + $request->setInspectConfig($inspectConfig); + $request->setItems($items); + + $mergedSettings = $this->defaultCallSettings['inspectContent']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->dlpServiceStub, + 'InspectContent', + $mergedSettings, + $this->descriptors['inspectContent'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Redacts potentially sensitive info from a list of strings. + * This method has limits on input size, processing time, and output size. + * + * Sample code: + * ``` + * try { + * $dlpServiceClient = new DlpServiceClient(); + * $inspectConfig = new InspectConfig(); + * $items = []; + * $replaceConfigs = []; + * $response = $dlpServiceClient->redactContent($inspectConfig, $items, $replaceConfigs); + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * @param InspectConfig $inspectConfig Configuration for the inspector. + * @param ContentItem[] $items The list of items to inspect. Up to 100 are allowed per request. + * @param ReplaceConfig[] $replaceConfigs The strings to replace findings text findings with. Must specify at least + * one of these or one ImageRedactionConfig if redacting images. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Privacy\Dlp\V2beta1\RedactContentResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function redactContent($inspectConfig, $items, $replaceConfigs, $optionalArgs = []) + { + $request = new RedactContentRequest(); + $request->setInspectConfig($inspectConfig); + $request->setItems($items); + $request->setReplaceConfigs($replaceConfigs); + if (isset($optionalArgs['imageRedactionConfigs'])) { + $request->setImageRedactionConfigs($optionalArgs['imageRedactionConfigs']); + } + + $mergedSettings = $this->defaultCallSettings['redactContent']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->dlpServiceStub, + 'RedactContent', + $mergedSettings, + $this->descriptors['redactContent'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Schedules a job scanning content in a Google Cloud Platform data + * repository. + * + * Sample code: + * ``` + * try { + * $dlpServiceClient = new DlpServiceClient(); + * $inspectConfig = new InspectConfig(); + * $storageConfig = new StorageConfig(); + * $outputConfig = new OutputStorageConfig(); + * $operationResponse = $dlpServiceClient->createInspectOperation($inspectConfig, $storageConfig, $outputConfig); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $dlpServiceClient->createInspectOperation($inspectConfig, $storageConfig, $outputConfig); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $dlpServiceClient->resumeOperation($operationName, 'createInspectOperation'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * @param InspectConfig $inspectConfig Configuration for the inspector. + * @param StorageConfig $storageConfig Specification of the data set to process. + * @param OutputStorageConfig $outputConfig Optional location to store findings. The bucket must already exist and + * the Google APIs service account for DLP must have write permission to + * write to the given bucket. + *

    Results are split over multiple csv files with each file name matching + * the pattern "[operation_id]_[count].csv", for example + * `3094877188788974909_1.csv`. The `operation_id` matches the + * identifier for the Operation, and the `count` is a counter used for + * tracking the number of files written.

    The CSV file(s) contain the + * following columns regardless of storage type scanned:

  • id
  • info_type + *
  • likelihood
  • byte size of finding
  • quote
  • timestamp
    + *

    For Cloud Storage the next columns are:

  • file_path + *
  • start_offset
    + *

    For Cloud Datastore the next columns are:

  • project_id + *
  • namespace_id
  • path
  • column_name
  • offset
    + *

    For BigQuery the next columns are:

  • row_number
  • project_id + *
  • dataset_id
  • table_id + * @param array $optionalArgs { + * 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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createInspectOperation($inspectConfig, $storageConfig, $outputConfig, $optionalArgs = []) + { + $request = new CreateInspectOperationRequest(); + $request->setInspectConfig($inspectConfig); + $request->setStorageConfig($storageConfig); + $request->setOutputConfig($outputConfig); + if (isset($optionalArgs['operationConfig'])) { + $request->setOperationConfig($optionalArgs['operationConfig']); + } + + $mergedSettings = $this->defaultCallSettings['createInspectOperation']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->dlpServiceStub, + 'CreateInspectOperation', + $mergedSettings, + $this->descriptors['createInspectOperation'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns list of results for given inspect operation result set id. + * + * Sample code: + * ``` + * try { + * $dlpServiceClient = new DlpServiceClient(); + * $formattedName = DlpServiceClient::formatResultName("[RESULT]"); + * $response = $dlpServiceClient->listInspectFindings($formattedName); + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * @param string $name Identifier of the results set returned as metadata of + * the longrunning operation created by a call to CreateInspectOperation. + * Should be in the format of `inspect/results/{id}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * Maximum number of results to return. + * If 0, the implementation selects a reasonable value. + * @type string $pageToken + * The value returned by the last `ListInspectFindingsResponse`; indicates + * that this is a continuation of a prior `ListInspectFindings` call, and that + * the system should return the next page of data. + * @type string $filter + * Restricts findings to items that match. Supports info_type and likelihood. + *

    Examples:
    + *

  • info_type=EMAIL_ADDRESS + *
  • info_type=PHONE_NUMBER,EMAIL_ADDRESS + *
  • 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. + * } + * + * @return \Google\Privacy\Dlp\V2beta1\ListInspectFindingsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listInspectFindings($name, $optionalArgs = []) + { + $request = new ListInspectFindingsRequest(); + $request->setName($name); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + + $mergedSettings = $this->defaultCallSettings['listInspectFindings']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->dlpServiceStub, + 'ListInspectFindings', + $mergedSettings, + $this->descriptors['listInspectFindings'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns sensitive information types for given category. + * + * Sample code: + * ``` + * try { + * $dlpServiceClient = new DlpServiceClient(); + * $category = ""; + * $languageCode = ""; + * $response = $dlpServiceClient->listInfoTypes($category, $languageCode); + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * @param string $category Category name as returned by ListRootCategories. + * @param string $languageCode Optional BCP-47 language code for localized info type friendly + * names. If omitted, or if localized strings are not available, + * en-US strings will be returned. + * @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. + * } + * + * @return \Google\Privacy\Dlp\V2beta1\ListInfoTypesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listInfoTypes($category, $languageCode, $optionalArgs = []) + { + $request = new ListInfoTypesRequest(); + $request->setCategory($category); + $request->setLanguageCode($languageCode); + + $mergedSettings = $this->defaultCallSettings['listInfoTypes']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->dlpServiceStub, + 'ListInfoTypes', + $mergedSettings, + $this->descriptors['listInfoTypes'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns the list of root categories of sensitive information. + * + * Sample code: + * ``` + * try { + * $dlpServiceClient = new DlpServiceClient(); + * $languageCode = ""; + * $response = $dlpServiceClient->listRootCategories($languageCode); + * } finally { + * $dlpServiceClient->close(); + * } + * ``` + * + * @param string $languageCode Optional language code for localized friendly category names. + * If omitted or if localized strings are not available, + * en-US strings will be returned. + * @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. + * } + * + * @return \Google\Privacy\Dlp\V2beta1\ListRootCategoriesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listRootCategories($languageCode, $optionalArgs = []) + { + $request = new ListRootCategoriesRequest(); + $request->setLanguageCode($languageCode); + + $mergedSettings = $this->defaultCallSettings['listRootCategories']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->dlpServiceStub, + 'ListRootCategories', + $mergedSettings, + $this->descriptors['listRootCategories'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->dlpServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Dlp/composer.json b/src/Dlp/composer.json index 29c681cc0d80..edfc62a60a63 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.21.0", - "google/gax": "^0.21.0" + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1" }, "extra": { "component": { diff --git a/src/ErrorReporting/V1beta1/ErrorGroupServiceClient.php b/src/ErrorReporting/V1beta1/ErrorGroupServiceClient.php index 91477936e4c6..3d09998e357f 100644 --- a/src/ErrorReporting/V1beta1/ErrorGroupServiceClient.php +++ b/src/ErrorReporting/V1beta1/ErrorGroupServiceClient.php @@ -30,364 +30,12 @@ namespace Google\Cloud\ErrorReporting\V1beta1; -use Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup; -use Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroupServiceGrpcClient; -use Google\Devtools\Clouderrorreporting\V1beta1\GetGroupRequest; -use Google\Devtools\Clouderrorreporting\V1beta1\UpdateGroupRequest; -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\Cloud\ErrorReporting\V1beta1\Gapic\ErrorGroupServiceGapicClient; /** - * Service Description: Service for retrieving and updating individual error groups. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $errorGroupServiceClient = new ErrorGroupServiceClient(); - * $formattedGroupName = ErrorGroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * $response = $errorGroupServiceClient->getGroup($formattedGroupName); - * } finally { - * $errorGroupServiceClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class ErrorGroupServiceClient +class ErrorGroupServiceClient extends ErrorGroupServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $groupNameTemplate; - - private $grpcCredentialsHelper; - private $errorGroupServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * 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 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 getGroupNameTemplate() - { - if (self::$groupNameTemplate == null) { - self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); - } - - return self::$groupNameTemplate; - } - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'clouderrorreporting.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Error Reporting API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'getGroup' => $defaultDescriptors, - 'updateGroup' => $defaultDescriptors, - ]; - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/error_group_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createErrorGroupServiceStubFunction = function ($hostname, $opts) { - return new ErrorGroupServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createErrorGroupServiceStubFunction', $options)) { - $createErrorGroupServiceStubFunction = $options['createErrorGroupServiceStubFunction']; - } - $this->errorGroupServiceStub = $this->grpcCredentialsHelper->createStub( - $createErrorGroupServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Get the specified group. - * - * Sample code: - * ``` - * try { - * $errorGroupServiceClient = new ErrorGroupServiceClient(); - * $formattedGroupName = ErrorGroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * $response = $errorGroupServiceClient->getGroup($formattedGroupName); - * } finally { - * $errorGroupServiceClient->close(); - * } - * ``` - * - * @param string $groupName [Required] The group resource name. Written as - * projects/projectID/groups/group_name. - * Call - * - * groupStats.list to return a list of groups belonging to - * this project. - * - * Example: projects/my-project-123/groups/my-group - * @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. - * } - * - * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getGroup($groupName, $optionalArgs = []) - { - $request = new GetGroupRequest(); - $request->setGroupName($groupName); - - $mergedSettings = $this->defaultCallSettings['getGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->errorGroupServiceStub, - 'GetGroup', - $mergedSettings, - $this->descriptors['getGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Replace the data for the specified group. - * Fails if the group does not exist. - * - * Sample code: - * ``` - * try { - * $errorGroupServiceClient = new ErrorGroupServiceClient(); - * $group = new ErrorGroup(); - * $response = $errorGroupServiceClient->updateGroup($group); - * } finally { - * $errorGroupServiceClient->close(); - * } - * ``` - * - * @param ErrorGroup $group [Required] The group which replaces the resource on the server. - * @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. - * } - * - * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateGroup($group, $optionalArgs = []) - { - $request = new UpdateGroupRequest(); - $request->setGroup($group); - - $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->errorGroupServiceStub, - 'UpdateGroup', - $mergedSettings, - $this->descriptors['updateGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->errorGroupServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ErrorGroupServiceClientImpl} class. } diff --git a/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php b/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php index c52614274088..8cf915ee7f17 100644 --- a/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php +++ b/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php @@ -30,576 +30,12 @@ namespace Google\Cloud\ErrorReporting\V1beta1; -use Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsRequest; -use Google\Devtools\Clouderrorreporting\V1beta1\ErrorStatsServiceGrpcClient; -use Google\Devtools\Clouderrorreporting\V1beta1\ListEventsRequest; -use Google\Devtools\Clouderrorreporting\V1beta1\ListGroupStatsRequest; -use Google\Devtools\Clouderrorreporting\V1beta1\QueryTimeRange; -use Google\Devtools\Clouderrorreporting\V1beta1\ServiceContextFilter; -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\Protobuf\Duration; -use Google\Protobuf\Timestamp; +use Google\Cloud\ErrorReporting\V1beta1\Gapic\ErrorStatsServiceGapicClient; /** - * Service Description: An API for retrieving and managing error statistics as well as data for - * individual events. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); - * $timeRange = new QueryTimeRange(); - * // Iterate through all elements - * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $errorStatsServiceClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class ErrorStatsServiceClient +class ErrorStatsServiceClient extends ErrorStatsServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - - private $grpcCredentialsHelper; - private $errorStatsServiceStub; - private $scopes; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listGroupStatsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getErrorGroupStats', - ]); - $listEventsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getErrorEvents', - ]); - - $pageStreamingDescriptors = [ - 'listGroupStats' => $listGroupStatsPageStreamingDescriptor, - 'listEvents' => $listEventsPageStreamingDescriptor, - ]; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'clouderrorreporting.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Error Reporting API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listGroupStats' => $defaultDescriptors, - 'listEvents' => $defaultDescriptors, - 'deleteEvents' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/error_stats_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createErrorStatsServiceStubFunction = function ($hostname, $opts) { - return new ErrorStatsServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createErrorStatsServiceStubFunction', $options)) { - $createErrorStatsServiceStubFunction = $options['createErrorStatsServiceStubFunction']; - } - $this->errorStatsServiceStub = $this->grpcCredentialsHelper->createStub( - $createErrorStatsServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists the specified groups. - * - * Sample code: - * ``` - * try { - * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); - * $timeRange = new QueryTimeRange(); - * // Iterate through all elements - * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $errorStatsServiceClient->close(); - * } - * ``` - * - * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written - * as projects/ plus the - * Google Cloud - * Platform project ID. - * - * Example: projects/my-project-123. - * @param QueryTimeRange $timeRange [Optional] List data for the given time range. - * If not set a default time range is used. The field time_range_begin - * in the response will specify the beginning of this time range. - * Only ErrorGroupStats with a non-zero count in the given time - * range are returned, unless the request contains an explicit group_id list. - * If a group_id list is given, also ErrorGroupStats with zero - * occurrences are returned. - * @param array $optionalArgs { - * Optional. - * - * @type string[] $groupId - * [Optional] List all ErrorGroupStats with these IDs. - * @type ServiceContextFilter $serviceFilter - * [Optional] List only ErrorGroupStats which belong to a service - * context that matches the filter. - * Data for all service contexts is returned if this field is not specified. - * @type Duration $timedCountDuration - * [Optional] The preferred duration for a single returned `TimedCount`. - * If not set, no timed counts are returned. - * @type int $alignment - * [Optional] The alignment of the timed counts to be returned. - * Default is `ALIGNMENT_EQUAL_AT_END`. - * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\TimedCountAlignment} - * @type Timestamp $alignmentTime - * [Optional] Time where the timed counts shall be aligned if rounded - * alignment is chosen. Default is 00:00 UTC. - * @type int $order - * [Optional] The sort order in which the results are returned. - * Default is `COUNT_DESC`. - * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroupOrder} - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listGroupStats($projectName, $timeRange, $optionalArgs = []) - { - $request = new ListGroupStatsRequest(); - $request->setProjectName($projectName); - $request->setTimeRange($timeRange); - if (isset($optionalArgs['groupId'])) { - $request->setGroupId($optionalArgs['groupId']); - } - if (isset($optionalArgs['serviceFilter'])) { - $request->setServiceFilter($optionalArgs['serviceFilter']); - } - if (isset($optionalArgs['timedCountDuration'])) { - $request->setTimedCountDuration($optionalArgs['timedCountDuration']); - } - if (isset($optionalArgs['alignment'])) { - $request->setAlignment($optionalArgs['alignment']); - } - if (isset($optionalArgs['alignmentTime'])) { - $request->setAlignmentTime($optionalArgs['alignmentTime']); - } - if (isset($optionalArgs['order'])) { - $request->setOrder($optionalArgs['order']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listGroupStats']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->errorStatsServiceStub, - 'ListGroupStats', - $mergedSettings, - $this->descriptors['listGroupStats'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the specified events. - * - * Sample code: - * ``` - * try { - * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); - * $groupId = ""; - * // Iterate through all elements - * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $errorStatsServiceClient->close(); - * } - * ``` - * - * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project - * ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. - * @param string $groupId [Required] The group for which events shall be returned. - * @param array $optionalArgs { - * Optional. - * - * @type ServiceContextFilter $serviceFilter - * [Optional] List only ErrorGroups which belong to a service context that - * matches the filter. - * Data for all service contexts is returned if this field is not specified. - * @type QueryTimeRange $timeRange - * [Optional] List only data for the given time range. - * If not set a default time range is used. The field time_range_begin - * in the response will specify the beginning of this time range. - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listEvents($projectName, $groupId, $optionalArgs = []) - { - $request = new ListEventsRequest(); - $request->setProjectName($projectName); - $request->setGroupId($groupId); - if (isset($optionalArgs['serviceFilter'])) { - $request->setServiceFilter($optionalArgs['serviceFilter']); - } - if (isset($optionalArgs['timeRange'])) { - $request->setTimeRange($optionalArgs['timeRange']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listEvents']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->errorStatsServiceStub, - 'ListEvents', - $mergedSettings, - $this->descriptors['listEvents'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes all error events of a given project. - * - * Sample code: - * ``` - * try { - * $errorStatsServiceClient = new ErrorStatsServiceClient(); - * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); - * $response = $errorStatsServiceClient->deleteEvents($formattedProjectName); - * } finally { - * $errorStatsServiceClient->close(); - * } - * ``` - * - * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project - * ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. - * @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. - * } - * - * @return \Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteEvents($projectName, $optionalArgs = []) - { - $request = new DeleteEventsRequest(); - $request->setProjectName($projectName); - - $mergedSettings = $this->defaultCallSettings['deleteEvents']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->errorStatsServiceStub, - 'DeleteEvents', - $mergedSettings, - $this->descriptors['deleteEvents'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->errorStatsServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ErrorStatsServiceClientImpl} class. } diff --git a/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php new file mode 100644 index 000000000000..a024985cdbc5 --- /dev/null +++ b/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php @@ -0,0 +1,392 @@ +getGroup($formattedGroupName); + * } finally { + * $errorGroupServiceClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class ErrorGroupServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $groupNameTemplate; + + protected $grpcCredentialsHelper; + protected $errorGroupServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * 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 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 getGroupNameTemplate() + { + if (self::$groupNameTemplate == null) { + self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); + } + + return self::$groupNameTemplate; + } + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'clouderrorreporting.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'getGroup' => $defaultDescriptors, + 'updateGroup' => $defaultDescriptors, + ]; + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/error_group_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createErrorGroupServiceStubFunction = function ($hostname, $opts, $channel) { + return new ErrorGroupServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createErrorGroupServiceStubFunction', $options)) { + $createErrorGroupServiceStubFunction = $options['createErrorGroupServiceStubFunction']; + } + $this->errorGroupServiceStub = $this->grpcCredentialsHelper->createStub($createErrorGroupServiceStubFunction); + } + + /** + * Get the specified group. + * + * Sample code: + * ``` + * try { + * $errorGroupServiceClient = new ErrorGroupServiceClient(); + * $formattedGroupName = ErrorGroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $response = $errorGroupServiceClient->getGroup($formattedGroupName); + * } finally { + * $errorGroupServiceClient->close(); + * } + * ``` + * + * @param string $groupName [Required] The group resource name. Written as + * projects/projectID/groups/group_name. + * Call + * + * groupStats.list to return a list of groups belonging to + * this project. + * + * Example: projects/my-project-123/groups/my-group + * @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. + * } + * + * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getGroup($groupName, $optionalArgs = []) + { + $request = new GetGroupRequest(); + $request->setGroupName($groupName); + + $mergedSettings = $this->defaultCallSettings['getGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->errorGroupServiceStub, + 'GetGroup', + $mergedSettings, + $this->descriptors['getGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Replace the data for the specified group. + * Fails if the group does not exist. + * + * Sample code: + * ``` + * try { + * $errorGroupServiceClient = new ErrorGroupServiceClient(); + * $group = new ErrorGroup(); + * $response = $errorGroupServiceClient->updateGroup($group); + * } finally { + * $errorGroupServiceClient->close(); + * } + * ``` + * + * @param ErrorGroup $group [Required] The group which replaces the resource on the server. + * @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. + * } + * + * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateGroup($group, $optionalArgs = []) + { + $request = new UpdateGroupRequest(); + $request->setGroup($group); + + $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->errorGroupServiceStub, + 'UpdateGroup', + $mergedSettings, + $this->descriptors['updateGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->errorGroupServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php new file mode 100644 index 000000000000..40ea53b5eec9 --- /dev/null +++ b/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php @@ -0,0 +1,604 @@ +listGroupStats($formattedProjectName, $timeRange); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $errorStatsServiceClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class ErrorStatsServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + + protected $grpcCredentialsHelper; + protected $errorStatsServiceStub; + private $scopes; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listGroupStatsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getErrorGroupStats', + ]); + $listEventsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getErrorEvents', + ]); + + $pageStreamingDescriptors = [ + 'listGroupStats' => $listGroupStatsPageStreamingDescriptor, + 'listEvents' => $listEventsPageStreamingDescriptor, + ]; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'clouderrorreporting.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listGroupStats' => $defaultDescriptors, + 'listEvents' => $defaultDescriptors, + 'deleteEvents' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/error_stats_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createErrorStatsServiceStubFunction = function ($hostname, $opts, $channel) { + return new ErrorStatsServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createErrorStatsServiceStubFunction', $options)) { + $createErrorStatsServiceStubFunction = $options['createErrorStatsServiceStubFunction']; + } + $this->errorStatsServiceStub = $this->grpcCredentialsHelper->createStub($createErrorStatsServiceStubFunction); + } + + /** + * Lists the specified groups. + * + * Sample code: + * ``` + * try { + * $errorStatsServiceClient = new ErrorStatsServiceClient(); + * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $timeRange = new QueryTimeRange(); + * // Iterate through all elements + * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $errorStatsServiceClient->close(); + * } + * ``` + * + * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written + * as projects/ plus the + * Google Cloud + * Platform project ID. + * + * Example: projects/my-project-123. + * @param QueryTimeRange $timeRange [Optional] List data for the given time range. + * If not set a default time range is used. The field time_range_begin + * in the response will specify the beginning of this time range. + * Only ErrorGroupStats with a non-zero count in the given time + * range are returned, unless the request contains an explicit group_id list. + * If a group_id list is given, also ErrorGroupStats with zero + * occurrences are returned. + * @param array $optionalArgs { + * Optional. + * + * @type string[] $groupId + * [Optional] List all ErrorGroupStats with these IDs. + * @type ServiceContextFilter $serviceFilter + * [Optional] List only ErrorGroupStats which belong to a service + * context that matches the filter. + * Data for all service contexts is returned if this field is not specified. + * @type Duration $timedCountDuration + * [Optional] The preferred duration for a single returned `TimedCount`. + * If not set, no timed counts are returned. + * @type int $alignment + * [Optional] The alignment of the timed counts to be returned. + * Default is `ALIGNMENT_EQUAL_AT_END`. + * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\TimedCountAlignment} + * @type Timestamp $alignmentTime + * [Optional] Time where the timed counts shall be aligned if rounded + * alignment is chosen. Default is 00:00 UTC. + * @type int $order + * [Optional] The sort order in which the results are returned. + * Default is `COUNT_DESC`. + * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroupOrder} + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listGroupStats($projectName, $timeRange, $optionalArgs = []) + { + $request = new ListGroupStatsRequest(); + $request->setProjectName($projectName); + $request->setTimeRange($timeRange); + if (isset($optionalArgs['groupId'])) { + $request->setGroupId($optionalArgs['groupId']); + } + if (isset($optionalArgs['serviceFilter'])) { + $request->setServiceFilter($optionalArgs['serviceFilter']); + } + if (isset($optionalArgs['timedCountDuration'])) { + $request->setTimedCountDuration($optionalArgs['timedCountDuration']); + } + if (isset($optionalArgs['alignment'])) { + $request->setAlignment($optionalArgs['alignment']); + } + if (isset($optionalArgs['alignmentTime'])) { + $request->setAlignmentTime($optionalArgs['alignmentTime']); + } + if (isset($optionalArgs['order'])) { + $request->setOrder($optionalArgs['order']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listGroupStats']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->errorStatsServiceStub, + 'ListGroupStats', + $mergedSettings, + $this->descriptors['listGroupStats'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the specified events. + * + * Sample code: + * ``` + * try { + * $errorStatsServiceClient = new ErrorStatsServiceClient(); + * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $groupId = ""; + * // Iterate through all elements + * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $errorStatsServiceClient->close(); + * } + * ``` + * + * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written + * as `projects/` plus the + * [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). + * Example: `projects/my-project-123`. + * @param string $groupId [Required] The group for which events shall be returned. + * @param array $optionalArgs { + * Optional. + * + * @type ServiceContextFilter $serviceFilter + * [Optional] List only ErrorGroups which belong to a service context that + * matches the filter. + * Data for all service contexts is returned if this field is not specified. + * @type QueryTimeRange $timeRange + * [Optional] List only data for the given time range. + * If not set a default time range is used. The field time_range_begin + * in the response will specify the beginning of this time range. + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listEvents($projectName, $groupId, $optionalArgs = []) + { + $request = new ListEventsRequest(); + $request->setProjectName($projectName); + $request->setGroupId($groupId); + if (isset($optionalArgs['serviceFilter'])) { + $request->setServiceFilter($optionalArgs['serviceFilter']); + } + if (isset($optionalArgs['timeRange'])) { + $request->setTimeRange($optionalArgs['timeRange']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listEvents']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->errorStatsServiceStub, + 'ListEvents', + $mergedSettings, + $this->descriptors['listEvents'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes all error events of a given project. + * + * Sample code: + * ``` + * try { + * $errorStatsServiceClient = new ErrorStatsServiceClient(); + * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]"); + * $response = $errorStatsServiceClient->deleteEvents($formattedProjectName); + * } finally { + * $errorStatsServiceClient->close(); + * } + * ``` + * + * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written + * as `projects/` plus the + * [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). + * Example: `projects/my-project-123`. + * @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. + * } + * + * @return \Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteEvents($projectName, $optionalArgs = []) + { + $request = new DeleteEventsRequest(); + $request->setProjectName($projectName); + + $mergedSettings = $this->defaultCallSettings['deleteEvents']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->errorStatsServiceStub, + 'DeleteEvents', + $mergedSettings, + $this->descriptors['deleteEvents'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->errorStatsServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php new file mode 100644 index 000000000000..6872418f026b --- /dev/null +++ b/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php @@ -0,0 +1,328 @@ +reportErrorEvent($formattedProjectName, $event); + * } finally { + * $reportErrorsServiceClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class ReportErrorsServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + + protected $grpcCredentialsHelper; + protected $reportErrorsServiceStub; + private $scopes; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'clouderrorreporting.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'reportErrorEvent' => $defaultDescriptors, + ]; + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/report_errors_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createReportErrorsServiceStubFunction = function ($hostname, $opts, $channel) { + return new ReportErrorsServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createReportErrorsServiceStubFunction', $options)) { + $createReportErrorsServiceStubFunction = $options['createReportErrorsServiceStubFunction']; + } + $this->reportErrorsServiceStub = $this->grpcCredentialsHelper->createStub($createReportErrorsServiceStubFunction); + } + + /** + * Report an individual error event. + * + * This endpoint accepts either an OAuth token, + * or an + * API key + * for authentication. To use an API key, append it to the URL as the value of + * a `key` parameter. For example: + *
    POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456
    + * + * Sample code: + * ``` + * try { + * $reportErrorsServiceClient = new ReportErrorsServiceClient(); + * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); + * $event = new ReportedErrorEvent(); + * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); + * } finally { + * $reportErrorsServiceClient->close(); + * } + * ``` + * + * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written + * as `projects/` plus the + * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). + * Example: `projects/my-project-123`. + * @param ReportedErrorEvent $event [Required] The error event to be reported. + * @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. + * } + * + * @return \Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function reportErrorEvent($projectName, $event, $optionalArgs = []) + { + $request = new ReportErrorEventRequest(); + $request->setProjectName($projectName); + $request->setEvent($event); + + $mergedSettings = $this->defaultCallSettings['reportErrorEvent']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->reportErrorsServiceStub, + 'ReportErrorEvent', + $mergedSettings, + $this->descriptors['reportErrorEvent'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->reportErrorsServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php b/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php index 9ab54bf3ee77..7a9a2439525c 100644 --- a/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php +++ b/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php @@ -30,300 +30,12 @@ namespace Google\Cloud\ErrorReporting\V1beta1; -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\Cloud\ErrorReporting\V1beta1\Gapic\ReportErrorsServiceGapicClient; /** - * Service Description: An API for reporting error events. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $reportErrorsServiceClient = new ReportErrorsServiceClient(); - * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); - * $event = new ReportedErrorEvent(); - * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); - * } finally { - * $reportErrorsServiceClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class ReportErrorsServiceClient +class ReportErrorsServiceClient extends ReportErrorsServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - - private $grpcCredentialsHelper; - private $reportErrorsServiceStub; - private $scopes; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'clouderrorreporting.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Error Reporting API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'reportErrorEvent' => $defaultDescriptors, - ]; - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/report_errors_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createReportErrorsServiceStubFunction = function ($hostname, $opts) { - return new ReportErrorsServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createReportErrorsServiceStubFunction', $options)) { - $createReportErrorsServiceStubFunction = $options['createReportErrorsServiceStubFunction']; - } - $this->reportErrorsServiceStub = $this->grpcCredentialsHelper->createStub( - $createReportErrorsServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Report an individual error event. - * - * This endpoint accepts either an OAuth token, - * or an - * API key - * for authentication. To use an API key, append it to the URL as the value of - * a `key` parameter. For example: - *
    POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456
    - * - * Sample code: - * ``` - * try { - * $reportErrorsServiceClient = new ReportErrorsServiceClient(); - * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); - * $event = new ReportedErrorEvent(); - * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); - * } finally { - * $reportErrorsServiceClient->close(); - * } - * ``` - * - * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. - * @param ReportedErrorEvent $event [Required] The error event to be reported. - * @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. - * } - * - * @return \Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function reportErrorEvent($projectName, $event, $optionalArgs = []) - { - $request = new ReportErrorEventRequest(); - $request->setProjectName($projectName); - $request->setEvent($event); - - $mergedSettings = $this->defaultCallSettings['reportErrorEvent']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->reportErrorsServiceStub, - 'ReportErrorEvent', - $mergedSettings, - $this->descriptors['reportErrorEvent'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->reportErrorsServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ReportErrorsServiceClientImpl} class. } diff --git a/src/ErrorReporting/composer.json b/src/ErrorReporting/composer.json index b17c545a3af1..42f5bfbbfd64 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.21.0", - "google/gax": "^0.21.0" + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1" }, "extra": { "component": { diff --git a/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php b/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php new file mode 100644 index 000000000000..23f7a374567a --- /dev/null +++ b/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php @@ -0,0 +1,526 @@ +analyzeSentiment($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @experimental + */ +class LanguageServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'language.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + protected $grpcCredentialsHelper; + protected $languageServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'language.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'analyzeSentiment' => $defaultDescriptors, + 'analyzeEntities' => $defaultDescriptors, + 'analyzeEntitySentiment' => $defaultDescriptors, + 'analyzeSyntax' => $defaultDescriptors, + 'annotateText' => $defaultDescriptors, + ]; + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/language_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.cloud.language.v1beta2.LanguageService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createLanguageServiceStubFunction = function ($hostname, $opts, $channel) { + return new LanguageServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createLanguageServiceStubFunction', $options)) { + $createLanguageServiceStubFunction = $options['createLanguageServiceStubFunction']; + } + $this->languageServiceStub = $this->grpcCredentialsHelper->createStub($createLanguageServiceStubFunction); + } + + /** + * Analyzes the sentiment of the provided text. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeSentiment($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @type int $encodingType + * 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. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeSentimentResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeSentiment($document, $optionalArgs = []) + { + $request = new AnalyzeSentimentRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeSentiment']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeSentiment', + $mergedSettings, + $this->descriptors['analyzeSentiment'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Finds named entities (currently proper names and common nouns) in the text + * along with entity types, salience, mentions for each entity, and + * other properties. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeEntities($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitiesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeEntities($document, $optionalArgs = []) + { + $request = new AnalyzeEntitiesRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeEntities']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeEntities', + $mergedSettings, + $this->descriptors['analyzeEntities'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes + * sentiment associated with each entity and its mentions. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeEntitySentiment($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitySentimentResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeEntitySentiment($document, $optionalArgs = []) + { + $request = new AnalyzeEntitySentimentRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeEntitySentiment']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeEntitySentiment', + $mergedSettings, + $this->descriptors['analyzeEntitySentiment'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Analyzes the syntax of the text and provides sentence boundaries and + * tokenization along with part of speech tags, dependency trees, and other + * properties. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeSyntax($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeSyntaxResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeSyntax($document, $optionalArgs = []) + { + $request = new AnalyzeSyntaxRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeSyntax']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeSyntax', + $mergedSettings, + $this->descriptors['analyzeSyntax'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * A convenience method that provides all syntax, sentiment, and entity + * features in one call. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $features = new Features(); + * $response = $languageServiceClient->annotateText($document, $features); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param Features $features The enabled features. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnnotateTextResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function annotateText($document, $features, $optionalArgs = []) + { + $request = new AnnotateTextRequest(); + $request->setDocument($document); + $request->setFeatures($features); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['annotateText']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnnotateText', + $mergedSettings, + $this->descriptors['annotateText'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->languageServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Language/V1beta2/LanguageServiceClient.php b/src/Language/V1beta2/LanguageServiceClient.php index 6a3d98151102..b8a7739d598b 100644 --- a/src/Language/V1beta2/LanguageServiceClient.php +++ b/src/Language/V1beta2/LanguageServiceClient.php @@ -30,482 +30,12 @@ namespace Google\Cloud\Language\V1beta2; -use Google\Cloud\Language\V1beta2\AnnotateTextRequest_Features as Features; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; +use Google\Cloud\Language\V1beta2\Gapic\LanguageServiceGapicClient; /** - * Service Description: Provides text analysis operations such as sentiment analysis and entity - * recognition. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $response = $languageServiceClient->analyzeSentiment($document); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @experimental + * {@inheritdoc} */ -class LanguageServiceClient +class LanguageServiceClient extends LanguageServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'language.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private $grpcCredentialsHelper; - private $languageServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'language.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Natural Language API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'analyzeSentiment' => $defaultDescriptors, - 'analyzeEntities' => $defaultDescriptors, - 'analyzeEntitySentiment' => $defaultDescriptors, - 'analyzeSyntax' => $defaultDescriptors, - 'annotateText' => $defaultDescriptors, - ]; - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/language_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.cloud.language.v1beta2.LanguageService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createLanguageServiceStubFunction = function ($hostname, $opts) { - return new LanguageServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createLanguageServiceStubFunction', $options)) { - $createLanguageServiceStubFunction = $options['createLanguageServiceStubFunction']; - } - $this->languageServiceStub = $this->grpcCredentialsHelper->createStub( - $createLanguageServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Analyzes the sentiment of the provided text. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $response = $languageServiceClient->analyzeSentiment($document); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param array $optionalArgs { - * Optional. - * - * @type int $encodingType - * 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. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeSentimentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeSentiment($document, $optionalArgs = []) - { - $request = new AnalyzeSentimentRequest(); - $request->setDocument($document); - if (isset($optionalArgs['encodingType'])) { - $request->setEncodingType($optionalArgs['encodingType']); - } - - $mergedSettings = $this->defaultCallSettings['analyzeSentiment']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeSentiment', - $mergedSettings, - $this->descriptors['analyzeSentiment'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Finds named entities (currently proper names and common nouns) in the text - * along with entity types, salience, mentions for each entity, and - * other properties. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->analyzeEntities($document, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param 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} - * @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. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitiesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeEntities($document, $encodingType, $optionalArgs = []) - { - $request = new AnalyzeEntitiesRequest(); - $request->setDocument($document); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['analyzeEntities']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeEntities', - $mergedSettings, - $this->descriptors['analyzeEntities'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes - * sentiment associated with each entity and its mentions. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->analyzeEntitySentiment($document, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param 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} - * @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. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitySentimentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeEntitySentiment($document, $encodingType, $optionalArgs = []) - { - $request = new AnalyzeEntitySentimentRequest(); - $request->setDocument($document); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['analyzeEntitySentiment']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeEntitySentiment', - $mergedSettings, - $this->descriptors['analyzeEntitySentiment'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Analyzes the syntax of the text and provides sentence boundaries and - * tokenization along with part of speech tags, dependency trees, and other - * properties. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->analyzeSyntax($document, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param 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} - * @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. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeSyntaxResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeSyntax($document, $encodingType, $optionalArgs = []) - { - $request = new AnalyzeSyntaxRequest(); - $request->setDocument($document); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['analyzeSyntax']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeSyntax', - $mergedSettings, - $this->descriptors['analyzeSyntax'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * A convenience method that provides all syntax, sentiment, and entity - * features in one call. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $features = new Features(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->annotateText($document, $features, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param Features $features The enabled features. - * @param 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} - * @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. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnnotateTextResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function annotateText($document, $features, $encodingType, $optionalArgs = []) - { - $request = new AnnotateTextRequest(); - $request->setDocument($document); - $request->setFeatures($features); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['annotateText']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnnotateText', - $mergedSettings, - $this->descriptors['annotateText'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->languageServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see LanguageServiceClientImpl} class. } diff --git a/src/Logging/V2/ConfigServiceV2Client.php b/src/Logging/V2/ConfigServiceV2Client.php index 57de6e1621d6..f3d39c9f70aa 100644 --- a/src/Logging/V2/ConfigServiceV2Client.php +++ b/src/Logging/V2/ConfigServiceV2Client.php @@ -30,710 +30,12 @@ namespace Google\Cloud\Logging\V2; -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\Logging\V2\ConfigServiceV2GrpcClient; -use Google\Logging\V2\CreateSinkRequest; -use Google\Logging\V2\DeleteSinkRequest; -use Google\Logging\V2\GetSinkRequest; -use Google\Logging\V2\ListSinksRequest; -use Google\Logging\V2\LogSink; -use Google\Logging\V2\UpdateSinkRequest; +use Google\Cloud\Logging\V2\Gapic\ConfigServiceV2GapicClient; /** - * Service Description: Service for configuring sinks used to export log entries outside of - * Stackdriver Logging. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class ConfigServiceV2Client +class ConfigServiceV2Client extends ConfigServiceV2GapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'logging.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $sinkNameTemplate; - - private $grpcCredentialsHelper; - private $configServiceV2Stub; - private $scopes; - 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 sink resource. - * - * @param string $project - * @param string $sink - * - * @return string The formatted sink resource. - * @experimental - */ - public static function formatSinkName($project, $sink) - { - return self::getSinkNameTemplate()->render([ - 'project' => $project, - 'sink' => $sink, - ]); - } - - /** - * 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 sink resource. - * - * @param string $sinkName The fully-qualified sink resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSinkName($sinkName) - { - return self::getSinkNameTemplate()->match($sinkName)['project']; - } - - /** - * 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']; - } - - 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 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'logging.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Logging API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listSinks' => $defaultDescriptors, - 'getSink' => $defaultDescriptors, - 'createSink' => $defaultDescriptors, - 'updateSink' => $defaultDescriptors, - 'deleteSink' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/config_service_v2_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.logging.v2.ConfigServiceV2', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createConfigServiceV2StubFunction = function ($hostname, $opts) { - return new ConfigServiceV2GrpcClient($hostname, $opts); - }; - if (array_key_exists('createConfigServiceV2StubFunction', $options)) { - $createConfigServiceV2StubFunction = $options['createConfigServiceV2StubFunction']; - } - $this->configServiceV2Stub = $this->grpcCredentialsHelper->createStub( - $createConfigServiceV2StubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists sinks. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * 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 int $pageSize - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listSinks($parent, $optionalArgs = []) - { - $request = new ListSinksRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - - $mergedSettings = $this->defaultCallSettings['listSinks']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'ListSinks', - $mergedSettings, - $this->descriptors['listSinks'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a sink. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); - * $response = $configServiceV2Client->getSink($formattedSinkName); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $sinkName Required. The resource name of the sink: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @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. - * } - * - * @return \Google\Logging\V2\LogSink - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getSink($sinkName, $optionalArgs = []) - { - $request = new GetSinkRequest(); - $request->setSinkName($sinkName); - - $mergedSettings = $this->defaultCallSettings['getSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'GetSink', - $mergedSettings, - $this->descriptors['getSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a sink that exports specified log entries to a destination. The - * export of newly-ingested log entries begins immediately, unless the current - * time is outside the sink's start and end times or the sink's - * `writer_identity` is not permitted to write to the destination. A sink can - * export log entries only from the resource owning the sink. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); - * $sink = new LogSink(); - * $response = $configServiceV2Client->createSink($formattedParent, $sink); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The resource in which to create the sink: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. - * @param LogSink $sink Required. The new sink, whose `name` parameter is a sink identifier that - * is not already in use. - * @param array $optionalArgs { - * Optional. - * - * @type bool $uniqueWriterIdentity - * Optional. Determines the kind of IAM identity returned as `writer_identity` - * in the new sink. If this value is omitted or set to false, and if the - * sink's parent is a project, then the value returned as `writer_identity` is - * the same group or service account used by Stackdriver Logging before the - * addition of writer identities to this API. The sink's destination must be - * in the same project as the sink itself. - * - * If this field is set to true, or if the sink is owned by a non-project - * 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. - * } - * - * @return \Google\Logging\V2\LogSink - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSink($parent, $sink, $optionalArgs = []) - { - $request = new CreateSinkRequest(); - $request->setParent($parent); - $request->setSink($sink); - if (isset($optionalArgs['uniqueWriterIdentity'])) { - $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); - } - - $mergedSettings = $this->defaultCallSettings['createSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'CreateSink', - $mergedSettings, - $this->descriptors['createSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates a sink. If the named sink doesn't exist, then this method is - * identical to - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create). - * If the named sink does exist, then this method replaces the following - * fields in the existing sink with values from the new sink: `destination`, - * `filter`, `output_version_format`, `start_time`, and `end_time`. - * The updated filter might also have a new `writer_identity`; see the - * `unique_writer_identity` field. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); - * $sink = new LogSink(); - * $response = $configServiceV2Client->updateSink($formattedSinkName, $sink); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $sinkName Required. The full resource name of the sink to update, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @param LogSink $sink Required. The updated sink, whose name is the same identifier that appears - * as part of `sink_name`. If `sink_name` does not exist, then - * this method creates a new sink. - * @param array $optionalArgs { - * Optional. - * - * @type bool $uniqueWriterIdentity - * Optional. See - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) - * for a description of this field. When updating a sink, the effect of this - * field on the value of `writer_identity` in the updated sink depends on both - * the old and new values of this field: - * - * + If the old and new values of this field are both false or both true, - * then there is no change to the sink's `writer_identity`. - * + If the old value is false and the new value is true, then - * `writer_identity` is changed to a unique service account. - * + It is an error if the old value is true and the new value is 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. - * } - * - * @return \Google\Logging\V2\LogSink - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateSink($sinkName, $sink, $optionalArgs = []) - { - $request = new UpdateSinkRequest(); - $request->setSinkName($sinkName); - $request->setSink($sink); - if (isset($optionalArgs['uniqueWriterIdentity'])) { - $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); - } - - $mergedSettings = $this->defaultCallSettings['updateSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'UpdateSink', - $mergedSettings, - $this->descriptors['updateSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes a sink. If the sink has a unique `writer_identity`, then that - * service account is also deleted. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); - * $configServiceV2Client->deleteSink($formattedSinkName); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $sinkName Required. The full resource name of the sink to delete, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSink($sinkName, $optionalArgs = []) - { - $request = new DeleteSinkRequest(); - $request->setSinkName($sinkName); - - $mergedSettings = $this->defaultCallSettings['deleteSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'DeleteSink', - $mergedSettings, - $this->descriptors['deleteSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->configServiceV2Stub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ConfigServiceV2ClientImpl} class. } diff --git a/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php b/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php new file mode 100644 index 000000000000..37fae77189a6 --- /dev/null +++ b/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php @@ -0,0 +1,738 @@ +listSinks($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class ConfigServiceV2GapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'logging.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $sinkNameTemplate; + + protected $grpcCredentialsHelper; + protected $configServiceV2Stub; + private $scopes; + 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 sink resource. + * + * @param string $project + * @param string $sink + * + * @return string The formatted sink resource. + * @experimental + */ + public static function formatSinkName($project, $sink) + { + return self::getSinkNameTemplate()->render([ + 'project' => $project, + 'sink' => $sink, + ]); + } + + /** + * 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 sink resource. + * + * @param string $sinkName The fully-qualified sink resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromSinkName($sinkName) + { + return self::getSinkNameTemplate()->match($sinkName)['project']; + } + + /** + * 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']; + } + + 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 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'logging.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listSinks' => $defaultDescriptors, + 'getSink' => $defaultDescriptors, + 'createSink' => $defaultDescriptors, + 'updateSink' => $defaultDescriptors, + 'deleteSink' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/config_service_v2_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.logging.v2.ConfigServiceV2', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createConfigServiceV2StubFunction = function ($hostname, $opts, $channel) { + return new ConfigServiceV2GrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createConfigServiceV2StubFunction', $options)) { + $createConfigServiceV2StubFunction = $options['createConfigServiceV2StubFunction']; + } + $this->configServiceV2Stub = $this->grpcCredentialsHelper->createStub($createConfigServiceV2StubFunction); + } + + /** + * Lists sinks. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * 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 int $pageSize + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listSinks($parent, $optionalArgs = []) + { + $request = new ListSinksRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + + $mergedSettings = $this->defaultCallSettings['listSinks']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'ListSinks', + $mergedSettings, + $this->descriptors['listSinks'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a sink. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $response = $configServiceV2Client->getSink($formattedSinkName); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $sinkName Required. The resource name of the sink: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @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. + * } + * + * @return \Google\Logging\V2\LogSink + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getSink($sinkName, $optionalArgs = []) + { + $request = new GetSinkRequest(); + $request->setSinkName($sinkName); + + $mergedSettings = $this->defaultCallSettings['getSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'GetSink', + $mergedSettings, + $this->descriptors['getSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a sink that exports specified log entries to a destination. The + * export of newly-ingested log entries begins immediately, unless the current + * time is outside the sink's start and end times or the sink's + * `writer_identity` is not permitted to write to the destination. A sink can + * export log entries only from the resource owning the sink. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * $sink = new LogSink(); + * $response = $configServiceV2Client->createSink($formattedParent, $sink); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The resource in which to create the sink: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param LogSink $sink Required. The new sink, whose `name` parameter is a sink identifier that + * is not already in use. + * @param array $optionalArgs { + * Optional. + * + * @type bool $uniqueWriterIdentity + * Optional. Determines the kind of IAM identity returned as `writer_identity` + * in the new sink. If this value is omitted or set to false, and if the + * sink's parent is a project, then the value returned as `writer_identity` is + * the same group or service account used by Stackdriver Logging before the + * addition of writer identities to this API. The sink's destination must be + * in the same project as the sink itself. + * + * If this field is set to true, or if the sink is owned by a non-project + * 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. + * } + * + * @return \Google\Logging\V2\LogSink + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSink($parent, $sink, $optionalArgs = []) + { + $request = new CreateSinkRequest(); + $request->setParent($parent); + $request->setSink($sink); + if (isset($optionalArgs['uniqueWriterIdentity'])) { + $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); + } + + $mergedSettings = $this->defaultCallSettings['createSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'CreateSink', + $mergedSettings, + $this->descriptors['createSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates a sink. If the named sink doesn't exist, then this method is + * identical to + * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create). + * If the named sink does exist, then this method replaces the following + * fields in the existing sink with values from the new sink: `destination`, + * `filter`, `output_version_format`, `start_time`, and `end_time`. + * The updated filter might also have a new `writer_identity`; see the + * `unique_writer_identity` field. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $sink = new LogSink(); + * $response = $configServiceV2Client->updateSink($formattedSinkName, $sink); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $sinkName Required. The full resource name of the sink to update, including the + * parent resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param LogSink $sink Required. The updated sink, whose name is the same identifier that appears + * as part of `sink_name`. If `sink_name` does not exist, then + * this method creates a new sink. + * @param array $optionalArgs { + * Optional. + * + * @type bool $uniqueWriterIdentity + * Optional. See + * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) + * for a description of this field. When updating a sink, the effect of this + * field on the value of `writer_identity` in the updated sink depends on both + * the old and new values of this field: + * + * + If the old and new values of this field are both false or both true, + * then there is no change to the sink's `writer_identity`. + * + If the old value is false and the new value is true, then + * `writer_identity` is changed to a unique service account. + * + It is an error if the old value is true and the new value is 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. + * } + * + * @return \Google\Logging\V2\LogSink + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateSink($sinkName, $sink, $optionalArgs = []) + { + $request = new UpdateSinkRequest(); + $request->setSinkName($sinkName); + $request->setSink($sink); + if (isset($optionalArgs['uniqueWriterIdentity'])) { + $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); + } + + $mergedSettings = $this->defaultCallSettings['updateSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'UpdateSink', + $mergedSettings, + $this->descriptors['updateSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that + * service account is also deleted. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $configServiceV2Client->deleteSink($formattedSinkName); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $sinkName Required. The full resource name of the sink to delete, including the + * parent resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSink($sinkName, $optionalArgs = []) + { + $request = new DeleteSinkRequest(); + $request->setSinkName($sinkName); + + $mergedSettings = $this->defaultCallSettings['deleteSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'DeleteSink', + $mergedSettings, + $this->descriptors['deleteSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->configServiceV2Stub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php b/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php new file mode 100644 index 000000000000..3ca10519b2fa --- /dev/null +++ b/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php @@ -0,0 +1,833 @@ +deleteLog($formattedLogName); + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class LoggingServiceV2GapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'logging.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $logNameTemplate; + + protected $grpcCredentialsHelper; + protected $loggingServiceV2Stub; + private $scopes; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getLogNameTemplate() + { + if (self::$logNameTemplate == null) { + self::$logNameTemplate = new PathTemplate('projects/{project}/logs/{log}'); + } + + return self::$logNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listLogEntriesPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getEntries', + ]); + $listMonitoredResourceDescriptorsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getResourceDescriptors', + ]); + $listLogsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getLogNames', + ]); + + $pageStreamingDescriptors = [ + 'listLogEntries' => $listLogEntriesPageStreamingDescriptor, + 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, + 'listLogs' => $listLogsPageStreamingDescriptor, + ]; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'logging.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'deleteLog' => $defaultDescriptors, + 'writeLogEntries' => $defaultDescriptors, + 'listLogEntries' => $defaultDescriptors, + 'listMonitoredResourceDescriptors' => $defaultDescriptors, + 'listLogs' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/logging_service_v2_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.logging.v2.LoggingServiceV2', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createLoggingServiceV2StubFunction = function ($hostname, $opts, $channel) { + return new LoggingServiceV2GrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createLoggingServiceV2StubFunction', $options)) { + $createLoggingServiceV2StubFunction = $options['createLoggingServiceV2StubFunction']; + } + $this->loggingServiceV2Stub = $this->grpcCredentialsHelper->createStub($createLoggingServiceV2StubFunction); + } + + /** + * Deletes all the log entries in a log. + * The log reappears if it receives new entries. + * Log entries written shortly before the delete operation might not be + * deleted. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); + * $loggingServiceV2Client->deleteLog($formattedLogName); + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param string $logName Required. The resource name of the log to delete: + * + * "projects/[PROJECT_ID]/logs/[LOG_ID]" + * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + * "folders/[FOLDER_ID]/logs/[LOG_ID]" + * + * `[LOG_ID]` must be URL-encoded. For example, + * `"projects/my-project-id/logs/syslog"`, + * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. + * For more information about log names, see + * [LogEntry][google.logging.v2.LogEntry]. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteLog($logName, $optionalArgs = []) + { + $request = new DeleteLogRequest(); + $request->setLogName($logName); + + $mergedSettings = $this->defaultCallSettings['deleteLog']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'DeleteLog', + $mergedSettings, + $this->descriptors['deleteLog'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Writes log entries to Stackdriver Logging. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $entries = []; + * $response = $loggingServiceV2Client->writeLogEntries($entries); + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param LogEntry[] $entries Required. The log entries to write. Values supplied for the fields + * `log_name`, `resource`, and `labels` in this `entries.write` request are + * inserted into those log entries in this list that do not provide their own + * values. + * + * Stackdriver Logging also creates and inserts values for `timestamp` and + * `insert_id` if the entries do not provide them. The created `insert_id` for + * the N'th entry in this list will be greater than earlier entries and less + * than later entries. Otherwise, the order of log entries in this list does + * not matter. + * + * To improve throughput and to avoid exceeding the + * [quota limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, + * you should write multiple log entries at once rather than + * calling this method for each individual log entry. + * @param array $optionalArgs { + * Optional. + * + * @type string $logName + * Optional. A default log resource name that is assigned to all log entries + * in `entries` that do not specify a value for `log_name`: + * + * "projects/[PROJECT_ID]/logs/[LOG_ID]" + * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + * "folders/[FOLDER_ID]/logs/[LOG_ID]" + * + * `[LOG_ID]` must be URL-encoded. For example, + * `"projects/my-project-id/logs/syslog"` or + * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. + * For more information about log names, see + * [LogEntry][google.logging.v2.LogEntry]. + * @type MonitoredResource $resource + * Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: + * + * { "type": "gce_instance", + * "labels": { + * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + * + * See [LogEntry][google.logging.v2.LogEntry]. + * @type array $labels + * Optional. Default labels that are added to the `labels` field of all log + * entries in `entries`. If a log entry already has a label with the same key + * as a label in this parameter, then the log entry's label is not changed. + * See [LogEntry][google.logging.v2.LogEntry]. + * @type bool $partialSuccess + * Optional. Whether valid entries should be written even if some other + * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any + * 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. + * } + * + * @return \Google\Logging\V2\WriteLogEntriesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function writeLogEntries($entries, $optionalArgs = []) + { + $request = new WriteLogEntriesRequest(); + $request->setEntries($entries); + if (isset($optionalArgs['logName'])) { + $request->setLogName($optionalArgs['logName']); + } + if (isset($optionalArgs['resource'])) { + $request->setResource($optionalArgs['resource']); + } + if (isset($optionalArgs['labels'])) { + $request->setLabels($optionalArgs['labels']); + } + if (isset($optionalArgs['partialSuccess'])) { + $request->setPartialSuccess($optionalArgs['partialSuccess']); + } + + $mergedSettings = $this->defaultCallSettings['writeLogEntries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'WriteLogEntries', + $mergedSettings, + $this->descriptors['writeLogEntries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists log entries. Use this method to retrieve log entries from + * Stackdriver Logging. For ways to export log entries, see + * [Exporting Logs](https://cloud.google.com/logging/docs/export). + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $resourceNames = []; + * // Iterate through all elements + * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param string[] $resourceNames Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * Projects listed in the `project_ids` field are added to this list. + * @param array $optionalArgs { + * Optional. + * + * @type string[] $projectIds + * Deprecated. Use `resource_names` instead. One or more project identifiers + * or project numbers from which to retrieve log entries. Example: + * `"my-project-1A"`. If present, these project identifiers are converted to + * resource name format and added to the list of resources in + * `resource_names`. + * @type string $filter + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that + * match the filter are returned. An empty filter matches all log entries in + * the resources listed in `resource_names`. Referencing a parent resource + * that is not listed in `resource_names` will cause the filter to return no + * results. + * The maximum length of the filter is 20000 characters. + * @type string $orderBy + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listLogEntries($resourceNames, $optionalArgs = []) + { + $request = new ListLogEntriesRequest(); + $request->setResourceNames($resourceNames); + if (isset($optionalArgs['projectIds'])) { + $request->setProjectIds($optionalArgs['projectIds']); + } + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['orderBy'])) { + $request->setOrderBy($optionalArgs['orderBy']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listLogEntries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'ListLogEntries', + $mergedSettings, + $this->descriptors['listLogEntries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the descriptors for monitored resource types used by Stackdriver + * Logging. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * + * // Iterate through all elements + * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listMonitoredResourceDescriptors($optionalArgs = []) + { + $request = new ListMonitoredResourceDescriptorsRequest(); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'ListMonitoredResourceDescriptors', + $mergedSettings, + $this->descriptors['listMonitoredResourceDescriptors'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the logs in projects, organizations, folders, or billing accounts. + * Only logs that have entries are listed. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $formattedParent = LoggingServiceV2Client::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The resource name that owns the logs: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listLogs($parent, $optionalArgs = []) + { + $request = new ListLogsRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listLogs']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'ListLogs', + $mergedSettings, + $this->descriptors['listLogs'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->loggingServiceV2Stub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php b/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php new file mode 100644 index 000000000000..f60547ee7165 --- /dev/null +++ b/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php @@ -0,0 +1,674 @@ +listLogMetrics($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class MetricsServiceV2GapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'logging.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $metricNameTemplate; + + protected $grpcCredentialsHelper; + protected $metricsServiceV2Stub; + private $scopes; + 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 resource. + * + * @param string $project + * @param string $metric + * + * @return string The formatted metric resource. + * @experimental + */ + public static function formatMetricName($project, $metric) + { + return self::getMetricNameTemplate()->render([ + 'project' => $project, + 'metric' => $metric, + ]); + } + + /** + * 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 resource. + * + * @param string $metricName The fully-qualified metric resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromMetricName($metricName) + { + return self::getMetricNameTemplate()->match($metricName)['project']; + } + + /** + * 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']; + } + + 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 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'logging.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listLogMetrics' => $defaultDescriptors, + 'getLogMetric' => $defaultDescriptors, + 'createLogMetric' => $defaultDescriptors, + 'updateLogMetric' => $defaultDescriptors, + 'deleteLogMetric' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/metrics_service_v2_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.logging.v2.MetricsServiceV2', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createMetricsServiceV2StubFunction = function ($hostname, $opts, $channel) { + return new MetricsServiceV2GrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createMetricsServiceV2StubFunction', $options)) { + $createMetricsServiceV2StubFunction = $options['createMetricsServiceV2StubFunction']; + } + $this->metricsServiceV2Stub = $this->grpcCredentialsHelper->createStub($createMetricsServiceV2StubFunction); + } + + /** + * Lists logs-based metrics. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * 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 int $pageSize + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listLogMetrics($parent, $optionalArgs = []) + { + $request = new ListLogMetricsRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + + $mergedSettings = $this->defaultCallSettings['listLogMetrics']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'ListLogMetrics', + $mergedSettings, + $this->descriptors['listLogMetrics'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $response = $metricsServiceV2Client->getLogMetric($formattedMetricName); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $metricName The resource name of the desired metric: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @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. + * } + * + * @return \Google\Logging\V2\LogMetric + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getLogMetric($metricName, $optionalArgs = []) + { + $request = new GetLogMetricRequest(); + $request->setMetricName($metricName); + + $mergedSettings = $this->defaultCallSettings['getLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'GetLogMetric', + $mergedSettings, + $this->descriptors['getLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * $metric = new LogMetric(); + * $response = $metricsServiceV2Client->createLogMetric($formattedParent, $metric); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $parent The resource name of the project in which to create the metric: + * + * "projects/[PROJECT_ID]" + * + * The new metric must be provided in the request. + * @param LogMetric $metric The new logs-based metric, which must not have an identifier that + * already exists. + * @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. + * } + * + * @return \Google\Logging\V2\LogMetric + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createLogMetric($parent, $metric, $optionalArgs = []) + { + $request = new CreateLogMetricRequest(); + $request->setParent($parent); + $request->setMetric($metric); + + $mergedSettings = $this->defaultCallSettings['createLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'CreateLogMetric', + $mergedSettings, + $this->descriptors['createLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates or updates a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $metric = new LogMetric(); + * $response = $metricsServiceV2Client->updateLogMetric($formattedMetricName, $metric); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $metricName The resource name of the metric to update: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * + * The updated metric must be provided in the request and it's + * `name` field must be the same as `[METRIC_ID]` If the metric + * does not exist in `[PROJECT_ID]`, then a new metric is created. + * @param LogMetric $metric The updated metric. + * @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. + * } + * + * @return \Google\Logging\V2\LogMetric + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateLogMetric($metricName, $metric, $optionalArgs = []) + { + $request = new UpdateLogMetricRequest(); + $request->setMetricName($metricName); + $request->setMetric($metric); + + $mergedSettings = $this->defaultCallSettings['updateLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'UpdateLogMetric', + $mergedSettings, + $this->descriptors['updateLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $metricsServiceV2Client->deleteLogMetric($formattedMetricName); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $metricName The resource name of the metric to delete: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteLogMetric($metricName, $optionalArgs = []) + { + $request = new DeleteLogMetricRequest(); + $request->setMetricName($metricName); + + $mergedSettings = $this->defaultCallSettings['deleteLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'DeleteLogMetric', + $mergedSettings, + $this->descriptors['deleteLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->metricsServiceV2Stub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Logging/V2/LoggingServiceV2Client.php b/src/Logging/V2/LoggingServiceV2Client.php index 82570ca8f2a8..ef13551c96b2 100644 --- a/src/Logging/V2/LoggingServiceV2Client.php +++ b/src/Logging/V2/LoggingServiceV2Client.php @@ -30,805 +30,12 @@ namespace Google\Cloud\Logging\V2; -use Google\Api\MonitoredResource; -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\Logging\V2\DeleteLogRequest; -use Google\Logging\V2\ListLogEntriesRequest; -use Google\Logging\V2\ListLogsRequest; -use Google\Logging\V2\ListMonitoredResourceDescriptorsRequest; -use Google\Logging\V2\LogEntry; -use Google\Logging\V2\LoggingServiceV2GrpcClient; -use Google\Logging\V2\WriteLogEntriesRequest; +use Google\Cloud\Logging\V2\Gapic\LoggingServiceV2GapicClient; /** - * Service Description: Service for ingesting and querying logs. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); - * $loggingServiceV2Client->deleteLog($formattedLogName); - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class LoggingServiceV2Client +class LoggingServiceV2Client extends LoggingServiceV2GapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'logging.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $logNameTemplate; - - private $grpcCredentialsHelper; - private $loggingServiceV2Stub; - private $scopes; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getLogNameTemplate() - { - if (self::$logNameTemplate == null) { - self::$logNameTemplate = new PathTemplate('projects/{project}/logs/{log}'); - } - - return self::$logNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listLogEntriesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getEntries', - ]); - $listMonitoredResourceDescriptorsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getResourceDescriptors', - ]); - $listLogsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getLogNames', - ]); - - $pageStreamingDescriptors = [ - 'listLogEntries' => $listLogEntriesPageStreamingDescriptor, - 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, - 'listLogs' => $listLogsPageStreamingDescriptor, - ]; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'logging.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Logging API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'deleteLog' => $defaultDescriptors, - 'writeLogEntries' => $defaultDescriptors, - 'listLogEntries' => $defaultDescriptors, - 'listMonitoredResourceDescriptors' => $defaultDescriptors, - 'listLogs' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/logging_service_v2_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.logging.v2.LoggingServiceV2', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createLoggingServiceV2StubFunction = function ($hostname, $opts) { - return new LoggingServiceV2GrpcClient($hostname, $opts); - }; - if (array_key_exists('createLoggingServiceV2StubFunction', $options)) { - $createLoggingServiceV2StubFunction = $options['createLoggingServiceV2StubFunction']; - } - $this->loggingServiceV2Stub = $this->grpcCredentialsHelper->createStub( - $createLoggingServiceV2StubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Deletes all the log entries in a log. - * The log reappears if it receives new entries. - * Log entries written shortly before the delete operation might not be - * deleted. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); - * $loggingServiceV2Client->deleteLog($formattedLogName); - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param string $logName Required. The resource name of the log to delete: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"`, - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * [LogEntry][google.logging.v2.LogEntry]. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteLog($logName, $optionalArgs = []) - { - $request = new DeleteLogRequest(); - $request->setLogName($logName); - - $mergedSettings = $this->defaultCallSettings['deleteLog']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'DeleteLog', - $mergedSettings, - $this->descriptors['deleteLog'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Writes log entries to Stackdriver Logging. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $entries = []; - * $response = $loggingServiceV2Client->writeLogEntries($entries); - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param LogEntry[] $entries Required. The log entries to write. Values supplied for the fields - * `log_name`, `resource`, and `labels` in this `entries.write` request are - * inserted into those log entries in this list that do not provide their own - * values. - * - * Stackdriver Logging also creates and inserts values for `timestamp` and - * `insert_id` if the entries do not provide them. The created `insert_id` for - * the N'th entry in this list will be greater than earlier entries and less - * than later entries. Otherwise, the order of log entries in this list does - * not matter. - * - * To improve throughput and to avoid exceeding the - * [quota limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, - * you should write multiple log entries at once rather than - * calling this method for each individual log entry. - * @param array $optionalArgs { - * Optional. - * - * @type string $logName - * Optional. A default log resource name that is assigned to all log entries - * in `entries` that do not specify a value for `log_name`: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"` or - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * [LogEntry][google.logging.v2.LogEntry]. - * @type MonitoredResource $resource - * Optional. A default monitored resource object that is assigned to all log - * entries in `entries` that do not specify a value for `resource`. Example: - * - * { "type": "gce_instance", - * "labels": { - * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - * - * See [LogEntry][google.logging.v2.LogEntry]. - * @type array $labels - * Optional. Default labels that are added to the `labels` field of all log - * entries in `entries`. If a log entry already has a label with the same key - * as a label in this parameter, then the log entry's label is not changed. - * See [LogEntry][google.logging.v2.LogEntry]. - * @type bool $partialSuccess - * Optional. Whether valid entries should be written even if some other - * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any - * 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. - * } - * - * @return \Google\Logging\V2\WriteLogEntriesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function writeLogEntries($entries, $optionalArgs = []) - { - $request = new WriteLogEntriesRequest(); - $request->setEntries($entries); - if (isset($optionalArgs['logName'])) { - $request->setLogName($optionalArgs['logName']); - } - if (isset($optionalArgs['resource'])) { - $request->setResource($optionalArgs['resource']); - } - if (isset($optionalArgs['labels'])) { - $request->setLabels($optionalArgs['labels']); - } - if (isset($optionalArgs['partialSuccess'])) { - $request->setPartialSuccess($optionalArgs['partialSuccess']); - } - - $mergedSettings = $this->defaultCallSettings['writeLogEntries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'WriteLogEntries', - $mergedSettings, - $this->descriptors['writeLogEntries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists log entries. Use this method to retrieve log entries from - * Stackdriver Logging. For ways to export log entries, see - * [Exporting Logs](https://cloud.google.com/logging/docs/export). - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $resourceNames = []; - * // Iterate through all elements - * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param string[] $resourceNames Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * Projects listed in the `project_ids` field are added to this list. - * @param array $optionalArgs { - * Optional. - * - * @type string[] $projectIds - * Deprecated. Use `resource_names` instead. One or more project identifiers - * or project numbers from which to retrieve log entries. Example: - * `"my-project-1A"`. If present, these project identifiers are converted to - * resource name format and added to the list of resources in - * `resource_names`. - * @type string $filter - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that - * match the filter are returned. An empty filter matches all log entries in - * the resources listed in `resource_names`. Referencing a parent resource - * that is not listed in `resource_names` will cause the filter to return no - * results. - * The maximum length of the filter is 20000 characters. - * @type string $orderBy - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listLogEntries($resourceNames, $optionalArgs = []) - { - $request = new ListLogEntriesRequest(); - $request->setResourceNames($resourceNames); - if (isset($optionalArgs['projectIds'])) { - $request->setProjectIds($optionalArgs['projectIds']); - } - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['orderBy'])) { - $request->setOrderBy($optionalArgs['orderBy']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listLogEntries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'ListLogEntries', - $mergedSettings, - $this->descriptors['listLogEntries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the descriptors for monitored resource types used by Stackdriver - * Logging. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * - * // Iterate through all elements - * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listMonitoredResourceDescriptors($optionalArgs = []) - { - $request = new ListMonitoredResourceDescriptorsRequest(); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'ListMonitoredResourceDescriptors', - $mergedSettings, - $this->descriptors['listMonitoredResourceDescriptors'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the logs in projects, organizations, folders, or billing accounts. - * Only logs that have entries are listed. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedParent = LoggingServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The resource name that owns the logs: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listLogs($parent, $optionalArgs = []) - { - $request = new ListLogsRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listLogs']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'ListLogs', - $mergedSettings, - $this->descriptors['listLogs'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->loggingServiceV2Stub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see LoggingServiceV2ClientImpl} class. } diff --git a/src/Logging/V2/MetricsServiceV2Client.php b/src/Logging/V2/MetricsServiceV2Client.php index 82586089bfee..8634ed20493a 100644 --- a/src/Logging/V2/MetricsServiceV2Client.php +++ b/src/Logging/V2/MetricsServiceV2Client.php @@ -30,646 +30,12 @@ namespace Google\Cloud\Logging\V2; -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\Logging\V2\CreateLogMetricRequest; -use Google\Logging\V2\DeleteLogMetricRequest; -use Google\Logging\V2\GetLogMetricRequest; -use Google\Logging\V2\ListLogMetricsRequest; -use Google\Logging\V2\LogMetric; -use Google\Logging\V2\MetricsServiceV2GrpcClient; -use Google\Logging\V2\UpdateLogMetricRequest; +use Google\Cloud\Logging\V2\Gapic\MetricsServiceV2GapicClient; /** - * Service Description: Service for configuring logs-based metrics. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class MetricsServiceV2Client +class MetricsServiceV2Client extends MetricsServiceV2GapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'logging.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $metricNameTemplate; - - private $grpcCredentialsHelper; - private $metricsServiceV2Stub; - private $scopes; - 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 resource. - * - * @param string $project - * @param string $metric - * - * @return string The formatted metric resource. - * @experimental - */ - public static function formatMetricName($project, $metric) - { - return self::getMetricNameTemplate()->render([ - 'project' => $project, - 'metric' => $metric, - ]); - } - - /** - * 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 resource. - * - * @param string $metricName The fully-qualified metric resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromMetricName($metricName) - { - return self::getMetricNameTemplate()->match($metricName)['project']; - } - - /** - * 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']; - } - - 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 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'logging.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Logging API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listLogMetrics' => $defaultDescriptors, - 'getLogMetric' => $defaultDescriptors, - 'createLogMetric' => $defaultDescriptors, - 'updateLogMetric' => $defaultDescriptors, - 'deleteLogMetric' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/metrics_service_v2_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.logging.v2.MetricsServiceV2', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createMetricsServiceV2StubFunction = function ($hostname, $opts) { - return new MetricsServiceV2GrpcClient($hostname, $opts); - }; - if (array_key_exists('createMetricsServiceV2StubFunction', $options)) { - $createMetricsServiceV2StubFunction = $options['createMetricsServiceV2StubFunction']; - } - $this->metricsServiceV2Stub = $this->grpcCredentialsHelper->createStub( - $createMetricsServiceV2StubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists logs-based metrics. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * 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 int $pageSize - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listLogMetrics($parent, $optionalArgs = []) - { - $request = new ListLogMetricsRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - - $mergedSettings = $this->defaultCallSettings['listLogMetrics']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'ListLogMetrics', - $mergedSettings, - $this->descriptors['listLogMetrics'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); - * $response = $metricsServiceV2Client->getLogMetric($formattedMetricName); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $metricName The resource name of the desired metric: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @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. - * } - * - * @return \Google\Logging\V2\LogMetric - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getLogMetric($metricName, $optionalArgs = []) - { - $request = new GetLogMetricRequest(); - $request->setMetricName($metricName); - - $mergedSettings = $this->defaultCallSettings['getLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'GetLogMetric', - $mergedSettings, - $this->descriptors['getLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); - * $metric = new LogMetric(); - * $response = $metricsServiceV2Client->createLogMetric($formattedParent, $metric); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $parent The resource name of the project in which to create the metric: - * - * "projects/[PROJECT_ID]" - * - * The new metric must be provided in the request. - * @param LogMetric $metric The new logs-based metric, which must not have an identifier that - * already exists. - * @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. - * } - * - * @return \Google\Logging\V2\LogMetric - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createLogMetric($parent, $metric, $optionalArgs = []) - { - $request = new CreateLogMetricRequest(); - $request->setParent($parent); - $request->setMetric($metric); - - $mergedSettings = $this->defaultCallSettings['createLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'CreateLogMetric', - $mergedSettings, - $this->descriptors['createLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates or updates a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); - * $metric = new LogMetric(); - * $response = $metricsServiceV2Client->updateLogMetric($formattedMetricName, $metric); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $metricName The resource name of the metric to update: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * The updated metric must be provided in the request and it's - * `name` field must be the same as `[METRIC_ID]` If the metric - * does not exist in `[PROJECT_ID]`, then a new metric is created. - * @param LogMetric $metric The updated metric. - * @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. - * } - * - * @return \Google\Logging\V2\LogMetric - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateLogMetric($metricName, $metric, $optionalArgs = []) - { - $request = new UpdateLogMetricRequest(); - $request->setMetricName($metricName); - $request->setMetric($metric); - - $mergedSettings = $this->defaultCallSettings['updateLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'UpdateLogMetric', - $mergedSettings, - $this->descriptors['updateLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); - * $metricsServiceV2Client->deleteLogMetric($formattedMetricName); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $metricName The resource name of the metric to delete: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteLogMetric($metricName, $optionalArgs = []) - { - $request = new DeleteLogMetricRequest(); - $request->setMetricName($metricName); - - $mergedSettings = $this->defaultCallSettings['deleteLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'DeleteLogMetric', - $mergedSettings, - $this->descriptors['deleteLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->metricsServiceV2Stub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see MetricsServiceV2ClientImpl} class. } diff --git a/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php b/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php new file mode 100644 index 000000000000..05475a813410 --- /dev/null +++ b/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php @@ -0,0 +1,817 @@ +listGroups($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class GroupServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'monitoring.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $groupNameTemplate; + + protected $grpcCredentialsHelper; + protected $groupServiceStub; + private $scopes; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getGroupNameTemplate() + { + if (self::$groupNameTemplate == null) { + self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); + } + + return self::$groupNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listGroupsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getGroup', + ]); + $listGroupMembersPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getMembers', + ]); + + $pageStreamingDescriptors = [ + 'listGroups' => $listGroupsPageStreamingDescriptor, + 'listGroupMembers' => $listGroupMembersPageStreamingDescriptor, + ]; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'monitoring.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listGroups' => $defaultDescriptors, + 'getGroup' => $defaultDescriptors, + 'createGroup' => $defaultDescriptors, + 'updateGroup' => $defaultDescriptors, + 'deleteGroup' => $defaultDescriptors, + 'listGroupMembers' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/group_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.monitoring.v3.GroupService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createGroupServiceStubFunction = function ($hostname, $opts, $channel) { + return new GroupServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createGroupServiceStubFunction', $options)) { + $createGroupServiceStubFunction = $options['createGroupServiceStubFunction']; + } + $this->groupServiceStub = $this->grpcCredentialsHelper->createStub($createGroupServiceStubFunction); + } + + /** + * Lists the existing groups. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $groupServiceClient->listGroups($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param array $optionalArgs { + * Optional. + * + * @type string $childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @type string $ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @type string $descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listGroups($name, $optionalArgs = []) + { + $request = new ListGroupsRequest(); + $request->setName($name); + if (isset($optionalArgs['childrenOfGroup'])) { + $request->setChildrenOfGroup($optionalArgs['childrenOfGroup']); + } + if (isset($optionalArgs['ancestorsOfGroup'])) { + $request->setAncestorsOfGroup($optionalArgs['ancestorsOfGroup']); + } + if (isset($optionalArgs['descendantsOfGroup'])) { + $request->setDescendantsOfGroup($optionalArgs['descendantsOfGroup']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listGroups']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'ListGroups', + $mergedSettings, + $this->descriptors['listGroups'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a single group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $response = $groupServiceClient->getGroup($formattedName); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The group to retrieve. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @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. + * } + * + * @return \Google\Monitoring\V3\Group + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getGroup($name, $optionalArgs = []) + { + $request = new GetGroupRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'GetGroup', + $mergedSettings, + $this->descriptors['getGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a new group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * $group = new Group(); + * $response = $groupServiceClient->createGroup($formattedName, $group); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The project in which to create the group. The format is + * `"projects/{project_id_or_number}"`. + * @param Group $group A group definition. It is an error to define the `name` field because + * the system assigns the name. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Monitoring\V3\Group + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createGroup($name, $group, $optionalArgs = []) + { + $request = new CreateGroupRequest(); + $request->setName($name); + $request->setGroup($group); + if (isset($optionalArgs['validateOnly'])) { + $request->setValidateOnly($optionalArgs['validateOnly']); + } + + $mergedSettings = $this->defaultCallSettings['createGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'CreateGroup', + $mergedSettings, + $this->descriptors['createGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates an existing group. + * You can change any group attributes except `name`. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $group = new Group(); + * $response = $groupServiceClient->updateGroup($group); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param Group $group The new definition of the group. All fields of the existing group, + * excepting `name`, are replaced with the corresponding fields of this group. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Monitoring\V3\Group + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateGroup($group, $optionalArgs = []) + { + $request = new UpdateGroupRequest(); + $request->setGroup($group); + if (isset($optionalArgs['validateOnly'])) { + $request->setValidateOnly($optionalArgs['validateOnly']); + } + + $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'UpdateGroup', + $mergedSettings, + $this->descriptors['updateGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes an existing group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $groupServiceClient->deleteGroup($formattedName); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The group to delete. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteGroup($name, $optionalArgs = []) + { + $request = new DeleteGroupRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['deleteGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'DeleteGroup', + $mergedSettings, + $this->descriptors['deleteGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the monitored resources that are members of a group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * // Iterate through all elements + * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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 string $filter + * An optional [list filter](https://cloud.google.com/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @type TimeInterval $interval + * An optional time interval for which results should be returned. Only + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listGroupMembers($name, $optionalArgs = []) + { + $request = new ListGroupMembersRequest(); + $request->setName($name); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['interval'])) { + $request->setInterval($optionalArgs['interval']); + } + + $mergedSettings = $this->defaultCallSettings['listGroupMembers']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'ListGroupMembers', + $mergedSettings, + $this->descriptors['listGroupMembers'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->groupServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php b/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php new file mode 100644 index 000000000000..b50d330297fa --- /dev/null +++ b/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php @@ -0,0 +1,1031 @@ +listMonitoredResourceDescriptors($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class MetricServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'monitoring.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $metricDescriptorNameTemplate; + private static $monitoredResourceDescriptorNameTemplate; + + protected $grpcCredentialsHelper; + protected $metricServiceStub; + private $scopes; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getMetricDescriptorNameTemplate() + { + if (self::$metricDescriptorNameTemplate == null) { + self::$metricDescriptorNameTemplate = new PathTemplate('projects/{project}/metricDescriptors/{metric_descriptor=**}'); + } + + return self::$metricDescriptorNameTemplate; + } + + private static function getMonitoredResourceDescriptorNameTemplate() + { + if (self::$monitoredResourceDescriptorNameTemplate == null) { + self::$monitoredResourceDescriptorNameTemplate = new PathTemplate('projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'); + } + + return self::$monitoredResourceDescriptorNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listMonitoredResourceDescriptorsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getResourceDescriptors', + ]); + $listMetricDescriptorsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getMetricDescriptors', + ]); + $listTimeSeriesPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getTimeSeries', + ]); + + $pageStreamingDescriptors = [ + 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, + 'listMetricDescriptors' => $listMetricDescriptorsPageStreamingDescriptor, + 'listTimeSeries' => $listTimeSeriesPageStreamingDescriptor, + ]; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'monitoring.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listMonitoredResourceDescriptors' => $defaultDescriptors, + 'getMonitoredResourceDescriptor' => $defaultDescriptors, + 'listMetricDescriptors' => $defaultDescriptors, + 'getMetricDescriptor' => $defaultDescriptors, + 'createMetricDescriptor' => $defaultDescriptors, + 'deleteMetricDescriptor' => $defaultDescriptors, + 'listTimeSeries' => $defaultDescriptors, + 'createTimeSeries' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/metric_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.monitoring.v3.MetricService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createMetricServiceStubFunction = function ($hostname, $opts, $channel) { + return new MetricServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createMetricServiceStubFunction', $options)) { + $createMetricServiceStubFunction = $options['createMetricServiceStubFunction']; + } + $this->metricServiceStub = $this->grpcCredentialsHelper->createStub($createMetricServiceStubFunction); + } + + /** + * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param array $optionalArgs { + * Optional. + * + * @type string $filter + * An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listMonitoredResourceDescriptors($name, $optionalArgs = []) + { + $request = new ListMonitoredResourceDescriptorsRequest(); + $request->setName($name); + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'ListMonitoredResourceDescriptors', + $mergedSettings, + $this->descriptors['listMonitoredResourceDescriptors'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); + * $response = $metricServiceClient->getMonitoredResourceDescriptor($formattedName); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The monitored resource descriptor to get. The format is + * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. + * The `{resource_type}` is a predefined type, such as + * `cloudsql_database`. + * @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. + * } + * + * @return \Google\Api\MonitoredResourceDescriptor + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getMonitoredResourceDescriptor($name, $optionalArgs = []) + { + $request = new GetMonitoredResourceDescriptorRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getMonitoredResourceDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'GetMonitoredResourceDescriptor', + $mergedSettings, + $this->descriptors['getMonitoredResourceDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param array $optionalArgs { + * Optional. + * + * @type string $filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](https://cloud.google.com/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listMetricDescriptors($name, $optionalArgs = []) + { + $request = new ListMetricDescriptorsRequest(); + $request->setName($name); + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listMetricDescriptors']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'ListMetricDescriptors', + $mergedSettings, + $this->descriptors['listMetricDescriptors'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a single metric descriptor. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); + * $response = $metricServiceClient->getMetricDescriptor($formattedName); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example value of `{metric_id}` is + * `"compute.googleapis.com/instance/disk/read_bytes_count"`. + * @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. + * } + * + * @return \Google\Api\MetricDescriptor + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getMetricDescriptor($name, $optionalArgs = []) + { + $request = new GetMetricDescriptorRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getMetricDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'GetMetricDescriptor', + $mergedSettings, + $this->descriptors['getMetricDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a new metric descriptor. + * User-created metric descriptors define + * [custom metrics](https://cloud.google.com/monitoring/custom-metrics). + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $metricDescriptor = new MetricDescriptor(); + * $response = $metricServiceClient->createMetricDescriptor($formattedName, $metricDescriptor); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param MetricDescriptor $metricDescriptor The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) + * descriptor. + * @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. + * } + * + * @return \Google\Api\MetricDescriptor + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = []) + { + $request = new CreateMetricDescriptorRequest(); + $request->setName($name); + $request->setMetricDescriptor($metricDescriptor); + + $mergedSettings = $this->defaultCallSettings['createMetricDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'CreateMetricDescriptor', + $mergedSettings, + $this->descriptors['createMetricDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes a metric descriptor. Only user-created + * [custom metrics](https://cloud.google.com/monitoring/custom-metrics) can be deleted. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); + * $metricServiceClient->deleteMetricDescriptor($formattedName); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example of `{metric_id}` is: + * `"custom.googleapis.com/my_test_metric"`. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteMetricDescriptor($name, $optionalArgs = []) + { + $request = new DeleteMetricDescriptorRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['deleteMetricDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'DeleteMetricDescriptor', + $mergedSettings, + $this->descriptors['deleteMetricDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists time series that match a filter. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $filter = ""; + * $interval = new TimeInterval(); + * $view = TimeSeriesView::FULL; + * // Iterate through all elements + * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param string $filter A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.label.instance_name = "my-instance-name" + * @param TimeInterval $interval The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param int $view Specifies which information is returned about the time series. + * For allowed values, use constants defined on {@see \Google\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView} + * @param array $optionalArgs { + * Optional. + * + * @type Aggregation $aggregation + * By default, the raw time series data is returned. + * Use this field to combine multiple time series for different + * views of the data. + * @type string $orderBy + * Specifies the order in which the points of the time series should + * be returned. By default, results are not ordered. Currently, + * this field must be left blank. + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = []) + { + $request = new ListTimeSeriesRequest(); + $request->setName($name); + $request->setFilter($filter); + $request->setInterval($interval); + $request->setView($view); + if (isset($optionalArgs['aggregation'])) { + $request->setAggregation($optionalArgs['aggregation']); + } + if (isset($optionalArgs['orderBy'])) { + $request->setOrderBy($optionalArgs['orderBy']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listTimeSeries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'ListTimeSeries', + $mergedSettings, + $this->descriptors['listTimeSeries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates or adds data to one or more time series. + * The response is empty if all time series in the request were written. + * If any time series could not be written, a corresponding failure message is + * included in the error response. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $timeSeries = []; + * $metricServiceClient->createTimeSeries($formattedName, $timeSeries); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param TimeSeries[] $timeSeries The new data to be added to a list of time series. + * Adds at most one data point to each of several time series. The new data + * point must be more recent than any other point in its time series. Each + * `TimeSeries` value must fully specify a unique time series by supplying + * all label values for the metric and the monitored resource. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createTimeSeries($name, $timeSeries, $optionalArgs = []) + { + $request = new CreateTimeSeriesRequest(); + $request->setName($name); + $request->setTimeSeries($timeSeries); + + $mergedSettings = $this->defaultCallSettings['createTimeSeries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'CreateTimeSeries', + $mergedSettings, + $this->descriptors['createTimeSeries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->metricServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Monitoring/V3/GroupServiceClient.php b/src/Monitoring/V3/GroupServiceClient.php index e2669101e697..4d9f7b4c7897 100644 --- a/src/Monitoring/V3/GroupServiceClient.php +++ b/src/Monitoring/V3/GroupServiceClient.php @@ -30,789 +30,12 @@ namespace Google\Cloud\Monitoring\V3; -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\Monitoring\V3\CreateGroupRequest; -use Google\Monitoring\V3\DeleteGroupRequest; -use Google\Monitoring\V3\GetGroupRequest; -use Google\Monitoring\V3\Group; -use Google\Monitoring\V3\GroupServiceGrpcClient; -use Google\Monitoring\V3\ListGroupMembersRequest; -use Google\Monitoring\V3\ListGroupsRequest; -use Google\Monitoring\V3\TimeInterval; -use Google\Monitoring\V3\UpdateGroupRequest; +use Google\Cloud\Monitoring\V3\Gapic\GroupServiceGapicClient; /** - * Service Description: The Group API lets you inspect and manage your - * [groups](https://cloud.google.comgoogle.monitoring.v3.Group). - * - * A group is a named filter that is used to identify - * a collection of monitored resources. Groups are typically used to - * mirror the physical and/or logical topology of the environment. - * Because group membership is computed dynamically, monitored - * resources that are started in the future are automatically placed - * in matching groups. By using a group to name monitored resources in, - * for example, an alert policy, the target of that alert policy is - * updated automatically as monitored resources are added and removed - * from the infrastructure. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $groupServiceClient->listGroups($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class GroupServiceClient +class GroupServiceClient extends GroupServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'monitoring.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $groupNameTemplate; - - private $grpcCredentialsHelper; - private $groupServiceStub; - private $scopes; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getGroupNameTemplate() - { - if (self::$groupNameTemplate == null) { - self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); - } - - return self::$groupNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listGroupsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getGroup', - ]); - $listGroupMembersPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getMembers', - ]); - - $pageStreamingDescriptors = [ - 'listGroups' => $listGroupsPageStreamingDescriptor, - 'listGroupMembers' => $listGroupMembersPageStreamingDescriptor, - ]; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'monitoring.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Monitoring API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listGroups' => $defaultDescriptors, - 'getGroup' => $defaultDescriptors, - 'createGroup' => $defaultDescriptors, - 'updateGroup' => $defaultDescriptors, - 'deleteGroup' => $defaultDescriptors, - 'listGroupMembers' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/group_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.monitoring.v3.GroupService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createGroupServiceStubFunction = function ($hostname, $opts) { - return new GroupServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createGroupServiceStubFunction', $options)) { - $createGroupServiceStubFunction = $options['createGroupServiceStubFunction']; - } - $this->groupServiceStub = $this->grpcCredentialsHelper->createStub( - $createGroupServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists the existing groups. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $groupServiceClient->listGroups($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param array $optionalArgs { - * Optional. - * - * @type string $childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @type string $ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @type string $descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listGroups($name, $optionalArgs = []) - { - $request = new ListGroupsRequest(); - $request->setName($name); - if (isset($optionalArgs['childrenOfGroup'])) { - $request->setChildrenOfGroup($optionalArgs['childrenOfGroup']); - } - if (isset($optionalArgs['ancestorsOfGroup'])) { - $request->setAncestorsOfGroup($optionalArgs['ancestorsOfGroup']); - } - if (isset($optionalArgs['descendantsOfGroup'])) { - $request->setDescendantsOfGroup($optionalArgs['descendantsOfGroup']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listGroups']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'ListGroups', - $mergedSettings, - $this->descriptors['listGroups'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a single group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * $response = $groupServiceClient->getGroup($formattedName); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The group to retrieve. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @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. - * } - * - * @return \Google\Monitoring\V3\Group - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getGroup($name, $optionalArgs = []) - { - $request = new GetGroupRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'GetGroup', - $mergedSettings, - $this->descriptors['getGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a new group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); - * $group = new Group(); - * $response = $groupServiceClient->createGroup($formattedName, $group); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The project in which to create the group. The format is - * `"projects/{project_id_or_number}"`. - * @param Group $group A group definition. It is an error to define the `name` field because - * the system assigns the name. - * @param array $optionalArgs { - * Optional. - * - * @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. - * } - * - * @return \Google\Monitoring\V3\Group - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createGroup($name, $group, $optionalArgs = []) - { - $request = new CreateGroupRequest(); - $request->setName($name); - $request->setGroup($group); - if (isset($optionalArgs['validateOnly'])) { - $request->setValidateOnly($optionalArgs['validateOnly']); - } - - $mergedSettings = $this->defaultCallSettings['createGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'CreateGroup', - $mergedSettings, - $this->descriptors['createGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates an existing group. - * You can change any group attributes except `name`. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $group = new Group(); - * $response = $groupServiceClient->updateGroup($group); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param Group $group The new definition of the group. All fields of the existing group, - * excepting `name`, are replaced with the corresponding fields of this group. - * @param array $optionalArgs { - * Optional. - * - * @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. - * } - * - * @return \Google\Monitoring\V3\Group - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateGroup($group, $optionalArgs = []) - { - $request = new UpdateGroupRequest(); - $request->setGroup($group); - if (isset($optionalArgs['validateOnly'])) { - $request->setValidateOnly($optionalArgs['validateOnly']); - } - - $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'UpdateGroup', - $mergedSettings, - $this->descriptors['updateGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes an existing group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * $groupServiceClient->deleteGroup($formattedName); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The group to delete. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteGroup($name, $optionalArgs = []) - { - $request = new DeleteGroupRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['deleteGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'DeleteGroup', - $mergedSettings, - $this->descriptors['deleteGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the monitored resources that are members of a group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * // Iterate through all elements - * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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 string $filter - * An optional [list filter](https://cloud.google.com/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @type TimeInterval $interval - * An optional time interval for which results should be returned. Only - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listGroupMembers($name, $optionalArgs = []) - { - $request = new ListGroupMembersRequest(); - $request->setName($name); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['interval'])) { - $request->setInterval($optionalArgs['interval']); - } - - $mergedSettings = $this->defaultCallSettings['listGroupMembers']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'ListGroupMembers', - $mergedSettings, - $this->descriptors['listGroupMembers'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->groupServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see GroupServiceClientImpl} class. } diff --git a/src/Monitoring/V3/MetricServiceClient.php b/src/Monitoring/V3/MetricServiceClient.php index add715ba45a8..71c27fac3c5b 100644 --- a/src/Monitoring/V3/MetricServiceClient.php +++ b/src/Monitoring/V3/MetricServiceClient.php @@ -30,1003 +30,12 @@ namespace Google\Cloud\Monitoring\V3; -use Google\Api\MetricDescriptor; -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\Monitoring\V3\Aggregation; -use Google\Monitoring\V3\CreateMetricDescriptorRequest; -use Google\Monitoring\V3\CreateTimeSeriesRequest; -use Google\Monitoring\V3\DeleteMetricDescriptorRequest; -use Google\Monitoring\V3\GetMetricDescriptorRequest; -use Google\Monitoring\V3\GetMonitoredResourceDescriptorRequest; -use Google\Monitoring\V3\ListMetricDescriptorsRequest; -use Google\Monitoring\V3\ListMonitoredResourceDescriptorsRequest; -use Google\Monitoring\V3\ListTimeSeriesRequest; -use Google\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView as TimeSeriesView; -use Google\Monitoring\V3\MetricServiceGrpcClient; -use Google\Monitoring\V3\TimeInterval; -use Google\Monitoring\V3\TimeSeries; +use Google\Cloud\Monitoring\V3\Gapic\MetricServiceGapicClient; /** - * Service Description: Manages metric descriptors, monitored resource descriptors, and - * time series data. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class MetricServiceClient +class MetricServiceClient extends MetricServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'monitoring.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $metricDescriptorNameTemplate; - private static $monitoredResourceDescriptorNameTemplate; - - private $grpcCredentialsHelper; - private $metricServiceStub; - private $scopes; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getMetricDescriptorNameTemplate() - { - if (self::$metricDescriptorNameTemplate == null) { - self::$metricDescriptorNameTemplate = new PathTemplate('projects/{project}/metricDescriptors/{metric_descriptor=**}'); - } - - return self::$metricDescriptorNameTemplate; - } - - private static function getMonitoredResourceDescriptorNameTemplate() - { - if (self::$monitoredResourceDescriptorNameTemplate == null) { - self::$monitoredResourceDescriptorNameTemplate = new PathTemplate('projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'); - } - - return self::$monitoredResourceDescriptorNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listMonitoredResourceDescriptorsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getResourceDescriptors', - ]); - $listMetricDescriptorsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getMetricDescriptors', - ]); - $listTimeSeriesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getTimeSeries', - ]); - - $pageStreamingDescriptors = [ - 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, - 'listMetricDescriptors' => $listMetricDescriptorsPageStreamingDescriptor, - 'listTimeSeries' => $listTimeSeriesPageStreamingDescriptor, - ]; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'monitoring.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Monitoring API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listMonitoredResourceDescriptors' => $defaultDescriptors, - 'getMonitoredResourceDescriptor' => $defaultDescriptors, - 'listMetricDescriptors' => $defaultDescriptors, - 'getMetricDescriptor' => $defaultDescriptors, - 'createMetricDescriptor' => $defaultDescriptors, - 'deleteMetricDescriptor' => $defaultDescriptors, - 'listTimeSeries' => $defaultDescriptors, - 'createTimeSeries' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/metric_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.monitoring.v3.MetricService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createMetricServiceStubFunction = function ($hostname, $opts) { - return new MetricServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createMetricServiceStubFunction', $options)) { - $createMetricServiceStubFunction = $options['createMetricServiceStubFunction']; - } - $this->metricServiceStub = $this->grpcCredentialsHelper->createStub( - $createMetricServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param array $optionalArgs { - * Optional. - * - * @type string $filter - * An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listMonitoredResourceDescriptors($name, $optionalArgs = []) - { - $request = new ListMonitoredResourceDescriptorsRequest(); - $request->setName($name); - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'ListMonitoredResourceDescriptors', - $mergedSettings, - $this->descriptors['listMonitoredResourceDescriptors'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); - * $response = $metricServiceClient->getMonitoredResourceDescriptor($formattedName); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The monitored resource descriptor to get. The format is - * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. - * The `{resource_type}` is a predefined type, such as - * `cloudsql_database`. - * @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. - * } - * - * @return \Google\Api\MonitoredResourceDescriptor - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getMonitoredResourceDescriptor($name, $optionalArgs = []) - { - $request = new GetMonitoredResourceDescriptorRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getMonitoredResourceDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'GetMonitoredResourceDescriptor', - $mergedSettings, - $this->descriptors['getMonitoredResourceDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param array $optionalArgs { - * Optional. - * - * @type string $filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listMetricDescriptors($name, $optionalArgs = []) - { - $request = new ListMetricDescriptorsRequest(); - $request->setName($name); - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listMetricDescriptors']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'ListMetricDescriptors', - $mergedSettings, - $this->descriptors['listMetricDescriptors'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a single metric descriptor. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); - * $response = $metricServiceClient->getMetricDescriptor($formattedName); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example value of `{metric_id}` is - * `"compute.googleapis.com/instance/disk/read_bytes_count"`. - * @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. - * } - * - * @return \Google\Api\MetricDescriptor - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getMetricDescriptor($name, $optionalArgs = []) - { - $request = new GetMetricDescriptorRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'GetMetricDescriptor', - $mergedSettings, - $this->descriptors['getMetricDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a new metric descriptor. - * User-created metric descriptors define - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics). - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * $metricDescriptor = new MetricDescriptor(); - * $response = $metricServiceClient->createMetricDescriptor($formattedName, $metricDescriptor); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param MetricDescriptor $metricDescriptor The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) - * descriptor. - * @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. - * } - * - * @return \Google\Api\MetricDescriptor - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = []) - { - $request = new CreateMetricDescriptorRequest(); - $request->setName($name); - $request->setMetricDescriptor($metricDescriptor); - - $mergedSettings = $this->defaultCallSettings['createMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'CreateMetricDescriptor', - $mergedSettings, - $this->descriptors['createMetricDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes a metric descriptor. Only user-created - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics) can be deleted. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); - * $metricServiceClient->deleteMetricDescriptor($formattedName); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example of `{metric_id}` is: - * `"custom.googleapis.com/my_test_metric"`. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteMetricDescriptor($name, $optionalArgs = []) - { - $request = new DeleteMetricDescriptorRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['deleteMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'DeleteMetricDescriptor', - $mergedSettings, - $this->descriptors['deleteMetricDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists time series that match a filter. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * $filter = ""; - * $interval = new TimeInterval(); - * $view = TimeSeriesView::FULL; - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param string $filter A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.label.instance_name = "my-instance-name" - * @param TimeInterval $interval The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param int $view Specifies which information is returned about the time series. - * For allowed values, use constants defined on {@see \Google\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView} - * @param array $optionalArgs { - * Optional. - * - * @type Aggregation $aggregation - * By default, the raw time series data is returned. - * Use this field to combine multiple time series for different - * views of the data. - * @type string $orderBy - * Specifies the order in which the points of the time series should - * be returned. By default, results are not ordered. Currently, - * this field must be left blank. - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = []) - { - $request = new ListTimeSeriesRequest(); - $request->setName($name); - $request->setFilter($filter); - $request->setInterval($interval); - $request->setView($view); - if (isset($optionalArgs['aggregation'])) { - $request->setAggregation($optionalArgs['aggregation']); - } - if (isset($optionalArgs['orderBy'])) { - $request->setOrderBy($optionalArgs['orderBy']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listTimeSeries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'ListTimeSeries', - $mergedSettings, - $this->descriptors['listTimeSeries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates or adds data to one or more time series. - * The response is empty if all time series in the request were written. - * If any time series could not be written, a corresponding failure message is - * included in the error response. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * $timeSeries = []; - * $metricServiceClient->createTimeSeries($formattedName, $timeSeries); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param TimeSeries[] $timeSeries The new data to be added to a list of time series. - * Adds at most one data point to each of several time series. The new data - * point must be more recent than any other point in its time series. Each - * `TimeSeries` value must fully specify a unique time series by supplying - * all label values for the metric and the monitored resource. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createTimeSeries($name, $timeSeries, $optionalArgs = []) - { - $request = new CreateTimeSeriesRequest(); - $request->setName($name); - $request->setTimeSeries($timeSeries); - - $mergedSettings = $this->defaultCallSettings['createTimeSeries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'CreateTimeSeries', - $mergedSettings, - $this->descriptors['createTimeSeries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->metricServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see MetricServiceClientImpl} class. } diff --git a/src/Monitoring/composer.json b/src/Monitoring/composer.json index 036f1d8a5174..f0fd72544d12 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.21.0", - "google/gax": "^0.21.0" + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1" }, "extra": { "component": { diff --git a/src/PubSub/V1/Gapic/PublisherGapicClient.php b/src/PubSub/V1/Gapic/PublisherGapicClient.php new file mode 100644 index 000000000000..5add6e38230c --- /dev/null +++ b/src/PubSub/V1/Gapic/PublisherGapicClient.php @@ -0,0 +1,951 @@ +createTopic($formattedName); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class PublisherGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'pubsub.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $topicNameTemplate; + + protected $grpcCredentialsHelper; + protected $iamPolicyStub; + protected $publisherStub; + private $scopes; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getTopicNameTemplate() + { + if (self::$topicNameTemplate == null) { + self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); + } + + return self::$topicNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listTopicsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getTopics', + ]); + $listTopicSubscriptionsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSubscriptions', + ]); + + $pageStreamingDescriptors = [ + 'listTopics' => $listTopicsPageStreamingDescriptor, + 'listTopicSubscriptions' => $listTopicSubscriptionsPageStreamingDescriptor, + ]; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'pubsub.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'createTopic' => $defaultDescriptors, + 'publish' => $defaultDescriptors, + 'getTopic' => $defaultDescriptors, + 'listTopics' => $defaultDescriptors, + 'listTopicSubscriptions' => $defaultDescriptors, + 'deleteTopic' => $defaultDescriptors, + 'setIamPolicy' => $defaultDescriptors, + 'getIamPolicy' => $defaultDescriptors, + 'testIamPermissions' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/publisher_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.pubsub.v1.Publisher', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createIamPolicyStubFunction = function ($hostname, $opts, $channel) { + return new IAMPolicyGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createIamPolicyStubFunction', $options)) { + $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; + } + $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub($createIamPolicyStubFunction); + $createPublisherStubFunction = function ($hostname, $opts, $channel) { + return new PublisherGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createPublisherStubFunction', $options)) { + $createPublisherStubFunction = $options['createPublisherStubFunction']; + } + $this->publisherStub = $this->grpcCredentialsHelper->createStub($createPublisherStubFunction); + } + + /** + * Creates the given topic with the given name. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $publisherClient->createTopic($formattedName); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $name The name of the topic. It must have the format + * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, + * and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), + * underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent + * signs (`%`). It must be between 3 and 255 characters in length, and it + * must not start with `"goog"`. + * @param array $optionalArgs { + * Optional. + * + * @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. + * } + * + * @return \Google\Pubsub\V1\Topic + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createTopic($name, $optionalArgs = []) + { + $request = new Topic(); + $request->setName($name); + if (isset($optionalArgs['labels'])) { + $request->setLabels($optionalArgs['labels']); + } + + $mergedSettings = $this->defaultCallSettings['createTopic']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'CreateTopic', + $mergedSettings, + $this->descriptors['createTopic'] + ); + + 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 + * either a non-empty data field, or at least one attribute. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $data = ""; + * $messagesElement = new PubsubMessage(); + * $messagesElement->setData($data); + * $messages = [$messagesElement]; + * $response = $publisherClient->publish($formattedTopic, $messages); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic The messages in the request will be published on this topic. + * Format is `projects/{project}/topics/{topic}`. + * @param PubsubMessage[] $messages The messages to publish. + * @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. + * } + * + * @return \Google\Pubsub\V1\PublishResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function publish($topic, $messages, $optionalArgs = []) + { + $request = new PublishRequest(); + $request->setTopic($topic); + $request->setMessages($messages); + + $mergedSettings = $this->defaultCallSettings['publish']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'Publish', + $mergedSettings, + $this->descriptors['publish'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the configuration of a topic. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $publisherClient->getTopic($formattedTopic); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic The name of the topic to get. + * Format is `projects/{project}/topics/{topic}`. + * @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. + * } + * + * @return \Google\Pubsub\V1\Topic + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getTopic($topic, $optionalArgs = []) + { + $request = new GetTopicRequest(); + $request->setTopic($topic); + + $mergedSettings = $this->defaultCallSettings['getTopic']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'GetTopic', + $mergedSettings, + $this->descriptors['getTopic'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists matching topics. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedProject = PublisherClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $publisherClient->listTopics($formattedProject); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $publisherClient->listTopics($formattedProject, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $project The name of the cloud project that topics belong to. + * Format is `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listTopics($project, $optionalArgs = []) + { + $request = new ListTopicsRequest(); + $request->setProject($project); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listTopics']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'ListTopics', + $mergedSettings, + $this->descriptors['listTopics'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the name of the subscriptions for this topic. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * // Iterate through all elements + * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic The name of the topic that subscriptions are attached to. + * Format is `projects/{project}/topics/{topic}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listTopicSubscriptions($topic, $optionalArgs = []) + { + $request = new ListTopicSubscriptionsRequest(); + $request->setTopic($topic); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listTopicSubscriptions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'ListTopicSubscriptions', + $mergedSettings, + $this->descriptors['listTopicSubscriptions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic + * does not exist. After a topic is deleted, a new topic may be created with + * the same name; this is an entirely new topic with none of the old + * configuration or subscriptions. Existing subscriptions to this topic are + * not deleted, but their `topic` field is set to `_deleted-topic_`. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $publisherClient->deleteTopic($formattedTopic); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic Name of the topic to delete. + * Format is `projects/{project}/topics/{topic}`. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteTopic($topic, $optionalArgs = []) + { + $request = new DeleteTopicRequest(); + $request->setTopic($topic); + + $mergedSettings = $this->defaultCallSettings['deleteTopic']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'DeleteTopic', + $mergedSettings, + $this->descriptors['deleteTopic'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Sets the access control policy on the specified resource. Replaces any + * existing policy. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $policy = new Policy(); + * $response = $publisherClient->setIamPolicy($formattedResource, $policy); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function setIamPolicy($resource, $policy, $optionalArgs = []) + { + $request = new SetIamPolicyRequest(); + $request->setResource($resource); + $request->setPolicy($policy); + + $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'SetIamPolicy', + $mergedSettings, + $this->descriptors['setIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the access control policy for a resource. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $publisherClient->getIamPolicy($formattedResource); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getIamPolicy($resource, $optionalArgs = []) + { + $request = new GetIamPolicyRequest(); + $request->setResource($resource); + + $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'GetIamPolicy', + $mergedSettings, + $this->descriptors['getIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns permissions that a caller has on the specified resource. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $permissions = []; + * $response = $publisherClient->testIamPermissions($formattedResource, $permissions); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @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. + * } + * + * @return \Google\Iam\V1\TestIamPermissionsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function testIamPermissions($resource, $permissions, $optionalArgs = []) + { + $request = new TestIamPermissionsRequest(); + $request->setResource($resource); + $request->setPermissions($permissions); + + $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'TestIamPermissions', + $mergedSettings, + $this->descriptors['testIamPermissions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->iamPolicyStub->close(); + $this->publisherStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/PubSub/V1/Gapic/SubscriberGapicClient.php b/src/PubSub/V1/Gapic/SubscriberGapicClient.php new file mode 100644 index 000000000000..52181dca86ea --- /dev/null +++ b/src/PubSub/V1/Gapic/SubscriberGapicClient.php @@ -0,0 +1,1711 @@ +createSubscription($formattedName, $formattedTopic); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class SubscriberGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'pubsub.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $snapshotNameTemplate; + private static $subscriptionNameTemplate; + private static $topicNameTemplate; + + protected $grpcCredentialsHelper; + protected $iamPolicyStub; + protected $subscriberStub; + private $scopes; + 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 snapshot resource. + * + * @param string $project + * @param string $snapshot + * + * @return string The formatted snapshot resource. + * @experimental + */ + public static function formatSnapshotName($project, $snapshot) + { + return self::getSnapshotNameTemplate()->render([ + 'project' => $project, + 'snapshot' => $snapshot, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a subscription resource. + * + * @param string $project + * @param string $subscription + * + * @return string The formatted subscription resource. + * @experimental + */ + public static function formatSubscriptionName($project, $subscription) + { + return self::getSubscriptionNameTemplate()->render([ + 'project' => $project, + 'subscription' => $subscription, + ]); + } + + /** + * 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 snapshot resource. + * + * @param string $snapshotName The fully-qualified snapshot resource. + * + * @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 $snapshotName The fully-qualified snapshot resource. + * + * @return string The extracted snapshot value. + * @experimental + */ + public static function parseSnapshotFromSnapshotName($snapshotName) + { + return self::getSnapshotNameTemplate()->match($snapshotName)['snapshot']; + } + + /** + * 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']; + } + + /** + * 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 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'pubsub.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'createSubscription' => $defaultDescriptors, + 'getSubscription' => $defaultDescriptors, + 'updateSubscription' => $defaultDescriptors, + 'listSubscriptions' => $defaultDescriptors, + 'deleteSubscription' => $defaultDescriptors, + 'modifyAckDeadline' => $defaultDescriptors, + 'acknowledge' => $defaultDescriptors, + 'pull' => $defaultDescriptors, + 'streamingPull' => $defaultDescriptors, + 'modifyPushConfig' => $defaultDescriptors, + 'listSnapshots' => $defaultDescriptors, + 'createSnapshot' => $defaultDescriptors, + 'deleteSnapshot' => $defaultDescriptors, + 'seek' => $defaultDescriptors, + 'setIamPolicy' => $defaultDescriptors, + 'getIamPolicy' => $defaultDescriptors, + 'testIamPermissions' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); + foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { + $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/subscriber_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.pubsub.v1.Subscriber', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createIamPolicyStubFunction = function ($hostname, $opts, $channel) { + return new IAMPolicyGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createIamPolicyStubFunction', $options)) { + $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; + } + $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub($createIamPolicyStubFunction); + $createSubscriberStubFunction = function ($hostname, $opts, $channel) { + return new SubscriberGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createSubscriberStubFunction', $options)) { + $createSubscriberStubFunction = $options['createSubscriberStubFunction']; + } + $this->subscriberStub = $this->grpcCredentialsHelper->createStub($createSubscriberStubFunction); + } + + /** + * Creates a subscription to a given topic. + * If the subscription already exists, returns `ALREADY_EXISTS`. + * If the corresponding topic doesn't exist, returns `NOT_FOUND`. + * + * If the name is not provided in the request, the server will assign a random + * name for this subscription on the same project as the topic, conforming + * to the + * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). + * The generated name is populated in the returned Subscription object. + * Note that for REST API requests, you must specify a name in the request. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $name The name of the subscription. It must have the format + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must + * start with a letter, and contain only letters (`[A-Za-z]`), numbers + * (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), + * plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters + * in length, and it must not start with `"goog"`. + * @param string $topic The name of the topic from which this subscription is receiving messages. + * Format is `projects/{project}/topics/{topic}`. + * The value of this field will be `_deleted-topic_` if the topic has been + * deleted. + * @param array $optionalArgs { + * Optional. + * + * @type PushConfig $pushConfig + * If push delivery is used with this subscription, this field is + * used to configure it. An empty `pushConfig` signifies that the subscriber + * will pull and ack messages using API methods. + * @type int $ackDeadlineSeconds + * This value is the maximum time after a subscriber receives a message + * before the subscriber should acknowledge the message. After message + * delivery but before the ack deadline expires and before the message is + * acknowledged, it is an outstanding message and will not be delivered + * again during that time (on a best-effort basis). + * + * For pull subscriptions, this value is used as the initial value for the ack + * deadline. To override this value for a given message, call + * `ModifyAckDeadline` with the corresponding `ack_id` if using + * pull. + * The minimum custom deadline you can specify is 10 seconds. + * The maximum custom deadline you can specify is 600 seconds (10 minutes). + * If this parameter is 0, a default value of 10 seconds is used. + * + * For push delivery, this value is also used to set the request timeout for + * the call to the push endpoint. + * + * If the subscriber never acknowledges the message, the Pub/Sub + * system will eventually redeliver the message. + * @type bool $retainAckedMessages + * Indicates whether to retain acknowledged messages. If true, then + * messages are not expunged from the subscription's backlog, even if they are + * acknowledged, until they fall out of the `message_retention_duration` + * window. + * @type Duration $messageRetentionDuration + * How long to retain unacknowledged messages in the subscription's backlog, + * from the moment a message is published. + * If `retain_acked_messages` is true, then this also configures the retention + * of acknowledged messages, and thus configures how far back in time a `Seek` + * can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 + * 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. + * } + * + * @return \Google\Pubsub\V1\Subscription + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSubscription($name, $topic, $optionalArgs = []) + { + $request = new Subscription(); + $request->setName($name); + $request->setTopic($topic); + if (isset($optionalArgs['pushConfig'])) { + $request->setPushConfig($optionalArgs['pushConfig']); + } + if (isset($optionalArgs['ackDeadlineSeconds'])) { + $request->setAckDeadlineSeconds($optionalArgs['ackDeadlineSeconds']); + } + if (isset($optionalArgs['retainAckedMessages'])) { + $request->setRetainAckedMessages($optionalArgs['retainAckedMessages']); + } + if (isset($optionalArgs['messageRetentionDuration'])) { + $request->setMessageRetentionDuration($optionalArgs['messageRetentionDuration']); + } + if (isset($optionalArgs['labels'])) { + $request->setLabels($optionalArgs['labels']); + } + + $mergedSettings = $this->defaultCallSettings['createSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'CreateSubscription', + $mergedSettings, + $this->descriptors['createSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the configuration details of a subscription. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->getSubscription($formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The name of the subscription to get. + * Format is `projects/{project}/subscriptions/{sub}`. + * @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. + * } + * + * @return \Google\Pubsub\V1\Subscription + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getSubscription($subscription, $optionalArgs = []) + { + $request = new GetSubscriptionRequest(); + $request->setSubscription($subscription); + + $mergedSettings = $this->defaultCallSettings['getSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'GetSubscription', + $mergedSettings, + $this->descriptors['getSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates an existing subscription. Note that certain properties of a + * subscription, such as its topic, are not modifiable. + * NOTE: The style guide requires body: "subscription" 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(); + * $subscription = new Subscription(); + * $updateMask = new FieldMask(); + * $response = $subscriberClient->updateSubscription($subscription, $updateMask); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param Subscription $subscription The updated subscription object. + * @param FieldMask $updateMask Indicates which fields in the provided subscription to update. + * Must be specified and non-empty. + * @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. + * } + * + * @return \Google\Pubsub\V1\Subscription + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateSubscription($subscription, $updateMask, $optionalArgs = []) + { + $request = new UpdateSubscriptionRequest(); + $request->setSubscription($subscription); + $request->setUpdateMask($updateMask); + + $mergedSettings = $this->defaultCallSettings['updateSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'UpdateSubscription', + $mergedSettings, + $this->descriptors['updateSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists matching subscriptions. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $project The name of the cloud project that subscriptions belong to. + * Format is `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listSubscriptions($project, $optionalArgs = []) + { + $request = new ListSubscriptionsRequest(); + $request->setProject($project); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listSubscriptions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ListSubscriptions', + $mergedSettings, + $this->descriptors['listSubscriptions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes an existing subscription. All messages retained in the subscription + * are immediately dropped. Calls to `Pull` after deletion will return + * `NOT_FOUND`. After a subscription is deleted, a new one may be created with + * the same name, but the new one has no association with the old + * subscription or its topic unless the same topic is specified. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $subscriberClient->deleteSubscription($formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription to delete. + * Format is `projects/{project}/subscriptions/{sub}`. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSubscription($subscription, $optionalArgs = []) + { + $request = new DeleteSubscriptionRequest(); + $request->setSubscription($subscription); + + $mergedSettings = $this->defaultCallSettings['deleteSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'DeleteSubscription', + $mergedSettings, + $this->descriptors['deleteSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Modifies the ack deadline for a specific message. This method is useful + * to indicate that more time is needed to process a message by the + * subscriber, or to make the message available for redelivery if the + * processing was interrupted. Note that this does not modify the + * subscription-level `ackDeadlineSeconds` used for subsequent messages. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $ackIds = []; + * $ackDeadlineSeconds = 0; + * $subscriberClient->modifyAckDeadline($formattedSubscription, $ackIds, $ackDeadlineSeconds); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The name of the subscription. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param string[] $ackIds List of acknowledgment IDs. + * @param int $ackDeadlineSeconds The new ack deadline with respect to the time this request was sent to + * the Pub/Sub system. For example, if the value is 10, the new + * ack deadline will expire 10 seconds after the `ModifyAckDeadline` call + * was made. Specifying zero may immediately make the message available for + * another pull request. + * The minimum deadline you can specify is 0 seconds. + * The maximum deadline you can specify is 600 seconds (10 minutes). + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $optionalArgs = []) + { + $request = new ModifyAckDeadlineRequest(); + $request->setSubscription($subscription); + $request->setAckIds($ackIds); + $request->setAckDeadlineSeconds($ackDeadlineSeconds); + + $mergedSettings = $this->defaultCallSettings['modifyAckDeadline']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ModifyAckDeadline', + $mergedSettings, + $this->descriptors['modifyAckDeadline'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Acknowledges the messages associated with the `ack_ids` in the + * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages + * from the subscription. + * + * Acknowledging a message whose ack deadline has expired may succeed, + * but such a message may be redelivered later. Acknowledging a message more + * than once will not result in an error. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $ackIds = []; + * $subscriberClient->acknowledge($formattedSubscription, $ackIds); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription whose message is being acknowledged. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param string[] $ackIds The acknowledgment ID for the messages being acknowledged that was returned + * by the Pub/Sub system in the `Pull` response. Must not be empty. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function acknowledge($subscription, $ackIds, $optionalArgs = []) + { + $request = new AcknowledgeRequest(); + $request->setSubscription($subscription); + $request->setAckIds($ackIds); + + $mergedSettings = $this->defaultCallSettings['acknowledge']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'Acknowledge', + $mergedSettings, + $this->descriptors['acknowledge'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Pulls messages from the server. Returns an empty list if there are no + * messages available in the backlog. The server may return `UNAVAILABLE` if + * there are too many concurrent pull requests pending for the given + * subscription. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $maxMessages = 0; + * $response = $subscriberClient->pull($formattedSubscription, $maxMessages); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription from which messages should be pulled. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param int $maxMessages The maximum number of messages returned for this request. The Pub/Sub + * system may return fewer than the number specified. + * @param array $optionalArgs { + * Optional. + * + * @type bool $returnImmediately + * If this field set to true, the system will respond immediately even if + * it there are no messages available to return in the `Pull` response. + * Otherwise, the system may wait (for a bounded amount of time) until at + * 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. + * } + * + * @return \Google\Pubsub\V1\PullResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function pull($subscription, $maxMessages, $optionalArgs = []) + { + $request = new PullRequest(); + $request->setSubscription($subscription); + $request->setMaxMessages($maxMessages); + if (isset($optionalArgs['returnImmediately'])) { + $request->setReturnImmediately($optionalArgs['returnImmediately']); + } + + $mergedSettings = $this->defaultCallSettings['pull']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'Pull', + $mergedSettings, + $this->descriptors['pull'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will + * respond with UNIMPLEMENTED errors unless you have been invited to test + * this feature. Contact cloud-pubsub@google.com with any questions. + * + * Establishes a stream with the server, which sends messages down to the + * client. The client streams acknowledgements and ack deadline modifications + * back to the server. The server will close the stream and return the status + * on any error. The server may close the stream with status `OK` to reassign + * server-side resources, in which case, the client should re-establish the + * stream. `UNAVAILABLE` may also be returned in the case of a transient error + * (e.g., a server restart). These should also be retried by the client. Flow + * control can be achieved by configuring the underlying RPC channel. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $streamAckDeadlineSeconds = 0; + * $request = new StreamingPullRequest(); + * $request->setSubscription($formattedSubscription); + * $request->setStreamAckDeadlineSeconds($streamAckDeadlineSeconds); + * $requests = [$request]; + * + * // Write all requests to the server, then read all responses until the + * // stream is complete + * $stream = $subscriberClient->streamingPull(); + * $stream->writeAll($requests); + * foreach ($stream->closeWriteAndReadAll() as $element) { + * // doSomethingWith($element); + * } + * + * // OR write requests individually, making read() calls if + * // required. Call closeWrite() once writes are complete, and read the + * // remaining responses from the server. + * $stream = $subscriberClient->streamingPull(); + * foreach ($requests as $request) { + * $stream->write($request); + * // if required, read a single response from the stream + * $element = $stream->read(); + * // doSomethingWith($element) + * } + * $stream->closeWrite(); + * $element = $stream->read(); + * while (!is_null($element)) { + * // doSomethingWith($element) + * $element = $stream->read(); + * } + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param array $optionalArgs { + * Optional. + * + * @type int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return \Google\GAX\BidiStream + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function streamingPull($optionalArgs = []) + { + $mergedSettings = $this->defaultCallSettings['streamingPull']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'StreamingPull', + $mergedSettings, + $this->descriptors['streamingPull'] + ); + + return $callable( + null, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Modifies the `PushConfig` for a specified subscription. + * + * This may be used to change a push subscription to a pull one (signified by + * an empty `PushConfig`) or vice versa, or change the endpoint URL and other + * attributes of a push subscription. Messages will accumulate for delivery + * continuously through the call regardless of changes to the `PushConfig`. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $pushConfig = new PushConfig(); + * $subscriberClient->modifyPushConfig($formattedSubscription, $pushConfig); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The name of the subscription. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param PushConfig $pushConfig The push configuration for future deliveries. + * + * An empty `pushConfig` indicates that the Pub/Sub system should + * stop pushing messages from the given subscription and allow + * messages to be pulled and acknowledged - effectively pausing + * the subscription if `Pull` is not called. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) + { + $request = new ModifyPushConfigRequest(); + $request->setSubscription($subscription); + $request->setPushConfig($pushConfig); + + $mergedSettings = $this->defaultCallSettings['modifyPushConfig']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ModifyPushConfig', + $mergedSettings, + $this->descriptors['modifyPushConfig'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the existing snapshots. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $subscriberClient->listSnapshots($formattedProject); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $subscriberClient->listSnapshots($formattedProject, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $project The name of the cloud project that snapshots belong to. + * Format is `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listSnapshots($project, $optionalArgs = []) + { + $request = new ListSnapshotsRequest(); + $request->setProject($project); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listSnapshots']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ListSnapshots', + $mergedSettings, + $this->descriptors['listSnapshots'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a snapshot from the requested subscription. + * If the snapshot already exists, returns `ALREADY_EXISTS`. + * If the requested subscription doesn't exist, returns `NOT_FOUND`. + * + * If the name is not provided in the request, the server will assign a random + * name for this snapshot on the same project as the subscription, conforming + * to the + * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). + * The generated name is populated in the returned Snapshot object. + * Note that for REST API requests, you must specify a name in the request. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedName = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->createSnapshot($formattedName, $formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $name Optional user-provided name for this snapshot. + * If the name is not provided in the request, the server will assign a random + * name for this snapshot on the same project as the subscription. + * Note that for REST API requests, you must specify a name. + * Format is `projects/{project}/snapshots/{snap}`. + * @param string $subscription The subscription whose backlog the snapshot retains. + * Specifically, the created snapshot is guaranteed to retain: + * (a) The existing backlog on the subscription. More precisely, this is + * defined as the messages in the subscription's backlog that are + * unacknowledged upon the successful completion of the + * `CreateSnapshot` request; as well as: + * (b) Any messages published to the subscription's topic following the + * successful completion of the CreateSnapshot request. + * Format is `projects/{project}/subscriptions/{sub}`. + * @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. + * } + * + * @return \Google\Pubsub\V1\Snapshot + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSnapshot($name, $subscription, $optionalArgs = []) + { + $request = new CreateSnapshotRequest(); + $request->setName($name); + $request->setSubscription($subscription); + + $mergedSettings = $this->defaultCallSettings['createSnapshot']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'CreateSnapshot', + $mergedSettings, + $this->descriptors['createSnapshot'] + ); + + 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 + * created with the same name, but the new one has no association with the old + * snapshot or its subscription, unless the same subscription is specified. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSnapshot = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); + * $subscriberClient->deleteSnapshot($formattedSnapshot); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $snapshot The name of the snapshot to delete. + * Format is `projects/{project}/snapshots/{snap}`. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSnapshot($snapshot, $optionalArgs = []) + { + $request = new DeleteSnapshotRequest(); + $request->setSnapshot($snapshot); + + $mergedSettings = $this->defaultCallSettings['deleteSnapshot']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'DeleteSnapshot', + $mergedSettings, + $this->descriptors['deleteSnapshot'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Seeks an existing subscription to a point in time or to a given snapshot, + * whichever is provided in the request. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->seek($formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription to affect. + * @param array $optionalArgs { + * Optional. + * + * @type Timestamp $time + * The time to seek to. + * Messages retained in the subscription that were published before this + * time are marked as acknowledged, and messages retained in the + * subscription that were published after this time are marked as + * unacknowledged. Note that this operation affects only those messages + * retained in the subscription (configured by the combination of + * `message_retention_duration` and `retain_acked_messages`). For example, + * if `time` corresponds to a point before the message retention + * window (or to a point before the system's notion of the subscription + * creation time), only retained messages will be marked as unacknowledged, + * and already-expunged messages will not be restored. + * @type string $snapshot + * 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. + * } + * + * @return \Google\Pubsub\V1\SeekResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function seek($subscription, $optionalArgs = []) + { + $request = new SeekRequest(); + $request->setSubscription($subscription); + if (isset($optionalArgs['time'])) { + $request->setTime($optionalArgs['time']); + } + if (isset($optionalArgs['snapshot'])) { + $request->setSnapshot($optionalArgs['snapshot']); + } + + $mergedSettings = $this->defaultCallSettings['seek']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'Seek', + $mergedSettings, + $this->descriptors['seek'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Sets the access control policy on the specified resource. Replaces any + * existing policy. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $policy = new Policy(); + * $response = $subscriberClient->setIamPolicy($formattedResource, $policy); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function setIamPolicy($resource, $policy, $optionalArgs = []) + { + $request = new SetIamPolicyRequest(); + $request->setResource($resource); + $request->setPolicy($policy); + + $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'SetIamPolicy', + $mergedSettings, + $this->descriptors['setIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the access control policy for a resource. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->getIamPolicy($formattedResource); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getIamPolicy($resource, $optionalArgs = []) + { + $request = new GetIamPolicyRequest(); + $request->setResource($resource); + + $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'GetIamPolicy', + $mergedSettings, + $this->descriptors['getIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns permissions that a caller has on the specified resource. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $permissions = []; + * $response = $subscriberClient->testIamPermissions($formattedResource, $permissions); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @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. + * } + * + * @return \Google\Iam\V1\TestIamPermissionsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function testIamPermissions($resource, $permissions, $optionalArgs = []) + { + $request = new TestIamPermissionsRequest(); + $request->setResource($resource); + $request->setPermissions($permissions); + + $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'TestIamPermissions', + $mergedSettings, + $this->descriptors['testIamPermissions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->iamPolicyStub->close(); + $this->subscriberStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/PubSub/V1/PublisherClient.php b/src/PubSub/V1/PublisherClient.php index cad46c40d935..8b46b6e2dc1a 100644 --- a/src/PubSub/V1/PublisherClient.php +++ b/src/PubSub/V1/PublisherClient.php @@ -30,923 +30,12 @@ namespace Google\Cloud\PubSub\V1; -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\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\Pubsub\V1\DeleteTopicRequest; -use Google\Pubsub\V1\GetTopicRequest; -use Google\Pubsub\V1\ListTopicSubscriptionsRequest; -use Google\Pubsub\V1\ListTopicsRequest; -use Google\Pubsub\V1\PublishRequest; -use Google\Pubsub\V1\PublisherGrpcClient; -use Google\Pubsub\V1\PubsubMessage; -use Google\Pubsub\V1\Topic; +use Google\Cloud\PubSub\V1\Gapic\PublisherGapicClient; /** - * Service Description: The service that an application uses to manipulate topics, and to send - * messages to a topic. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->createTopic($formattedName); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class PublisherClient +class PublisherClient extends PublisherGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'pubsub.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $topicNameTemplate; - - private $grpcCredentialsHelper; - private $iamPolicyStub; - private $publisherStub; - private $scopes; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getTopicNameTemplate() - { - if (self::$topicNameTemplate == null) { - self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); - } - - return self::$topicNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listTopicsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getTopics', - ]); - $listTopicSubscriptionsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSubscriptions', - ]); - - $pageStreamingDescriptors = [ - 'listTopics' => $listTopicsPageStreamingDescriptor, - 'listTopicSubscriptions' => $listTopicSubscriptionsPageStreamingDescriptor, - ]; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'pubsub.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Pub/Sub API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'createTopic' => $defaultDescriptors, - 'publish' => $defaultDescriptors, - 'getTopic' => $defaultDescriptors, - 'listTopics' => $defaultDescriptors, - 'listTopicSubscriptions' => $defaultDescriptors, - 'deleteTopic' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/publisher_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.pubsub.v1.Publisher', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createIamPolicyStubFunction = function ($hostname, $opts) { - return new IAMPolicyGrpcClient($hostname, $opts); - }; - if (array_key_exists('createIamPolicyStubFunction', $options)) { - $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; - } - $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub( - $createIamPolicyStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - $createPublisherStubFunction = function ($hostname, $opts) { - return new PublisherGrpcClient($hostname, $opts); - }; - if (array_key_exists('createPublisherStubFunction', $options)) { - $createPublisherStubFunction = $options['createPublisherStubFunction']; - } - $this->publisherStub = $this->grpcCredentialsHelper->createStub( - $createPublisherStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Creates the given topic with the given name. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->createTopic($formattedName); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $name The name of the topic. It must have the format - * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, - * and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), - * underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent - * signs (`%`). It must be between 3 and 255 characters in length, and it - * must not start with `"goog"`. - * @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. - * } - * - * @return \Google\Pubsub\V1\Topic - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createTopic($name, $optionalArgs = []) - { - $request = new Topic(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['createTopic']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'CreateTopic', - $mergedSettings, - $this->descriptors['createTopic'] - ); - - 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 - * either a non-empty data field, or at least one attribute. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $data = ""; - * $messagesElement = new PubsubMessage(); - * $messagesElement->setData($data); - * $messages = [$messagesElement]; - * $response = $publisherClient->publish($formattedTopic, $messages); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic The messages in the request will be published on this topic. - * Format is `projects/{project}/topics/{topic}`. - * @param PubsubMessage[] $messages The messages to publish. - * @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. - * } - * - * @return \Google\Pubsub\V1\PublishResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function publish($topic, $messages, $optionalArgs = []) - { - $request = new PublishRequest(); - $request->setTopic($topic); - $request->setMessages($messages); - - $mergedSettings = $this->defaultCallSettings['publish']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'Publish', - $mergedSettings, - $this->descriptors['publish'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the configuration of a topic. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->getTopic($formattedTopic); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic The name of the topic to get. - * Format is `projects/{project}/topics/{topic}`. - * @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. - * } - * - * @return \Google\Pubsub\V1\Topic - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getTopic($topic, $optionalArgs = []) - { - $request = new GetTopicRequest(); - $request->setTopic($topic); - - $mergedSettings = $this->defaultCallSettings['getTopic']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'GetTopic', - $mergedSettings, - $this->descriptors['getTopic'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists matching topics. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedProject = PublisherClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $publisherClient->listTopics($formattedProject); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $publisherClient->listTopics($formattedProject, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $project The name of the cloud project that topics belong to. - * Format is `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listTopics($project, $optionalArgs = []) - { - $request = new ListTopicsRequest(); - $request->setProject($project); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listTopics']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'ListTopics', - $mergedSettings, - $this->descriptors['listTopics'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the name of the subscriptions for this topic. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * // Iterate through all elements - * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic The name of the topic that subscriptions are attached to. - * Format is `projects/{project}/topics/{topic}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listTopicSubscriptions($topic, $optionalArgs = []) - { - $request = new ListTopicSubscriptionsRequest(); - $request->setTopic($topic); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listTopicSubscriptions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'ListTopicSubscriptions', - $mergedSettings, - $this->descriptors['listTopicSubscriptions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic - * does not exist. After a topic is deleted, a new topic may be created with - * the same name; this is an entirely new topic with none of the old - * configuration or subscriptions. Existing subscriptions to this topic are - * not deleted, but their `topic` field is set to `_deleted-topic_`. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $publisherClient->deleteTopic($formattedTopic); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic Name of the topic to delete. - * Format is `projects/{project}/topics/{topic}`. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteTopic($topic, $optionalArgs = []) - { - $request = new DeleteTopicRequest(); - $request->setTopic($topic); - - $mergedSettings = $this->defaultCallSettings['deleteTopic']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'DeleteTopic', - $mergedSettings, - $this->descriptors['deleteTopic'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Sets the access control policy on the specified resource. Replaces any - * existing policy. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $policy = new Policy(); - * $response = $publisherClient->setIamPolicy($formattedResource, $policy); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being specified. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function setIamPolicy($resource, $policy, $optionalArgs = []) - { - $request = new SetIamPolicyRequest(); - $request->setResource($resource); - $request->setPolicy($policy); - - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'SetIamPolicy', - $mergedSettings, - $this->descriptors['setIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the access control policy for a resource. - * Returns an empty policy if the resource exists and does not have a policy - * set. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->getIamPolicy($formattedResource); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getIamPolicy($resource, $optionalArgs = []) - { - $request = new GetIamPolicyRequest(); - $request->setResource($resource); - - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'GetIamPolicy', - $mergedSettings, - $this->descriptors['getIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns permissions that a caller has on the specified resource. - * If the resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $permissions = []; - * $response = $publisherClient->testIamPermissions($formattedResource, $permissions); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy detail is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @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. - * } - * - * @return \Google\Iam\V1\TestIamPermissionsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function testIamPermissions($resource, $permissions, $optionalArgs = []) - { - $request = new TestIamPermissionsRequest(); - $request->setResource($resource); - $request->setPermissions($permissions); - - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'TestIamPermissions', - $mergedSettings, - $this->descriptors['testIamPermissions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->iamPolicyStub->close(); - $this->publisherStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see PublisherClientImpl} class. } diff --git a/src/PubSub/V1/SubscriberClient.php b/src/PubSub/V1/SubscriberClient.php index b81cf7c0ad1d..3a80dea17e78 100644 --- a/src/PubSub/V1/SubscriberClient.php +++ b/src/PubSub/V1/SubscriberClient.php @@ -30,1679 +30,12 @@ namespace Google\Cloud\PubSub\V1; -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\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\Duration; -use Google\Protobuf\FieldMask; -use Google\Protobuf\Timestamp; -use Google\Pubsub\V1\AcknowledgeRequest; -use Google\Pubsub\V1\CreateSnapshotRequest; -use Google\Pubsub\V1\DeleteSnapshotRequest; -use Google\Pubsub\V1\DeleteSubscriptionRequest; -use Google\Pubsub\V1\GetSubscriptionRequest; -use Google\Pubsub\V1\ListSnapshotsRequest; -use Google\Pubsub\V1\ListSubscriptionsRequest; -use Google\Pubsub\V1\ModifyAckDeadlineRequest; -use Google\Pubsub\V1\ModifyPushConfigRequest; -use Google\Pubsub\V1\PullRequest; -use Google\Pubsub\V1\PushConfig; -use Google\Pubsub\V1\SeekRequest; -use Google\Pubsub\V1\StreamingPullRequest; -use Google\Pubsub\V1\SubscriberGrpcClient; -use Google\Pubsub\V1\Subscription; -use Google\Pubsub\V1\UpdateSubscriptionRequest; +use Google\Cloud\PubSub\V1\Gapic\SubscriberGapicClient; /** - * Service Description: The service that an application uses to manipulate subscriptions and to - * consume messages from a subscription via the `Pull` method. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class SubscriberClient +class SubscriberClient extends SubscriberGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'pubsub.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $snapshotNameTemplate; - private static $subscriptionNameTemplate; - private static $topicNameTemplate; - - private $grpcCredentialsHelper; - private $iamPolicyStub; - private $subscriberStub; - private $scopes; - 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 snapshot resource. - * - * @param string $project - * @param string $snapshot - * - * @return string The formatted snapshot resource. - * @experimental - */ - public static function formatSnapshotName($project, $snapshot) - { - return self::getSnapshotNameTemplate()->render([ - 'project' => $project, - 'snapshot' => $snapshot, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a subscription resource. - * - * @param string $project - * @param string $subscription - * - * @return string The formatted subscription resource. - * @experimental - */ - public static function formatSubscriptionName($project, $subscription) - { - return self::getSubscriptionNameTemplate()->render([ - 'project' => $project, - 'subscription' => $subscription, - ]); - } - - /** - * 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 snapshot resource. - * - * @param string $snapshotName The fully-qualified snapshot resource. - * - * @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 $snapshotName The fully-qualified snapshot resource. - * - * @return string The extracted snapshot value. - * @experimental - */ - public static function parseSnapshotFromSnapshotName($snapshotName) - { - return self::getSnapshotNameTemplate()->match($snapshotName)['snapshot']; - } - - /** - * 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']; - } - - /** - * 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 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'pubsub.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Pub/Sub API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'createSubscription' => $defaultDescriptors, - 'getSubscription' => $defaultDescriptors, - 'updateSubscription' => $defaultDescriptors, - 'listSubscriptions' => $defaultDescriptors, - 'deleteSubscription' => $defaultDescriptors, - 'modifyAckDeadline' => $defaultDescriptors, - 'acknowledge' => $defaultDescriptors, - 'pull' => $defaultDescriptors, - 'streamingPull' => $defaultDescriptors, - 'modifyPushConfig' => $defaultDescriptors, - 'listSnapshots' => $defaultDescriptors, - 'createSnapshot' => $defaultDescriptors, - 'deleteSnapshot' => $defaultDescriptors, - 'seek' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); - foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { - $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/subscriber_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.pubsub.v1.Subscriber', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createIamPolicyStubFunction = function ($hostname, $opts) { - return new IAMPolicyGrpcClient($hostname, $opts); - }; - if (array_key_exists('createIamPolicyStubFunction', $options)) { - $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; - } - $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub( - $createIamPolicyStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - $createSubscriberStubFunction = function ($hostname, $opts) { - return new SubscriberGrpcClient($hostname, $opts); - }; - if (array_key_exists('createSubscriberStubFunction', $options)) { - $createSubscriberStubFunction = $options['createSubscriberStubFunction']; - } - $this->subscriberStub = $this->grpcCredentialsHelper->createStub( - $createSubscriberStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Creates a subscription to a given topic. - * If the subscription already exists, returns `ALREADY_EXISTS`. - * If the corresponding topic doesn't exist, returns `NOT_FOUND`. - * - * If the name is not provided in the request, the server will assign a random - * name for this subscription on the same project as the topic, conforming - * to the - * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - * The generated name is populated in the returned Subscription object. - * Note that for REST API requests, you must specify a name in the request. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $name The name of the subscription. It must have the format - * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must - * start with a letter, and contain only letters (`[A-Za-z]`), numbers - * (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), - * plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters - * in length, and it must not start with `"goog"`. - * @param string $topic The name of the topic from which this subscription is receiving messages. - * Format is `projects/{project}/topics/{topic}`. - * The value of this field will be `_deleted-topic_` if the topic has been - * deleted. - * @param array $optionalArgs { - * Optional. - * - * @type PushConfig $pushConfig - * If push delivery is used with this subscription, this field is - * used to configure it. An empty `pushConfig` signifies that the subscriber - * will pull and ack messages using API methods. - * @type int $ackDeadlineSeconds - * This value is the maximum time after a subscriber receives a message - * before the subscriber should acknowledge the message. After message - * delivery but before the ack deadline expires and before the message is - * acknowledged, it is an outstanding message and will not be delivered - * again during that time (on a best-effort basis). - * - * For pull subscriptions, this value is used as the initial value for the ack - * deadline. To override this value for a given message, call - * `ModifyAckDeadline` with the corresponding `ack_id` if using - * pull. - * The minimum custom deadline you can specify is 10 seconds. - * The maximum custom deadline you can specify is 600 seconds (10 minutes). - * If this parameter is 0, a default value of 10 seconds is used. - * - * For push delivery, this value is also used to set the request timeout for - * the call to the push endpoint. - * - * If the subscriber never acknowledges the message, the Pub/Sub - * system will eventually redeliver the message. - * @type bool $retainAckedMessages - * Indicates whether to retain acknowledged messages. If true, then - * messages are not expunged from the subscription's backlog, even if they are - * acknowledged, until they fall out of the `message_retention_duration` - * window. - * @type Duration $messageRetentionDuration - * How long to retain unacknowledged messages in the subscription's backlog, - * from the moment a message is published. - * If `retain_acked_messages` is true, then this also configures the retention - * of acknowledged messages, and thus configures how far back in time a `Seek` - * can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 - * minutes. - * @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. - * } - * - * @return \Google\Pubsub\V1\Subscription - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSubscription($name, $topic, $optionalArgs = []) - { - $request = new Subscription(); - $request->setName($name); - $request->setTopic($topic); - if (isset($optionalArgs['pushConfig'])) { - $request->setPushConfig($optionalArgs['pushConfig']); - } - if (isset($optionalArgs['ackDeadlineSeconds'])) { - $request->setAckDeadlineSeconds($optionalArgs['ackDeadlineSeconds']); - } - if (isset($optionalArgs['retainAckedMessages'])) { - $request->setRetainAckedMessages($optionalArgs['retainAckedMessages']); - } - if (isset($optionalArgs['messageRetentionDuration'])) { - $request->setMessageRetentionDuration($optionalArgs['messageRetentionDuration']); - } - - $mergedSettings = $this->defaultCallSettings['createSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'CreateSubscription', - $mergedSettings, - $this->descriptors['createSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the configuration details of a subscription. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->getSubscription($formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The name of the subscription to get. - * Format is `projects/{project}/subscriptions/{sub}`. - * @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. - * } - * - * @return \Google\Pubsub\V1\Subscription - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getSubscription($subscription, $optionalArgs = []) - { - $request = new GetSubscriptionRequest(); - $request->setSubscription($subscription); - - $mergedSettings = $this->defaultCallSettings['getSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'GetSubscription', - $mergedSettings, - $this->descriptors['getSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates an existing subscription. Note that certain properties of a - * subscription, such as its topic, are not modifiable. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $subscription = new Subscription(); - * $updateMask = new FieldMask(); - * $response = $subscriberClient->updateSubscription($subscription, $updateMask); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param Subscription $subscription The updated subscription object. - * @param FieldMask $updateMask Indicates which fields in the provided subscription to update. - * Must be specified and non-empty. - * @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. - * } - * - * @return \Google\Pubsub\V1\Subscription - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateSubscription($subscription, $updateMask, $optionalArgs = []) - { - $request = new UpdateSubscriptionRequest(); - $request->setSubscription($subscription); - $request->setUpdateMask($updateMask); - - $mergedSettings = $this->defaultCallSettings['updateSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'UpdateSubscription', - $mergedSettings, - $this->descriptors['updateSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists matching subscriptions. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $project The name of the cloud project that subscriptions belong to. - * Format is `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listSubscriptions($project, $optionalArgs = []) - { - $request = new ListSubscriptionsRequest(); - $request->setProject($project); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listSubscriptions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ListSubscriptions', - $mergedSettings, - $this->descriptors['listSubscriptions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes an existing subscription. All messages retained in the subscription - * are immediately dropped. Calls to `Pull` after deletion will return - * `NOT_FOUND`. After a subscription is deleted, a new one may be created with - * the same name, but the new one has no association with the old - * subscription or its topic unless the same topic is specified. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $subscriberClient->deleteSubscription($formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription to delete. - * Format is `projects/{project}/subscriptions/{sub}`. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSubscription($subscription, $optionalArgs = []) - { - $request = new DeleteSubscriptionRequest(); - $request->setSubscription($subscription); - - $mergedSettings = $this->defaultCallSettings['deleteSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'DeleteSubscription', - $mergedSettings, - $this->descriptors['deleteSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Modifies the ack deadline for a specific message. This method is useful - * to indicate that more time is needed to process a message by the - * subscriber, or to make the message available for redelivery if the - * processing was interrupted. Note that this does not modify the - * subscription-level `ackDeadlineSeconds` used for subsequent messages. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $ackIds = []; - * $ackDeadlineSeconds = 0; - * $subscriberClient->modifyAckDeadline($formattedSubscription, $ackIds, $ackDeadlineSeconds); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The name of the subscription. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param string[] $ackIds List of acknowledgment IDs. - * @param int $ackDeadlineSeconds The new ack deadline with respect to the time this request was sent to - * the Pub/Sub system. For example, if the value is 10, the new - * ack deadline will expire 10 seconds after the `ModifyAckDeadline` call - * was made. Specifying zero may immediately make the message available for - * another pull request. - * The minimum deadline you can specify is 0 seconds. - * The maximum deadline you can specify is 600 seconds (10 minutes). - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $optionalArgs = []) - { - $request = new ModifyAckDeadlineRequest(); - $request->setSubscription($subscription); - $request->setAckIds($ackIds); - $request->setAckDeadlineSeconds($ackDeadlineSeconds); - - $mergedSettings = $this->defaultCallSettings['modifyAckDeadline']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ModifyAckDeadline', - $mergedSettings, - $this->descriptors['modifyAckDeadline'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Acknowledges the messages associated with the `ack_ids` in the - * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages - * from the subscription. - * - * Acknowledging a message whose ack deadline has expired may succeed, - * but such a message may be redelivered later. Acknowledging a message more - * than once will not result in an error. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $ackIds = []; - * $subscriberClient->acknowledge($formattedSubscription, $ackIds); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription whose message is being acknowledged. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param string[] $ackIds The acknowledgment ID for the messages being acknowledged that was returned - * by the Pub/Sub system in the `Pull` response. Must not be empty. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function acknowledge($subscription, $ackIds, $optionalArgs = []) - { - $request = new AcknowledgeRequest(); - $request->setSubscription($subscription); - $request->setAckIds($ackIds); - - $mergedSettings = $this->defaultCallSettings['acknowledge']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'Acknowledge', - $mergedSettings, - $this->descriptors['acknowledge'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Pulls messages from the server. Returns an empty list if there are no - * messages available in the backlog. The server may return `UNAVAILABLE` if - * there are too many concurrent pull requests pending for the given - * subscription. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $maxMessages = 0; - * $response = $subscriberClient->pull($formattedSubscription, $maxMessages); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription from which messages should be pulled. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param int $maxMessages The maximum number of messages returned for this request. The Pub/Sub - * system may return fewer than the number specified. - * @param array $optionalArgs { - * Optional. - * - * @type bool $returnImmediately - * If this field set to true, the system will respond immediately even if - * it there are no messages available to return in the `Pull` response. - * Otherwise, the system may wait (for a bounded amount of time) until at - * 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. - * } - * - * @return \Google\Pubsub\V1\PullResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function pull($subscription, $maxMessages, $optionalArgs = []) - { - $request = new PullRequest(); - $request->setSubscription($subscription); - $request->setMaxMessages($maxMessages); - if (isset($optionalArgs['returnImmediately'])) { - $request->setReturnImmediately($optionalArgs['returnImmediately']); - } - - $mergedSettings = $this->defaultCallSettings['pull']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'Pull', - $mergedSettings, - $this->descriptors['pull'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will - * respond with UNIMPLEMENTED errors unless you have been invited to test - * this feature. Contact cloud-pubsub@google.com with any questions. - * - * Establishes a stream with the server, which sends messages down to the - * client. The client streams acknowledgements and ack deadline modifications - * back to the server. The server will close the stream and return the status - * on any error. The server may close the stream with status `OK` to reassign - * server-side resources, in which case, the client should re-establish the - * stream. `UNAVAILABLE` may also be returned in the case of a transient error - * (e.g., a server restart). These should also be retried by the client. Flow - * control can be achieved by configuring the underlying RPC channel. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $streamAckDeadlineSeconds = 0; - * $request = new StreamingPullRequest(); - * $request->setSubscription($formattedSubscription); - * $request->setStreamAckDeadlineSeconds($streamAckDeadlineSeconds); - * $requests = [$request]; - * - * // Write all requests to the server, then read all responses until the - * // stream is complete - * $stream = $subscriberClient->streamingPull(); - * $stream->writeAll($requests); - * foreach ($stream->closeWriteAndReadAll() as $element) { - * // doSomethingWith($element); - * } - * - * // OR write requests individually, making read() calls if - * // required. Call closeWrite() once writes are complete, and read the - * // remaining responses from the server. - * $stream = $subscriberClient->streamingPull(); - * foreach ($requests as $request) { - * $stream->write($request); - * // if required, read a single response from the stream - * $element = $stream->read(); - * // doSomethingWith($element) - * } - * $stream->closeWrite(); - * $element = $stream->read(); - * while (!is_null($element)) { - * // doSomethingWith($element) - * $element = $stream->read(); - * } - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param array $optionalArgs { - * Optional. - * - * @type int $timeoutMillis - * Timeout to use for this call. - * } - * - * @return \Google\GAX\BidiStream - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function streamingPull($optionalArgs = []) - { - $mergedSettings = $this->defaultCallSettings['streamingPull']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'StreamingPull', - $mergedSettings, - $this->descriptors['streamingPull'] - ); - - return $callable( - null, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Modifies the `PushConfig` for a specified subscription. - * - * This may be used to change a push subscription to a pull one (signified by - * an empty `PushConfig`) or vice versa, or change the endpoint URL and other - * attributes of a push subscription. Messages will accumulate for delivery - * continuously through the call regardless of changes to the `PushConfig`. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $pushConfig = new PushConfig(); - * $subscriberClient->modifyPushConfig($formattedSubscription, $pushConfig); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The name of the subscription. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param PushConfig $pushConfig The push configuration for future deliveries. - * - * An empty `pushConfig` indicates that the Pub/Sub system should - * stop pushing messages from the given subscription and allow - * messages to be pulled and acknowledged - effectively pausing - * the subscription if `Pull` is not called. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) - { - $request = new ModifyPushConfigRequest(); - $request->setSubscription($subscription); - $request->setPushConfig($pushConfig); - - $mergedSettings = $this->defaultCallSettings['modifyPushConfig']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ModifyPushConfig', - $mergedSettings, - $this->descriptors['modifyPushConfig'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the existing snapshots. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $subscriberClient->listSnapshots($formattedProject); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $subscriberClient->listSnapshots($formattedProject, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $project The name of the cloud project that snapshots belong to. - * Format is `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listSnapshots($project, $optionalArgs = []) - { - $request = new ListSnapshotsRequest(); - $request->setProject($project); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listSnapshots']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ListSnapshots', - $mergedSettings, - $this->descriptors['listSnapshots'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a snapshot from the requested subscription. - * If the snapshot already exists, returns `ALREADY_EXISTS`. - * If the requested subscription doesn't exist, returns `NOT_FOUND`. - * - * If the name is not provided in the request, the server will assign a random - * name for this snapshot on the same project as the subscription, conforming - * to the - * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - * The generated name is populated in the returned Snapshot object. - * Note that for REST API requests, you must specify a name in the request. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->createSnapshot($formattedName, $formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $name Optional user-provided name for this snapshot. - * If the name is not provided in the request, the server will assign a random - * name for this snapshot on the same project as the subscription. - * Note that for REST API requests, you must specify a name. - * Format is `projects/{project}/snapshots/{snap}`. - * @param string $subscription The subscription whose backlog the snapshot retains. - * Specifically, the created snapshot is guaranteed to retain: - * (a) The existing backlog on the subscription. More precisely, this is - * defined as the messages in the subscription's backlog that are - * unacknowledged upon the successful completion of the - * `CreateSnapshot` request; as well as: - * (b) Any messages published to the subscription's topic following the - * successful completion of the CreateSnapshot request. - * Format is `projects/{project}/subscriptions/{sub}`. - * @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. - * } - * - * @return \Google\Pubsub\V1\Snapshot - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSnapshot($name, $subscription, $optionalArgs = []) - { - $request = new CreateSnapshotRequest(); - $request->setName($name); - $request->setSubscription($subscription); - - $mergedSettings = $this->defaultCallSettings['createSnapshot']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'CreateSnapshot', - $mergedSettings, - $this->descriptors['createSnapshot'] - ); - - 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 - * created with the same name, but the new one has no association with the old - * snapshot or its subscription, unless the same subscription is specified. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSnapshot = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); - * $subscriberClient->deleteSnapshot($formattedSnapshot); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $snapshot The name of the snapshot to delete. - * Format is `projects/{project}/snapshots/{snap}`. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSnapshot($snapshot, $optionalArgs = []) - { - $request = new DeleteSnapshotRequest(); - $request->setSnapshot($snapshot); - - $mergedSettings = $this->defaultCallSettings['deleteSnapshot']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'DeleteSnapshot', - $mergedSettings, - $this->descriptors['deleteSnapshot'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Seeks an existing subscription to a point in time or to a given snapshot, - * whichever is provided in the request. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->seek($formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription to affect. - * @param array $optionalArgs { - * Optional. - * - * @type Timestamp $time - * The time to seek to. - * Messages retained in the subscription that were published before this - * time are marked as acknowledged, and messages retained in the - * subscription that were published after this time are marked as - * unacknowledged. Note that this operation affects only those messages - * retained in the subscription (configured by the combination of - * `message_retention_duration` and `retain_acked_messages`). For example, - * if `time` corresponds to a point before the message retention - * window (or to a point before the system's notion of the subscription - * creation time), only retained messages will be marked as unacknowledged, - * and already-expunged messages will not be restored. - * @type string $snapshot - * 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. - * } - * - * @return \Google\Pubsub\V1\SeekResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function seek($subscription, $optionalArgs = []) - { - $request = new SeekRequest(); - $request->setSubscription($subscription); - if (isset($optionalArgs['time'])) { - $request->setTime($optionalArgs['time']); - } - if (isset($optionalArgs['snapshot'])) { - $request->setSnapshot($optionalArgs['snapshot']); - } - - $mergedSettings = $this->defaultCallSettings['seek']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'Seek', - $mergedSettings, - $this->descriptors['seek'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Sets the access control policy on the specified resource. Replaces any - * existing policy. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $policy = new Policy(); - * $response = $subscriberClient->setIamPolicy($formattedResource, $policy); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being specified. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function setIamPolicy($resource, $policy, $optionalArgs = []) - { - $request = new SetIamPolicyRequest(); - $request->setResource($resource); - $request->setPolicy($policy); - - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'SetIamPolicy', - $mergedSettings, - $this->descriptors['setIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the access control policy for a resource. - * Returns an empty policy if the resource exists and does not have a policy - * set. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->getIamPolicy($formattedResource); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getIamPolicy($resource, $optionalArgs = []) - { - $request = new GetIamPolicyRequest(); - $request->setResource($resource); - - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'GetIamPolicy', - $mergedSettings, - $this->descriptors['getIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns permissions that a caller has on the specified resource. - * If the resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $permissions = []; - * $response = $subscriberClient->testIamPermissions($formattedResource, $permissions); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy detail is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @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. - * } - * - * @return \Google\Iam\V1\TestIamPermissionsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function testIamPermissions($resource, $permissions, $optionalArgs = []) - { - $request = new TestIamPermissionsRequest(); - $request->setResource($resource); - $request->setPermissions($permissions); - - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'TestIamPermissions', - $mergedSettings, - $this->descriptors['testIamPermissions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->iamPolicyStub->close(); - $this->subscriberStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see SubscriberClientImpl} class. } diff --git a/src/PubSub/V1/resources/publisher_client_config.json b/src/PubSub/V1/resources/publisher_client_config.json index 905e790b2181..9fb679cbad27 100644 --- a/src/PubSub/V1/resources/publisher_client_config.json +++ b/src/PubSub/V1/resources/publisher_client_config.json @@ -33,7 +33,7 @@ "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 12000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 12000, + "max_rpc_timeout_millis": 30000, "total_timeout_millis": 600000 } }, diff --git a/src/PubSub/V1/resources/subscriber_client_config.json b/src/PubSub/V1/resources/subscriber_client_config.json index e5ae4c0b2719..413a57aed9f2 100644 --- a/src/PubSub/V1/resources/subscriber_client_config.json +++ b/src/PubSub/V1/resources/subscriber_client_config.json @@ -33,6 +33,15 @@ "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 12000, "total_timeout_millis": 600000 + }, + "streaming_messaging": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 600000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 600000, + "total_timeout_millis": 600000 } }, "methods": { diff --git a/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php b/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php index e01212747758..5b64c92de04b 100644 --- a/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php +++ b/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php @@ -30,1079 +30,12 @@ namespace Google\Cloud\Spanner\Admin\Database\V1; -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\Iam\V1\GetIamPolicyRequest; -use Google\Iam\V1\Policy; -use Google\Iam\V1\SetIamPolicyRequest; -use Google\Iam\V1\TestIamPermissionsRequest; -use Google\Spanner\Admin\Database\V1\CreateDatabaseMetadata; -use Google\Spanner\Admin\Database\V1\CreateDatabaseRequest; -use Google\Spanner\Admin\Database\V1\Database; -use Google\Spanner\Admin\Database\V1\DatabaseAdminGrpcClient; -use Google\Spanner\Admin\Database\V1\DropDatabaseRequest; -use Google\Spanner\Admin\Database\V1\GetDatabaseDdlRequest; -use Google\Spanner\Admin\Database\V1\GetDatabaseRequest; -use Google\Spanner\Admin\Database\V1\ListDatabasesRequest; -use Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlMetadata; -use Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlRequest; +use Google\Cloud\Spanner\Admin\Database\V1\Gapic\DatabaseAdminGapicClient; /** - * Service Description: Cloud Spanner Database Admin API. - * - * The Cloud Spanner Database Admin API can be used to create, drop, and - * list databases. It also enables updating the schema of pre-existing - * databases. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * // Iterate through all elements - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class DatabaseAdminClient +class DatabaseAdminClient extends DatabaseAdminGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'spanner.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $instanceNameTemplate; - private static $databaseNameTemplate; - - private $grpcCredentialsHelper; - private $databaseAdminStub; - private $scopes; - private $defaultCallSettings; - 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) { - self::$instanceNameTemplate = new PathTemplate('projects/{project}/instances/{instance}'); - } - - return self::$instanceNameTemplate; - } - - private static function getDatabaseNameTemplate() - { - if (self::$databaseNameTemplate == null) { - self::$databaseNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}'); - } - - return self::$databaseNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listDatabasesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getDatabases', - ]); - - $pageStreamingDescriptors = [ - 'listDatabases' => $listDatabasesPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getLongRunningDescriptors() - { - return [ - 'createDatabase' => [ - 'operationReturnType' => '\Google\Spanner\Admin\Database\V1\Database', - 'metadataReturnType' => '\Google\Spanner\Admin\Database\V1\CreateDatabaseMetadata', - ], - 'updateDatabaseDdl' => [ - 'operationReturnType' => '\Google\Protobuf\GPBEmpty', - 'metadataReturnType' => '\Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlMetadata', - ], - ]; - } - - 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; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'spanner.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Cloud Spanner Database Admin API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/spanner.admin', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listDatabases' => $defaultDescriptors, - 'createDatabase' => $defaultDescriptors, - 'getDatabase' => $defaultDescriptors, - 'updateDatabaseDdl' => $defaultDescriptors, - 'dropDatabase' => $defaultDescriptors, - 'getDatabaseDdl' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/database_admin_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.spanner.admin.database.v1.DatabaseAdmin', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createDatabaseAdminStubFunction = function ($hostname, $opts) { - return new DatabaseAdminGrpcClient($hostname, $opts); - }; - if (array_key_exists('createDatabaseAdminStubFunction', $options)) { - $createDatabaseAdminStubFunction = $options['createDatabaseAdminStubFunction']; - } - $this->databaseAdminStub = $this->grpcCredentialsHelper->createStub( - $createDatabaseAdminStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists Cloud Spanner databases. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * // Iterate through all elements - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $parent Required. The instance whose databases should be listed. - * Values are of the form `projects//instances/`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listDatabases($parent, $optionalArgs = []) - { - $request = new ListDatabasesRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listDatabases']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'ListDatabases', - $mergedSettings, - $this->descriptors['listDatabases'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a new Cloud Spanner database and starts to prepare it for serving. - * The returned [long-running operation][google.longrunning.Operation] will - * have a name of the format `/operations/` and - * can be used to track preparation of the database. The - * [metadata][google.longrunning.Operation.metadata] field type is - * [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. The - * [response][google.longrunning.Operation.response] field type is - * [Database][google.spanner.admin.database.v1.Database], if successful. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * $createStatement = ""; - * $operationResponse = $databaseAdminClient->createDatabase($formattedParent, $createStatement); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $databaseAdminClient->createDatabase($formattedParent, $createStatement); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $databaseAdminClient->resumeOperation($operationName, 'createDatabase'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $parent Required. The name of the instance that will serve the new database. - * Values are of the form `projects//instances/`. - * @param string $createStatement Required. A `CREATE DATABASE` statement, which specifies the ID of the - * new database. The database ID must conform to the regular expression - * `[a-z][a-z0-9_\-]*[a-z0-9]` and be between 2 and 30 characters in length. - * @param array $optionalArgs { - * Optional. - * - * @type string[] $extraStatements - * An optional list of DDL statements to run inside the newly created - * 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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createDatabase($parent, $createStatement, $optionalArgs = []) - { - $request = new CreateDatabaseRequest(); - $request->setParent($parent); - $request->setCreateStatement($createStatement); - if (isset($optionalArgs['extraStatements'])) { - $request->setExtraStatements($optionalArgs['extraStatements']); - } - - $mergedSettings = $this->defaultCallSettings['createDatabase']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'CreateDatabase', - $mergedSettings, - $this->descriptors['createDatabase'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the state of a Cloud Spanner database. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedName = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $response = $databaseAdminClient->getDatabase($formattedName); - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $name Required. The name of the requested database. Values are of the form - * `projects//instances//databases/`. - * @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. - * } - * - * @return \Google\Spanner\Admin\Database\V1\Database - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getDatabase($name, $optionalArgs = []) - { - $request = new GetDatabaseRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getDatabase']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'GetDatabase', - $mergedSettings, - $this->descriptors['getDatabase'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates the schema of a Cloud Spanner database by - * creating/altering/dropping tables, columns, indexes, etc. The returned - * [long-running operation][google.longrunning.Operation] will have a name of - * the format `/operations/` and can be used to - * track execution of the schema change(s). The - * [metadata][google.longrunning.Operation.metadata] field type is - * [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. The operation has no response. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $statements = []; - * $operationResponse = $databaseAdminClient->updateDatabaseDdl($formattedDatabase, $statements); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * // operation succeeded and returns no value - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $databaseAdminClient->updateDatabaseDdl($formattedDatabase, $statements); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $databaseAdminClient->resumeOperation($operationName, 'updateDatabaseDdl'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * // operation succeeded and returns no value - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $database Required. The database to update. - * @param string[] $statements DDL statements to be applied to the database. - * @param array $optionalArgs { - * Optional. - * - * @type string $operationId - * If empty, the new update request is assigned an - * automatically-generated operation ID. Otherwise, `operation_id` - * is used to construct the name of the resulting - * [Operation][google.longrunning.Operation]. - * - * Specifying an explicit operation ID simplifies determining - * whether the statements were executed in the event that the - * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, - * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and - * `operation_id` fields can be combined to form the - * [name][google.longrunning.Operation.name] of the resulting - * [longrunning.Operation][google.longrunning.Operation]: `/operations/`. - * - * `operation_id` should be unique within the database, and must be - * a valid identifier: `[a-z][a-z0-9_]*`. Note that - * automatically-generated operation IDs always begin with an - * 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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateDatabaseDdl($database, $statements, $optionalArgs = []) - { - $request = new UpdateDatabaseDdlRequest(); - $request->setDatabase($database); - $request->setStatements($statements); - if (isset($optionalArgs['operationId'])) { - $request->setOperationId($optionalArgs['operationId']); - } - - $mergedSettings = $this->defaultCallSettings['updateDatabaseDdl']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'UpdateDatabaseDdl', - $mergedSettings, - $this->descriptors['updateDatabaseDdl'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Drops (aka deletes) a Cloud Spanner database. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $databaseAdminClient->dropDatabase($formattedDatabase); - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $database Required. The database to be dropped. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function dropDatabase($database, $optionalArgs = []) - { - $request = new DropDatabaseRequest(); - $request->setDatabase($database); - - $mergedSettings = $this->defaultCallSettings['dropDatabase']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'DropDatabase', - $mergedSettings, - $this->descriptors['dropDatabase'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns the schema of a Cloud Spanner database as a list of formatted - * DDL statements. This method does not show pending schema updates, those may - * be queried using the [Operations][google.longrunning.Operations] API. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $response = $databaseAdminClient->getDatabaseDdl($formattedDatabase); - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $database Required. The database whose schema we wish to get. - * @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. - * } - * - * @return \Google\Spanner\Admin\Database\V1\GetDatabaseDdlResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getDatabaseDdl($database, $optionalArgs = []) - { - $request = new GetDatabaseDdlRequest(); - $request->setDatabase($database); - - $mergedSettings = $this->defaultCallSettings['getDatabaseDdl']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'GetDatabaseDdl', - $mergedSettings, - $this->descriptors['getDatabaseDdl'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Sets the access control policy on a database resource. Replaces any - * existing policy. - * - * Authorization requires `spanner.databases.setIamPolicy` permission on - * [resource][google.iam.v1.SetIamPolicyRequest.resource]. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $policy = new Policy(); - * $response = $databaseAdminClient->setIamPolicy($formattedResource, $policy); - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being specified. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function setIamPolicy($resource, $policy, $optionalArgs = []) - { - $request = new SetIamPolicyRequest(); - $request->setResource($resource); - $request->setPolicy($policy); - - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'SetIamPolicy', - $mergedSettings, - $this->descriptors['setIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the access control policy for a database resource. Returns an empty - * policy if a database exists but does not have a policy set. - * - * Authorization requires `spanner.databases.getIamPolicy` permission on - * [resource][google.iam.v1.GetIamPolicyRequest.resource]. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $response = $databaseAdminClient->getIamPolicy($formattedResource); - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getIamPolicy($resource, $optionalArgs = []) - { - $request = new GetIamPolicyRequest(); - $request->setResource($resource); - - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'GetIamPolicy', - $mergedSettings, - $this->descriptors['getIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns permissions that the caller has on the specified database resource. - * - * Attempting this RPC on a non-existent Cloud Spanner database will result in - * a NOT_FOUND error if the user has `spanner.databases.list` permission on - * the containing Cloud Spanner instance. Otherwise returns an empty set of - * permissions. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $permissions = []; - * $response = $databaseAdminClient->testIamPermissions($formattedResource, $permissions); - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy detail is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @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. - * } - * - * @return \Google\Iam\V1\TestIamPermissionsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function testIamPermissions($resource, $permissions, $optionalArgs = []) - { - $request = new TestIamPermissionsRequest(); - $request->setResource($resource); - $request->setPermissions($permissions); - - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->databaseAdminStub, - 'TestIamPermissions', - $mergedSettings, - $this->descriptors['testIamPermissions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->databaseAdminStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see DatabaseAdminClientImpl} class. } diff --git a/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php b/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php new file mode 100644 index 000000000000..cfa6b2d89acb --- /dev/null +++ b/src/Spanner/Admin/Database/V1/Gapic/DatabaseAdminGapicClient.php @@ -0,0 +1,1107 @@ +listDatabases($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class DatabaseAdminGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'spanner.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $instanceNameTemplate; + private static $databaseNameTemplate; + + protected $grpcCredentialsHelper; + protected $databaseAdminStub; + private $scopes; + private $defaultCallSettings; + 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) { + self::$instanceNameTemplate = new PathTemplate('projects/{project}/instances/{instance}'); + } + + return self::$instanceNameTemplate; + } + + private static function getDatabaseNameTemplate() + { + if (self::$databaseNameTemplate == null) { + self::$databaseNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}'); + } + + return self::$databaseNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listDatabasesPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getDatabases', + ]); + + $pageStreamingDescriptors = [ + 'listDatabases' => $listDatabasesPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getLongRunningDescriptors() + { + return [ + 'createDatabase' => [ + 'operationReturnType' => '\Google\Spanner\Admin\Database\V1\Database', + 'metadataReturnType' => '\Google\Spanner\Admin\Database\V1\CreateDatabaseMetadata', + ], + 'updateDatabaseDdl' => [ + 'operationReturnType' => '\Google\Protobuf\GPBEmpty', + 'metadataReturnType' => '\Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlMetadata', + ], + ]; + } + + 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; + } + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return \Google\GAX\LongRunning\OperationsClient + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started + * by a long running API method. If $methodName is not provided, or does + * not match a long running API method, then the operation can still be + * resumed, but the OperationResponse object will not deserialize the + * final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return \Google\GAX\OperationResponse + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $lroDescriptors = self::getLongRunningDescriptors(); + if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { + $options = $lroDescriptors[$methodName]; + } else { + $options = []; + } + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'spanner.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.admin', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + if (array_key_exists('operationsClient', $options)) { + $this->operationsClient = $options['operationsClient']; + } else { + $operationsClientOptions = $options; + unset($operationsClientOptions['timeoutMillis']); + unset($operationsClientOptions['retryingOverride']); + $this->operationsClient = new OperationsClient($operationsClientOptions); + } + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listDatabases' => $defaultDescriptors, + 'createDatabase' => $defaultDescriptors, + 'getDatabase' => $defaultDescriptors, + 'updateDatabaseDdl' => $defaultDescriptors, + 'dropDatabase' => $defaultDescriptors, + 'getDatabaseDdl' => $defaultDescriptors, + 'setIamPolicy' => $defaultDescriptors, + 'getIamPolicy' => $defaultDescriptors, + 'testIamPermissions' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + $longRunningDescriptors = self::getLongRunningDescriptors(); + foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { + $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/database_admin_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.spanner.admin.database.v1.DatabaseAdmin', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createDatabaseAdminStubFunction = function ($hostname, $opts, $channel) { + return new DatabaseAdminGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createDatabaseAdminStubFunction', $options)) { + $createDatabaseAdminStubFunction = $options['createDatabaseAdminStubFunction']; + } + $this->databaseAdminStub = $this->grpcCredentialsHelper->createStub($createDatabaseAdminStubFunction); + } + + /** + * Lists Cloud Spanner databases. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * // Iterate through all elements + * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $parent Required. The instance whose databases should be listed. + * Values are of the form `projects//instances/`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listDatabases($parent, $optionalArgs = []) + { + $request = new ListDatabasesRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listDatabases']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'ListDatabases', + $mergedSettings, + $this->descriptors['listDatabases'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a new Cloud Spanner database and starts to prepare it for serving. + * The returned [long-running operation][google.longrunning.Operation] will + * have a name of the format `/operations/` and + * can be used to track preparation of the database. The + * [metadata][google.longrunning.Operation.metadata] field type is + * [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. The + * [response][google.longrunning.Operation.response] field type is + * [Database][google.spanner.admin.database.v1.Database], if successful. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $createStatement = ""; + * $operationResponse = $databaseAdminClient->createDatabase($formattedParent, $createStatement); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $databaseAdminClient->createDatabase($formattedParent, $createStatement); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $databaseAdminClient->resumeOperation($operationName, 'createDatabase'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $parent Required. The name of the instance that will serve the new database. + * Values are of the form `projects//instances/`. + * @param string $createStatement Required. A `CREATE DATABASE` statement, which specifies the ID of the + * new database. The database ID must conform to the regular expression + * `[a-z][a-z0-9_\-]*[a-z0-9]` and be between 2 and 30 characters in length. + * @param array $optionalArgs { + * Optional. + * + * @type string[] $extraStatements + * An optional list of DDL statements to run inside the newly created + * 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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createDatabase($parent, $createStatement, $optionalArgs = []) + { + $request = new CreateDatabaseRequest(); + $request->setParent($parent); + $request->setCreateStatement($createStatement); + if (isset($optionalArgs['extraStatements'])) { + $request->setExtraStatements($optionalArgs['extraStatements']); + } + + $mergedSettings = $this->defaultCallSettings['createDatabase']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'CreateDatabase', + $mergedSettings, + $this->descriptors['createDatabase'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the state of a Cloud Spanner database. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedName = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $response = $databaseAdminClient->getDatabase($formattedName); + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $name Required. The name of the requested database. Values are of the form + * `projects//instances//databases/`. + * @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. + * } + * + * @return \Google\Spanner\Admin\Database\V1\Database + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getDatabase($name, $optionalArgs = []) + { + $request = new GetDatabaseRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getDatabase']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'GetDatabase', + $mergedSettings, + $this->descriptors['getDatabase'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates the schema of a Cloud Spanner database by + * creating/altering/dropping tables, columns, indexes, etc. The returned + * [long-running operation][google.longrunning.Operation] will have a name of + * the format `/operations/` and can be used to + * track execution of the schema change(s). The + * [metadata][google.longrunning.Operation.metadata] field type is + * [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. The operation has no response. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $statements = []; + * $operationResponse = $databaseAdminClient->updateDatabaseDdl($formattedDatabase, $statements); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * // operation succeeded and returns no value + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $databaseAdminClient->updateDatabaseDdl($formattedDatabase, $statements); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $databaseAdminClient->resumeOperation($operationName, 'updateDatabaseDdl'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * // operation succeeded and returns no value + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $database Required. The database to update. + * @param string[] $statements DDL statements to be applied to the database. + * @param array $optionalArgs { + * Optional. + * + * @type string $operationId + * If empty, the new update request is assigned an + * automatically-generated operation ID. Otherwise, `operation_id` + * is used to construct the name of the resulting + * [Operation][google.longrunning.Operation]. + * + * Specifying an explicit operation ID simplifies determining + * whether the statements were executed in the event that the + * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, + * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and + * `operation_id` fields can be combined to form the + * [name][google.longrunning.Operation.name] of the resulting + * [longrunning.Operation][google.longrunning.Operation]: `/operations/`. + * + * `operation_id` should be unique within the database, and must be + * a valid identifier: `[a-z][a-z0-9_]*`. Note that + * automatically-generated operation IDs always begin with an + * 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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateDatabaseDdl($database, $statements, $optionalArgs = []) + { + $request = new UpdateDatabaseDdlRequest(); + $request->setDatabase($database); + $request->setStatements($statements); + if (isset($optionalArgs['operationId'])) { + $request->setOperationId($optionalArgs['operationId']); + } + + $mergedSettings = $this->defaultCallSettings['updateDatabaseDdl']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'UpdateDatabaseDdl', + $mergedSettings, + $this->descriptors['updateDatabaseDdl'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Drops (aka deletes) a Cloud Spanner database. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $databaseAdminClient->dropDatabase($formattedDatabase); + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $database Required. The database to be dropped. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function dropDatabase($database, $optionalArgs = []) + { + $request = new DropDatabaseRequest(); + $request->setDatabase($database); + + $mergedSettings = $this->defaultCallSettings['dropDatabase']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'DropDatabase', + $mergedSettings, + $this->descriptors['dropDatabase'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns the schema of a Cloud Spanner database as a list of formatted + * DDL statements. This method does not show pending schema updates, those may + * be queried using the [Operations][google.longrunning.Operations] API. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedDatabase = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $response = $databaseAdminClient->getDatabaseDdl($formattedDatabase); + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $database Required. The database whose schema we wish to get. + * @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. + * } + * + * @return \Google\Spanner\Admin\Database\V1\GetDatabaseDdlResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getDatabaseDdl($database, $optionalArgs = []) + { + $request = new GetDatabaseDdlRequest(); + $request->setDatabase($database); + + $mergedSettings = $this->defaultCallSettings['getDatabaseDdl']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'GetDatabaseDdl', + $mergedSettings, + $this->descriptors['getDatabaseDdl'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Sets the access control policy on a database resource. Replaces any + * existing policy. + * + * Authorization requires `spanner.databases.setIamPolicy` permission on + * [resource][google.iam.v1.SetIamPolicyRequest.resource]. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $policy = new Policy(); + * $response = $databaseAdminClient->setIamPolicy($formattedResource, $policy); + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function setIamPolicy($resource, $policy, $optionalArgs = []) + { + $request = new SetIamPolicyRequest(); + $request->setResource($resource); + $request->setPolicy($policy); + + $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'SetIamPolicy', + $mergedSettings, + $this->descriptors['setIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the access control policy for a database resource. Returns an empty + * policy if a database exists but does not have a policy set. + * + * Authorization requires `spanner.databases.getIamPolicy` permission on + * [resource][google.iam.v1.GetIamPolicyRequest.resource]. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $response = $databaseAdminClient->getIamPolicy($formattedResource); + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getIamPolicy($resource, $optionalArgs = []) + { + $request = new GetIamPolicyRequest(); + $request->setResource($resource); + + $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'GetIamPolicy', + $mergedSettings, + $this->descriptors['getIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns permissions that the caller has on the specified database resource. + * + * Attempting this RPC on a non-existent Cloud Spanner database will result in + * a NOT_FOUND error if the user has `spanner.databases.list` permission on + * the containing Cloud Spanner instance. Otherwise returns an empty set of + * permissions. + * + * Sample code: + * ``` + * try { + * $databaseAdminClient = new DatabaseAdminClient(); + * $formattedResource = DatabaseAdminClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $permissions = []; + * $response = $databaseAdminClient->testIamPermissions($formattedResource, $permissions); + * } finally { + * $databaseAdminClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @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. + * } + * + * @return \Google\Iam\V1\TestIamPermissionsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function testIamPermissions($resource, $permissions, $optionalArgs = []) + { + $request = new TestIamPermissionsRequest(); + $request->setResource($resource); + $request->setPermissions($permissions); + + $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->databaseAdminStub, + 'TestIamPermissions', + $mergedSettings, + $this->descriptors['testIamPermissions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->databaseAdminStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php b/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php new file mode 100644 index 000000000000..182b04e1a135 --- /dev/null +++ b/src/Spanner/Admin/Instance/V1/Gapic/InstanceAdminGapicClient.php @@ -0,0 +1,1312 @@ +listInstanceConfigs($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class InstanceAdminGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'spanner.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $instanceConfigNameTemplate; + private static $instanceNameTemplate; + + protected $grpcCredentialsHelper; + protected $instanceAdminStub; + private $scopes; + private $defaultCallSettings; + 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) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getInstanceConfigNameTemplate() + { + if (self::$instanceConfigNameTemplate == null) { + self::$instanceConfigNameTemplate = new PathTemplate('projects/{project}/instanceConfigs/{instance_config}'); + } + + return self::$instanceConfigNameTemplate; + } + + private static function getInstanceNameTemplate() + { + if (self::$instanceNameTemplate == null) { + self::$instanceNameTemplate = new PathTemplate('projects/{project}/instances/{instance}'); + } + + return self::$instanceNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listInstanceConfigsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getInstanceConfigs', + ]); + $listInstancesPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getInstances', + ]); + + $pageStreamingDescriptors = [ + 'listInstanceConfigs' => $listInstanceConfigsPageStreamingDescriptor, + 'listInstances' => $listInstancesPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getLongRunningDescriptors() + { + return [ + 'createInstance' => [ + 'operationReturnType' => '\Google\Spanner\Admin\Instance\V1\Instance', + 'metadataReturnType' => '\Google\Spanner\Admin\Instance\V1\CreateInstanceMetadata', + ], + 'updateInstance' => [ + 'operationReturnType' => '\Google\Spanner\Admin\Instance\V1\Instance', + 'metadataReturnType' => '\Google\Spanner\Admin\Instance\V1\UpdateInstanceMetadata', + ], + ]; + } + + 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; + } + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return \Google\GAX\LongRunning\OperationsClient + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started + * by a long running API method. If $methodName is not provided, or does + * not match a long running API method, then the operation can still be + * resumed, but the OperationResponse object will not deserialize the + * final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return \Google\GAX\OperationResponse + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $lroDescriptors = self::getLongRunningDescriptors(); + if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { + $options = $lroDescriptors[$methodName]; + } else { + $options = []; + } + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'spanner.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.admin', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + if (array_key_exists('operationsClient', $options)) { + $this->operationsClient = $options['operationsClient']; + } else { + $operationsClientOptions = $options; + unset($operationsClientOptions['timeoutMillis']); + unset($operationsClientOptions['retryingOverride']); + $this->operationsClient = new OperationsClient($operationsClientOptions); + } + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listInstanceConfigs' => $defaultDescriptors, + 'getInstanceConfig' => $defaultDescriptors, + 'listInstances' => $defaultDescriptors, + 'getInstance' => $defaultDescriptors, + 'createInstance' => $defaultDescriptors, + 'updateInstance' => $defaultDescriptors, + 'deleteInstance' => $defaultDescriptors, + 'setIamPolicy' => $defaultDescriptors, + 'getIamPolicy' => $defaultDescriptors, + 'testIamPermissions' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + $longRunningDescriptors = self::getLongRunningDescriptors(); + foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { + $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/instance_admin_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.spanner.admin.instance.v1.InstanceAdmin', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createInstanceAdminStubFunction = function ($hostname, $opts, $channel) { + return new InstanceAdminGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createInstanceAdminStubFunction', $options)) { + $createInstanceAdminStubFunction = $options['createInstanceAdminStubFunction']; + } + $this->instanceAdminStub = $this->grpcCredentialsHelper->createStub($createInstanceAdminStubFunction); + } + + /** + * Lists the supported instance configurations for a given project. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $parent Required. The name of the project for which a list of supported instance + * configurations is requested. Values are of the form + * `projects/`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listInstanceConfigs($parent, $optionalArgs = []) + { + $request = new ListInstanceConfigsRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listInstanceConfigs']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'ListInstanceConfigs', + $mergedSettings, + $this->descriptors['listInstanceConfigs'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets information about a particular instance configuration. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedName = InstanceAdminClient::formatInstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"); + * $response = $instanceAdminClient->getInstanceConfig($formattedName); + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $name Required. The name of the requested instance configuration. Values are of + * the form `projects//instanceConfigs/`. + * @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. + * } + * + * @return \Google\Spanner\Admin\Instance\V1\InstanceConfig + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getInstanceConfig($name, $optionalArgs = []) + { + $request = new GetInstanceConfigRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getInstanceConfig']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'GetInstanceConfig', + $mergedSettings, + $this->descriptors['getInstanceConfig'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists all instances in the given project. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $instanceAdminClient->listInstances($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $instanceAdminClient->listInstances($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $parent Required. The name of the project for which a list of instances is + * requested. Values are of the form `projects/`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * 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 string $pageToken + * A page token is used to specify a page of values to be returned. + * 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 string $filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * name + * * display_name + * * labels.key where key is the name of a label + * + * Some examples of using filters are: + * + * * name:* --> The instance has a name. + * * name:Howl --> The instance's name contains the string "howl". + * * name:HOWL --> Equivalent to above. + * * NAME:howl --> Equivalent to above. + * * labels.env:* --> The instance has the label "env". + * * labels.env:dev --> The instance has the label "env" and the value of + * the label contains the string "dev". + * * 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. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listInstances($parent, $optionalArgs = []) + { + $request = new ListInstancesRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + + $mergedSettings = $this->defaultCallSettings['listInstances']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'ListInstances', + $mergedSettings, + $this->descriptors['listInstances'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets information about a particular instance. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedName = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $response = $instanceAdminClient->getInstance($formattedName); + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $name Required. The name of the requested instance. Values are of the form + * `projects//instances/`. + * @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. + * } + * + * @return \Google\Spanner\Admin\Instance\V1\Instance + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getInstance($name, $optionalArgs = []) + { + $request = new GetInstanceRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getInstance']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'GetInstance', + $mergedSettings, + $this->descriptors['getInstance'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates an instance and begins preparing it to begin serving. The + * returned [long-running operation][google.longrunning.Operation] + * can be used to track the progress of preparing the new + * instance. The instance name is assigned by the caller. If the + * named instance already exists, `CreateInstance` returns + * `ALREADY_EXISTS`. + * + * Immediately upon completion of this request: + * + * * The instance is readable via the API, with all requested attributes + * but no allocated resources. Its state is `CREATING`. + * + * Until completion of the returned operation: + * + * * Cancelling the operation renders the instance immediately unreadable + * via the API. + * * The instance can be deleted. + * * All other attempts to modify the instance are rejected. + * + * Upon completion of the returned operation: + * + * * Billing for all successfully-allocated resources begins (some types + * may have lower than the requested levels). + * * Databases can be created in the instance. + * * The instance's allocated resource levels are readable via the API. + * * The instance's state becomes `READY`. + * + * The returned [long-running operation][google.longrunning.Operation] will + * have a name of the format `/operations/` and + * can be used to track creation of the instance. The + * [metadata][google.longrunning.Operation.metadata] field type is + * [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. + * The [response][google.longrunning.Operation.response] field type is + * [Instance][google.spanner.admin.instance.v1.Instance], if successful. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); + * $instanceId = ""; + * $instance = new Instance(); + * $operationResponse = $instanceAdminClient->createInstance($formattedParent, $instanceId, $instance); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $instanceAdminClient->createInstance($formattedParent, $instanceId, $instance); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $instanceAdminClient->resumeOperation($operationName, 'createInstance'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $parent Required. The name of the project in which to create the instance. Values + * are of the form `projects/`. + * @param string $instanceId Required. The ID of the instance to create. Valid identifiers are of the + * form `[a-z][-a-z0-9]*[a-z0-9]` and must be between 6 and 30 characters in + * length. + * @param Instance $instance Required. The instance to create. The name may be omitted, but if + * specified must be `/instances/`. + * @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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createInstance($parent, $instanceId, $instance, $optionalArgs = []) + { + $request = new CreateInstanceRequest(); + $request->setParent($parent); + $request->setInstanceId($instanceId); + $request->setInstance($instance); + + $mergedSettings = $this->defaultCallSettings['createInstance']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'CreateInstance', + $mergedSettings, + $this->descriptors['createInstance'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates an instance, and begins allocating or releasing resources + * as requested. The returned [long-running + * operation][google.longrunning.Operation] can be used to track the + * progress of updating the instance. If the named instance does not + * exist, returns `NOT_FOUND`. + * + * Immediately upon completion of this request: + * + * * For resource types for which a decrease in the instance's allocation + * has been requested, billing is based on the newly-requested level. + * + * Until completion of the returned operation: + * + * * Cancelling the operation sets its metadata's + * [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins + * restoring resources to their pre-request values. The operation + * is guaranteed to succeed at undoing all resource changes, + * after which point it terminates with a `CANCELLED` status. + * * All other attempts to modify the instance are rejected. + * * Reading the instance via the API continues to give the pre-request + * resource levels. + * + * Upon completion of the returned operation: + * + * * Billing begins for all successfully-allocated resources (some types + * may have lower than the requested levels). + * * All newly-reserved resources are available for serving the instance's + * tables. + * * The instance's new resource levels are readable via the API. + * + * The returned [long-running operation][google.longrunning.Operation] will + * have a name of the format `/operations/` and + * can be used to track the instance modification. The + * [metadata][google.longrunning.Operation.metadata] field type is + * [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. + * The [response][google.longrunning.Operation.response] field type is + * [Instance][google.spanner.admin.instance.v1.Instance], if successful. + * + * Authorization requires `spanner.instances.update` permission on + * resource [name][google.spanner.admin.instance.v1.Instance.name]. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $instance = new Instance(); + * $fieldMask = new FieldMask(); + * $operationResponse = $instanceAdminClient->updateInstance($instance, $fieldMask); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $instanceAdminClient->updateInstance($instance, $fieldMask); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $instanceAdminClient->resumeOperation($operationName, 'updateInstance'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param Instance $instance Required. The instance to update, which must always include the instance + * name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] need be included. + * @param FieldMask $fieldMask Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. + * The field mask must always be specified; this prevents any future fields in + * [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know + * about them. + * @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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateInstance($instance, $fieldMask, $optionalArgs = []) + { + $request = new UpdateInstanceRequest(); + $request->setInstance($instance); + $request->setFieldMask($fieldMask); + + $mergedSettings = $this->defaultCallSettings['updateInstance']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'UpdateInstance', + $mergedSettings, + $this->descriptors['updateInstance'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes an instance. + * + * Immediately upon completion of the request: + * + * * Billing ceases for all of the instance's reserved resources. + * + * Soon afterward: + * + * * The instance and *all of its databases* immediately and + * irrevocably disappear from the API. All data in the databases + * is permanently deleted. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedName = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $instanceAdminClient->deleteInstance($formattedName); + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $name Required. The name of the instance to be deleted. Values are of the form + * `projects//instances/` + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteInstance($name, $optionalArgs = []) + { + $request = new DeleteInstanceRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['deleteInstance']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'DeleteInstance', + $mergedSettings, + $this->descriptors['deleteInstance'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Sets the access control policy on an instance resource. Replaces any + * existing policy. + * + * Authorization requires `spanner.instances.setIamPolicy` on + * [resource][google.iam.v1.SetIamPolicyRequest.resource]. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $policy = new Policy(); + * $response = $instanceAdminClient->setIamPolicy($formattedResource, $policy); + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function setIamPolicy($resource, $policy, $optionalArgs = []) + { + $request = new SetIamPolicyRequest(); + $request->setResource($resource); + $request->setPolicy($policy); + + $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'SetIamPolicy', + $mergedSettings, + $this->descriptors['setIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the access control policy for an instance resource. Returns an empty + * policy if an instance exists but does not have a policy set. + * + * Authorization requires `spanner.instances.getIamPolicy` on + * [resource][google.iam.v1.GetIamPolicyRequest.resource]. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $response = $instanceAdminClient->getIamPolicy($formattedResource); + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @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. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getIamPolicy($resource, $optionalArgs = []) + { + $request = new GetIamPolicyRequest(); + $request->setResource($resource); + + $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'GetIamPolicy', + $mergedSettings, + $this->descriptors['getIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns permissions that the caller has on the specified instance resource. + * + * Attempting this RPC on a non-existent Cloud Spanner instance resource will + * result in a NOT_FOUND error if the user has `spanner.instances.list` + * permission on the containing Google Cloud Project. Otherwise returns an + * empty set of permissions. + * + * Sample code: + * ``` + * try { + * $instanceAdminClient = new InstanceAdminClient(); + * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); + * $permissions = []; + * $response = $instanceAdminClient->testIamPermissions($formattedResource, $permissions); + * } finally { + * $instanceAdminClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @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. + * } + * + * @return \Google\Iam\V1\TestIamPermissionsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function testIamPermissions($resource, $permissions, $optionalArgs = []) + { + $request = new TestIamPermissionsRequest(); + $request->setResource($resource); + $request->setPermissions($permissions); + + $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->instanceAdminStub, + 'TestIamPermissions', + $mergedSettings, + $this->descriptors['testIamPermissions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->instanceAdminStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Spanner/Admin/Instance/V1/InstanceAdminClient.php b/src/Spanner/Admin/Instance/V1/InstanceAdminClient.php index 7747521ca41f..5f116d18cf24 100644 --- a/src/Spanner/Admin/Instance/V1/InstanceAdminClient.php +++ b/src/Spanner/Admin/Instance/V1/InstanceAdminClient.php @@ -30,1284 +30,12 @@ namespace Google\Cloud\Spanner\Admin\Instance\V1; -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\Iam\V1\GetIamPolicyRequest; -use Google\Iam\V1\Policy; -use Google\Iam\V1\SetIamPolicyRequest; -use Google\Iam\V1\TestIamPermissionsRequest; -use Google\Protobuf\FieldMask; -use Google\Spanner\Admin\Instance\V1\CreateInstanceMetadata; -use Google\Spanner\Admin\Instance\V1\CreateInstanceRequest; -use Google\Spanner\Admin\Instance\V1\DeleteInstanceRequest; -use Google\Spanner\Admin\Instance\V1\GetInstanceConfigRequest; -use Google\Spanner\Admin\Instance\V1\GetInstanceRequest; -use Google\Spanner\Admin\Instance\V1\Instance; -use Google\Spanner\Admin\Instance\V1\InstanceAdminGrpcClient; -use Google\Spanner\Admin\Instance\V1\ListInstanceConfigsRequest; -use Google\Spanner\Admin\Instance\V1\ListInstancesRequest; -use Google\Spanner\Admin\Instance\V1\UpdateInstanceMetadata; -use Google\Spanner\Admin\Instance\V1\UpdateInstanceRequest; +use Google\Cloud\Spanner\Admin\Instance\V1\Gapic\InstanceAdminGapicClient; /** - * Service Description: Cloud Spanner Instance Admin API. - * - * The Cloud Spanner Instance Admin API can be used to create, delete, - * modify and list instances. Instances are dedicated Cloud Spanner serving - * and storage resources to be used by Cloud Spanner databases. - * - * Each instance has a "configuration", which dictates where the - * serving resources for the Cloud Spanner instance are located (e.g., - * US-central, Europe). Configurations are created by Google based on - * resource availability. - * - * Cloud Spanner billing is based on the instances that exist and their - * sizes. After an instance exists, there are no additional - * per-database or per-operation charges for use of the instance - * (though there may be additional network bandwidth charges). - * Instances offer isolation: problems with databases in one instance - * will not affect other instances. However, within an instance - * databases can affect each other. For example, if one database in an - * instance receives a lot of requests and consumes most of the - * instance resources, fewer resources are available for other - * databases in that instance, and their performance may suffer. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class InstanceAdminClient +class InstanceAdminClient extends InstanceAdminGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'spanner.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $instanceConfigNameTemplate; - private static $instanceNameTemplate; - - private $grpcCredentialsHelper; - private $instanceAdminStub; - private $scopes; - private $defaultCallSettings; - 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) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getInstanceConfigNameTemplate() - { - if (self::$instanceConfigNameTemplate == null) { - self::$instanceConfigNameTemplate = new PathTemplate('projects/{project}/instanceConfigs/{instance_config}'); - } - - return self::$instanceConfigNameTemplate; - } - - private static function getInstanceNameTemplate() - { - if (self::$instanceNameTemplate == null) { - self::$instanceNameTemplate = new PathTemplate('projects/{project}/instances/{instance}'); - } - - return self::$instanceNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listInstanceConfigsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getInstanceConfigs', - ]); - $listInstancesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getInstances', - ]); - - $pageStreamingDescriptors = [ - 'listInstanceConfigs' => $listInstanceConfigsPageStreamingDescriptor, - 'listInstances' => $listInstancesPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getLongRunningDescriptors() - { - return [ - 'createInstance' => [ - 'operationReturnType' => '\Google\Spanner\Admin\Instance\V1\Instance', - 'metadataReturnType' => '\Google\Spanner\Admin\Instance\V1\CreateInstanceMetadata', - ], - 'updateInstance' => [ - 'operationReturnType' => '\Google\Spanner\Admin\Instance\V1\Instance', - 'metadataReturnType' => '\Google\Spanner\Admin\Instance\V1\UpdateInstanceMetadata', - ], - ]; - } - - 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; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'spanner.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Cloud Spanner Instance Admin API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/spanner.admin', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listInstanceConfigs' => $defaultDescriptors, - 'getInstanceConfig' => $defaultDescriptors, - 'listInstances' => $defaultDescriptors, - 'getInstance' => $defaultDescriptors, - 'createInstance' => $defaultDescriptors, - 'updateInstance' => $defaultDescriptors, - 'deleteInstance' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/instance_admin_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.spanner.admin.instance.v1.InstanceAdmin', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createInstanceAdminStubFunction = function ($hostname, $opts) { - return new InstanceAdminGrpcClient($hostname, $opts); - }; - if (array_key_exists('createInstanceAdminStubFunction', $options)) { - $createInstanceAdminStubFunction = $options['createInstanceAdminStubFunction']; - } - $this->instanceAdminStub = $this->grpcCredentialsHelper->createStub( - $createInstanceAdminStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists the supported instance configurations for a given project. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $instanceAdminClient->listInstanceConfigs($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $parent Required. The name of the project for which a list of supported instance - * configurations is requested. Values are of the form - * `projects/`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listInstanceConfigs($parent, $optionalArgs = []) - { - $request = new ListInstanceConfigsRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listInstanceConfigs']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'ListInstanceConfigs', - $mergedSettings, - $this->descriptors['listInstanceConfigs'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets information about a particular instance configuration. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedName = InstanceAdminClient::formatInstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"); - * $response = $instanceAdminClient->getInstanceConfig($formattedName); - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $name Required. The name of the requested instance configuration. Values are of - * the form `projects//instanceConfigs/`. - * @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. - * } - * - * @return \Google\Spanner\Admin\Instance\V1\InstanceConfig - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getInstanceConfig($name, $optionalArgs = []) - { - $request = new GetInstanceConfigRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getInstanceConfig']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'GetInstanceConfig', - $mergedSettings, - $this->descriptors['getInstanceConfig'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists all instances in the given project. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $instanceAdminClient->listInstances($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $instanceAdminClient->listInstances($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $parent Required. The name of the project for which a list of instances is - * requested. Values are of the form `projects/`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * 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 string $pageToken - * A page token is used to specify a page of values to be returned. - * 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 string $filter - * An expression for filtering the results of the request. Filter rules are - * case insensitive. The fields eligible for filtering are: - * - * * name - * * display_name - * * labels.key where key is the name of a label - * - * Some examples of using filters are: - * - * * name:* --> The instance has a name. - * * name:Howl --> The instance's name contains the string "howl". - * * name:HOWL --> Equivalent to above. - * * NAME:howl --> Equivalent to above. - * * labels.env:* --> The instance has the label "env". - * * labels.env:dev --> The instance has the label "env" and the value of - * the label contains the string "dev". - * * 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. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listInstances($parent, $optionalArgs = []) - { - $request = new ListInstancesRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - - $mergedSettings = $this->defaultCallSettings['listInstances']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'ListInstances', - $mergedSettings, - $this->descriptors['listInstances'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets information about a particular instance. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedName = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * $response = $instanceAdminClient->getInstance($formattedName); - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $name Required. The name of the requested instance. Values are of the form - * `projects//instances/`. - * @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. - * } - * - * @return \Google\Spanner\Admin\Instance\V1\Instance - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getInstance($name, $optionalArgs = []) - { - $request = new GetInstanceRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getInstance']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'GetInstance', - $mergedSettings, - $this->descriptors['getInstance'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates an instance and begins preparing it to begin serving. The - * returned [long-running operation][google.longrunning.Operation] - * can be used to track the progress of preparing the new - * instance. The instance name is assigned by the caller. If the - * named instance already exists, `CreateInstance` returns - * `ALREADY_EXISTS`. - * - * Immediately upon completion of this request: - * - * * The instance is readable via the API, with all requested attributes - * but no allocated resources. Its state is `CREATING`. - * - * Until completion of the returned operation: - * - * * Cancelling the operation renders the instance immediately unreadable - * via the API. - * * The instance can be deleted. - * * All other attempts to modify the instance are rejected. - * - * Upon completion of the returned operation: - * - * * Billing for all successfully-allocated resources begins (some types - * may have lower than the requested levels). - * * Databases can be created in the instance. - * * The instance's allocated resource levels are readable via the API. - * * The instance's state becomes `READY`. - * - * The returned [long-running operation][google.longrunning.Operation] will - * have a name of the format `/operations/` and - * can be used to track creation of the instance. The - * [metadata][google.longrunning.Operation.metadata] field type is - * [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. - * The [response][google.longrunning.Operation.response] field type is - * [Instance][google.spanner.admin.instance.v1.Instance], if successful. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedParent = InstanceAdminClient::formatProjectName("[PROJECT]"); - * $instanceId = ""; - * $instance = new Instance(); - * $operationResponse = $instanceAdminClient->createInstance($formattedParent, $instanceId, $instance); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $instanceAdminClient->createInstance($formattedParent, $instanceId, $instance); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $instanceAdminClient->resumeOperation($operationName, 'createInstance'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $parent Required. The name of the project in which to create the instance. Values - * are of the form `projects/`. - * @param string $instanceId Required. The ID of the instance to create. Valid identifiers are of the - * form `[a-z][-a-z0-9]*[a-z0-9]` and must be between 6 and 30 characters in - * length. - * @param Instance $instance Required. The instance to create. The name may be omitted, but if - * specified must be `/instances/`. - * @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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createInstance($parent, $instanceId, $instance, $optionalArgs = []) - { - $request = new CreateInstanceRequest(); - $request->setParent($parent); - $request->setInstanceId($instanceId); - $request->setInstance($instance); - - $mergedSettings = $this->defaultCallSettings['createInstance']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'CreateInstance', - $mergedSettings, - $this->descriptors['createInstance'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates an instance, and begins allocating or releasing resources - * as requested. The returned [long-running - * operation][google.longrunning.Operation] can be used to track the - * progress of updating the instance. If the named instance does not - * exist, returns `NOT_FOUND`. - * - * Immediately upon completion of this request: - * - * * For resource types for which a decrease in the instance's allocation - * has been requested, billing is based on the newly-requested level. - * - * Until completion of the returned operation: - * - * * Cancelling the operation sets its metadata's - * [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins - * restoring resources to their pre-request values. The operation - * is guaranteed to succeed at undoing all resource changes, - * after which point it terminates with a `CANCELLED` status. - * * All other attempts to modify the instance are rejected. - * * Reading the instance via the API continues to give the pre-request - * resource levels. - * - * Upon completion of the returned operation: - * - * * Billing begins for all successfully-allocated resources (some types - * may have lower than the requested levels). - * * All newly-reserved resources are available for serving the instance's - * tables. - * * The instance's new resource levels are readable via the API. - * - * The returned [long-running operation][google.longrunning.Operation] will - * have a name of the format `/operations/` and - * can be used to track the instance modification. The - * [metadata][google.longrunning.Operation.metadata] field type is - * [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. - * The [response][google.longrunning.Operation.response] field type is - * [Instance][google.spanner.admin.instance.v1.Instance], if successful. - * - * Authorization requires `spanner.instances.update` permission on - * resource [name][google.spanner.admin.instance.v1.Instance.name]. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $instance = new Instance(); - * $fieldMask = new FieldMask(); - * $operationResponse = $instanceAdminClient->updateInstance($instance, $fieldMask); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $instanceAdminClient->updateInstance($instance, $fieldMask); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $instanceAdminClient->resumeOperation($operationName, 'updateInstance'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param Instance $instance Required. The instance to update, which must always include the instance - * name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] need be included. - * @param FieldMask $fieldMask Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. - * The field mask must always be specified; this prevents any future fields in - * [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know - * about them. - * @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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateInstance($instance, $fieldMask, $optionalArgs = []) - { - $request = new UpdateInstanceRequest(); - $request->setInstance($instance); - $request->setFieldMask($fieldMask); - - $mergedSettings = $this->defaultCallSettings['updateInstance']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'UpdateInstance', - $mergedSettings, - $this->descriptors['updateInstance'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes an instance. - * - * Immediately upon completion of the request: - * - * * Billing ceases for all of the instance's reserved resources. - * - * Soon afterward: - * - * * The instance and *all of its databases* immediately and - * irrevocably disappear from the API. All data in the databases - * is permanently deleted. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedName = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * $instanceAdminClient->deleteInstance($formattedName); - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $name Required. The name of the instance to be deleted. Values are of the form - * `projects//instances/` - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteInstance($name, $optionalArgs = []) - { - $request = new DeleteInstanceRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['deleteInstance']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'DeleteInstance', - $mergedSettings, - $this->descriptors['deleteInstance'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Sets the access control policy on an instance resource. Replaces any - * existing policy. - * - * Authorization requires `spanner.instances.setIamPolicy` on - * [resource][google.iam.v1.SetIamPolicyRequest.resource]. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * $policy = new Policy(); - * $response = $instanceAdminClient->setIamPolicy($formattedResource, $policy); - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being specified. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function setIamPolicy($resource, $policy, $optionalArgs = []) - { - $request = new SetIamPolicyRequest(); - $request->setResource($resource); - $request->setPolicy($policy); - - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'SetIamPolicy', - $mergedSettings, - $this->descriptors['setIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the access control policy for an instance resource. Returns an empty - * policy if an instance exists but does not have a policy set. - * - * Authorization requires `spanner.instances.getIamPolicy` on - * [resource][google.iam.v1.GetIamPolicyRequest.resource]. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * $response = $instanceAdminClient->getIamPolicy($formattedResource); - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @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. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getIamPolicy($resource, $optionalArgs = []) - { - $request = new GetIamPolicyRequest(); - $request->setResource($resource); - - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'GetIamPolicy', - $mergedSettings, - $this->descriptors['getIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns permissions that the caller has on the specified instance resource. - * - * Attempting this RPC on a non-existent Cloud Spanner instance resource will - * result in a NOT_FOUND error if the user has `spanner.instances.list` - * permission on the containing Google Cloud Project. Otherwise returns an - * empty set of permissions. - * - * Sample code: - * ``` - * try { - * $instanceAdminClient = new InstanceAdminClient(); - * $formattedResource = InstanceAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * $permissions = []; - * $response = $instanceAdminClient->testIamPermissions($formattedResource, $permissions); - * } finally { - * $instanceAdminClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy detail is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @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. - * } - * - * @return \Google\Iam\V1\TestIamPermissionsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function testIamPermissions($resource, $permissions, $optionalArgs = []) - { - $request = new TestIamPermissionsRequest(); - $request->setResource($resource); - $request->setPermissions($permissions); - - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->instanceAdminStub, - 'TestIamPermissions', - $mergedSettings, - $this->descriptors['testIamPermissions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->instanceAdminStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see InstanceAdminClientImpl} class. } diff --git a/src/Spanner/Connection/Grpc.php b/src/Spanner/Connection/Grpc.php index e53d3ab1fd5e..6d93f80cd03e 100644 --- a/src/Spanner/Connection/Grpc.php +++ b/src/Spanner/Connection/Grpc.php @@ -129,13 +129,13 @@ public function __construct(array $config = []) return $this->formatTimestampFromApi($v); } ], [ - '.google.protobuf.Value' => function ($v) { + 'google.protobuf.Value' => function ($v) { return $this->flattenValue($v); }, - '.google.protobuf.ListValue' => function ($v) { + 'google.protobuf.ListValue' => function ($v) { return $this->flattenListValue($v); }, - '.google.protobuf.Struct' => function ($v) { + 'google.protobuf.Struct' => function ($v) { return $this->flattenStruct($v); }, ]); diff --git a/src/Spanner/V1/Gapic/SpannerGapicClient.php b/src/Spanner/V1/Gapic/SpannerGapicClient.php new file mode 100644 index 000000000000..eabdc3d93e86 --- /dev/null +++ b/src/Spanner/V1/Gapic/SpannerGapicClient.php @@ -0,0 +1,1243 @@ +createSession($formattedDatabase); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * 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. + * + * @experimental + */ +class SpannerGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'spanner.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $databaseNameTemplate; + private static $sessionNameTemplate; + + protected $grpcCredentialsHelper; + protected $spannerStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * 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, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a session resource. + * + * @param string $project + * @param string $instance + * @param string $database + * @param string $session + * + * @return string The formatted session resource. + * @experimental + */ + public static function formatSessionName($project, $instance, $database, $session) + { + return self::getSessionNameTemplate()->render([ + 'project' => $project, + 'instance' => $instance, + 'database' => $database, + 'session' => $session, + ]); + } + + /** + * 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. + * + * @param string $sessionName The fully-qualified session resource. + * + * @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 $sessionName The fully-qualified session resource. + * + * @return string The extracted database value. + * @experimental + */ + public static function parseDatabaseFromSessionName($sessionName) + { + 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}'); + } + + 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 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'spanner.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.data', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'createSession' => $defaultDescriptors, + 'getSession' => $defaultDescriptors, + 'deleteSession' => $defaultDescriptors, + 'executeSql' => $defaultDescriptors, + 'executeStreamingSql' => $defaultDescriptors, + 'read' => $defaultDescriptors, + 'streamingRead' => $defaultDescriptors, + 'beginTransaction' => $defaultDescriptors, + 'commit' => $defaultDescriptors, + 'rollback' => $defaultDescriptors, + ]; + $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); + foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { + $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/spanner_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.spanner.v1.Spanner', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createSpannerStubFunction = function ($hostname, $opts, $channel) { + return new SpannerGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createSpannerStubFunction', $options)) { + $createSpannerStubFunction = $options['createSpannerStubFunction']; + } + $this->spannerStub = $this->grpcCredentialsHelper->createStub($createSpannerStubFunction); + } + + /** + * Creates a new session. A session can be used to perform + * transactions that read and/or modify data in a Cloud Spanner database. + * Sessions are meant to be reused for many consecutive + * transactions. + * + * Sessions can only execute one transaction at a time. To execute + * multiple concurrent read-write/write-only transactions, create + * multiple sessions. Note that standalone reads and queries use a + * transaction internally, and count toward the one transaction + * limit. + * + * Cloud Spanner limits the number of sessions that can exist at any given + * time; thus, it is a good idea to delete idle and/or unneeded sessions. + * Aside from explicit deletes, Cloud Spanner can delete sessions for which no + * operations are sent for more than an hour. If a session is deleted, + * requests to it return `NOT_FOUND`. + * + * Idle sessions can be kept alive by sending a trivial SQL query + * periodically, e.g., `"SELECT 1"`. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedDatabase = SpannerClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); + * $response = $spannerClient->createSession($formattedDatabase); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $database Required. The database in which the new session is created. + * @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. + * } + * + * @return \Google\Spanner\V1\Session + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSession($database, $optionalArgs = []) + { + $request = new CreateSessionRequest(); + $request->setDatabase($database); + + $mergedSettings = $this->defaultCallSettings['createSession']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'CreateSession', + $mergedSettings, + $this->descriptors['createSession'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a session. Returns `NOT_FOUND` if the session does not exist. + * This is mainly useful for determining whether a session is still + * alive. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedName = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $response = $spannerClient->getSession($formattedName); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $name Required. The name of the session to retrieve. + * @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. + * } + * + * @return \Google\Spanner\V1\Session + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getSession($name, $optionalArgs = []) + { + $request = new GetSessionRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getSession']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'GetSession', + $mergedSettings, + $this->descriptors['getSession'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Ends a session, releasing server resources associated with it. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedName = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $spannerClient->deleteSession($formattedName); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $name Required. The name of the session to delete. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSession($name, $optionalArgs = []) + { + $request = new DeleteSessionRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['deleteSession']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'DeleteSession', + $mergedSettings, + $this->descriptors['deleteSession'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Executes an SQL query, returning all rows in a single reply. This + * method cannot be used to return a result set larger than 10 MiB; + * if the query yields more data than that, the query fails with + * a `FAILED_PRECONDITION` error. + * + * Queries inside read-write transactions might return `ABORTED`. If + * this occurs, the application should restart the transaction from + * the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + * + * Larger result sets can be fetched in streaming fashion by calling + * [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $sql = ""; + * $response = $spannerClient->executeSql($formattedSession, $sql); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the SQL query should be performed. + * @param string $sql Required. The SQL query string. + * @param array $optionalArgs { + * Optional. + * + * @type TransactionSelector $transaction + * The transaction to use. If none is provided, the default is a + * temporary read-only transaction with strong concurrency. + * @type Struct $params + * The SQL query string can contain parameter placeholders. A parameter + * placeholder consists of `'@'` followed by the parameter + * name. Parameter names consist of any combination of letters, + * numbers, and underscores. + * + * Parameters can appear anywhere that a literal value is expected. The same + * parameter name can be used more than once, for example: + * `"WHERE id > @msg_id AND id < @msg_id + 100"` + * + * It is an error to execute an SQL query with unbound parameters. + * + * Parameter values are specified using `params`, which is a JSON + * object whose keys are parameter names, and whose values are the + * corresponding parameter values. + * @type array $paramTypes + * It is not always possible for Cloud Spanner to infer the right SQL type + * from a JSON value. For example, values of type `BYTES` and values + * of type `STRING` both appear in [params][google.spanner.v1.ExecuteSqlRequest.params] as JSON strings. + * + * In these cases, `param_types` can be used to specify the exact + * SQL type for some or all of the SQL query parameters. See the + * definition of [Type][google.spanner.v1.Type] for more information + * about SQL types. + * @type string $resumeToken + * If this request is resuming a previously interrupted SQL query + * execution, `resume_token` should be copied from the last + * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this + * enables the new SQL query execution to resume where the last one left + * off. The rest of the request parameters must exactly match the + * request that yielded this token. + * @type int $queryMode + * 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. + * } + * + * @return \Google\Spanner\V1\ResultSet + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function executeSql($session, $sql, $optionalArgs = []) + { + $request = new ExecuteSqlRequest(); + $request->setSession($session); + $request->setSql($sql); + if (isset($optionalArgs['transaction'])) { + $request->setTransaction($optionalArgs['transaction']); + } + if (isset($optionalArgs['params'])) { + $request->setParams($optionalArgs['params']); + } + if (isset($optionalArgs['paramTypes'])) { + $request->setParamTypes($optionalArgs['paramTypes']); + } + if (isset($optionalArgs['resumeToken'])) { + $request->setResumeToken($optionalArgs['resumeToken']); + } + if (isset($optionalArgs['queryMode'])) { + $request->setQueryMode($optionalArgs['queryMode']); + } + + $mergedSettings = $this->defaultCallSettings['executeSql']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'ExecuteSql', + $mergedSettings, + $this->descriptors['executeSql'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result + * set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there + * is no limit on the size of the returned result set. However, no + * individual row in the result set can exceed 100 MiB, and no + * column value can exceed 10 MiB. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $sql = ""; + * // Read all responses until the stream is complete + * $stream = $spannerClient->executeStreamingSql($formattedSession, $sql); + * foreach ($stream->readAll() as $element) { + * // doSomethingWith($element); + * } + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the SQL query should be performed. + * @param string $sql Required. The SQL query string. + * @param array $optionalArgs { + * Optional. + * + * @type TransactionSelector $transaction + * The transaction to use. If none is provided, the default is a + * temporary read-only transaction with strong concurrency. + * @type Struct $params + * The SQL query string can contain parameter placeholders. A parameter + * placeholder consists of `'@'` followed by the parameter + * name. Parameter names consist of any combination of letters, + * numbers, and underscores. + * + * Parameters can appear anywhere that a literal value is expected. The same + * parameter name can be used more than once, for example: + * `"WHERE id > @msg_id AND id < @msg_id + 100"` + * + * It is an error to execute an SQL query with unbound parameters. + * + * Parameter values are specified using `params`, which is a JSON + * object whose keys are parameter names, and whose values are the + * corresponding parameter values. + * @type array $paramTypes + * It is not always possible for Cloud Spanner to infer the right SQL type + * from a JSON value. For example, values of type `BYTES` and values + * of type `STRING` both appear in [params][google.spanner.v1.ExecuteSqlRequest.params] as JSON strings. + * + * In these cases, `param_types` can be used to specify the exact + * SQL type for some or all of the SQL query parameters. See the + * definition of [Type][google.spanner.v1.Type] for more information + * about SQL types. + * @type string $resumeToken + * If this request is resuming a previously interrupted SQL query + * execution, `resume_token` should be copied from the last + * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this + * enables the new SQL query execution to resume where the last one left + * off. The rest of the request parameters must exactly match the + * request that yielded this token. + * @type int $queryMode + * 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 int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return \Google\GAX\ServerStream + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function executeStreamingSql($session, $sql, $optionalArgs = []) + { + $request = new ExecuteSqlRequest(); + $request->setSession($session); + $request->setSql($sql); + if (isset($optionalArgs['transaction'])) { + $request->setTransaction($optionalArgs['transaction']); + } + if (isset($optionalArgs['params'])) { + $request->setParams($optionalArgs['params']); + } + if (isset($optionalArgs['paramTypes'])) { + $request->setParamTypes($optionalArgs['paramTypes']); + } + if (isset($optionalArgs['resumeToken'])) { + $request->setResumeToken($optionalArgs['resumeToken']); + } + if (isset($optionalArgs['queryMode'])) { + $request->setQueryMode($optionalArgs['queryMode']); + } + + $mergedSettings = $this->defaultCallSettings['executeStreamingSql']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'ExecuteStreamingSql', + $mergedSettings, + $this->descriptors['executeStreamingSql'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Reads rows from the database using key lookups and scans, as a + * simple key/value style alternative to + * [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to + * return a result set larger than 10 MiB; if the read matches more + * data than that, the read fails with a `FAILED_PRECONDITION` + * error. + * + * Reads inside read-write transactions might return `ABORTED`. If + * this occurs, the application should restart the transaction from + * the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + * + * Larger result sets can be yielded in streaming fashion by calling + * [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $table = ""; + * $columns = []; + * $keySet = new KeySet(); + * $response = $spannerClient->read($formattedSession, $table, $columns, $keySet); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the read should be performed. + * @param string $table Required. The name of the table in the database to be read. + * @param string[] $columns The columns of [table][google.spanner.v1.ReadRequest.table] to be returned for each row matching + * this request. + * @param KeySet $keySet Required. `key_set` identifies the rows to be yielded. `key_set` names the + * primary keys of the rows in [table][google.spanner.v1.ReadRequest.table] to be yielded, unless [index][google.spanner.v1.ReadRequest.index] + * is present. If [index][google.spanner.v1.ReadRequest.index] is present, then [key_set][google.spanner.v1.ReadRequest.key_set] instead names + * index keys in [index][google.spanner.v1.ReadRequest.index]. + * + * Rows are yielded in table primary key order (if [index][google.spanner.v1.ReadRequest.index] is empty) + * or index key order (if [index][google.spanner.v1.ReadRequest.index] is non-empty). + * + * It is not an error for the `key_set` to name rows that do not + * exist in the database. Read yields nothing for nonexistent rows. + * @param array $optionalArgs { + * Optional. + * + * @type TransactionSelector $transaction + * The transaction to use. If none is provided, the default is a + * temporary read-only transaction with strong concurrency. + * @type string $index + * If non-empty, the name of an index on [table][google.spanner.v1.ReadRequest.table]. This index is + * used instead of the table primary key when interpreting [key_set][google.spanner.v1.ReadRequest.key_set] + * and sorting result rows. See [key_set][google.spanner.v1.ReadRequest.key_set] for further information. + * @type int $limit + * If greater than zero, only the first `limit` rows are yielded. If `limit` + * is zero, the default is no limit. + * @type string $resumeToken + * If this request is resuming a previously interrupted read, + * `resume_token` should be copied from the last + * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this + * 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. + * } + * + * @return \Google\Spanner\V1\ResultSet + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function read($session, $table, $columns, $keySet, $optionalArgs = []) + { + $request = new ReadRequest(); + $request->setSession($session); + $request->setTable($table); + $request->setColumns($columns); + $request->setKeySet($keySet); + if (isset($optionalArgs['transaction'])) { + $request->setTransaction($optionalArgs['transaction']); + } + if (isset($optionalArgs['index'])) { + $request->setIndex($optionalArgs['index']); + } + if (isset($optionalArgs['limit'])) { + $request->setLimit($optionalArgs['limit']); + } + if (isset($optionalArgs['resumeToken'])) { + $request->setResumeToken($optionalArgs['resumeToken']); + } + + $mergedSettings = $this->defaultCallSettings['read']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'Read', + $mergedSettings, + $this->descriptors['read'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a + * stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the + * size of the returned result set. However, no individual row in + * the result set can exceed 100 MiB, and no column value can exceed + * 10 MiB. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $table = ""; + * $columns = []; + * $keySet = new KeySet(); + * // Read all responses until the stream is complete + * $stream = $spannerClient->streamingRead($formattedSession, $table, $columns, $keySet); + * foreach ($stream->readAll() as $element) { + * // doSomethingWith($element); + * } + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the read should be performed. + * @param string $table Required. The name of the table in the database to be read. + * @param string[] $columns The columns of [table][google.spanner.v1.ReadRequest.table] to be returned for each row matching + * this request. + * @param KeySet $keySet Required. `key_set` identifies the rows to be yielded. `key_set` names the + * primary keys of the rows in [table][google.spanner.v1.ReadRequest.table] to be yielded, unless [index][google.spanner.v1.ReadRequest.index] + * is present. If [index][google.spanner.v1.ReadRequest.index] is present, then [key_set][google.spanner.v1.ReadRequest.key_set] instead names + * index keys in [index][google.spanner.v1.ReadRequest.index]. + * + * Rows are yielded in table primary key order (if [index][google.spanner.v1.ReadRequest.index] is empty) + * or index key order (if [index][google.spanner.v1.ReadRequest.index] is non-empty). + * + * It is not an error for the `key_set` to name rows that do not + * exist in the database. Read yields nothing for nonexistent rows. + * @param array $optionalArgs { + * Optional. + * + * @type TransactionSelector $transaction + * The transaction to use. If none is provided, the default is a + * temporary read-only transaction with strong concurrency. + * @type string $index + * If non-empty, the name of an index on [table][google.spanner.v1.ReadRequest.table]. This index is + * used instead of the table primary key when interpreting [key_set][google.spanner.v1.ReadRequest.key_set] + * and sorting result rows. See [key_set][google.spanner.v1.ReadRequest.key_set] for further information. + * @type int $limit + * If greater than zero, only the first `limit` rows are yielded. If `limit` + * is zero, the default is no limit. + * @type string $resumeToken + * If this request is resuming a previously interrupted read, + * `resume_token` should be copied from the last + * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this + * 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 int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return \Google\GAX\ServerStream + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function streamingRead($session, $table, $columns, $keySet, $optionalArgs = []) + { + $request = new ReadRequest(); + $request->setSession($session); + $request->setTable($table); + $request->setColumns($columns); + $request->setKeySet($keySet); + if (isset($optionalArgs['transaction'])) { + $request->setTransaction($optionalArgs['transaction']); + } + if (isset($optionalArgs['index'])) { + $request->setIndex($optionalArgs['index']); + } + if (isset($optionalArgs['limit'])) { + $request->setLimit($optionalArgs['limit']); + } + if (isset($optionalArgs['resumeToken'])) { + $request->setResumeToken($optionalArgs['resumeToken']); + } + + $mergedSettings = $this->defaultCallSettings['streamingRead']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'StreamingRead', + $mergedSettings, + $this->descriptors['streamingRead'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Begins a new transaction. This step can often be skipped: + * [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + * [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a + * side-effect. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $options = new TransactionOptions(); + * $response = $spannerClient->beginTransaction($formattedSession, $options); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the transaction runs. + * @param TransactionOptions $options Required. Options for the new transaction. + * @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. + * } + * + * @return \Google\Spanner\V1\Transaction + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function beginTransaction($session, $options, $optionalArgs = []) + { + $request = new BeginTransactionRequest(); + $request->setSession($session); + $request->setOptions($options); + + $mergedSettings = $this->defaultCallSettings['beginTransaction']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'BeginTransaction', + $mergedSettings, + $this->descriptors['beginTransaction'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Commits a transaction. The request includes the mutations to be + * applied to rows in the database. + * + * `Commit` might return an `ABORTED` error. This can occur at any time; + * commonly, the cause is conflicts with concurrent + * transactions. However, it can also happen for a variety of other + * reasons. If `Commit` returns `ABORTED`, the caller should re-attempt + * the transaction from the beginning, re-using the same session. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $mutations = []; + * $response = $spannerClient->commit($formattedSession, $mutations); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the transaction to be committed is running. + * @param Mutation[] $mutations The mutations to be executed when this transaction commits. All + * mutations are applied atomically, in the order they appear in + * this list. + * @param array $optionalArgs { + * Optional. + * + * @type string $transactionId + * Commit a previously-started transaction. + * @type TransactionOptions $singleUseTransaction + * Execute mutations in a temporary transaction. Note that unlike + * commit of a previously-started transaction, commit with a + * temporary transaction is non-idempotent. That is, if the + * `CommitRequest` is sent to Cloud Spanner more than once (for + * instance, due to retries in the application, or in the + * transport library), it is possible that the mutations are + * 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. + * } + * + * @return \Google\Spanner\V1\CommitResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function commit($session, $mutations, $optionalArgs = []) + { + $request = new CommitRequest(); + $request->setSession($session); + $request->setMutations($mutations); + if (isset($optionalArgs['transactionId'])) { + $request->setTransactionId($optionalArgs['transactionId']); + } + if (isset($optionalArgs['singleUseTransaction'])) { + $request->setSingleUseTransaction($optionalArgs['singleUseTransaction']); + } + + $mergedSettings = $this->defaultCallSettings['commit']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'Commit', + $mergedSettings, + $this->descriptors['commit'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Rolls back a transaction, releasing any locks it holds. It is a good + * idea to call this for any transaction that includes one or more + * [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and + * ultimately decides not to commit. + * + * `Rollback` returns `OK` if it successfully aborts the transaction, the + * transaction was already aborted, or the transaction is not + * found. `Rollback` never returns `ABORTED`. + * + * Sample code: + * ``` + * try { + * $spannerClient = new SpannerClient(); + * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); + * $transactionId = ""; + * $spannerClient->rollback($formattedSession, $transactionId); + * } finally { + * $spannerClient->close(); + * } + * ``` + * + * @param string $session Required. The session in which the transaction to roll back is running. + * @param string $transactionId Required. The transaction to roll back. + * @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. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function rollback($session, $transactionId, $optionalArgs = []) + { + $request = new RollbackRequest(); + $request->setSession($session); + $request->setTransactionId($transactionId); + + $mergedSettings = $this->defaultCallSettings['rollback']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->spannerStub, + 'Rollback', + $mergedSettings, + $this->descriptors['rollback'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->spannerStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Spanner/V1/SpannerClient.php b/src/Spanner/V1/SpannerClient.php index 150e665b5bbd..e078ad3ca308 100644 --- a/src/Spanner/V1/SpannerClient.php +++ b/src/Spanner/V1/SpannerClient.php @@ -30,1215 +30,12 @@ namespace Google\Cloud\Spanner\V1; -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\Protobuf\Struct; -use Google\Spanner\V1\BeginTransactionRequest; -use Google\Spanner\V1\CommitRequest; -use Google\Spanner\V1\CreateSessionRequest; -use Google\Spanner\V1\DeleteSessionRequest; -use Google\Spanner\V1\ExecuteSqlRequest; -use Google\Spanner\V1\ExecuteSqlRequest_QueryMode as QueryMode; -use Google\Spanner\V1\GetSessionRequest; -use Google\Spanner\V1\KeySet; -use Google\Spanner\V1\Mutation; -use Google\Spanner\V1\ReadRequest; -use Google\Spanner\V1\RollbackRequest; -use Google\Spanner\V1\SpannerGrpcClient; -use Google\Spanner\V1\TransactionOptions; -use Google\Spanner\V1\TransactionSelector; +use Google\Cloud\Spanner\V1\Gapic\SpannerGapicClient; /** - * Service Description: Cloud Spanner API. - * - * The Cloud Spanner API can be used to manage sessions and execute - * transactions on data stored in Cloud Spanner databases. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedDatabase = SpannerClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $response = $spannerClient->createSession($formattedDatabase); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * 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. - * - * @experimental + * {@inheritdoc} */ -class SpannerClient +class SpannerClient extends SpannerGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'spanner.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $databaseNameTemplate; - private static $sessionNameTemplate; - - private $grpcCredentialsHelper; - private $spannerStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * 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, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a session resource. - * - * @param string $project - * @param string $instance - * @param string $database - * @param string $session - * - * @return string The formatted session resource. - * @experimental - */ - public static function formatSessionName($project, $instance, $database, $session) - { - return self::getSessionNameTemplate()->render([ - 'project' => $project, - 'instance' => $instance, - 'database' => $database, - 'session' => $session, - ]); - } - - /** - * 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. - * - * @param string $sessionName The fully-qualified session resource. - * - * @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 $sessionName The fully-qualified session resource. - * - * @return string The extracted database value. - * @experimental - */ - public static function parseDatabaseFromSessionName($sessionName) - { - 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}'); - } - - 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 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'spanner.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Cloud Spanner API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/spanner.data', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'createSession' => $defaultDescriptors, - 'getSession' => $defaultDescriptors, - 'deleteSession' => $defaultDescriptors, - 'executeSql' => $defaultDescriptors, - 'executeStreamingSql' => $defaultDescriptors, - 'read' => $defaultDescriptors, - 'streamingRead' => $defaultDescriptors, - 'beginTransaction' => $defaultDescriptors, - 'commit' => $defaultDescriptors, - 'rollback' => $defaultDescriptors, - ]; - $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); - foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { - $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/spanner_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.spanner.v1.Spanner', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createSpannerStubFunction = function ($hostname, $opts) { - return new SpannerGrpcClient($hostname, $opts); - }; - if (array_key_exists('createSpannerStubFunction', $options)) { - $createSpannerStubFunction = $options['createSpannerStubFunction']; - } - $this->spannerStub = $this->grpcCredentialsHelper->createStub( - $createSpannerStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Creates a new session. A session can be used to perform - * transactions that read and/or modify data in a Cloud Spanner database. - * Sessions are meant to be reused for many consecutive - * transactions. - * - * Sessions can only execute one transaction at a time. To execute - * multiple concurrent read-write/write-only transactions, create - * multiple sessions. Note that standalone reads and queries use a - * transaction internally, and count toward the one transaction - * limit. - * - * Cloud Spanner limits the number of sessions that can exist at any given - * time; thus, it is a good idea to delete idle and/or unneeded sessions. - * Aside from explicit deletes, Cloud Spanner can delete sessions for which no - * operations are sent for more than an hour. If a session is deleted, - * requests to it return `NOT_FOUND`. - * - * Idle sessions can be kept alive by sending a trivial SQL query - * periodically, e.g., `"SELECT 1"`. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedDatabase = SpannerClient::formatDatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); - * $response = $spannerClient->createSession($formattedDatabase); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $database Required. The database in which the new session is created. - * @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. - * } - * - * @return \Google\Spanner\V1\Session - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSession($database, $optionalArgs = []) - { - $request = new CreateSessionRequest(); - $request->setDatabase($database); - - $mergedSettings = $this->defaultCallSettings['createSession']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'CreateSession', - $mergedSettings, - $this->descriptors['createSession'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a session. Returns `NOT_FOUND` if the session does not exist. - * This is mainly useful for determining whether a session is still - * alive. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedName = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $response = $spannerClient->getSession($formattedName); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $name Required. The name of the session to retrieve. - * @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. - * } - * - * @return \Google\Spanner\V1\Session - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getSession($name, $optionalArgs = []) - { - $request = new GetSessionRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getSession']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'GetSession', - $mergedSettings, - $this->descriptors['getSession'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Ends a session, releasing server resources associated with it. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedName = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $spannerClient->deleteSession($formattedName); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $name Required. The name of the session to delete. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSession($name, $optionalArgs = []) - { - $request = new DeleteSessionRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['deleteSession']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'DeleteSession', - $mergedSettings, - $this->descriptors['deleteSession'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Executes an SQL query, returning all rows in a single reply. This - * method cannot be used to return a result set larger than 10 MiB; - * if the query yields more data than that, the query fails with - * a `FAILED_PRECONDITION` error. - * - * Queries inside read-write transactions might return `ABORTED`. If - * this occurs, the application should restart the transaction from - * the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. - * - * Larger result sets can be fetched in streaming fashion by calling - * [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $sql = ""; - * $response = $spannerClient->executeSql($formattedSession, $sql); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the SQL query should be performed. - * @param string $sql Required. The SQL query string. - * @param array $optionalArgs { - * Optional. - * - * @type TransactionSelector $transaction - * The transaction to use. If none is provided, the default is a - * temporary read-only transaction with strong concurrency. - * @type Struct $params - * The SQL query string can contain parameter placeholders. A parameter - * placeholder consists of `'@'` followed by the parameter - * name. Parameter names consist of any combination of letters, - * numbers, and underscores. - * - * Parameters can appear anywhere that a literal value is expected. The same - * parameter name can be used more than once, for example: - * `"WHERE id > @msg_id AND id < @msg_id + 100"` - * - * It is an error to execute an SQL query with unbound parameters. - * - * Parameter values are specified using `params`, which is a JSON - * object whose keys are parameter names, and whose values are the - * corresponding parameter values. - * @type array $paramTypes - * It is not always possible for Cloud Spanner to infer the right SQL type - * from a JSON value. For example, values of type `BYTES` and values - * of type `STRING` both appear in [params][google.spanner.v1.ExecuteSqlRequest.params] as JSON strings. - * - * In these cases, `param_types` can be used to specify the exact - * SQL type for some or all of the SQL query parameters. See the - * definition of [Type][google.spanner.v1.Type] for more information - * about SQL types. - * @type string $resumeToken - * If this request is resuming a previously interrupted SQL query - * execution, `resume_token` should be copied from the last - * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this - * enables the new SQL query execution to resume where the last one left - * off. The rest of the request parameters must exactly match the - * request that yielded this token. - * @type int $queryMode - * 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. - * } - * - * @return \Google\Spanner\V1\ResultSet - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function executeSql($session, $sql, $optionalArgs = []) - { - $request = new ExecuteSqlRequest(); - $request->setSession($session); - $request->setSql($sql); - if (isset($optionalArgs['transaction'])) { - $request->setTransaction($optionalArgs['transaction']); - } - if (isset($optionalArgs['params'])) { - $request->setParams($optionalArgs['params']); - } - if (isset($optionalArgs['paramTypes'])) { - $request->setParamTypes($optionalArgs['paramTypes']); - } - if (isset($optionalArgs['resumeToken'])) { - $request->setResumeToken($optionalArgs['resumeToken']); - } - if (isset($optionalArgs['queryMode'])) { - $request->setQueryMode($optionalArgs['queryMode']); - } - - $mergedSettings = $this->defaultCallSettings['executeSql']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'ExecuteSql', - $mergedSettings, - $this->descriptors['executeSql'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result - * set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there - * is no limit on the size of the returned result set. However, no - * individual row in the result set can exceed 100 MiB, and no - * column value can exceed 10 MiB. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $sql = ""; - * // Read all responses until the stream is complete - * $stream = $spannerClient->executeStreamingSql($formattedSession, $sql); - * foreach ($stream->readAll() as $element) { - * // doSomethingWith($element); - * } - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the SQL query should be performed. - * @param string $sql Required. The SQL query string. - * @param array $optionalArgs { - * Optional. - * - * @type TransactionSelector $transaction - * The transaction to use. If none is provided, the default is a - * temporary read-only transaction with strong concurrency. - * @type Struct $params - * The SQL query string can contain parameter placeholders. A parameter - * placeholder consists of `'@'` followed by the parameter - * name. Parameter names consist of any combination of letters, - * numbers, and underscores. - * - * Parameters can appear anywhere that a literal value is expected. The same - * parameter name can be used more than once, for example: - * `"WHERE id > @msg_id AND id < @msg_id + 100"` - * - * It is an error to execute an SQL query with unbound parameters. - * - * Parameter values are specified using `params`, which is a JSON - * object whose keys are parameter names, and whose values are the - * corresponding parameter values. - * @type array $paramTypes - * It is not always possible for Cloud Spanner to infer the right SQL type - * from a JSON value. For example, values of type `BYTES` and values - * of type `STRING` both appear in [params][google.spanner.v1.ExecuteSqlRequest.params] as JSON strings. - * - * In these cases, `param_types` can be used to specify the exact - * SQL type for some or all of the SQL query parameters. See the - * definition of [Type][google.spanner.v1.Type] for more information - * about SQL types. - * @type string $resumeToken - * If this request is resuming a previously interrupted SQL query - * execution, `resume_token` should be copied from the last - * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this - * enables the new SQL query execution to resume where the last one left - * off. The rest of the request parameters must exactly match the - * request that yielded this token. - * @type int $queryMode - * 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 int $timeoutMillis - * Timeout to use for this call. - * } - * - * @return \Google\GAX\ServerStream - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function executeStreamingSql($session, $sql, $optionalArgs = []) - { - $request = new ExecuteSqlRequest(); - $request->setSession($session); - $request->setSql($sql); - if (isset($optionalArgs['transaction'])) { - $request->setTransaction($optionalArgs['transaction']); - } - if (isset($optionalArgs['params'])) { - $request->setParams($optionalArgs['params']); - } - if (isset($optionalArgs['paramTypes'])) { - $request->setParamTypes($optionalArgs['paramTypes']); - } - if (isset($optionalArgs['resumeToken'])) { - $request->setResumeToken($optionalArgs['resumeToken']); - } - if (isset($optionalArgs['queryMode'])) { - $request->setQueryMode($optionalArgs['queryMode']); - } - - $mergedSettings = $this->defaultCallSettings['executeStreamingSql']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'ExecuteStreamingSql', - $mergedSettings, - $this->descriptors['executeStreamingSql'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Reads rows from the database using key lookups and scans, as a - * simple key/value style alternative to - * [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to - * return a result set larger than 10 MiB; if the read matches more - * data than that, the read fails with a `FAILED_PRECONDITION` - * error. - * - * Reads inside read-write transactions might return `ABORTED`. If - * this occurs, the application should restart the transaction from - * the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. - * - * Larger result sets can be yielded in streaming fashion by calling - * [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $table = ""; - * $columns = []; - * $keySet = new KeySet(); - * $response = $spannerClient->read($formattedSession, $table, $columns, $keySet); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the read should be performed. - * @param string $table Required. The name of the table in the database to be read. - * @param string[] $columns The columns of [table][google.spanner.v1.ReadRequest.table] to be returned for each row matching - * this request. - * @param KeySet $keySet Required. `key_set` identifies the rows to be yielded. `key_set` names the - * primary keys of the rows in [table][google.spanner.v1.ReadRequest.table] to be yielded, unless [index][google.spanner.v1.ReadRequest.index] - * is present. If [index][google.spanner.v1.ReadRequest.index] is present, then [key_set][google.spanner.v1.ReadRequest.key_set] instead names - * index keys in [index][google.spanner.v1.ReadRequest.index]. - * - * Rows are yielded in table primary key order (if [index][google.spanner.v1.ReadRequest.index] is empty) - * or index key order (if [index][google.spanner.v1.ReadRequest.index] is non-empty). - * - * It is not an error for the `key_set` to name rows that do not - * exist in the database. Read yields nothing for nonexistent rows. - * @param array $optionalArgs { - * Optional. - * - * @type TransactionSelector $transaction - * The transaction to use. If none is provided, the default is a - * temporary read-only transaction with strong concurrency. - * @type string $index - * If non-empty, the name of an index on [table][google.spanner.v1.ReadRequest.table]. This index is - * used instead of the table primary key when interpreting [key_set][google.spanner.v1.ReadRequest.key_set] - * and sorting result rows. See [key_set][google.spanner.v1.ReadRequest.key_set] for further information. - * @type int $limit - * If greater than zero, only the first `limit` rows are yielded. If `limit` - * is zero, the default is no limit. - * @type string $resumeToken - * If this request is resuming a previously interrupted read, - * `resume_token` should be copied from the last - * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this - * 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. - * } - * - * @return \Google\Spanner\V1\ResultSet - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function read($session, $table, $columns, $keySet, $optionalArgs = []) - { - $request = new ReadRequest(); - $request->setSession($session); - $request->setTable($table); - $request->setColumns($columns); - $request->setKeySet($keySet); - if (isset($optionalArgs['transaction'])) { - $request->setTransaction($optionalArgs['transaction']); - } - if (isset($optionalArgs['index'])) { - $request->setIndex($optionalArgs['index']); - } - if (isset($optionalArgs['limit'])) { - $request->setLimit($optionalArgs['limit']); - } - if (isset($optionalArgs['resumeToken'])) { - $request->setResumeToken($optionalArgs['resumeToken']); - } - - $mergedSettings = $this->defaultCallSettings['read']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'Read', - $mergedSettings, - $this->descriptors['read'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a - * stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the - * size of the returned result set. However, no individual row in - * the result set can exceed 100 MiB, and no column value can exceed - * 10 MiB. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $table = ""; - * $columns = []; - * $keySet = new KeySet(); - * // Read all responses until the stream is complete - * $stream = $spannerClient->streamingRead($formattedSession, $table, $columns, $keySet); - * foreach ($stream->readAll() as $element) { - * // doSomethingWith($element); - * } - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the read should be performed. - * @param string $table Required. The name of the table in the database to be read. - * @param string[] $columns The columns of [table][google.spanner.v1.ReadRequest.table] to be returned for each row matching - * this request. - * @param KeySet $keySet Required. `key_set` identifies the rows to be yielded. `key_set` names the - * primary keys of the rows in [table][google.spanner.v1.ReadRequest.table] to be yielded, unless [index][google.spanner.v1.ReadRequest.index] - * is present. If [index][google.spanner.v1.ReadRequest.index] is present, then [key_set][google.spanner.v1.ReadRequest.key_set] instead names - * index keys in [index][google.spanner.v1.ReadRequest.index]. - * - * Rows are yielded in table primary key order (if [index][google.spanner.v1.ReadRequest.index] is empty) - * or index key order (if [index][google.spanner.v1.ReadRequest.index] is non-empty). - * - * It is not an error for the `key_set` to name rows that do not - * exist in the database. Read yields nothing for nonexistent rows. - * @param array $optionalArgs { - * Optional. - * - * @type TransactionSelector $transaction - * The transaction to use. If none is provided, the default is a - * temporary read-only transaction with strong concurrency. - * @type string $index - * If non-empty, the name of an index on [table][google.spanner.v1.ReadRequest.table]. This index is - * used instead of the table primary key when interpreting [key_set][google.spanner.v1.ReadRequest.key_set] - * and sorting result rows. See [key_set][google.spanner.v1.ReadRequest.key_set] for further information. - * @type int $limit - * If greater than zero, only the first `limit` rows are yielded. If `limit` - * is zero, the default is no limit. - * @type string $resumeToken - * If this request is resuming a previously interrupted read, - * `resume_token` should be copied from the last - * [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the interruption. Doing this - * 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 int $timeoutMillis - * Timeout to use for this call. - * } - * - * @return \Google\GAX\ServerStream - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function streamingRead($session, $table, $columns, $keySet, $optionalArgs = []) - { - $request = new ReadRequest(); - $request->setSession($session); - $request->setTable($table); - $request->setColumns($columns); - $request->setKeySet($keySet); - if (isset($optionalArgs['transaction'])) { - $request->setTransaction($optionalArgs['transaction']); - } - if (isset($optionalArgs['index'])) { - $request->setIndex($optionalArgs['index']); - } - if (isset($optionalArgs['limit'])) { - $request->setLimit($optionalArgs['limit']); - } - if (isset($optionalArgs['resumeToken'])) { - $request->setResumeToken($optionalArgs['resumeToken']); - } - - $mergedSettings = $this->defaultCallSettings['streamingRead']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'StreamingRead', - $mergedSettings, - $this->descriptors['streamingRead'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Begins a new transaction. This step can often be skipped: - * [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and - * [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a - * side-effect. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $options = new TransactionOptions(); - * $response = $spannerClient->beginTransaction($formattedSession, $options); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the transaction runs. - * @param TransactionOptions $options Required. Options for the new transaction. - * @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. - * } - * - * @return \Google\Spanner\V1\Transaction - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function beginTransaction($session, $options, $optionalArgs = []) - { - $request = new BeginTransactionRequest(); - $request->setSession($session); - $request->setOptions($options); - - $mergedSettings = $this->defaultCallSettings['beginTransaction']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'BeginTransaction', - $mergedSettings, - $this->descriptors['beginTransaction'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Commits a transaction. The request includes the mutations to be - * applied to rows in the database. - * - * `Commit` might return an `ABORTED` error. This can occur at any time; - * commonly, the cause is conflicts with concurrent - * transactions. However, it can also happen for a variety of other - * reasons. If `Commit` returns `ABORTED`, the caller should re-attempt - * the transaction from the beginning, re-using the same session. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $mutations = []; - * $response = $spannerClient->commit($formattedSession, $mutations); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the transaction to be committed is running. - * @param Mutation[] $mutations The mutations to be executed when this transaction commits. All - * mutations are applied atomically, in the order they appear in - * this list. - * @param array $optionalArgs { - * Optional. - * - * @type string $transactionId - * Commit a previously-started transaction. - * @type TransactionOptions $singleUseTransaction - * Execute mutations in a temporary transaction. Note that unlike - * commit of a previously-started transaction, commit with a - * temporary transaction is non-idempotent. That is, if the - * `CommitRequest` is sent to Cloud Spanner more than once (for - * instance, due to retries in the application, or in the - * transport library), it is possible that the mutations are - * 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. - * } - * - * @return \Google\Spanner\V1\CommitResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function commit($session, $mutations, $optionalArgs = []) - { - $request = new CommitRequest(); - $request->setSession($session); - $request->setMutations($mutations); - if (isset($optionalArgs['transactionId'])) { - $request->setTransactionId($optionalArgs['transactionId']); - } - if (isset($optionalArgs['singleUseTransaction'])) { - $request->setSingleUseTransaction($optionalArgs['singleUseTransaction']); - } - - $mergedSettings = $this->defaultCallSettings['commit']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'Commit', - $mergedSettings, - $this->descriptors['commit'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Rolls back a transaction, releasing any locks it holds. It is a good - * idea to call this for any transaction that includes one or more - * [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and - * ultimately decides not to commit. - * - * `Rollback` returns `OK` if it successfully aborts the transaction, the - * transaction was already aborted, or the transaction is not - * found. `Rollback` never returns `ABORTED`. - * - * Sample code: - * ``` - * try { - * $spannerClient = new SpannerClient(); - * $formattedSession = SpannerClient::formatSessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); - * $transactionId = ""; - * $spannerClient->rollback($formattedSession, $transactionId); - * } finally { - * $spannerClient->close(); - * } - * ``` - * - * @param string $session Required. The session in which the transaction to roll back is running. - * @param string $transactionId Required. The transaction to roll back. - * @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. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function rollback($session, $transactionId, $optionalArgs = []) - { - $request = new RollbackRequest(); - $request->setSession($session); - $request->setTransactionId($transactionId); - - $mergedSettings = $this->defaultCallSettings['rollback']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->spannerStub, - 'Rollback', - $mergedSettings, - $this->descriptors['rollback'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->spannerStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see SpannerClientImpl} class. } diff --git a/src/Spanner/V1/resources/spanner_client_config.json b/src/Spanner/V1/resources/spanner_client_config.json index eedf9cc717ba..322d0e9449f2 100644 --- a/src/Spanner/V1/resources/spanner_client_config.json +++ b/src/Spanner/V1/resources/spanner_client_config.json @@ -6,7 +6,10 @@ "DEADLINE_EXCEEDED", "UNAVAILABLE" ], - "non_idempotent": [] + "non_idempotent": [], + "long_running": [ + "UNAVAILABLE" + ] }, "retry_params": { "default": { @@ -17,12 +20,21 @@ "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 60000, "total_timeout_millis": 600000 + }, + "long_running": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 3600000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 3600000, + "total_timeout_millis": 36000000 } }, "methods": { "CreateSession": { "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", + "retry_codes_name": "idempotent", "retry_params_name": "default" }, "GetSession": { @@ -37,33 +49,33 @@ }, "ExecuteSql": { "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", + "retry_codes_name": "idempotent", "retry_params_name": "default" }, "ExecuteStreamingSql": { - "timeout_millis": 30000 + "timeout_millis": 3600000 }, "Read": { "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", + "retry_codes_name": "idempotent", "retry_params_name": "default" }, "StreamingRead": { - "timeout_millis": 30000 + "timeout_millis": 3600000 }, "BeginTransaction": { "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", + "retry_codes_name": "idempotent", "retry_params_name": "default" }, "Commit": { - "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" + "timeout_millis": 3600000, + "retry_codes_name": "long_running", + "retry_params_name": "long_running" }, "Rollback": { "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", + "retry_codes_name": "idempotent", "retry_params_name": "default" } } diff --git a/src/Spanner/composer.json b/src/Spanner/composer.json index ce0c2ec237ed..140e88aa834d 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.21.0", - "google/proto-client": "^0.21.0" + "google/gax": "^0.22.1", + "google/proto-client": "^0.22.0" }, "extra": { "component": { diff --git a/src/Speech/V1/Gapic/SpeechGapicClient.php b/src/Speech/V1/Gapic/SpeechGapicClient.php new file mode 100644 index 000000000000..797cf7e3c7de --- /dev/null +++ b/src/Speech/V1/Gapic/SpeechGapicClient.php @@ -0,0 +1,534 @@ +setEncoding($encoding); + * $config->setSampleRateHertz($sampleRateHertz); + * $config->setLanguageCode($languageCode); + * $uri = "gs://bucket_name/file_name.flac"; + * $audio = new RecognitionAudio(); + * $audio->setUri($uri); + * $response = $speechClient->recognize($config, $audio); + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @experimental + */ +class SpeechGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'speech.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + protected $grpcCredentialsHelper; + protected $speechStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + private $operationsClient; + + private static function getLongRunningDescriptors() + { + return [ + 'longRunningRecognize' => [ + 'operationReturnType' => '\Google\Cloud\Speech\V1\LongRunningRecognizeResponse', + 'metadataReturnType' => '\Google\Cloud\Speech\V1\LongRunningRecognizeMetadata', + ], + ]; + } + + private static function getGrpcStreamingDescriptors() + { + return [ + 'streamingRecognize' => [ + 'grpcStreamingType' => 'BidiStreaming', + ], + ]; + } + + 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; + } + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return \Google\GAX\LongRunning\OperationsClient + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started + * by a long running API method. If $methodName is not provided, or does + * not match a long running API method, then the operation can still be + * resumed, but the OperationResponse object will not deserialize the + * final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return \Google\GAX\OperationResponse + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $lroDescriptors = self::getLongRunningDescriptors(); + if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { + $options = $lroDescriptors[$methodName]; + } else { + $options = []; + } + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'speech.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + if (array_key_exists('operationsClient', $options)) { + $this->operationsClient = $options['operationsClient']; + } else { + $operationsClientOptions = $options; + unset($operationsClientOptions['timeoutMillis']); + unset($operationsClientOptions['retryingOverride']); + $this->operationsClient = new OperationsClient($operationsClientOptions); + } + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'recognize' => $defaultDescriptors, + 'longRunningRecognize' => $defaultDescriptors, + 'streamingRecognize' => $defaultDescriptors, + ]; + $longRunningDescriptors = self::getLongRunningDescriptors(); + foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { + $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; + } + $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); + foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { + $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/speech_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.cloud.speech.v1.Speech', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createSpeechStubFunction = function ($hostname, $opts, $channel) { + return new SpeechGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createSpeechStubFunction', $options)) { + $createSpeechStubFunction = $options['createSpeechStubFunction']; + } + $this->speechStub = $this->grpcCredentialsHelper->createStub($createSpeechStubFunction); + } + + /** + * Performs synchronous speech recognition: receive results after all audio + * has been sent and processed. + * + * Sample code: + * ``` + * try { + * $speechClient = new SpeechClient(); + * $encoding = AudioEncoding::FLAC; + * $sampleRateHertz = 44100; + * $languageCode = "en-US"; + * $config = new RecognitionConfig(); + * $config->setEncoding($encoding); + * $config->setSampleRateHertz($sampleRateHertz); + * $config->setLanguageCode($languageCode); + * $uri = "gs://bucket_name/file_name.flac"; + * $audio = new RecognitionAudio(); + * $audio->setUri($uri); + * $response = $speechClient->recognize($config, $audio); + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to + * process the request. + * @param RecognitionAudio $audio *Required* The audio data to be recognized. + * @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. + * } + * + * @return \Google\Cloud\Speech\V1\RecognizeResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function recognize($config, $audio, $optionalArgs = []) + { + $request = new RecognizeRequest(); + $request->setConfig($config); + $request->setAudio($audio); + + $mergedSettings = $this->defaultCallSettings['recognize']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->speechStub, + 'Recognize', + $mergedSettings, + $this->descriptors['recognize'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Performs asynchronous speech recognition: receive results via the + * google.longrunning.Operations interface. Returns either an + * `Operation.error` or an `Operation.response` which contains + * a `LongRunningRecognizeResponse` message. + * + * Sample code: + * ``` + * try { + * $speechClient = new SpeechClient(); + * $encoding = AudioEncoding::FLAC; + * $sampleRateHertz = 44100; + * $languageCode = "en-US"; + * $config = new RecognitionConfig(); + * $config->setEncoding($encoding); + * $config->setSampleRateHertz($sampleRateHertz); + * $config->setLanguageCode($languageCode); + * $uri = "gs://bucket_name/file_name.flac"; + * $audio = new RecognitionAudio(); + * $audio->setUri($uri); + * $operationResponse = $speechClient->longRunningRecognize($config, $audio); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $speechClient->longRunningRecognize($config, $audio); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $speechClient->resumeOperation($operationName, 'longRunningRecognize'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to + * process the request. + * @param RecognitionAudio $audio *Required* The audio data to be recognized. + * @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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function longRunningRecognize($config, $audio, $optionalArgs = []) + { + $request = new LongRunningRecognizeRequest(); + $request->setConfig($config); + $request->setAudio($audio); + + $mergedSettings = $this->defaultCallSettings['longRunningRecognize']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->speechStub, + 'LongRunningRecognize', + $mergedSettings, + $this->descriptors['longRunningRecognize'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Performs bidirectional streaming speech recognition: receive results while + * sending audio. This method is only available via the gRPC API (not REST). + * + * Sample code: + * ``` + * try { + * $speechClient = new SpeechClient(); + * $request = new StreamingRecognizeRequest(); + * $requests = [$request]; + * + * // Write all requests to the server, then read all responses until the + * // stream is complete + * $stream = $speechClient->streamingRecognize(); + * $stream->writeAll($requests); + * foreach ($stream->closeWriteAndReadAll() as $element) { + * // doSomethingWith($element); + * } + * + * // OR write requests individually, making read() calls if + * // required. Call closeWrite() once writes are complete, and read the + * // remaining responses from the server. + * $stream = $speechClient->streamingRecognize(); + * foreach ($requests as $request) { + * $stream->write($request); + * // if required, read a single response from the stream + * $element = $stream->read(); + * // doSomethingWith($element) + * } + * $stream->closeWrite(); + * $element = $stream->read(); + * while (!is_null($element)) { + * // doSomethingWith($element) + * $element = $stream->read(); + * } + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @param array $optionalArgs { + * Optional. + * + * @type int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return \Google\GAX\BidiStream + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function streamingRecognize($optionalArgs = []) + { + $mergedSettings = $this->defaultCallSettings['streamingRecognize']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->speechStub, + 'StreamingRecognize', + $mergedSettings, + $this->descriptors['streamingRecognize'] + ); + + return $callable( + null, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->speechStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Speech/V1/SpeechClient.php b/src/Speech/V1/SpeechClient.php index 0301a2bd314c..4f5a3931d951 100644 --- a/src/Speech/V1/SpeechClient.php +++ b/src/Speech/V1/SpeechClient.php @@ -30,499 +30,12 @@ namespace Google\Cloud\Speech\V1; -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\Cloud\Speech\V1\Gapic\SpeechGapicClient; /** - * Service Description: Service that implements Google Cloud Speech API. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $speechClient = new SpeechClient(); - * $encoding = AudioEncoding::FLAC; - * $sampleRateHertz = 44100; - * $languageCode = "en-US"; - * $config = new RecognitionConfig(); - * $config->setEncoding($encoding); - * $config->setSampleRateHertz($sampleRateHertz); - * $config->setLanguageCode($languageCode); - * $uri = "gs://bucket_name/file_name.flac"; - * $audio = new RecognitionAudio(); - * $audio->setUri($uri); - * $response = $speechClient->recognize($config, $audio); - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @experimental + * {@inheritdoc} */ -class SpeechClient +class SpeechClient extends SpeechGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'speech.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private $grpcCredentialsHelper; - private $speechStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - private $operationsClient; - - private static function getLongRunningDescriptors() - { - return [ - 'longRunningRecognize' => [ - 'operationReturnType' => '\Google\Cloud\Speech\V1\LongRunningRecognizeResponse', - 'metadataReturnType' => '\Google\Cloud\Speech\V1\LongRunningRecognizeMetadata', - ], - ]; - } - - private static function getGrpcStreamingDescriptors() - { - return [ - 'streamingRecognize' => [ - 'grpcStreamingType' => 'BidiStreaming', - ], - ]; - } - - 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; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'speech.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Speech API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'recognize' => $defaultDescriptors, - 'longRunningRecognize' => $defaultDescriptors, - 'streamingRecognize' => $defaultDescriptors, - ]; - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); - foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { - $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/speech_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.cloud.speech.v1.Speech', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createSpeechStubFunction = function ($hostname, $opts) { - return new SpeechGrpcClient($hostname, $opts); - }; - if (array_key_exists('createSpeechStubFunction', $options)) { - $createSpeechStubFunction = $options['createSpeechStubFunction']; - } - $this->speechStub = $this->grpcCredentialsHelper->createStub( - $createSpeechStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Performs synchronous speech recognition: receive results after all audio - * has been sent and processed. - * - * Sample code: - * ``` - * try { - * $speechClient = new SpeechClient(); - * $encoding = AudioEncoding::FLAC; - * $sampleRateHertz = 44100; - * $languageCode = "en-US"; - * $config = new RecognitionConfig(); - * $config->setEncoding($encoding); - * $config->setSampleRateHertz($sampleRateHertz); - * $config->setLanguageCode($languageCode); - * $uri = "gs://bucket_name/file_name.flac"; - * $audio = new RecognitionAudio(); - * $audio->setUri($uri); - * $response = $speechClient->recognize($config, $audio); - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to - * process the request. - * @param RecognitionAudio $audio *Required* The audio data to be recognized. - * @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. - * } - * - * @return \Google\Cloud\Speech\V1\RecognizeResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function recognize($config, $audio, $optionalArgs = []) - { - $request = new RecognizeRequest(); - $request->setConfig($config); - $request->setAudio($audio); - - $mergedSettings = $this->defaultCallSettings['recognize']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->speechStub, - 'Recognize', - $mergedSettings, - $this->descriptors['recognize'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Performs asynchronous speech recognition: receive results via the - * google.longrunning.Operations interface. Returns either an - * `Operation.error` or an `Operation.response` which contains - * a `LongRunningRecognizeResponse` message. - * - * Sample code: - * ``` - * try { - * $speechClient = new SpeechClient(); - * $encoding = AudioEncoding::FLAC; - * $sampleRateHertz = 44100; - * $languageCode = "en-US"; - * $config = new RecognitionConfig(); - * $config->setEncoding($encoding); - * $config->setSampleRateHertz($sampleRateHertz); - * $config->setLanguageCode($languageCode); - * $uri = "gs://bucket_name/file_name.flac"; - * $audio = new RecognitionAudio(); - * $audio->setUri($uri); - * $operationResponse = $speechClient->longRunningRecognize($config, $audio); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $speechClient->longRunningRecognize($config, $audio); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $speechClient->resumeOperation($operationName, 'longRunningRecognize'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to - * process the request. - * @param RecognitionAudio $audio *Required* The audio data to be recognized. - * @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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function longRunningRecognize($config, $audio, $optionalArgs = []) - { - $request = new LongRunningRecognizeRequest(); - $request->setConfig($config); - $request->setAudio($audio); - - $mergedSettings = $this->defaultCallSettings['longRunningRecognize']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->speechStub, - 'LongRunningRecognize', - $mergedSettings, - $this->descriptors['longRunningRecognize'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Performs bidirectional streaming speech recognition: receive results while - * sending audio. This method is only available via the gRPC API (not REST). - * - * Sample code: - * ``` - * try { - * $speechClient = new SpeechClient(); - * $request = new StreamingRecognizeRequest(); - * $requests = [$request]; - * - * // Write all requests to the server, then read all responses until the - * // stream is complete - * $stream = $speechClient->streamingRecognize(); - * $stream->writeAll($requests); - * foreach ($stream->closeWriteAndReadAll() as $element) { - * // doSomethingWith($element); - * } - * - * // OR write requests individually, making read() calls if - * // required. Call closeWrite() once writes are complete, and read the - * // remaining responses from the server. - * $stream = $speechClient->streamingRecognize(); - * foreach ($requests as $request) { - * $stream->write($request); - * // if required, read a single response from the stream - * $element = $stream->read(); - * // doSomethingWith($element) - * } - * $stream->closeWrite(); - * $element = $stream->read(); - * while (!is_null($element)) { - * // doSomethingWith($element) - * $element = $stream->read(); - * } - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @param array $optionalArgs { - * Optional. - * - * @type int $timeoutMillis - * Timeout to use for this call. - * } - * - * @return \Google\GAX\BidiStream - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function streamingRecognize($optionalArgs = []) - { - $mergedSettings = $this->defaultCallSettings['streamingRecognize']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->speechStub, - 'StreamingRecognize', - $mergedSettings, - $this->descriptors['streamingRecognize'] - ); - - return $callable( - null, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->speechStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see SpeechClientImpl} class. } diff --git a/src/Speech/V1beta1/Gapic/SpeechGapicClient.php b/src/Speech/V1beta1/Gapic/SpeechGapicClient.php new file mode 100644 index 000000000000..d59c0189aaf4 --- /dev/null +++ b/src/Speech/V1beta1/Gapic/SpeechGapicClient.php @@ -0,0 +1,530 @@ +setEncoding($encoding); + * $config->setSampleRate($sampleRate); + * $uri = "gs://bucket_name/file_name.flac"; + * $audio = new RecognitionAudio(); + * $audio->setUri($uri); + * $response = $speechClient->syncRecognize($config, $audio); + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @experimental + */ +class SpeechGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'speech.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + protected $grpcCredentialsHelper; + protected $speechStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + private $operationsClient; + + private static function getLongRunningDescriptors() + { + return [ + 'asyncRecognize' => [ + 'operationReturnType' => '\Google\Cloud\Speech\V1beta1\AsyncRecognizeResponse', + 'metadataReturnType' => '\Google\Cloud\Speech\V1beta1\AsyncRecognizeMetadata', + ], + ]; + } + + private static function getGrpcStreamingDescriptors() + { + return [ + 'streamingRecognize' => [ + 'grpcStreamingType' => 'BidiStreaming', + ], + ]; + } + + 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; + } + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return \Google\GAX\LongRunning\OperationsClient + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started + * by a long running API method. If $methodName is not provided, or does + * not match a long running API method, then the operation can still be + * resumed, but the OperationResponse object will not deserialize the + * final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return \Google\GAX\OperationResponse + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $lroDescriptors = self::getLongRunningDescriptors(); + if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { + $options = $lroDescriptors[$methodName]; + } else { + $options = []; + } + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'speech.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + if (array_key_exists('operationsClient', $options)) { + $this->operationsClient = $options['operationsClient']; + } else { + $operationsClientOptions = $options; + unset($operationsClientOptions['timeoutMillis']); + unset($operationsClientOptions['retryingOverride']); + $this->operationsClient = new OperationsClient($operationsClientOptions); + } + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'syncRecognize' => $defaultDescriptors, + 'asyncRecognize' => $defaultDescriptors, + 'streamingRecognize' => $defaultDescriptors, + ]; + $longRunningDescriptors = self::getLongRunningDescriptors(); + foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { + $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; + } + $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); + foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { + $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/speech_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.cloud.speech.v1beta1.Speech', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createSpeechStubFunction = function ($hostname, $opts, $channel) { + return new SpeechGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createSpeechStubFunction', $options)) { + $createSpeechStubFunction = $options['createSpeechStubFunction']; + } + $this->speechStub = $this->grpcCredentialsHelper->createStub($createSpeechStubFunction); + } + + /** + * Performs synchronous speech recognition: receive results after all audio + * has been sent and processed. + * + * Sample code: + * ``` + * try { + * $speechClient = new SpeechClient(); + * $encoding = AudioEncoding::FLAC; + * $sampleRate = 44100; + * $config = new RecognitionConfig(); + * $config->setEncoding($encoding); + * $config->setSampleRate($sampleRate); + * $uri = "gs://bucket_name/file_name.flac"; + * $audio = new RecognitionAudio(); + * $audio->setUri($uri); + * $response = $speechClient->syncRecognize($config, $audio); + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to + * process the request. + * @param RecognitionAudio $audio *Required* The audio data to be recognized. + * @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. + * } + * + * @return \Google\Cloud\Speech\V1beta1\SyncRecognizeResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function syncRecognize($config, $audio, $optionalArgs = []) + { + $request = new SyncRecognizeRequest(); + $request->setConfig($config); + $request->setAudio($audio); + + $mergedSettings = $this->defaultCallSettings['syncRecognize']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->speechStub, + 'SyncRecognize', + $mergedSettings, + $this->descriptors['syncRecognize'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Performs asynchronous speech recognition: receive results via the + * [google.longrunning.Operations] + * (/speech/reference/rest/v1beta1/operations#Operation) + * interface. Returns either an + * `Operation.error` or an `Operation.response` which contains + * an `AsyncRecognizeResponse` message. + * + * Sample code: + * ``` + * try { + * $speechClient = new SpeechClient(); + * $encoding = AudioEncoding::FLAC; + * $sampleRate = 44100; + * $config = new RecognitionConfig(); + * $config->setEncoding($encoding); + * $config->setSampleRate($sampleRate); + * $uri = "gs://bucket_name/file_name.flac"; + * $audio = new RecognitionAudio(); + * $audio->setUri($uri); + * $operationResponse = $speechClient->asyncRecognize($config, $audio); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $speechClient->asyncRecognize($config, $audio); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $speechClient->resumeOperation($operationName, 'asyncRecognize'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to + * process the request. + * @param RecognitionAudio $audio *Required* The audio data to be recognized. + * @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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function asyncRecognize($config, $audio, $optionalArgs = []) + { + $request = new AsyncRecognizeRequest(); + $request->setConfig($config); + $request->setAudio($audio); + + $mergedSettings = $this->defaultCallSettings['asyncRecognize']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->speechStub, + 'AsyncRecognize', + $mergedSettings, + $this->descriptors['asyncRecognize'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Performs bidirectional streaming speech recognition: receive results while + * sending audio. This method is only available via the gRPC API (not REST). + * + * Sample code: + * ``` + * try { + * $speechClient = new SpeechClient(); + * $request = new StreamingRecognizeRequest(); + * $requests = [$request]; + * + * // Write all requests to the server, then read all responses until the + * // stream is complete + * $stream = $speechClient->streamingRecognize(); + * $stream->writeAll($requests); + * foreach ($stream->closeWriteAndReadAll() as $element) { + * // doSomethingWith($element); + * } + * + * // OR write requests individually, making read() calls if + * // required. Call closeWrite() once writes are complete, and read the + * // remaining responses from the server. + * $stream = $speechClient->streamingRecognize(); + * foreach ($requests as $request) { + * $stream->write($request); + * // if required, read a single response from the stream + * $element = $stream->read(); + * // doSomethingWith($element) + * } + * $stream->closeWrite(); + * $element = $stream->read(); + * while (!is_null($element)) { + * // doSomethingWith($element) + * $element = $stream->read(); + * } + * } finally { + * $speechClient->close(); + * } + * ``` + * + * @param array $optionalArgs { + * Optional. + * + * @type int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return \Google\GAX\BidiStream + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function streamingRecognize($optionalArgs = []) + { + $mergedSettings = $this->defaultCallSettings['streamingRecognize']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->speechStub, + 'StreamingRecognize', + $mergedSettings, + $this->descriptors['streamingRecognize'] + ); + + return $callable( + null, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->speechStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Speech/V1beta1/SpeechClient.php b/src/Speech/V1beta1/SpeechClient.php index 70927daac8e0..94a19027a7c8 100644 --- a/src/Speech/V1beta1/SpeechClient.php +++ b/src/Speech/V1beta1/SpeechClient.php @@ -30,495 +30,12 @@ namespace Google\Cloud\Speech\V1beta1; -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\Cloud\Speech\V1beta1\Gapic\SpeechGapicClient; /** - * Service Description: Service that implements Google Cloud Speech API. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $speechClient = new SpeechClient(); - * $encoding = AudioEncoding::FLAC; - * $sampleRate = 44100; - * $config = new RecognitionConfig(); - * $config->setEncoding($encoding); - * $config->setSampleRate($sampleRate); - * $uri = "gs://bucket_name/file_name.flac"; - * $audio = new RecognitionAudio(); - * $audio->setUri($uri); - * $response = $speechClient->syncRecognize($config, $audio); - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @experimental + * {@inheritdoc} */ -class SpeechClient +class SpeechClient extends SpeechGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'speech.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private $grpcCredentialsHelper; - private $speechStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - private $operationsClient; - - private static function getLongRunningDescriptors() - { - return [ - 'asyncRecognize' => [ - 'operationReturnType' => '\Google\Cloud\Speech\V1beta1\AsyncRecognizeResponse', - 'metadataReturnType' => '\Google\Cloud\Speech\V1beta1\AsyncRecognizeMetadata', - ], - ]; - } - - private static function getGrpcStreamingDescriptors() - { - return [ - 'streamingRecognize' => [ - 'grpcStreamingType' => 'BidiStreaming', - ], - ]; - } - - 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; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'speech.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Speech API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'syncRecognize' => $defaultDescriptors, - 'asyncRecognize' => $defaultDescriptors, - 'streamingRecognize' => $defaultDescriptors, - ]; - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); - foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { - $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/speech_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.cloud.speech.v1beta1.Speech', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createSpeechStubFunction = function ($hostname, $opts) { - return new SpeechGrpcClient($hostname, $opts); - }; - if (array_key_exists('createSpeechStubFunction', $options)) { - $createSpeechStubFunction = $options['createSpeechStubFunction']; - } - $this->speechStub = $this->grpcCredentialsHelper->createStub( - $createSpeechStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Performs synchronous speech recognition: receive results after all audio - * has been sent and processed. - * - * Sample code: - * ``` - * try { - * $speechClient = new SpeechClient(); - * $encoding = AudioEncoding::FLAC; - * $sampleRate = 44100; - * $config = new RecognitionConfig(); - * $config->setEncoding($encoding); - * $config->setSampleRate($sampleRate); - * $uri = "gs://bucket_name/file_name.flac"; - * $audio = new RecognitionAudio(); - * $audio->setUri($uri); - * $response = $speechClient->syncRecognize($config, $audio); - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to - * process the request. - * @param RecognitionAudio $audio *Required* The audio data to be recognized. - * @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. - * } - * - * @return \Google\Cloud\Speech\V1beta1\SyncRecognizeResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function syncRecognize($config, $audio, $optionalArgs = []) - { - $request = new SyncRecognizeRequest(); - $request->setConfig($config); - $request->setAudio($audio); - - $mergedSettings = $this->defaultCallSettings['syncRecognize']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->speechStub, - 'SyncRecognize', - $mergedSettings, - $this->descriptors['syncRecognize'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Performs asynchronous speech recognition: receive results via the - * [google.longrunning.Operations] - * (/speech/reference/rest/v1beta1/operations#Operation) - * interface. Returns either an - * `Operation.error` or an `Operation.response` which contains - * an `AsyncRecognizeResponse` message. - * - * Sample code: - * ``` - * try { - * $speechClient = new SpeechClient(); - * $encoding = AudioEncoding::FLAC; - * $sampleRate = 44100; - * $config = new RecognitionConfig(); - * $config->setEncoding($encoding); - * $config->setSampleRate($sampleRate); - * $uri = "gs://bucket_name/file_name.flac"; - * $audio = new RecognitionAudio(); - * $audio->setUri($uri); - * $operationResponse = $speechClient->asyncRecognize($config, $audio); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $speechClient->asyncRecognize($config, $audio); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $speechClient->resumeOperation($operationName, 'asyncRecognize'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @param RecognitionConfig $config *Required* Provides information to the recognizer that specifies how to - * process the request. - * @param RecognitionAudio $audio *Required* The audio data to be recognized. - * @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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function asyncRecognize($config, $audio, $optionalArgs = []) - { - $request = new AsyncRecognizeRequest(); - $request->setConfig($config); - $request->setAudio($audio); - - $mergedSettings = $this->defaultCallSettings['asyncRecognize']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->speechStub, - 'AsyncRecognize', - $mergedSettings, - $this->descriptors['asyncRecognize'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Performs bidirectional streaming speech recognition: receive results while - * sending audio. This method is only available via the gRPC API (not REST). - * - * Sample code: - * ``` - * try { - * $speechClient = new SpeechClient(); - * $request = new StreamingRecognizeRequest(); - * $requests = [$request]; - * - * // Write all requests to the server, then read all responses until the - * // stream is complete - * $stream = $speechClient->streamingRecognize(); - * $stream->writeAll($requests); - * foreach ($stream->closeWriteAndReadAll() as $element) { - * // doSomethingWith($element); - * } - * - * // OR write requests individually, making read() calls if - * // required. Call closeWrite() once writes are complete, and read the - * // remaining responses from the server. - * $stream = $speechClient->streamingRecognize(); - * foreach ($requests as $request) { - * $stream->write($request); - * // if required, read a single response from the stream - * $element = $stream->read(); - * // doSomethingWith($element) - * } - * $stream->closeWrite(); - * $element = $stream->read(); - * while (!is_null($element)) { - * // doSomethingWith($element) - * $element = $stream->read(); - * } - * } finally { - * $speechClient->close(); - * } - * ``` - * - * @param array $optionalArgs { - * Optional. - * - * @type int $timeoutMillis - * Timeout to use for this call. - * } - * - * @return \Google\GAX\BidiStream - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function streamingRecognize($optionalArgs = []) - { - $mergedSettings = $this->defaultCallSettings['streamingRecognize']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->speechStub, - 'StreamingRecognize', - $mergedSettings, - $this->descriptors['streamingRecognize'] - ); - - return $callable( - null, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->speechStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see SpeechClientImpl} class. } diff --git a/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php b/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php new file mode 100644 index 000000000000..d9044d7b7558 --- /dev/null +++ b/src/VideoIntelligence/V1beta1/Gapic/VideoIntelligenceServiceGapicClient.php @@ -0,0 +1,429 @@ +annotateVideo($inputUri, $features); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $videoIntelligenceServiceClient->resumeOperation($operationName, 'annotateVideo'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $videoIntelligenceServiceClient->close(); + * } + * ``` + * + * @experimental + */ +class VideoIntelligenceServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'videointelligence.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + protected $grpcCredentialsHelper; + protected $videoIntelligenceServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + private $operationsClient; + + private static function getLongRunningDescriptors() + { + return [ + 'annotateVideo' => [ + 'operationReturnType' => '\Google\Cloud\Videointelligence\V1beta1\AnnotateVideoResponse', + 'metadataReturnType' => '\Google\Cloud\Videointelligence\V1beta1\AnnotateVideoProgress', + ], + ]; + } + + 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; + } + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return \Google\GAX\LongRunning\OperationsClient + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started + * by a long running API method. If $methodName is not provided, or does + * not match a long running API method, then the operation can still be + * resumed, but the OperationResponse object will not deserialize the + * final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return \Google\GAX\OperationResponse + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $lroDescriptors = self::getLongRunningDescriptors(); + if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { + $options = $lroDescriptors[$methodName]; + } else { + $options = []; + } + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'videointelligence.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + if (array_key_exists('operationsClient', $options)) { + $this->operationsClient = $options['operationsClient']; + } else { + $operationsClientOptions = $options; + unset($operationsClientOptions['timeoutMillis']); + unset($operationsClientOptions['retryingOverride']); + $this->operationsClient = new OperationsClient($operationsClientOptions); + } + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'annotateVideo' => $defaultDescriptors, + ]; + $longRunningDescriptors = self::getLongRunningDescriptors(); + foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { + $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/video_intelligence_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.cloud.videointelligence.v1beta1.VideoIntelligenceService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createVideoIntelligenceServiceStubFunction = function ($hostname, $opts, $channel) { + return new VideoIntelligenceServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createVideoIntelligenceServiceStubFunction', $options)) { + $createVideoIntelligenceServiceStubFunction = $options['createVideoIntelligenceServiceStubFunction']; + } + $this->videoIntelligenceServiceStub = $this->grpcCredentialsHelper->createStub($createVideoIntelligenceServiceStubFunction); + } + + /** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * Sample code: + * ``` + * try { + * $videoIntelligenceServiceClient = new VideoIntelligenceServiceClient(); + * $inputUri = ""; + * $features = []; + * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); + * $operationResponse->pollUntilComplete(); + * if ($operationResponse->operationSucceeded()) { + * $result = $operationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $operationResponse->getError(); + * // handleError($error) + * } + * + * // OR start the operation, keep the operation name, and resume later + * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); + * $operationName = $operationResponse->getName(); + * // ... do other work + * $newOperationResponse = $videoIntelligenceServiceClient->resumeOperation($operationName, 'annotateVideo'); + * while (!$newOperationResponse->isDone()) { + * // ... do other work + * $newOperationResponse->reload(); + * } + * if ($newOperationResponse->operationSucceeded()) { + * $result = $newOperationResponse->getResult(); + * // doSomethingWith($result) + * } else { + * $error = $newOperationResponse->getError(); + * // handleError($error) + * } + * } finally { + * $videoIntelligenceServiceClient->close(); + * } + * ``` + * + * @param string $inputUri Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/reference-uris). + * A video URI may include wildcards in `object-id`, and thus identify + * multiple videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param int[] $features Requested video annotation features. + * For allowed values, use constants defined on {@see \Google\Cloud\Videointelligence\V1beta1\Feature} + * @param array $optionalArgs { + * Optional. + * + * @type string $inputContent + * The video data bytes. Encoding: base64. If unset, the input video(s) + * should be specified via `input_uri`. If set, `input_uri` should be unset. + * @type VideoContext $videoContext + * Additional video context and/or feature-specific parameters. + * @type string $outputUri + * Optional location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/reference-uris). + * @type string $locationId + * 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. + * } + * + * @return \Google\Longrunning\Operation + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function annotateVideo($inputUri, $features, $optionalArgs = []) + { + $request = new AnnotateVideoRequest(); + $request->setInputUri($inputUri); + $request->setFeatures($features); + if (isset($optionalArgs['inputContent'])) { + $request->setInputContent($optionalArgs['inputContent']); + } + if (isset($optionalArgs['videoContext'])) { + $request->setVideoContext($optionalArgs['videoContext']); + } + if (isset($optionalArgs['outputUri'])) { + $request->setOutputUri($optionalArgs['outputUri']); + } + if (isset($optionalArgs['locationId'])) { + $request->setLocationId($optionalArgs['locationId']); + } + + $mergedSettings = $this->defaultCallSettings['annotateVideo']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->videoIntelligenceServiceStub, + 'AnnotateVideo', + $mergedSettings, + $this->descriptors['annotateVideo'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->videoIntelligenceServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/VideoIntelligence/V1beta1/VideoIntelligenceServiceClient.php b/src/VideoIntelligence/V1beta1/VideoIntelligenceServiceClient.php index f9c568d5c213..b004beaf83d5 100644 --- a/src/VideoIntelligence/V1beta1/VideoIntelligenceServiceClient.php +++ b/src/VideoIntelligence/V1beta1/VideoIntelligenceServiceClient.php @@ -30,401 +30,12 @@ namespace Google\Cloud\VideoIntelligence\V1beta1; -use Google\Cloud\Videointelligence\V1beta1\AnnotateVideoProgress; -use Google\Cloud\Videointelligence\V1beta1\AnnotateVideoRequest; -use Google\Cloud\Videointelligence\V1beta1\AnnotateVideoResponse; -use Google\Cloud\Videointelligence\V1beta1\Feature; -use Google\Cloud\Videointelligence\V1beta1\VideoContext; -use Google\Cloud\Videointelligence\V1beta1\VideoIntelligenceServiceGrpcClient; -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\Cloud\VideoIntelligence\V1beta1\Gapic\VideoIntelligenceServiceGapicClient; /** - * Service Description: Service that implements Google Cloud Video Intelligence API. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $videoIntelligenceServiceClient = new VideoIntelligenceServiceClient(); - * $inputUri = ""; - * $features = []; - * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $videoIntelligenceServiceClient->resumeOperation($operationName, 'annotateVideo'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $videoIntelligenceServiceClient->close(); - * } - * ``` - * - * @experimental + * {@inheritdoc} */ -class VideoIntelligenceServiceClient +class VideoIntelligenceServiceClient extends VideoIntelligenceServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'videointelligence.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private $grpcCredentialsHelper; - private $videoIntelligenceServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - private $operationsClient; - - private static function getLongRunningDescriptors() - { - return [ - 'annotateVideo' => [ - 'operationReturnType' => '\Google\Cloud\Videointelligence\V1beta1\AnnotateVideoResponse', - 'metadataReturnType' => '\Google\Cloud\Videointelligence\V1beta1\AnnotateVideoProgress', - ], - ]; - } - - 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; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'videointelligence.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Video Intelligence API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'annotateVideo' => $defaultDescriptors, - ]; - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/video_intelligence_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.cloud.videointelligence.v1beta1.VideoIntelligenceService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createVideoIntelligenceServiceStubFunction = function ($hostname, $opts) { - return new VideoIntelligenceServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createVideoIntelligenceServiceStubFunction', $options)) { - $createVideoIntelligenceServiceStubFunction = $options['createVideoIntelligenceServiceStubFunction']; - } - $this->videoIntelligenceServiceStub = $this->grpcCredentialsHelper->createStub( - $createVideoIntelligenceServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * Sample code: - * ``` - * try { - * $videoIntelligenceServiceClient = new VideoIntelligenceServiceClient(); - * $inputUri = ""; - * $features = []; - * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $videoIntelligenceServiceClient->resumeOperation($operationName, 'annotateVideo'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $videoIntelligenceServiceClient->close(); - * } - * ``` - * - * @param string $inputUri Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/reference-uris). - * A video URI may include wildcards in `object-id`, and thus identify - * multiple videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param int[] $features Requested video annotation features. - * For allowed values, use constants defined on {@see \Google\Cloud\Videointelligence\V1beta1\Feature} - * @param array $optionalArgs { - * Optional. - * - * @type string $inputContent - * The video data bytes. Encoding: base64. If unset, the input video(s) - * should be specified via `input_uri`. If set, `input_uri` should be unset. - * @type VideoContext $videoContext - * Additional video context and/or feature-specific parameters. - * @type string $outputUri - * Optional location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/reference-uris). - * @type string $locationId - * 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. - * } - * - * @return \Google\Longrunning\Operation - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function annotateVideo($inputUri, $features, $optionalArgs = []) - { - $request = new AnnotateVideoRequest(); - $request->setInputUri($inputUri); - $request->setFeatures($features); - if (isset($optionalArgs['inputContent'])) { - $request->setInputContent($optionalArgs['inputContent']); - } - if (isset($optionalArgs['videoContext'])) { - $request->setVideoContext($optionalArgs['videoContext']); - } - if (isset($optionalArgs['outputUri'])) { - $request->setOutputUri($optionalArgs['outputUri']); - } - if (isset($optionalArgs['locationId'])) { - $request->setLocationId($optionalArgs['locationId']); - } - - $mergedSettings = $this->defaultCallSettings['annotateVideo']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->videoIntelligenceServiceStub, - 'AnnotateVideo', - $mergedSettings, - $this->descriptors['annotateVideo'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->videoIntelligenceServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see VideoIntelligenceServiceClientImpl} class. } diff --git a/src/VideoIntelligence/composer.json b/src/VideoIntelligence/composer.json index cab0f0460327..5c1cc3bf6766 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.21.0", - "google/gax": "^0.21.0" + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1" }, "extra": { "component": { diff --git a/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php b/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php new file mode 100644 index 000000000000..fbf97a0214dd --- /dev/null +++ b/src/Vision/V1/Gapic/ImageAnnotatorGapicClient.php @@ -0,0 +1,269 @@ +batchAnnotateImages($requests); + * } finally { + * $imageAnnotatorClient->close(); + * } + * ``` + * + * @experimental + */ +class ImageAnnotatorGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'vision.googleapis.com'; + + /** + * The default port of the service. + */ + 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. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + protected $grpcCredentialsHelper; + protected $imageAnnotatorStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + 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; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'vision.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * 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 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) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'batchAnnotateImages' => $defaultDescriptors, + ]; + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/image_annotator_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.cloud.vision.v1.ImageAnnotator', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createImageAnnotatorStubFunction = function ($hostname, $opts, $channel) { + return new ImageAnnotatorGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createImageAnnotatorStubFunction', $options)) { + $createImageAnnotatorStubFunction = $options['createImageAnnotatorStubFunction']; + } + $this->imageAnnotatorStub = $this->grpcCredentialsHelper->createStub($createImageAnnotatorStubFunction); + } + + /** + * Run image detection and annotation for a batch of images. + * + * Sample code: + * ``` + * try { + * $imageAnnotatorClient = new ImageAnnotatorClient(); + * $requests = []; + * $response = $imageAnnotatorClient->batchAnnotateImages($requests); + * } finally { + * $imageAnnotatorClient->close(); + * } + * ``` + * + * @param AnnotateImageRequest[] $requests Individual image annotation requests for this batch. + * @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. + * } + * + * @return \Google\Cloud\Vision\V1\BatchAnnotateImagesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function batchAnnotateImages($requests, $optionalArgs = []) + { + $request = new BatchAnnotateImagesRequest(); + $request->setRequests($requests); + + $mergedSettings = $this->defaultCallSettings['batchAnnotateImages']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->imageAnnotatorStub, + 'BatchAnnotateImages', + $mergedSettings, + $this->descriptors['batchAnnotateImages'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->imageAnnotatorStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Vision/V1/ImageAnnotatorClient.php b/src/Vision/V1/ImageAnnotatorClient.php index 51a44e5b97b6..cce5e5ee8440 100644 --- a/src/Vision/V1/ImageAnnotatorClient.php +++ b/src/Vision/V1/ImageAnnotatorClient.php @@ -30,238 +30,12 @@ namespace Google\Cloud\Vision\V1; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; +use Google\Cloud\Vision\V1\Gapic\ImageAnnotatorGapicClient; /** - * Service Description: Service that performs Google Cloud Vision API detection tasks over client - * images, such as face, landmark, logo, label, and text detection. The - * ImageAnnotator service returns detected entities from the images. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $imageAnnotatorClient = new ImageAnnotatorClient(); - * $requests = []; - * $response = $imageAnnotatorClient->batchAnnotateImages($requests); - * } finally { - * $imageAnnotatorClient->close(); - * } - * ``` - * - * @experimental + * {@inheritdoc} */ -class ImageAnnotatorClient +class ImageAnnotatorClient extends ImageAnnotatorGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'vision.googleapis.com'; - - /** - * The default port of the service. - */ - 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. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private $grpcCredentialsHelper; - private $imageAnnotatorStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - 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; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'vision.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Vision API. - * @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) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'batchAnnotateImages' => $defaultDescriptors, - ]; - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/image_annotator_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.cloud.vision.v1.ImageAnnotator', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createImageAnnotatorStubFunction = function ($hostname, $opts) { - return new ImageAnnotatorGrpcClient($hostname, $opts); - }; - if (array_key_exists('createImageAnnotatorStubFunction', $options)) { - $createImageAnnotatorStubFunction = $options['createImageAnnotatorStubFunction']; - } - $this->imageAnnotatorStub = $this->grpcCredentialsHelper->createStub( - $createImageAnnotatorStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Run image detection and annotation for a batch of images. - * - * Sample code: - * ``` - * try { - * $imageAnnotatorClient = new ImageAnnotatorClient(); - * $requests = []; - * $response = $imageAnnotatorClient->batchAnnotateImages($requests); - * } finally { - * $imageAnnotatorClient->close(); - * } - * ``` - * - * @param AnnotateImageRequest[] $requests Individual image annotation requests for this batch. - * @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. - * } - * - * @return \Google\Cloud\Vision\V1\BatchAnnotateImagesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function batchAnnotateImages($requests, $optionalArgs = []) - { - $request = new BatchAnnotateImagesRequest(); - $request->setRequests($requests); - - $mergedSettings = $this->defaultCallSettings['batchAnnotateImages']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->imageAnnotatorStub, - 'BatchAnnotateImages', - $mergedSettings, - $this->descriptors['batchAnnotateImages'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->imageAnnotatorStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ImageAnnotatorClientImpl} class. } diff --git a/tests/unit/Core/GrpcRequestWrapperTest.php b/tests/unit/Core/GrpcRequestWrapperTest.php index 08969590bb29..eff18c2fdd5a 100644 --- a/tests/unit/Core/GrpcRequestWrapperTest.php +++ b/tests/unit/Core/GrpcRequestWrapperTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Tests\Unit\Core; +use Google\Api\Http; use Google\Auth\FetchAuthTokenInterface; use Google\Cloud\Core\Exception; use Google\Cloud\Tests\GrpcTestTrait; @@ -80,16 +81,16 @@ public function responseProvider() return []; } $expectedMessage = ['successful' => 'request']; - $message = $this->prophesize(Message::class); + $message = new Http(); $serializer = $this->prophesize(Serializer::class); - $serializer->encodeMessage($message->reveal())->willReturn($expectedMessage); + $serializer->encodeMessage($message)->willReturn($expectedMessage); $pagedMessage = $this->prophesize(PagedListResponse::class); $page = $this->prophesize(Page::class); - $page->getResponseObject()->willReturn($message->reveal()); + $page->getResponseObject()->willReturn($message); $pagedMessage->getPage()->willReturn($page->reveal()); return [ - [$message->reveal(), $expectedMessage, $serializer->reveal()], + [$message, $expectedMessage, $serializer->reveal()], [$pagedMessage->reveal(), $expectedMessage, $serializer->reveal()], [null, null, $serializer->reveal()] ];