From 800d1b842c41b4e6bb8bf6a59686bc771eb5b8c1 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 30 Sep 2026 23:59:44 +0000 Subject: [PATCH 01/10] feat(Gax): add ServiceInterface, LongRunningOperationProviderInterface, and IamProviderInterface --- Gax/src/GapicClientTrait.php | 12 +++-- Gax/src/IamProviderInterface.php | 53 +++++++++++++++++++ .../LongRunningOperationProviderInterface.php | 44 +++++++++++++++ Gax/src/ServiceInterface.php | 46 ++++++++++++++++ 4 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 Gax/src/IamProviderInterface.php create mode 100644 Gax/src/LongRunningOperationProviderInterface.php create mode 100644 Gax/src/ServiceInterface.php diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index 6cf858f21d16..e0e54594eae7 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -50,6 +50,7 @@ use Google\ApiCore\Transport\RestTransport; use Google\ApiCore\Transport\TransportInterface; use Google\Auth\FetchAuthTokenInterface; +use Google\LongRunning\Client\OperationsClient as V2OperationsClient; use Google\LongRunning\Operation; use Google\Protobuf\Internal\Message; use GuzzleHttp\Promise\PromiseInterface; @@ -174,7 +175,7 @@ public static function getServiceScopes(): array * * @experimental */ - public function close() + public function close(): void { $this->transport->close(); } @@ -454,9 +455,9 @@ private function createTransport( /** * @param array $options - * @return OperationsClient + * @return OperationsClient|V2OperationsClient|object */ - private function createOperationsClient(array $options) + protected function createOperationsClient(array $options) { $this->pluckArray([ 'serviceName', @@ -470,8 +471,11 @@ private function createOperationsClient(array $options) } // operationsClientClass option + $defaultClass = $this->isBackwardsCompatibilityMode() + ? OperationsClient::class + : V2OperationsClient::class; $operationsClientClass = $this->pluck('operationsClientClass', $options, false) - ?: OperationsCLient::class; + ?: $defaultClass; return new $operationsClientClass($options); } diff --git a/Gax/src/IamProviderInterface.php b/Gax/src/IamProviderInterface.php new file mode 100644 index 000000000000..5a55183e0c99 --- /dev/null +++ b/Gax/src/IamProviderInterface.php @@ -0,0 +1,53 @@ + Date: Thu, 1 Oct 2026 00:17:43 +0000 Subject: [PATCH 02/10] feat(Gax)!: remove V1 GAPIC backwards compatibility and deprecated classes --- Gax/composer.json | 2 +- ...eAddressTrait.php => ApiEndpointTrait.php} | 10 +- Gax/src/ClientOptionsTrait.php | 35 +-- Gax/src/GPBLabel.php | 43 --- Gax/src/GPBType.php | 58 ---- Gax/src/GapicClientTrait.php | 49 +-- Gax/src/OperationResponse.php | 33 +- Gax/src/Options/CallOptions.php | 10 - .../TransportOptions/GrpcTransportOptions.php | 13 +- Gax/src/Serializer.php | 2 + .../Grpc/UnaryInterceptorInterface.php | 61 ---- Gax/src/Transport/GrpcFallbackTransport.php | 6 +- Gax/src/Transport/GrpcTransport.php | 23 +- Gax/src/Transport/HttpUnaryTransportTrait.php | 10 - Gax/src/Transport/RestTransport.php | 12 +- .../Testing/MockGrpcTransport.php | 8 +- ...TraitTest.php => ApiEndpointTraitTest.php} | 26 +- Gax/tests/Unit/GapicClientTraitTest.php | 293 ++++++++---------- .../Middleware/OperationsMiddlewareTest.php | 10 +- Gax/tests/Unit/OperationResponseTest.php | 26 +- .../Unit/Transport/GrpcTransportTest.php | 12 +- .../CustomOperation/GetOperationRequest.php | 4 +- .../mocks/DeprecatedTestInterceptor.php | 32 -- .../mocks/DeprecatedTestUnaryInterceptor.php | 20 -- Ids/src/V1/Client/IDSClient.php | 19 -- dev/tests/fixtures/phpdoc/gax.xml | 120 ------- 26 files changed, 212 insertions(+), 725 deletions(-) rename Gax/src/{ServiceAddressTrait.php => ApiEndpointTrait.php} (89%) delete mode 100644 Gax/src/GPBLabel.php delete mode 100644 Gax/src/GPBType.php delete mode 100644 Gax/src/Transport/Grpc/UnaryInterceptorInterface.php rename Gax/{src => tests}/Testing/MockGrpcTransport.php (95%) rename Gax/tests/Unit/{ServiceAddressTraitTest.php => ApiEndpointTraitTest.php} (62%) delete mode 100644 Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php delete mode 100644 Gax/tests/Unit/testdata/mocks/DeprecatedTestUnaryInterceptor.php diff --git a/Gax/composer.json b/Gax/composer.json index 3d9607c015b1..f904c2ffe5a3 100644 --- a/Gax/composer.json +++ b/Gax/composer.json @@ -16,7 +16,7 @@ "guzzlehttp/promises": "^2.0.3||^3.0", "guzzlehttp/psr7": "^2.6.3||^3.0", "google/common-protos": "^4.9", - "google/longrunning": "~0.4", + "google/longrunning": "~0.4||^1.0", "ramsey/uuid": "^4.2.3" }, "require-dev": { diff --git a/Gax/src/ServiceAddressTrait.php b/Gax/src/ApiEndpointTrait.php similarity index 89% rename from Gax/src/ServiceAddressTrait.php rename to Gax/src/ApiEndpointTrait.php index 1343a233caed..df74fed5ccba 100644 --- a/Gax/src/ServiceAddressTrait.php +++ b/Gax/src/ApiEndpointTrait.php @@ -1,4 +1,6 @@ isBackwardsCompatibilityMode()) { - $preModifiedOptions = $options; - $this->modifyClientOptions($options); - // NOTE: this is required to ensure backwards compatiblity with $options['apiEndpoint'] - if ($options['apiEndpoint'] !== $preModifiedOptions['apiEndpoint']) { - $apiEndpoint = $options['apiEndpoint']; - } - - // serviceAddress is now deprecated and acts as an alias for apiEndpoint - if (isset($options['serviceAddress'])) { - $apiEndpoint = $this->pluck('serviceAddress', $options, false); - } - } else { - // Ads is using this method in their new surface clients, so we need to call it. - // However, this method is not used anywhere else for the new surface clients - // @TODO: Remove this in GAX V2 - $this->modifyClientOptions($options); + $preModifiedOptions = $options; + $this->modifyClientOptions($options); + // NOTE: this is required to ensure backwards compatiblity with $options['apiEndpoint'] + if ($options['apiEndpoint'] !== $preModifiedOptions['apiEndpoint']) { + $apiEndpoint = $options['apiEndpoint']; + } + // serviceAddress is now deprecated and acts as an alias for apiEndpoint + if (isset($options['serviceAddress'])) { + $apiEndpoint = $this->pluck('serviceAddress', $options, false); } // If an API endpoint is different form the default, ensure the "audience" does not conflict // with the custom endpoint by setting "user defined" scopes. @@ -366,14 +357,6 @@ protected function modifyClientOptions(array &$options) // Do nothing - this method exists to allow option modification by partial veneers. } - /** - * @internal - */ - private function isBackwardsCompatibilityMode(): bool - { - return false; - } - /** * @param null|false|LoggerInterface $logger * @param string $options diff --git a/Gax/src/GPBLabel.php b/Gax/src/GPBLabel.php deleted file mode 100644 index 18208cd64862..000000000000 --- a/Gax/src/GPBLabel.php +++ /dev/null @@ -1,43 +0,0 @@ - 'startClientStreamingCall', Call::SERVER_STREAMING_CALL => 'startServerStreamingCall', ]; - private bool $backwardsCompatibilityMode; /** * Add a middleware to the call stack by providing a callable which will be @@ -295,20 +293,8 @@ private function setClientOptions(array $options) // Therefore, we need to remove it from the $options array before // creating the ClientOptions. $hasEmulator = $this->pluck('hasEmulator', $options, false) ?? false; - if ($this->isBackwardsCompatibilityMode()) { - if (is_string($options['clientConfig'])) { - // perform validation for V1 surfaces which is done in the - // ClientOptions class for v2 surfaces. - $options['clientConfig'] = json_decode( - file_get_contents($options['clientConfig']), - true - ); - self::validateFileExists($options['descriptorsConfigPath']); - } - } else { - // cast to ClientOptions for new surfaces only - $options = new ClientOptions($options); - } + // cast to ClientOptions for new surfaces only + $options = new ClientOptions($options); $this->serviceName = $options['serviceName']; $this->retrySettings = RetrySettings::load( $this->serviceName, @@ -331,14 +317,6 @@ private function setClientOptions(array $options) } $this->agentHeader = AgentHeader::buildAgentHeader($headerInfo); - // Set "client_library_name" depending on client library surface being used - $userAgentHeader = sprintf( - 'gcloud-php-%s/%s', - $this->isBackwardsCompatibilityMode() ? 'legacy' : 'new', - $options['gapicVersion'] - ); - $this->agentHeader['User-Agent'] = [$userAgentHeader]; - self::validateFileExists($options['descriptorsConfigPath']); $descriptors = require($options['descriptorsConfigPath']); @@ -455,7 +433,7 @@ private function createTransport( /** * @param array $options - * @return OperationsClient|V2OperationsClient|object + * @return OperationsClient|object */ protected function createOperationsClient(array $options) { @@ -471,12 +449,7 @@ protected function createOperationsClient(array $options) } // operationsClientClass option - $defaultClass = $this->isBackwardsCompatibilityMode() - ? OperationsClient::class - : V2OperationsClient::class; - $operationsClientClass = $this->pluck('operationsClientClass', $options, false) - ?: $defaultClass; - return new $operationsClientClass($options); + return new OperationsClient($options); } /** @@ -796,9 +769,6 @@ private function configureCallConstructionOptions(string $methodName, array $opt */ private function configureCallOptions(array $optionalArgs): array { - if ($this->isBackwardsCompatibilityMode()) { - return $optionalArgs; - } // cast to CallOptions for new surfaces only return (new CallOptions($optionalArgs))->toArray(); } @@ -1075,13 +1045,4 @@ protected function modifyStreamingCallable(callable &$callable) { // Do nothing - this method exists to allow callable modification by partial veneers. } - - /** - * @internal - */ - private function isBackwardsCompatibilityMode(): bool - { - return $this->backwardsCompatibilityMode - ?? $this->backwardsCompatibilityMode = substr(__CLASS__, -11) === 'GapicClient'; - } } diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 9dfeb0a73129..51c39770a6d6 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -37,7 +37,6 @@ use Google\LongRunning\DeleteOperationRequest; use Google\LongRunning\GetOperationRequest; use Google\LongRunning\Operation; -use Google\LongRunning\OperationsClient as LegacyOperationsClient; use Google\Protobuf\Any; use Google\Protobuf\Internal\Message; use Google\Rpc\Status; @@ -67,7 +66,6 @@ class OperationResponse const DEFAULT_POLLING_MULTIPLIER = 2; const DEFAULT_MAX_POLLING_INTERVAL = 60000; const DEFAULT_MAX_POLLING_DURATION = 0; - private const NEW_CLIENT_NAMESPACE = '\\Client\\'; private string $operationName; private ?object $operationsClient; @@ -277,8 +275,7 @@ public function reload() throw new ValidationException('Cannot call reload() on a deleted operation'); } - $requestClass = $this->isNewSurfaceOperationsClient() ? $this->getOperationRequest : null; - $this->lastProtoResponse = $this->operationsCall($this->getOperationMethod, $requestClass); + $this->lastProtoResponse = $this->operationsCall($this->getOperationMethod, $this->getOperationRequest); } /** @@ -403,8 +400,7 @@ public function cancel() throw new LogicException('The cancel operation is not supported by this API'); } - $requestClass = $this->isNewSurfaceOperationsClient() ? $this->cancelOperationRequest : null; - $this->operationsCall($this->cancelOperationMethod, $requestClass); + $this->operationsCall($this->cancelOperationMethod, $this->cancelOperationRequest); } /** @@ -424,8 +420,7 @@ public function delete() throw new LogicException('The delete operation is not supported by this API'); } - $requestClass = $this->isNewSurfaceOperationsClient() ? $this->deleteOperationRequest : null; - $this->operationsCall($this->deleteOperationMethod, $requestClass); + $this->operationsCall($this->deleteOperationMethod, $this->deleteOperationRequest); $this->deleted = true; } @@ -471,22 +466,10 @@ public function getMetadata() * Call the operations client to perform an operation. * * @param string $method The method to call on the operations client. - * @param string|null $requestClass The request class to use for the call. - * Will be null for legacy operations clients. + * @param string $requestClass The request class to use for the call. */ - private function operationsCall(string $method, ?string $requestClass) + private function operationsCall(string $method, string $requestClass) { - // V1 GAPIC clients have an empty $requestClass - if (empty($requestClass)) { - if ($this->additionalArgs) { - return $this->operationsClient->$method( - $this->getName(), - ...array_values($this->additionalArgs) - ); - } - return $this->operationsClient->$method($this->getName()); - } - if (!method_exists($requestClass, 'build')) { throw new LogicException('Request class must support the static build method'); } @@ -530,10 +513,4 @@ private function hasProtoResponse() { return !is_null($this->lastProtoResponse); } - - private function isNewSurfaceOperationsClient(): bool - { - return !$this->operationsClient instanceof LegacyOperationsClient - && false !== strpos(get_class($this->operationsClient), self::NEW_CLIENT_NAMESPACE); - } } diff --git a/Gax/src/Options/CallOptions.php b/Gax/src/Options/CallOptions.php index c58c53ed14f2..2b67bd8367f4 100644 --- a/Gax/src/Options/CallOptions.php +++ b/Gax/src/Options/CallOptions.php @@ -142,16 +142,6 @@ public function setTransportOptions(array $transportOptions): self return $this; } - /** - * @deprecated use CallOptions::setTransportOptions - */ - public function setTransportSpecificOptions(array $transportSpecificOptions): self - { - $this->setTransportOptions($transportSpecificOptions); - - return $this; - } - /** * @param RetrySettings|array|null $retrySettings * diff --git a/Gax/src/Options/TransportOptions/GrpcTransportOptions.php b/Gax/src/Options/TransportOptions/GrpcTransportOptions.php index 051b57bbea04..c1b622d045e1 100644 --- a/Gax/src/Options/TransportOptions/GrpcTransportOptions.php +++ b/Gax/src/Options/TransportOptions/GrpcTransportOptions.php @@ -36,7 +36,6 @@ use Closure; use Google\ApiCore\Options\OptionsInterface; use Google\ApiCore\Options\OptionsTrait; -use Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface; use Grpc\Channel; use Grpc\Interceptor; use Psr\Log\LoggerInterface; @@ -56,7 +55,7 @@ class GrpcTransportOptions implements ArrayAccess, OptionsInterface private null|false|LoggerInterface $logger; /** - * @var Interceptor[]|UnaryInterceptorInterface[] + * @var Interceptor[] */ private array $interceptors; @@ -69,14 +68,8 @@ class GrpcTransportOptions implements ArrayAccess, OptionsInterface * @type array $stubOpts Options used to construct the gRPC stub (see * {@link https://grpc.github.io/grpc/core/group__grpc__arg__keys.html}). * @type Channel $channel Grpc channel to be used. - * @type Interceptor[]|UnaryInterceptorInterface[] $interceptors *EXPERIMENTAL* + * @type Interceptor[] $interceptors *EXPERIMENTAL* * Interceptors used to intercept RPC invocations before a call starts. - * Please note that implementations of - * {@see \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface} are - * considered deprecated and support will be removed in a future - * release. To prepare for this, please take the time to convert - * `UnaryInterceptorInterface` implementations over to a class which - * extends {@see Grpc\Interceptor}. * @type callable $clientCertSource A callable which returns the client cert as a string. * @type null|false|LoggerInterface A PSR-3 Logger Interface. * } @@ -125,7 +118,7 @@ public function setChannel(?Channel $channel): self } /** - * @param Interceptor[]|UnaryInterceptorInterface[] $interceptors + * @param Interceptor[] $interceptors * * @return $this */ diff --git a/Gax/src/Serializer.php b/Gax/src/Serializer.php index 3f50da5fcd13..b65fffdebfaa 100644 --- a/Gax/src/Serializer.php +++ b/Gax/src/Serializer.php @@ -36,6 +36,8 @@ use Google\Protobuf\Descriptor; use Google\Protobuf\DescriptorPool; use Google\Protobuf\FieldDescriptor; +use Google\Protobuf\Internal\GPBLabel; +use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\Message; use Google\Rpc\BadRequest; use Google\Rpc\DebugInfo; diff --git a/Gax/src/Transport/Grpc/UnaryInterceptorInterface.php b/Gax/src/Transport/Grpc/UnaryInterceptorInterface.php deleted file mode 100644 index fa510ea39a6f..000000000000 --- a/Gax/src/Transport/Grpc/UnaryInterceptorInterface.php +++ /dev/null @@ -1,61 +0,0 @@ - null, 'logger' => null, ]; - list($baseUri, $port) = self::normalizeServiceAddress($apiEndpoint); + list($baseUri, $port) = self::normalizeApiEndpoint($apiEndpoint); $httpHandler = $config['httpHandler'] ?: self::buildHttpHandlerAsync(logger: $config['logger']); $transport = new GrpcFallbackTransport("$baseUri:$port", $httpHandler); if ($config['clientCertSource']) { diff --git a/Gax/src/Transport/GrpcTransport.php b/Gax/src/Transport/GrpcTransport.php index 50bdc3d7de1a..cce4b4e7865a 100644 --- a/Gax/src/Transport/GrpcTransport.php +++ b/Gax/src/Transport/GrpcTransport.php @@ -33,15 +33,14 @@ namespace Google\ApiCore\Transport; use Exception; +use Google\ApiCore\ApiEndpointTrait; use Google\ApiCore\ApiException; use Google\ApiCore\BidiStream; use Google\ApiCore\Call; use Google\ApiCore\ClientStream; use Google\ApiCore\GrpcSupportTrait; use Google\ApiCore\ServerStream; -use Google\ApiCore\ServiceAddressTrait; use Google\ApiCore\Transport\Grpc\ServerStreamingCallWrapper; -use Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface; use Google\ApiCore\ValidationException; use Google\ApiCore\ValidationTrait; use Google\Auth\Logging\LoggingTrait; @@ -59,9 +58,9 @@ */ class GrpcTransport extends BaseStub implements TransportInterface { + use ApiEndpointTrait; use ValidationTrait; use GrpcSupportTrait; - use ServiceAddressTrait; use LoggingTrait; private null|LoggerInterface $logger; @@ -73,14 +72,8 @@ class GrpcTransport extends BaseStub implements TransportInterface * metadata array, and returns an updated metadata array * - 'grpc.primary_user_agent': (optional) a user-agent string * @param Channel $channel An already created Channel object (optional) - * @param Interceptor[]|UnaryInterceptorInterface[] $interceptors *EXPERIMENTAL* + * @param Interceptor[] $interceptors *EXPERIMENTAL* * Interceptors used to intercept RPC invocations before a call starts. - * Please note that implementations of - * {@see \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface} are - * considered deprecated and support will be removed in a future - * release. To prepare for this, please take the time to convert - * `UnaryInterceptorInterface` implementations over to a class which - * extends {@see Grpc\Interceptor}. * @param null|false|LoggerInterface $logger A PSR-3 Compliant logger. * @throws Exception */ @@ -114,14 +107,8 @@ public function __construct( * @type array $stubOpts Options used to construct the gRPC stub (see * {@link https://grpc.github.io/grpc/core/group__grpc__arg__keys.html}). * @type Channel $channel Grpc channel to be used. - * @type Interceptor[]|UnaryInterceptorInterface[] $interceptors *EXPERIMENTAL* + * @type Interceptor[] $interceptors *EXPERIMENTAL* * Interceptors used to intercept RPC invocations before a call starts. - * Please note that implementations of - * {@see \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface} are - * considered deprecated and support will be removed in a future - * release. To prepare for this, please take the time to convert - * `UnaryInterceptorInterface` implementations over to a class which - * extends {@see Grpc\Interceptor}. * @type callable $clientCertSource A callable which returns the client cert as a string. * } * @return GrpcTransport @@ -137,7 +124,7 @@ public static function build(string $apiEndpoint, array $config = []) 'clientCertSource' => null, 'logger' => null, ]; - list($addr, $port) = self::normalizeServiceAddress($apiEndpoint); + list($addr, $port) = self::normalizeApiEndpoint($apiEndpoint); $host = "$addr:$port"; $stubOpts = $config['stubOpts']; // Set the required 'credentials' key in stubOpts if it is not already set. Use diff --git a/Gax/src/Transport/HttpUnaryTransportTrait.php b/Gax/src/Transport/HttpUnaryTransportTrait.php index 38c4ca1f5522..5e4bb242d23c 100644 --- a/Gax/src/Transport/HttpUnaryTransportTrait.php +++ b/Gax/src/Transport/HttpUnaryTransportTrait.php @@ -59,16 +59,6 @@ public function startClientStreamingCall(Call $call, array $options) $this->throwUnsupportedException(); } - /** - * {@inheritdoc} - * @return never - * @throws \BadMethodCallException - */ - public function startServerStreamingCall(Call $call, array $options) - { - $this->throwUnsupportedException(); - } - /** * {@inheritdoc} * @return never diff --git a/Gax/src/Transport/RestTransport.php b/Gax/src/Transport/RestTransport.php index ae0245130dd9..2ab582338320 100644 --- a/Gax/src/Transport/RestTransport.php +++ b/Gax/src/Transport/RestTransport.php @@ -31,13 +31,13 @@ */ namespace Google\ApiCore\Transport; +use Google\ApiCore\ApiEndpointTrait; use Google\ApiCore\ApiException; use Google\ApiCore\Call; use Google\ApiCore\InsecureRequestBuilder; use Google\ApiCore\RequestBuilder; use Google\ApiCore\ResumableUpload\ResumableUploadTransportInterface; use Google\ApiCore\ServerStream; -use Google\ApiCore\ServiceAddressTrait; use Google\ApiCore\Transport\Rest\RestServerStreamingCall; use Google\ApiCore\ValidationException; use Google\ApiCore\ValidationTrait; @@ -51,11 +51,9 @@ */ class RestTransport implements TransportInterface, ResumableUploadTransportInterface { + use ApiEndpointTrait; use ValidationTrait; - use ServiceAddressTrait; - use HttpUnaryTransportTrait { - startServerStreamingCall as protected unsupportedServerStreamingCall; - } + use HttpUnaryTransportTrait; private RequestBuilder $requestBuilder; @@ -98,7 +96,7 @@ public static function build(string $apiEndpoint, string $restConfigPath, array 'hasEmulator' => false, 'logger' => null, ]; - list($baseUri, $port) = self::normalizeServiceAddress($apiEndpoint); + list($baseUri, $port) = self::normalizeApiEndpoint($apiEndpoint); $requestBuilder = $config['hasEmulator'] ? new InsecureRequestBuilder("$baseUri:$port", $restConfigPath) : new RequestBuilder("$baseUri:$port", $restConfigPath); @@ -196,7 +194,7 @@ public function startServerStreamingCall(Call $call, array $options) // Maintain forwards compatibility with older GAPIC clients not configured for REST server streaming // @see https://github.com/googleapis/gax-php/issues/370 if (!$this->requestBuilder->pathExists($call->getMethod())) { - $this->unsupportedServerStreamingCall($call, $options); + $this->throwUnsupportedException(); } $headers = self::buildCommonHeaders($options); diff --git a/Gax/src/Testing/MockGrpcTransport.php b/Gax/tests/Testing/MockGrpcTransport.php similarity index 95% rename from Gax/src/Testing/MockGrpcTransport.php rename to Gax/tests/Testing/MockGrpcTransport.php index d6af2fe4f4b7..8b1baa203146 100644 --- a/Gax/src/Testing/MockGrpcTransport.php +++ b/Gax/tests/Testing/MockGrpcTransport.php @@ -1,4 +1,6 @@ mockCall; } + // phpcs:enable + /** * @param string $method * @param callable $deserialize diff --git a/Gax/tests/Unit/ServiceAddressTraitTest.php b/Gax/tests/Unit/ApiEndpointTraitTest.php similarity index 62% rename from Gax/tests/Unit/ServiceAddressTraitTest.php rename to Gax/tests/Unit/ApiEndpointTraitTest.php index ba5cf81c7a64..807f2beee0d7 100644 --- a/Gax/tests/Unit/ServiceAddressTraitTest.php +++ b/Gax/tests/Unit/ApiEndpointTraitTest.php @@ -17,29 +17,25 @@ namespace Google\ApiCore\Tests\Unit; -use Google\ApiCore\ServiceAddressTrait; +use Google\ApiCore\ApiEndpointTrait; use Google\ApiCore\ValidationException; use PHPUnit\Framework\TestCase; -/** - * @todo (dwsupplee) serviceAddress is deprecated now in favor of - * apiEndpoint. Rename the tests/variables in our next major release. - */ -class ServiceAddressTraitTest extends TestCase +class ApiEndpointTraitTest extends TestCase { - use ServiceAddressTrait; + use ApiEndpointTrait; /** - * @dataProvider normalizeServiceAddressData + * @dataProvider normalizeApiEndpointData */ - public function testNormalizeServiceAddress($serviceAddressString, $expectedAddress, $expectedPort) + public function testNormalizeApiEndpoint($apiEndpointString, $expectedAddress, $expectedPort) { - list($actualAddress, $actualPort) = self::normalizeServiceAddress($serviceAddressString); + list($actualAddress, $actualPort) = self::normalizeApiEndpoint($apiEndpointString); $this->assertSame($expectedAddress, $actualAddress); $this->assertSame($expectedPort, $actualPort); } - public function normalizeServiceAddressData() + public function normalizeApiEndpointData() { return [ ['simple.com:123', 'simple.com', '123'], @@ -49,17 +45,17 @@ public function normalizeServiceAddressData() } /** - * @dataProvider normalizeServiceAddressInvalidData + * @dataProvider normalizeApiEndpointInvalidData */ - public function testNormalizeServiceAddressInvalid($serviceAddressString) + public function testNormalizeApiEndpointInvalid($apiEndpointString) { $this->expectException(ValidationException::class); $this->expectExceptionMessage('Invalid apiEndpoint'); - self::normalizeServiceAddress($serviceAddressString); + self::normalizeApiEndpoint($apiEndpointString); } - public function normalizeServiceAddressInvalidData() + public function normalizeApiEndpointInvalidData() { return [ ['too.many:colons:123'], diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index e6cec22e1a3b..3715a14c82cd 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -39,7 +39,6 @@ use Google\ApiCore\ClientStream; use Google\ApiCore\CredentialsWrapper; use Google\ApiCore\GapicClientTrait; -use Google\ApiCore\LongRunning\OperationsClient; use Google\ApiCore\Middleware\MiddlewareInterface; use Google\ApiCore\OperationResponse; use Google\ApiCore\RequestParamsHeaderDescriptor; @@ -54,6 +53,7 @@ use Google\ApiCore\Transport\TransportInterface; use Google\ApiCore\ValidationException; use Google\Auth\FetchAuthTokenInterface; +use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\Operation; use Grpc\Gcp\Config; use GuzzleHttp\Promise\FulfilledPromise; @@ -68,6 +68,11 @@ class GapicClientTraitTest extends TestCase use ProphecyTrait; use TestTrait; + public static function setUpBeforeClass(): void + { + self::autoloadTestdata('mocks', 'Google'); + } + public function setUp(): void { $keyFilePath = __DIR__ . '/testdata/creds/json-key-file.json'; @@ -114,14 +119,16 @@ public function testHeadersOverwriteBehavior() 'x-goog-request-params' => ['name=foos%2F123%2Fbars%2F456'] ]; $transport = $this->prophesize(TransportInterface::class); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $transport->startUnaryCall( Argument::type(Call::class), [ 'headers' => $expectedHeaders, 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -130,7 +137,7 @@ public function testHeadersOverwriteBehavior() $client->set('agentHeader', $header); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); @@ -163,15 +170,13 @@ public function testMiddlewareOptionsIsPreservedByFilterAndVisibleToMiddlewares( ->shouldBeCalledOnce() ->willReturn($this->prophesize(PromiseInterface::class)->reveal()); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $client = new StubGapicClient(); $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); @@ -230,20 +235,14 @@ public function testMiddlewareOptionsPreservedByCallOptionsOnNewSurface() ->shouldBeCalledOnce() ->willReturn($this->prophesize(PromiseInterface::class)->reveal()); - $credentialsWrapper = CredentialsWrapper::build([ - "keyFile" => __DIR__ . "/testdata/creds/json-key-file.json" - ]); + $credentialsWrapper = CredentialsWrapper::build(); - $client = new class extends StubGapicClient { - protected function isNewClientSurface(): bool { - return true; - } - }; + $client = new StubGapicClient(); $client->set("agentHeader", []); $client->set( "retrySettings", - ["method" => $this->prophesize(RetrySettings::class)->reveal()] + ["method" => RetrySettings::constructDefault()] ); $client->set("transport", $transport->reveal()); $client->set("credentialsWrapper", $credentialsWrapper); @@ -302,14 +301,16 @@ public function testVersionedHeadersOverwriteBehavior() 'x-goog-request-params' => ['name=foos%2F123%2Fbars%2F456'], ]; $transport = $this->prophesize(TransportInterface::class); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $transport->startUnaryCall( Argument::type(Call::class), [ 'headers' => $expectedHeaders, 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -318,7 +319,7 @@ public function testVersionedHeadersOverwriteBehavior() $client->set('agentHeader', $header); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); @@ -376,7 +377,7 @@ public function testConfigureCallConstructionOptionsAcceptsRetryObjectOrArray() public function testStartOperationsCall() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'longRunning' => [ 'operationReturnType' => 'operationType', @@ -397,7 +398,7 @@ public function testStartOperationsCall() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $longRunningDescriptors]); $message = new MockRequest(); $operationsClient = $this->prophesize(OperationsClient::class); @@ -421,7 +422,7 @@ public function testStartOperationsCall() public function testStartApiCallOperation() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'callType' => Call::LONGRUNNING_CALL, @@ -444,7 +445,7 @@ public function testStartApiCallOperation() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $longRunningDescriptors]); $operationsClient = $this->prophesize(OperationsClient::class); $client->set('operationsClient', $operationsClient->reveal()); @@ -467,7 +468,7 @@ public function testStartApiCallOperation() public function testStartApiCallCustomOperation() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'callType' => Call::LONGRUNNING_CALL, @@ -491,7 +492,7 @@ public function testStartApiCallCustomOperation() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $longRunningDescriptors]); $operationsClient = $this->prophesize(OperationsClient::class)->reveal(); $client->set('operationsClient', $operationsClient); @@ -573,7 +574,7 @@ public function startApiCallExceptions() public function testStartApiCallUnary() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $unaryDescriptors = [ 'callType' => Call::UNARY_CALL, 'responseType' => 'Google\Longrunning\Operation', @@ -594,7 +595,7 @@ public function testStartApiCallUnary() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $unaryDescriptors]); $request = new MockRequest(); @@ -607,7 +608,7 @@ public function testStartApiCallUnary() public function testStartApiCallPaged() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $pagedDescriptors = [ 'callType' => Call::PAGINATED_CALL, 'responseType' => 'Google\Longrunning\ListOperationsResponse', @@ -630,7 +631,7 @@ public function testStartApiCallPaged() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $pagedDescriptors]); $request = new MockRequest(); @@ -643,7 +644,7 @@ public function testStartApiCallPaged() public function testStartAsyncCall() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $unaryDescriptors = [ 'callType' => Call::UNARY_CALL, 'responseType' => 'Google\Longrunning\Operation' @@ -658,7 +659,7 @@ public function testStartAsyncCall() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['Method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['Method' => $retrySettings]); $client->set('descriptors', ['Method' => $unaryDescriptors]); $request = new MockRequest(); @@ -671,7 +672,7 @@ public function testStartAsyncCall() public function testStartAsyncCallPaged() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $pagedDescriptors = [ 'callType' => Call::PAGINATED_CALL, 'responseType' => 'Google\Longrunning\ListOperationsResponse', @@ -700,7 +701,7 @@ public function testStartAsyncCallPaged() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['Method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['Method' => $retrySettings]); $client->set('descriptors', ['Method' => $pagedDescriptors]); $request = new MockRequest(); @@ -846,34 +847,11 @@ public function createTransportDataInvalid() ], ]; return [ - [$apiEndpoint, null, $transportConfig], - [$apiEndpoint, ['transport' => 'weirdstring'], $transportConfig], - [$apiEndpoint, ['transport' => new \stdClass()], $transportConfig], - [$apiEndpoint, ['transport' => 'rest'], []], + [$apiEndpoint, 'weirdstring', $transportConfig], + [$apiEndpoint, 'rest', []], ]; } - public function testServiceAddressAlias() - { - $client = new StubGapicClient(); - $apiEndpoint = 'test.address.com:443'; - $updatedOptions = $client->buildClientOptions( - ['serviceAddress' => $apiEndpoint] - ); - $client->setClientOptions($updatedOptions); - - $this->assertEquals($apiEndpoint, $updatedOptions['apiEndpoint']); - $this->assertArrayNotHasKey('serviceAddress', $updatedOptions); - } - - public function testOperationClientClassOption() - { - $options = ['operationsClientClass' => CustomOperationsClient::class]; - $client = new StubGapicClient(); - $operationsClient = $client->createOperationsClient($options); - $this->assertInstanceOf(CustomOperationsClient::class, $operationsClient); - } - public function testAdditionalArgumentMethods() { $client = new StubGapicClient(); @@ -881,6 +859,7 @@ public function testAdditionalArgumentMethods() // Set the LRO descriptors we are testing. $longRunningDescriptors = [ 'longRunning' => [ + 'getOperationRequest' => \Google\CustomOperation\GetOperationRequest::class, 'additionalArgumentMethods' => [ 'getPageToken', 'getPageSize', @@ -900,7 +879,6 @@ public function testAdditionalArgumentMethods() // Set up things for the mock call to work. $client->set('credentialsWrapper', CredentialsWrapper::build([])); $client->set('agentHeader', []); - $retrySettings = $this->prophesize(RetrySettings::class); $client->set('retrySettings', [ 'method.name' => RetrySettings::constructDefault() ]); @@ -915,7 +893,9 @@ public function testAdditionalArgumentMethods() // Create mock operations client to test the additional arguments from // the request object are used. $operationsClient = $this->prophesize(CustomOperationsClient::class); - $operationsClient->getOperation('test-123', 'abc', 100) + $operationsClient->getOperation( + \Google\CustomOperation\GetOperationRequest::build('abc', 100, 'test-123') + ) ->shouldBeCalledOnce(); $operationResponse = $client->startOperationsCall( @@ -959,7 +939,7 @@ public function setClientOptionsData() } $expectedProperties = [ 'serviceName' => 'test.interface.v1.api', - 'agentHeader' => AgentHeader::buildAgentHeader([]) + ['User-Agent' => ['gcloud-php-legacy/']], + 'agentHeader' => AgentHeader::buildAgentHeader([]), 'retrySettings' => $expectedRetrySettings, ]; return [ @@ -1096,6 +1076,19 @@ public function buildRequestHeaderParams() ]; } + public function testServiceAddressOption() + { + $client = new StubGapicClient(); + $apiEndpoint = 'test.address.com:443'; + $updatedOptions = $client->buildClientOptions( + ['serviceAddress' => $apiEndpoint] + ); + $client->setClientOptions($updatedOptions); + + $this->assertEquals($apiEndpoint, $updatedOptions['apiEndpoint']); + $this->assertArrayNotHasKey('serviceAddress', $updatedOptions); + } + public function testModifyClientOptions() { $options = []; @@ -1111,7 +1104,7 @@ public function testModifyClientOptions() private function buildClientToTestModifyCallMethods($clientClass = null) { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'longRunning' => [ @@ -1130,21 +1123,19 @@ private function buildClientToTestModifyCallMethods($clientClass = null) ], ]; $transport = $this->prophesize(TransportInterface::class); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $clientClass = $clientClass ?: StubGapicClientExtension::class; $client = new $clientClass(); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); $client->set('retrySettings', [ - 'simpleMethod' => $retrySettings->reveal(), - 'longRunningMethod' => $retrySettings->reveal(), - 'pagedMethod' => $retrySettings->reveal(), - 'bidiStreamingMethod' => $retrySettings->reveal(), - 'clientStreamingMethod' => $retrySettings->reveal(), - 'serverStreamingMethod' => $retrySettings->reveal(), + 'simpleMethod' => $retrySettings, + 'longRunningMethod' => $retrySettings, + 'pagedMethod' => $retrySettings, + 'bidiStreamingMethod' => $retrySettings, + 'clientStreamingMethod' => $retrySettings, + 'serverStreamingMethod' => $retrySettings, ]); $client->set('descriptors', [ 'longRunningMethod' => $longRunningDescriptors, @@ -1163,9 +1154,10 @@ public function testModifyUnaryCallFromStartCall() 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1189,10 +1181,11 @@ public function testModifyUnaryCallFromOperationsCall() 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]), - 'metadataReturnType' => 'metadataType' + 'credentialsWrapper' => CredentialsWrapper::build(), + 'metadataReturnType' => 'metadataType', + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1217,9 +1210,10 @@ public function testModifyUnaryCallFromGetPagedListResponse() 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1245,9 +1239,10 @@ public function testModifyStreamingCallFromStartCall($callArgs, $expectedMethod, 'custom' => ['addModifyStreamingCallable' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1323,9 +1318,12 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() [ 'headers' => AgentHeader::buildAgentHeader([]) + [ 'X-Goog-User-Project' => [$quotaProject], - 'User-Agent' => ['gcloud-php-legacy/'] ], - 'credentialsWrapper' => $credentialsWrapper->reveal() + 'credentialsWrapper' => $credentialsWrapper->reveal(), + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1340,7 +1338,7 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() $client->setClientOptions($updatedOptions); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->startCall( 'method', @@ -1350,7 +1348,7 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() public function testDefaultAudience() { - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $credentialsWrapper = $this->prophesize(CredentialsWrapper::class) ->reveal(); $transport = $this->prophesize(TransportInterface::class); @@ -1361,6 +1359,10 @@ public function testDefaultAudience() 'audience' => 'https://service-address/', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1371,7 +1373,7 @@ public function testDefaultAudience() $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method.name' => $retrySettings->reveal()] + ['method.name' => $retrySettings] ); $client->set('transport', $transport->reveal()); $client->startCall('method.name', 'decodeType'); @@ -1383,6 +1385,10 @@ public function testDefaultAudience() 'audience' => 'custom-audience', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1395,7 +1401,7 @@ public function testDefaultAudience() public function testDefaultAudienceWithOperations() { - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $credentialsWrapper = $this->prophesize(CredentialsWrapper::class) ->reveal(); $transport = $this->prophesize(TransportInterface::class); @@ -1406,7 +1412,11 @@ public function testDefaultAudienceWithOperations() 'audience' => 'https://service-address/', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, - 'metadataReturnType' => 'metadataType' + 'metadataReturnType' => 'metadataType', + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1427,7 +1437,7 @@ public function testDefaultAudienceWithOperations() $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method.name' => $retrySettings->reveal()] + ['method.name' => $retrySettings] ); $client->set('transport', $transport->reveal()); $client->set('descriptors', ['method.name' => $longRunningDescriptors]); @@ -1444,7 +1454,7 @@ public function testDefaultAudienceWithOperations() public function testDefaultAudienceWithPagedList() { - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $credentialsWrapper = $this->prophesize(CredentialsWrapper::class) ->reveal(); $transport = $this->prophesize(TransportInterface::class); @@ -1455,6 +1465,10 @@ public function testDefaultAudienceWithPagedList() 'audience' => 'https://service-address/', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1474,7 +1488,7 @@ public function testDefaultAudienceWithPagedList() $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method.name' => $retrySettings->reveal()] + ['method.name' => $retrySettings] ); $client->set('transport', $transport->reveal()); $client->set('descriptors', [ @@ -1562,9 +1576,10 @@ public function __invoke(Call $call, array $options) 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1632,9 +1647,10 @@ public function __invoke(Call $call, array $options) 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1702,13 +1718,14 @@ public function __invoke(Call $call, array $options) 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) - ->shouldBeCalledOnce() - ->willReturn(new FulfilledPromise(new Operation())); + ->shouldBeCalledOnce() + ->willReturn(new FulfilledPromise(new Operation())); $client->startCall( 'simpleMethod', @@ -1720,12 +1737,8 @@ public function __invoke(Call $call, array $options) $this->assertEquals(['middleware2', 'middleware1'], $callOrder); } - public function testInvalidClientOptionsTypeThrowsExceptionForV2SurfaceOnly() + public function testInvalidClientOptionsTypeThrowsException() { - // v1 client - new StubGapicClient(['apiEndpoint' => ['foo']]); - $this->assertTrue(true, 'Test made it to here without throwing an exception'); - $this->expectException(\TypeError::class); $this->expectExceptionMessage( PHP_MAJOR_VERSION < 8 @@ -1735,7 +1748,6 @@ public function testInvalidClientOptionsTypeThrowsExceptionForV2SurfaceOnly() . '($apiEndpoint) must be of type ?string, array given' ); - // v2 client new GapicV2SurfaceClient(['apiEndpoint' => ['foo']]); } @@ -1749,10 +1761,8 @@ public function testCallOptionsForV2Surface() Argument::type(Call::class), [ 'headers' => AgentHeader::buildAgentHeader([]) + ['Foo' => 'Bar'], - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]), - 'timeoutMillis' => null, // adds null timeoutMillis, + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, // adds null timeoutMillis, 'transportOptions' => [], 'metadataCallback' => null, 'middlewareOptions' => null, @@ -1774,32 +1784,6 @@ public function testCallOptionsForV2Surface() )->wait(); } - public function testInvalidCallOptionsTypeForV1SurfaceDoesNotThrowException() - { - list($client, $transport) = $this->buildClientToTestModifyCallMethods(); - - $transport->startUnaryCall( - Argument::type(Call::class), - [ - 'transportOptions' => ['custom' => ['addModifyUnaryCallableOption' => true]], - 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]), - 'timeoutMillis' => 'blue', // invalid type, this is ignored - ] - ) - ->shouldBeCalledOnce() - ->willReturn(new FulfilledPromise(new Operation())); - - $client->startCall( - 'simpleMethod', - 'decodeType', - ['timeoutMillis' => 'blue'], - new MockRequest(), - )->wait(); - } - public function testInvalidCallOptionsTypeForV2SurfaceThrowsException() { $this->expectException(\TypeError::class); @@ -1821,25 +1805,6 @@ public function testInvalidCallOptionsTypeForV2SurfaceThrowsException() )->wait(); } - public function testSurfaceAgentHeaders() - { - // V1 does not contain new headers - $client = new RestOnlyGapicClient([ - 'gapicVersion' => '0.0.2', - ]); - $agentHeader = $client->getAgentHeader(); - $this->assertStringContainsString(' gapic/0.0.2 ', $agentHeader['x-goog-api-client'][0]); - $this->assertEquals('gcloud-php-legacy/0.0.2', $agentHeader['User-Agent'][0]); - - // V2 contains new headers - $client = new GapicV2SurfaceClient([ - 'gapicVersion' => '0.0.1', - ]); - $agentHeader = $client->getAgentHeader(); - $this->assertStringContainsString(' gapic/0.0.1 ', $agentHeader['x-goog-api-client'][0]); - $this->assertEquals('gcloud-php-new/0.0.1', $agentHeader['User-Agent'][0]); - } - public function testApiKeyOption() { $transport = $this->prophesize(TransportInterface::class); @@ -2153,7 +2118,7 @@ public function getOperationsClient() class CustomOperationsClient { - public function getOperation($name, $arg1, $arg2) + public function getOperation($request) { } } diff --git a/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php b/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php index 7d7dac94189e..1c264ae76ee9 100644 --- a/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php @@ -33,9 +33,9 @@ namespace Google\ApiCore\Tests\Unit\Middleware; use Google\ApiCore\Call; -use Google\ApiCore\LongRunning\OperationsClient; +use Google\LongRunning\Client\OperationsClient; use Google\ApiCore\Middleware\OperationsMiddleware; -use Google\ApiCore\Testing\MockResponse; +use Google\ApiCore\Testing\MockRequest; use GuzzleHttp\Promise\Promise; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; @@ -50,11 +50,11 @@ public function testOperationNameMethodDescriptor() $operationsClient = $this->prophesize(OperationsClient::class); $descriptor = [ - 'operationNameMethod' => 'getNumber' + 'operationNameMethod' => 'getPageToken' ]; $handler = function (Call $call, $options) use (&$callCount) { return $promise = new Promise(function () use (&$promise) { - $response = new MockResponse(['number' => 123]); + $response = new MockRequest(['page_token' => 'abc']); $promise->resolve($response); }); }; @@ -64,6 +64,6 @@ public function testOperationNameMethodDescriptor() [] )->wait(); - $this->assertEquals(123, $response->getName()); + $this->assertEquals('abc', $response->getName()); } } diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 0901be1bb5c8..4ef50bb3ac77 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -38,14 +38,14 @@ use Google\CustomOperation\CustomOperationWithErrorAnnotations; use Google\CustomOperation\DeleteOperationRequest as CustomDeleteOperationRequest; use Google\CustomOperation\GetOperationRequest as CustomGetOperationRequest; -use Google\ApiCore\LongRunning\OperationsClient; use Google\ApiCore\OperationResponse; use Google\LongRunning\CancelOperationRequest; -use Google\LongRunning\Client\OperationsClient as LROOperationsClient; +use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\DeleteOperationRequest; use Google\LongRunning\GetOperationRequest; use Google\LongRunning\Operation; use Google\Protobuf\Any; +use Google\Protobuf\Internal\Message; use Google\Rpc\Code; use LogicException; use PHPUnit\Framework\TestCase; @@ -78,7 +78,7 @@ public function provideOperationsClients() { return [ [$this->createOperationsClient()], - [$this->prophesize(LROOperationsClient::class)->reveal()], + [$this->prophesize(OperationsClient::class)->reveal()], ]; } @@ -237,13 +237,13 @@ public function testCustomOperation() ->shouldBeCalledOnce() ->willReturn(null); $operationClient = $this->prophesize(CustomOperationClient::class); - $operationClient->getMyOperationPlease($operationName, 'arg1', 'arg2') + $operationClient->getMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn($operation->reveal()); - $operationClient->cancelMyOperationPlease($operationName, 'arg1', 'arg2') + $operationClient->cancelMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn(true); - $operationClient->deleteMyOperationPlease($operationName, 'arg1', 'arg2') + $operationClient->deleteMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn(true); $options = [ @@ -481,9 +481,9 @@ public function testPollingCastToInt() $this->assertEquals($op->getSleeps(), [3, 4, 6]); } - public function testReloadWithLROOperationsClient() + public function testReloadWithOperationsClient() { - $operationClient = $this->prophesize(LROOperationsClient::class); + $operationClient = $this->prophesize(OperationsClient::class); $request = new GetOperationRequest(['name' => 'test-123']); $operationClient->getOperation($request) ->shouldBeCalledOnce() @@ -493,9 +493,9 @@ public function testReloadWithLROOperationsClient() $operationResponse->reload(); } - public function testCancelWithLROOperationsClient() + public function testCancelWithOperationsClient() { - $operationClient = $this->prophesize(LROOperationsClient::class); + $operationClient = $this->prophesize(OperationsClient::class); $request = new CancelOperationRequest(['name' => 'test-123']); $operationClient->cancelOperation($request) ->shouldBeCalledOnce(); @@ -504,9 +504,9 @@ public function testCancelWithLROOperationsClient() $operationResponse->cancel(); } - public function testDeleteWithLROOperationsClient() + public function testDeleteWithOperationsClient() { - $operationClient = $this->prophesize(LROOperationsClient::class); + $operationClient = $this->prophesize(OperationsClient::class); $request = new DeleteOperationRequest(['name' => 'test-123']); $operationClient->deleteOperation($request) ->shouldBeCalledOnce(); @@ -555,7 +555,7 @@ private function createOperationClient($reloadCount) $opClient = $this->prophesize(OperationsClient::class); - $opClient->getOperation(Argument::type('string')) + $opClient->getOperation(Argument::type('object')) ->shouldBeCalledTimes($reloadCount) ->willReturn(...$consecutiveCalls); diff --git a/Gax/tests/Unit/Transport/GrpcTransportTest.php b/Gax/tests/Unit/Transport/GrpcTransportTest.php index f2c69e1f0401..66a0616e1c86 100644 --- a/Gax/tests/Unit/Transport/GrpcTransportTest.php +++ b/Gax/tests/Unit/Transport/GrpcTransportTest.php @@ -35,8 +35,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\Call; use Google\ApiCore\CredentialsWrapper; -use Google\ApiCore\Testing\MockGrpcTransport; use Google\ApiCore\Testing\MockRequest; +use Google\ApiCore\Tests\Testing\MockGrpcTransport; use Google\ApiCore\Tests\Unit\TestTrait; use Google\ApiCore\Transport\GrpcTransport; use Google\ApiCore\ValidationException; @@ -50,7 +50,6 @@ use Grpc\CallInvoker; use Grpc\ChannelCredentials; use Grpc\ClientStreamingCall; -use Grpc\Interceptor; use Grpc\ServerStreamingCall; use Grpc\UnaryCall; use GuzzleHttp\Promise\Promise; @@ -668,13 +667,8 @@ public function interceptorDataProvider() { $this->autoloadTestdata('mocks', __NAMESPACE__); - $deprecatedInterceptors = (new \ReflectionClass(Interceptor::class)) - ->getMethod('interceptUnaryUnary') - ->getParameters()[3] - ->getName() === 'metadata'; - - $interceptor = $deprecatedInterceptors ? new DeprecatedTestInterceptor(): new TestInterceptor(); - $unaryInterceptor = $deprecatedInterceptors ? new DeprecatedTestUnaryInterceptor(): new TestUnaryInterceptor(); + $interceptor = new TestInterceptor(); + $unaryInterceptor = new TestUnaryInterceptor(); return [ [ diff --git a/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php b/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php index 7e2783ccb015..31af507fad80 100644 --- a/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php +++ b/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php @@ -6,9 +6,9 @@ class GetOperationRequest { public string $name; public string $arg2; - public string $arg3; + public string|int $arg3; - public static function build(string $arg2, string $arg3, string $name): static + public static function build(string $arg2, string|int $arg3, string $name): static { $request = new static(); $request->name = $name; diff --git a/Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php b/Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php deleted file mode 100644 index cc625ae4477f..000000000000 --- a/Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - UnaryInterceptorInterface - \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface - - Temporary class to support an interceptor-like interface until gRPC interceptor support is -available. - - - - - - - - interceptUnaryUnary - \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface::interceptUnaryUnary() - - - method - - string - - - - argument - - \Google\Protobuf\Internal\Message - - - - deserialize - - callable - - - - metadata - - array - - - - options - - array - - - - continuation - - callable - - - - - - - - - - - - - - - - - - - - - From 33e0d2325b95913a1b92d0b6b755cb1e58ff7f30 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 18:06:47 +0000 Subject: [PATCH 03/10] test(Gax): add interface tests, PHPDocs, and DeprecatedOperationsClient alias --- Gax/src/GapicClientTrait.php | 10 +- Gax/src/IamProviderInterface.php | 66 ++++++++ .../LongRunningOperationProviderInterface.php | 20 +++ Gax/src/ServiceInterface.php | 77 +++++++++ Gax/tests/Unit/GapicClientTraitTest.php | 153 +++++++++++++++++- 5 files changed, 319 insertions(+), 7 deletions(-) diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index e0e54594eae7..af39308499a8 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -32,7 +32,7 @@ namespace Google\ApiCore; -use Google\ApiCore\LongRunning\OperationsClient; +use Google\ApiCore\LongRunning\OperationsClient as DeprecatedOperationsClient; use Google\ApiCore\Middleware\CredentialsWrapperMiddleware; use Google\ApiCore\Middleware\FixedHeaderMiddleware; use Google\ApiCore\Middleware\OperationsMiddleware; @@ -50,7 +50,7 @@ use Google\ApiCore\Transport\RestTransport; use Google\ApiCore\Transport\TransportInterface; use Google\Auth\FetchAuthTokenInterface; -use Google\LongRunning\Client\OperationsClient as V2OperationsClient; +use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\Operation; use Google\Protobuf\Internal\Message; use GuzzleHttp\Promise\PromiseInterface; @@ -455,7 +455,7 @@ private function createTransport( /** * @param array $options - * @return OperationsClient|V2OperationsClient|object + * @return DeprecatedOperationsClient|OperationsClient|object */ protected function createOperationsClient(array $options) { @@ -472,8 +472,8 @@ protected function createOperationsClient(array $options) // operationsClientClass option $defaultClass = $this->isBackwardsCompatibilityMode() - ? OperationsClient::class - : V2OperationsClient::class; + ? DeprecatedOperationsClient::class + : OperationsClient::class; $operationsClientClass = $this->pluck('operationsClientClass', $options, false) ?: $defaultClass; return new $operationsClientClass($options); diff --git a/Gax/src/IamProviderInterface.php b/Gax/src/IamProviderInterface.php index 5a55183e0c99..92b41802ee31 100644 --- a/Gax/src/IamProviderInterface.php +++ b/Gax/src/IamProviderInterface.php @@ -40,12 +40,78 @@ use Google\Cloud\Iam\V1\TestIamPermissionsRequest; use Google\Cloud\Iam\V1\TestIamPermissionsResponse; +/** + * Interface implemented by GAPIC service clients that expose IAM policy + * management methods (`getIamPolicy`, `setIamPolicy`, and `testIamPermissions`). + */ interface IamProviderInterface { + /** + * Gets the access control policy for a resource. Returns an empty policy + * if the resource exists and does not have a policy set. + * + * @param GetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see \Google\ApiCore\RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see \Google\ApiCore\RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ public function getIamPolicy(GetIamPolicyRequest $request, array $callOptions = []): Policy; + /** + * Sets the access control policy on the specified resource. Replaces + * any existing policy. + * + * Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` + * errors. + * + * @param SetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see \Google\ApiCore\RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see \Google\ApiCore\RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ public function setIamPolicy(SetIamPolicyRequest $request, array $callOptions = []): Policy; + /** + * 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. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param TestIamPermissionsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see \Google\ApiCore\RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see \Google\ApiCore\RetrySettings} for example usage. + * } + * + * @return TestIamPermissionsResponse + * + * @throws ApiException Thrown if the API call fails. + */ public function testIamPermissions( TestIamPermissionsRequest $request, array $callOptions = [] diff --git a/Gax/src/LongRunningOperationProviderInterface.php b/Gax/src/LongRunningOperationProviderInterface.php index a030dc8864a5..ff9c39a35bac 100644 --- a/Gax/src/LongRunningOperationProviderInterface.php +++ b/Gax/src/LongRunningOperationProviderInterface.php @@ -36,9 +36,29 @@ use Google\LongRunning\Client\OperationsClient; +/** + * Interface implemented by GAPIC service clients that support standard + * Google Cloud Long-Running Operations (LROs). + */ interface LongRunningOperationProviderInterface { + /** + * 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|null $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ public function resumeOperation(string $operationName, ?string $methodName = null): OperationResponse; + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ public function getOperationsClient(): OperationsClient; } diff --git a/Gax/src/ServiceInterface.php b/Gax/src/ServiceInterface.php index 75547f57b3d7..98f445053105 100644 --- a/Gax/src/ServiceInterface.php +++ b/Gax/src/ServiceInterface.php @@ -34,13 +34,90 @@ namespace Google\ApiCore; +/** + * Interface implemented by all GAPIC service clients, defining common lifecycle, + * scope, and middleware configuration methods. + */ interface ServiceInterface { + /** + * Add a middleware to the call stack by providing a callable which will be + * invoked at the start of each call, and will return an instance of + * {@see \Google\ApiCore\Middleware\MiddlewareInterface} when invoked. + * + * The callable must have the following method signature: + * + * callable(MiddlewareInterface): MiddlewareInterface + * + * An implementation may look something like this: + * ``` + * $client->addMiddleware(function (MiddlewareInterface $handler) { + * return new class ($handler) implements MiddlewareInterface { + * public function __construct(private MiddlewareInterface $handler) { + * } + * + * public function __invoke(Call $call, array $options) { + * // modify call and options (pre-request) + * $response = ($this->handler)($call, $options); + * // modify the response (post-request) + * return $response; + * } + * }; + * }); + * ``` + * + * @param callable $middlewareCallable A callable which returns an instance + * of {@see \Google\ApiCore\Middleware\MiddlewareInterface} when invoked with a + * MiddlewareInterface instance as its first argument. + * @return void + */ public function addMiddleware(callable $middlewareCallable): void; + /** + * Prepend a middleware to the call stack by providing a callable which will be + * invoked at the end of each call, and will return an instance of + * {@see \Google\ApiCore\Middleware\MiddlewareInterface} when invoked. + * + * The callable must have the following method signature: + * + * callable(MiddlewareInterface): MiddlewareInterface + * + * An implementation may look something like this: + * ``` + * $client->prependMiddleware(function (MiddlewareInterface $handler) { + * return new class ($handler) implements MiddlewareInterface { + * public function __construct(private MiddlewareInterface $handler) { + * } + * + * public function __invoke(Call $call, array $options) { + * // modify call and options (pre-request) + * $response = ($this->handler)($call, $options); + * // modify the response (post-request) + * return $response; + * } + * }; + * }); + * ``` + * + * @param callable $middlewareCallable A callable which returns an instance + * of {@see \Google\ApiCore\Middleware\MiddlewareInterface} when invoked with a + * MiddlewareInterface instance as its first argument. + * @return void + */ public function prependMiddleware(callable $middlewareCallable): void; + /** + * Get the default scopes required by the service. + * + * @return array + */ public static function getServiceScopes(): array; + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @return void + */ public function close(): void; } diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index e6cec22e1a3b..0c252860b088 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -39,12 +39,15 @@ use Google\ApiCore\ClientStream; use Google\ApiCore\CredentialsWrapper; use Google\ApiCore\GapicClientTrait; -use Google\ApiCore\LongRunning\OperationsClient; +use Google\ApiCore\IamProviderInterface; +use Google\ApiCore\LongRunning\OperationsClient as DeprecatedOperationsClient; +use Google\ApiCore\LongRunningOperationProviderInterface; use Google\ApiCore\Middleware\MiddlewareInterface; use Google\ApiCore\OperationResponse; use Google\ApiCore\RequestParamsHeaderDescriptor; use Google\ApiCore\RetrySettings; use Google\ApiCore\ServerStream; +use Google\ApiCore\ServiceInterface; use Google\ApiCore\Testing\MockRequest; use Google\ApiCore\Testing\MockRequestBody; use Google\ApiCore\Testing\MockResponse; @@ -54,6 +57,13 @@ use Google\ApiCore\Transport\TransportInterface; use Google\ApiCore\ValidationException; use Google\Auth\FetchAuthTokenInterface; +use Google\Cloud\Iam\V1\GetIamPolicyRequest; +use Google\Cloud\Iam\V1\Policy; +use Google\Cloud\Iam\V1\SetIamPolicyRequest; +use Google\Cloud\Iam\V1\TestIamPermissionsRequest; +use Google\Cloud\Iam\V1\TestIamPermissionsResponse; +use Google\LongRunning\Client\OperationsClient; +use Google\LongRunning\GetOperationRequest; use Google\LongRunning\Operation; use Grpc\Gcp\Config; use GuzzleHttp\Promise\FulfilledPromise; @@ -1968,6 +1978,112 @@ public function testGetServiceScopes() DefaultScopeAndAudienceGapicClient::getServiceScopes() ); } + + public function testCreateOperationsClientDefaultClass() + { + $v1Client = new StubGapicClient(); + $this->assertInstanceOf( + DeprecatedOperationsClient::class, + $v1Client->createOperationsClient([]) + ); + + $v2Client = new GapicV2SurfaceClient(); + $this->assertInstanceOf( + OperationsClient::class, + $v2Client->getOperationsClient() + ); + } + + public function testServiceInterface() + { + $transport = $this->prophesize(TransportInterface::class); + $transport->close()->shouldBeCalledOnce(); + + $client = new GapicV2SurfaceClient([ + 'transport' => $transport->reveal(), + ]); + + $this->assertInstanceOf(ServiceInterface::class, $client); + $this->assertEquals([], GapicV2SurfaceClient::getServiceScopes()); + $client->close(); + } + + public function testLongRunningOperationProviderInterface() + { + $operationsClient = $this->prophesize(OperationsClient::class); + $operationsClient->getOperation( + Argument::that(fn (GetOperationRequest $req) => $req->getName() === 'operations/test-op') + ) + ->shouldBeCalledOnce() + ->willReturn(new Operation(['name' => 'operations/test-op', 'done' => true])); + + $client = new GapicV2SurfaceClient([ + 'operationsClient' => $operationsClient->reveal(), + ]); + + $this->assertInstanceOf(LongRunningOperationProviderInterface::class, $client); + $this->assertSame($operationsClient->reveal(), $client->getOperationsClient()); + + $operation = $client->resumeOperation('operations/test-op'); + $this->assertInstanceOf(OperationResponse::class, $operation); + $this->assertEquals('operations/test-op', $operation->getName()); + $this->assertTrue($operation->isDone()); + } + + public function testIamProviderInterface() + { + $policy = new Policy(); + $permissionsResponse = new TestIamPermissionsResponse(); + + $transport = $this->prophesize(TransportInterface::class); + $transport->startUnaryCall( + Argument::that(fn (Call $call) => $call->getMethod() === 'test.interface.v1.api/GetIamPolicy'), + Argument::type('array') + ) + ->shouldBeCalledOnce() + ->willReturn(new FulfilledPromise($policy)); + $transport->startUnaryCall( + Argument::that(fn (Call $call) => $call->getMethod() === 'test.interface.v1.api/SetIamPolicy'), + Argument::type('array') + ) + ->shouldBeCalledOnce() + ->willReturn(new FulfilledPromise($policy)); + $transport->startUnaryCall( + Argument::that(fn (Call $call) => $call->getMethod() === 'test.interface.v1.api/TestIamPermissions'), + Argument::type('array') + ) + ->shouldBeCalledOnce() + ->willReturn(new FulfilledPromise($permissionsResponse)); + + $client = new GapicV2SurfaceClient([ + 'transport' => $transport->reveal(), + ]); + $client->set('descriptors', [ + 'GetIamPolicy' => [ + 'callType' => Call::UNARY_CALL, + 'responseType' => Policy::class, + ], + 'SetIamPolicy' => [ + 'callType' => Call::UNARY_CALL, + 'responseType' => Policy::class, + ], + 'TestIamPermissions' => [ + 'callType' => Call::UNARY_CALL, + 'responseType' => TestIamPermissionsResponse::class, + ], + ]); + $retrySettings = $this->prophesize(RetrySettings::class)->reveal(); + $client->set('retrySettings', [ + 'GetIamPolicy' => $retrySettings, + 'SetIamPolicy' => $retrySettings, + 'TestIamPermissions' => $retrySettings, + ]); + + $this->assertInstanceOf(IamProviderInterface::class, $client); + $this->assertSame($policy, $client->getIamPolicy(new GetIamPolicyRequest())); + $this->assertSame($policy, $client->setIamPolicy(new SetIamPolicyRequest())); + $this->assertSame($permissionsResponse, $client->testIamPermissions(new TestIamPermissionsRequest())); + } } class StubGapicClient @@ -2158,7 +2274,7 @@ public function getOperation($name, $arg1, $arg2) } } -class GapicV2SurfaceClient +class GapicV2SurfaceClient implements ServiceInterface, LongRunningOperationProviderInterface, IamProviderInterface { use GapicClientTrait { startCall as public; @@ -2168,10 +2284,14 @@ class GapicV2SurfaceClient ClientDefaultsTrait::getClientDefaults insteadof GapicClientTrait; } + public static array $serviceScopes = []; + private OperationsClient $operationsClient; + public function __construct(array $options = []) { $clientOptions = $this->buildClientOptions($options); $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); } public function getAgentHeader() @@ -2179,4 +2299,33 @@ public function getAgentHeader() return $this->agentHeader; } + public function getOperationsClient(): OperationsClient + { + return $this->operationsClient; + } + + public function resumeOperation(string $operationName, ?string $methodName = null): OperationResponse + { + $options = $this->descriptors[$methodName]['longRunning'] ?? []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + public function getIamPolicy(GetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetIamPolicy', $request, $callOptions)->wait(); + } + + public function setIamPolicy(SetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('SetIamPolicy', $request, $callOptions)->wait(); + } + + public function testIamPermissions( + TestIamPermissionsRequest $request, + array $callOptions = [] + ): TestIamPermissionsResponse { + return $this->startApiCall('TestIamPermissions', $request, $callOptions)->wait(); + } } From ef0053d58fe9ab2b9411a66e92fd50815d97c9ff Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 20:42:15 +0000 Subject: [PATCH 04/10] fix(Gax): keep createOperationsClient private and use ReflectionMethod in test --- Gax/src/GapicClientTrait.php | 2 +- Gax/tests/Unit/GapicClientTraitTest.php | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index af39308499a8..77a20e4be2d6 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -457,7 +457,7 @@ private function createTransport( * @param array $options * @return DeprecatedOperationsClient|OperationsClient|object */ - protected function createOperationsClient(array $options) + private function createOperationsClient(array $options) { $this->pluckArray([ 'serviceName', diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 0c252860b088..e1115ad00ae4 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1988,9 +1988,10 @@ public function testCreateOperationsClientDefaultClass() ); $v2Client = new GapicV2SurfaceClient(); + $method = new \ReflectionMethod($v2Client, 'createOperationsClient'); $this->assertInstanceOf( OperationsClient::class, - $v2Client->getOperationsClient() + $method->invoke($v2Client, []) ); } @@ -2072,7 +2073,7 @@ public function testIamProviderInterface() 'responseType' => TestIamPermissionsResponse::class, ], ]); - $retrySettings = $this->prophesize(RetrySettings::class)->reveal(); + $retrySettings = RetrySettings::constructDefault(); $client->set('retrySettings', [ 'GetIamPolicy' => $retrySettings, 'SetIamPolicy' => $retrySettings, From 2a1cc798aabcb7c198b9aed98f70ae8638f01ec4 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 21:08:04 +0000 Subject: [PATCH 05/10] test(Gax): update CustomOperationClient mock signature for V2 --- .../mocks/CustomOperation/CustomOperationClient.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php index f7d992940db5..1b1b5def6ad2 100644 --- a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php +++ b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php @@ -4,7 +4,7 @@ interface CustomOperationClient { - public function getMyOperationPlease($name, $requiredArg1, $requiredArg2); - public function cancelMyOperationPlease($name, $requiredArg1, $requiredArg2); - public function deleteMyOperationPlease($name, $requiredArg1, $requiredArg2); + public function getMyOperationPlease($request); + public function cancelMyOperationPlease($request); + public function deleteMyOperationPlease($request); } From 43cb2f350916283dc4ad8dde00e6416e4fcf551c Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 21:48:54 +0000 Subject: [PATCH 06/10] test(Logging): replace deprecated Google\ApiCore\GPBType with Google\Protobuf\Internal\GPBType --- Logging/tests/Unit/Connection/GapicTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Logging/tests/Unit/Connection/GapicTest.php b/Logging/tests/Unit/Connection/GapicTest.php index 35265bc3a8ee..dbe501401944 100644 --- a/Logging/tests/Unit/Connection/GapicTest.php +++ b/Logging/tests/Unit/Connection/GapicTest.php @@ -17,7 +17,7 @@ namespace Google\Cloud\Logging\Tests\Unit\Connection; -use Google\ApiCore\GPBType; +use Google\Protobuf\Internal\GPBType; use Google\ApiCore\Page; use Google\ApiCore\PagedListResponse; use Google\Cloud\Logging\Connection\Grpc; From 8ebed501fef4a05d4bb23d4a616975049cc6ca95 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 5 Oct 2026 20:05:48 +0000 Subject: [PATCH 07/10] chore(Gax): remove audience from CallOptions and test audience override via middleware --- Gax/src/Options/CallOptions.php | 11 ----------- Gax/tests/Unit/GapicClientTraitTest.php | 16 +++++++++++++--- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/Gax/src/Options/CallOptions.php b/Gax/src/Options/CallOptions.php index 20577eadd72d..2b67bd8367f4 100644 --- a/Gax/src/Options/CallOptions.php +++ b/Gax/src/Options/CallOptions.php @@ -52,7 +52,6 @@ class CallOptions implements ArrayAccess, OptionsInterface private ?int $timeoutMillis; private array $transportOptions; private ?array $middlewareOptions; - private ?string $audience; /** @var callable|null $metadataCallback */ private $metadataCallback; @@ -95,9 +94,6 @@ private function fromArray(array $arr): void $this->setRetrySettings($arr['retrySettings'] ?? null); $this->setMetadataCallback($arr['metadataCallback'] ?? null); $this->setMiddlewareOptions($arr['middlewareOptions'] ?? null); - if (isset($arr['audience'])) { - $this->setAudience($arr['audience']); - } } /** @@ -176,11 +172,4 @@ public function setMetadataCallback(callable|null $metadataCallback): self return $this; } - - public function setAudience(?string $audience): self - { - $this->audience = $audience; - - return $this; - } } diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 556b90745983..00afda4dabfd 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1403,9 +1403,19 @@ public function testDefaultAudience() ->shouldBeCalledOnce() ->willReturn($this->prophesize(PromiseInterface::class)->reveal()); - $client->startCall('method.name', 'decodeType', [ - 'audience' => 'custom-audience', - ]); + $client->addMiddleware(function (MiddlewareInterface $handler) { + return new class ($handler) implements MiddlewareInterface { + public function __construct(private MiddlewareInterface $handler) + { + } + public function __invoke(Call $call, array $options): PromiseInterface + { + $options['audience'] = 'custom-audience'; + return ($this->handler)($call, $options); + } + }; + }); + $client->startCall('method.name', 'decodeType'); } public function testDefaultAudienceWithOperations() From c5183aaf1e6350a0d897cd47be427e26bc2419a2 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 12 Nov 2026 18:38:36 +0000 Subject: [PATCH 08/10] test(Gax): avoid PHP 8.5 null array offset deprecation in GapicV2SurfaceClient --- Gax/tests/Unit/GapicClientTraitTest.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index e1115ad00ae4..85153e5cb316 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -2307,7 +2307,9 @@ public function getOperationsClient(): OperationsClient public function resumeOperation(string $operationName, ?string $methodName = null): OperationResponse { - $options = $this->descriptors[$methodName]['longRunning'] ?? []; + $options = $methodName && isset($this->descriptors[$methodName]['longRunning']) + ? $this->descriptors[$methodName]['longRunning'] + : []; $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); $operation->reload(); return $operation; From f60493e60452600c1b9adbd7c0de1f376f1831b0 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 13 Nov 2026 19:27:53 +0000 Subject: [PATCH 09/10] chore: mark GPBType, GPBLabel, and V1 LongRunning OperationsClient as deprecated --- Gax/src/GPBLabel.php | 2 ++ Gax/src/GPBType.php | 2 ++ LongRunning/src/LongRunning/OperationsClient.php | 6 +++++- LongRunning/src/LongRunning/OperationsGrpcClient.php | 2 ++ 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Gax/src/GPBLabel.php b/Gax/src/GPBLabel.php index 18208cd64862..79cbf77e5bb8 100644 --- a/Gax/src/GPBLabel.php +++ b/Gax/src/GPBLabel.php @@ -34,6 +34,8 @@ /** * Container class for Protobuf label constants. See FieldDescriptorProto.Label in * https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto + * + * @deprecated Use {@see \Google\Protobuf\Internal\GPBLabel} instead. */ class GPBLabel { diff --git a/Gax/src/GPBType.php b/Gax/src/GPBType.php index e6f50fa93ec2..0fd2755b9445 100644 --- a/Gax/src/GPBType.php +++ b/Gax/src/GPBType.php @@ -34,6 +34,8 @@ /** * Container class for Protobuf type constants. See FieldDescriptorProto.Type in * https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto + * + * @deprecated Use {@see \Google\Protobuf\Internal\GPBType} instead. */ class GPBType { diff --git a/LongRunning/src/LongRunning/OperationsClient.php b/LongRunning/src/LongRunning/OperationsClient.php index 06fd3141386b..9f2886b1ef84 100644 --- a/LongRunning/src/LongRunning/OperationsClient.php +++ b/LongRunning/src/LongRunning/OperationsClient.php @@ -26,7 +26,11 @@ use Google\LongRunning\Gapic\OperationsGapicClient; -/** {@inheritdoc} */ +/** + * {@inheritdoc} + * + * @deprecated Please use the new service client {@see \Google\LongRunning\Client\OperationsClient}. + */ class OperationsClient extends OperationsGapicClient { // This class is intentionally empty, and is intended to hold manual additions to diff --git a/LongRunning/src/LongRunning/OperationsGrpcClient.php b/LongRunning/src/LongRunning/OperationsGrpcClient.php index 9d68de24641c..d592111d4e06 100644 --- a/LongRunning/src/LongRunning/OperationsGrpcClient.php +++ b/LongRunning/src/LongRunning/OperationsGrpcClient.php @@ -28,6 +28,8 @@ * Google Cloud Pub/Sub API) to receive the response. Any API service that * returns long-running operations should implement the `Operations` interface * so developers can have a consistent client experience. + * + * @deprecated Please use the new service client {@see \Google\LongRunning\Client\OperationsClient}. */ class OperationsGrpcClient extends \Grpc\BaseStub { From 7dc673539cc3af7fb03789b6fe55b3de92041a47 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 16 Nov 2026 23:02:40 +0000 Subject: [PATCH 10/10] chore(Gax): mark new client interfaces as experimental and internal --- Gax/src/IamProviderInterface.php | 3 +++ Gax/src/LongRunningOperationProviderInterface.php | 3 +++ Gax/src/ServiceInterface.php | 3 +++ 3 files changed, 9 insertions(+) diff --git a/Gax/src/IamProviderInterface.php b/Gax/src/IamProviderInterface.php index 92b41802ee31..e33621dabd16 100644 --- a/Gax/src/IamProviderInterface.php +++ b/Gax/src/IamProviderInterface.php @@ -43,6 +43,9 @@ /** * Interface implemented by GAPIC service clients that expose IAM policy * management methods (`getIamPolicy`, `setIamPolicy`, and `testIamPermissions`). + * + * @experimental + * @internal */ interface IamProviderInterface { diff --git a/Gax/src/LongRunningOperationProviderInterface.php b/Gax/src/LongRunningOperationProviderInterface.php index ff9c39a35bac..4635ad6d14d2 100644 --- a/Gax/src/LongRunningOperationProviderInterface.php +++ b/Gax/src/LongRunningOperationProviderInterface.php @@ -39,6 +39,9 @@ /** * Interface implemented by GAPIC service clients that support standard * Google Cloud Long-Running Operations (LROs). + * + * @experimental + * @internal */ interface LongRunningOperationProviderInterface { diff --git a/Gax/src/ServiceInterface.php b/Gax/src/ServiceInterface.php index 98f445053105..11ea07b3eb92 100644 --- a/Gax/src/ServiceInterface.php +++ b/Gax/src/ServiceInterface.php @@ -37,6 +37,9 @@ /** * Interface implemented by all GAPIC service clients, defining common lifecycle, * scope, and middleware configuration methods. + * + * @experimental + * @internal */ interface ServiceInterface {