From 71f53fc82cf5f3bf2583773f92db13a1cccb8ec7 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 30 Sep 2026 21:52:09 +0000 Subject: [PATCH 01/11] feat(Gax)!: refactor OperationResponse with OperationsClientInterface and CustomOperationsClient --- .../OperationResponseTraitTest.php | 56 ++-- Gax/MIGRATING.md | 8 + Gax/src/CustomOperationsClient.php | 242 ++++++++++++++++++ Gax/src/Middleware/OperationsMiddleware.php | 6 +- Gax/src/OperationResponse.php | 242 ++++-------------- Gax/src/OperationsClientInterface.php | 49 ++++ Gax/tests/Unit/OperationResponseTest.php | 12 +- Spanner/tests/Unit/BackupTest.php | 2 + Spanner/tests/Unit/DatabaseTest.php | 2 + .../tests/Unit/InstanceConfigurationTest.php | 5 +- Spanner/tests/Unit/InstanceTest.php | 2 + Spanner/tests/Unit/SpannerClientTest.php | 2 + 12 files changed, 409 insertions(+), 219 deletions(-) create mode 100644 Gax/src/CustomOperationsClient.php create mode 100644 Gax/src/OperationsClientInterface.php diff --git a/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php b/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php index dc61548dc79f..b090f9eb5931 100644 --- a/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php +++ b/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php @@ -18,10 +18,14 @@ namespace Google\Cloud\Core\Tests\Unit\LongRunning; use Google\ApiCore\OperationResponse; +use Google\ApiCore\OperationsClientInterface; use Google\ApiCore\Serializer; use Google\Cloud\Core\LongRunning\OperationResponseTrait; use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\LongRunning\LongRunningConnectionInterface; +use Google\LongRunning\Operation; +use Google\Protobuf\Any; +use Google\Rpc\Status; use Prophecy\Argument; use Google\Cloud\Audit\RequestMetadata; use Google\Cloud\Audit\AuthorizationInfo; @@ -43,6 +47,7 @@ class OperationResponseTraitTest extends TestCase const OPERATION_NAME = 'test-operation'; private $serializer; + private $operationsClient; private $lroResponseMappers = [ [ 'typeUrl' => self::METADATA_TYPE, @@ -61,6 +66,7 @@ public function setUp(): void return json_decode($json, true); }); $this->serializer = $serializer->reveal(); + $this->operationsClient = $this->prophesize(OperationsClientInterface::class)->reveal(); } public function testOperationWithResponse() @@ -74,7 +80,11 @@ public function testOperationWithResponse() 'caller_ip' => '127.8.9.10', // Sic(!) ]); $response = new Response(self::METADATA_TYPE, $meta, self::RESULT_TYPE, $result); - $operation = new OperationResponse(self::OPERATION_NAME, null, ['lastProtoResponse' => $response]); + $operation = new OperationResponse( + self::OPERATION_NAME, + $this->operationsClient, + ['lastProtoResponse' => $response] + ); $got = $this->operationToArray($operation, $this->serializer, $this->lroResponseMappers); $expected = [ @@ -95,17 +105,20 @@ public function testOperationWithResponse() public function testOperationWithError() { - $error = new AuthorizationInfo([ - 'resource' => 'any', - 'permission' => 'all', - 'granted' => true, + $error = new Status([ + 'code' => 1, + 'message' => 'error', ]); $meta = new RequestMetadata([ 'caller_ip' => '127.8.9.10', // Sic(!) ]); $response = new Response(self::METADATA_TYPE, $meta); $response->error = $error; - $operation = new OperationResponse(self::OPERATION_NAME, null, ['lastProtoResponse' => $response]); + $operation = new OperationResponse( + self::OPERATION_NAME, + $this->operationsClient, + ['lastProtoResponse' => $response] + ); $got = $this->operationToArray($operation, $this->serializer, $this->lroResponseMappers); $expected = [ @@ -115,9 +128,8 @@ public function testOperationWithError() 'typeUrl' => self::METADATA_TYPE, ], 'error' => [ - 'resource' => 'any', - 'permission' => 'all', - 'granted' => true, + 'code' => 1, + 'message' => 'error', ], 'response' => null, ]; @@ -126,7 +138,7 @@ public function testOperationWithError() public function testNullProtoResponse() { - $operation = new OperationResponse(self::OPERATION_NAME, null); + $operation = new OperationResponse(self::OPERATION_NAME, $this->operationsClient); $got = $this->operationToArray($operation, $this->serializer, $this->lroResponseMappers); $this->assertNull($got); } @@ -142,7 +154,11 @@ public function testLroCallable() 'caller_ip' => '127.8.9.10', ]); $response = new Response(self::METADATA_TYPE, $meta, self::RESULT_TYPE, $result); - $operation = new OperationResponse(self::OPERATION_NAME, null, ['lastProtoResponse' => $response]); + $operation = new OperationResponse( + self::OPERATION_NAME, + $this->operationsClient, + ['lastProtoResponse' => $response] + ); $connection = $this->prophesize(LongRunningConnectionInterface::class); $t = $this; @@ -166,7 +182,7 @@ public function testLroCallable() //@codingStandardsIgnoreStart -class Value +class Value extends Any { public $value; @@ -175,13 +191,13 @@ public function __construct($value = null) $this->value = $value; } - public function getValue() + public function getValue(): string { - return $this->value; + return (string) $this->value; } } -class Response extends \Google\Protobuf\Internal\Message +class Response extends Operation { public $metadataType; public $metadata; @@ -199,27 +215,27 @@ public function __construct($metaType, $metadata, $respType = null, $response = } } - public function getResponse() + public function getResponse(): ?Any { return new Value($this->response); } - public function getMetadata() + public function getMetadata(): ?Any { return new Value($this->metadata); } - public function getDone() + public function getDone(): bool { return (isset($this->response) or isset($this->error)); } - public function getError() + public function getError(): ?Status { return $this->error; } - public function serializeToJsonString($options = 0) + public function serializeToJsonString($options = 0): string { $result = [ 'done' => true, diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 7e8f2a66d409..2ce02d51584f 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -54,3 +54,11 @@ Update your `google/gax` dependency to `^2.0`: - Added `declare(strict_types=1)` across all `Google\ApiCore` files. - Added native parameter, property, and return type declarations across all `Google\ApiCore` classes, interfaces (`TransportInterface`, `MiddlewareInterface`, `ResourceTemplateInterface`, `ServerStreamingCallInterface`, `ResumableUploadTransportInterface`, `HeaderCredentialsInterface`), and traits. - **`PathTemplate::__construct(string $path)`** now requires a non-null `string`. +- **`OperationResponse`**: + - `__construct(string $operationName, object $operationsClient, array $options = [])` now requires non-null `$operationName` (`string`) and `$operationsClient` (`object`). + - `getName()` now returns non-nullable `string`. + - `getError()` now returns `?Google\Rpc\Status`. + - `getLastProtoResponse()` now returns `?Google\LongRunning\Operation`. + - `getOperationsClient()` now returns `Google\LongRunning\Client\OperationsClient|Google\ApiCore\OperationsClientInterface`. + - Custom operations clients (e.g., Compute's `ZoneOperationsClient`) and custom operation options are now encapsulated in `Google\ApiCore\CustomOperationsClient` (implementing `Google\ApiCore\OperationsClientInterface`), which normalizes custom operation proto responses into `Google\LongRunning\Operation`. + diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php new file mode 100644 index 000000000000..9cf111dd2164 --- /dev/null +++ b/Gax/src/CustomOperationsClient.php @@ -0,0 +1,242 @@ +client = $client; + $options += [ + 'getOperationMethod' => 'getOperation', + 'cancelOperationMethod' => 'cancelOperation', + 'deleteOperationMethod' => 'deleteOperation', + 'getOperationRequest' => GetOperationRequest::class, + 'cancelOperationRequest' => CancelOperationRequest::class, + 'deleteOperationRequest' => DeleteOperationRequest::class, + 'additionalOperationArguments' => [], + 'operationNameMethod' => 'getName', + 'operationStatusMethod' => 'getDone', + 'operationStatusDoneValue' => true, + 'operationErrorCodeMethod' => null, + 'operationErrorMessageMethod' => null, + ]; + + $this->getOperationMethod = $options['getOperationMethod']; + $this->cancelOperationMethod = $options['cancelOperationMethod']; + $this->deleteOperationMethod = $options['deleteOperationMethod']; + $this->getOperationRequest = $options['getOperationRequest']; + $this->cancelOperationRequest = $options['cancelOperationRequest']; + $this->deleteOperationRequest = $options['deleteOperationRequest']; + $this->additionalArgs = $options['additionalOperationArguments']; + $this->operationNameMethod = $options['operationNameMethod']; + $this->operationStatusMethod = $options['operationStatusMethod']; + $this->operationStatusDoneValue = $options['operationStatusDoneValue']; + $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; + $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; + } + + public static function hasCustomOptions(array $options): bool + { + foreach (self::CUSTOM_OPTION_KEYS as $key) { + if (array_key_exists($key, $options)) { + return true; + } + } + + return false; + } + + public function getOperation(GetOperationRequest $request, array $callOptions = []): Operation + { + $response = $this->operationsCall( + $this->getOperationMethod, + $this->getOperationRequest, + $request->getName(), + $callOptions + ); + + return $this->toOperation($response); + } + + public function cancelOperation(CancelOperationRequest $request, array $callOptions = []): void + { + if (is_null($this->cancelOperationMethod) || is_null($this->cancelOperationRequest)) { + throw new LogicException('The cancel operation is not supported by this API'); + } + + $this->operationsCall( + $this->cancelOperationMethod, + $this->cancelOperationRequest, + $request->getName(), + $callOptions + ); + } + + public function deleteOperation(DeleteOperationRequest $request, array $callOptions = []): void + { + if (is_null($this->deleteOperationMethod) || is_null($this->deleteOperationRequest)) { + throw new LogicException('The delete operation is not supported by this API'); + } + + $this->operationsCall( + $this->deleteOperationMethod, + $this->deleteOperationRequest, + $request->getName(), + $callOptions + ); + } + + public function toOperation(?object $response): Operation + { + if (is_null($response)) { + return new Operation(); + } + + if ($response instanceof Operation) { + return $response; + } + + $operation = new Operation(); + if (method_exists($response, $this->operationNameMethod)) { + $name = $response->{$this->operationNameMethod}(); + if (is_string($name)) { + $operation->setName($name); + } + } + + if (!method_exists($response, $this->operationStatusMethod)) { + return $operation; + } + + $status = $response->{$this->operationStatusMethod}(); + $done = !is_null($status) && $status === $this->operationStatusDoneValue; + $operation->setDone($done); + + if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { + $errorCode = $this->operationErrorCodeMethod + ? $response->{$this->operationErrorCodeMethod}() + : null; + if (!empty($errorCode)) { + $errorMessage = $this->operationErrorMessageMethod + ? $response->{$this->operationErrorMessageMethod}() + : ''; + $operation->setError( + (new Status()) + ->setCode(ApiStatus::rpcCodeFromHttpStatusCode($errorCode)) + ->setMessage((string) $errorMessage) + ); + } + } elseif (method_exists($response, 'getError')) { + $error = $response->getError(); + if (!empty($error)) { + $operation->setError( + $error instanceof Status ? $error : (new Status())->setCode(Code::UNKNOWN) + ); + } + } elseif ($done) { + throw new LogicException('Unable to determine operation error status for this service'); + } + + return $operation; + } + + private function operationsCall( + string $method, + string $requestClass, + string $operationName, + array $callOptions = [] + ): mixed { + if (!method_exists($requestClass, 'build')) { + throw new LogicException('Request class must support the static build method'); + } + + // In Compute, the Request "build" methods contain the operation ID last instead + // of first. Compute is the only API which uses $additionalArgs, so switching the order + // will not break anything. + $request = $requestClass::build(...array_merge( + array_values($this->additionalArgs), + [$operationName] + )); + + if ($callOptions) { + return $this->client->$method($request, $callOptions); + } + + return $this->client->$method($request); + } +} diff --git a/Gax/src/Middleware/OperationsMiddleware.php b/Gax/src/Middleware/OperationsMiddleware.php index 07bbe42cc23c..4637a8e31e62 100644 --- a/Gax/src/Middleware/OperationsMiddleware.php +++ b/Gax/src/Middleware/OperationsMiddleware.php @@ -35,6 +35,8 @@ use Google\ApiCore\Call; use Google\ApiCore\OperationResponse; +use Google\ApiCore\OperationsClientInterface; +use Google\LongRunning\Client\OperationsClient; use Google\Protobuf\Internal\Message; use GuzzleHttp\Promise\PromiseInterface; @@ -71,7 +73,9 @@ public function __invoke(Call $call, array $options): PromiseInterface 'lastProtoResponse' => $response ]; $operationNameMethod = $options['operationNameMethod'] ?? 'getName'; - $operationName = call_user_func([$response, $operationNameMethod]); + $operationName = method_exists($response, $operationNameMethod) + ? (string) $response->$operationNameMethod() + : ''; return new OperationResponse($operationName, $this->operationsClient, $options); }); } diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 35bde207400c..85674952a0a1 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -69,8 +69,8 @@ class OperationResponse const DEFAULT_MAX_POLLING_INTERVAL = 60000; const DEFAULT_MAX_POLLING_DURATION = 0; - private ?string $operationName; - private ?object $operationsClient; + private string $operationName; + private OperationsClient|OperationsClientInterface $operationsClient; private ?string $operationReturnType; private ?string $metadataReturnType; @@ -81,26 +81,14 @@ class OperationResponse 'totalPollTimeoutMillis' => self::DEFAULT_MAX_POLLING_DURATION, ]; - private ?object $lastProtoResponse; + private ?Operation $lastProtoResponse; private bool $deleted = false; - private array $additionalArgs; - private string $getOperationMethod; - private ?string $cancelOperationMethod; - private ?string $deleteOperationMethod; - private string $getOperationRequest; - private ?string $cancelOperationRequest; - private ?string $deleteOperationRequest; - private string $operationStatusMethod; - private mixed $operationStatusDoneValue; - private ?string $operationErrorCodeMethod; - private ?string $operationErrorMessageMethod; - /** * OperationResponse constructor. * - * @param string|null $operationName - * @param ServiceInterface|object|null $operationsClient + * @param string $operationName + * @param OperationsClient|OperationsClientInterface|object $operationsClient * @param array $options { * Optional. Options for configuring the operation response object. * @@ -110,51 +98,40 @@ class OperationResponse * @type int $pollDelayMultiplier Multiplier applied to the polling interval on each retry. * @type int $maxPollDelayMillis The maximum polling interval to use, in milliseconds. * @type int $totalPollTimeoutMillis The maximum amount of time to continue polling. - * @type object $lastProtoResponse A response already received from the server. + * @type Operation|object $lastProtoResponse A response already received from the server. * @type string $getOperationMethod The method on $operationsClient to get the operation. * @type string $cancelOperationMethod The method on $operationsClient to cancel the operation. * @type string $deleteOperationMethod The method on $operationsClient to delete the operation. * @type string $operationStatusMethod The method on the operation to get the status. - * @type string $operationStatusDoneValue The method on the operation to determine if the status is done. + * @type mixed $operationStatusDoneValue The value on the operation indicating status is done. * @type array $additionalOperationArguments Additional arguments to pass to $operationsClient methods. * @type string $operationErrorCodeMethod The method on the operation to get the error code * @type string $operationErrorMessageMethod The method on the operation to get the error status * } */ - public function __construct(?string $operationName, ?object $operationsClient, array $options = []) - { + public function __construct( + string $operationName, + object $operationsClient, + array $options = [] + ) { $this->operationName = $operationName; + $isStandardClient = $operationsClient instanceof OperationsClient + || $operationsClient instanceof OperationsClientInterface; + if (!$isStandardClient || CustomOperationsClient::hasCustomOptions($options)) { + $operationsClient = new CustomOperationsClient($operationsClient, $options); + } $this->operationsClient = $operationsClient; - $options += [ - 'operationReturnType' => null, - 'metadataReturnType' => null, - 'lastProtoResponse' => null, - 'getOperationMethod' => 'getOperation', - 'cancelOperationMethod' => 'cancelOperation', - 'deleteOperationMethod' => 'deleteOperation', - 'operationStatusMethod' => 'getDone', - 'operationStatusDoneValue' => true, - 'additionalOperationArguments' => [], - 'operationErrorCodeMethod' => null, - 'operationErrorMessageMethod' => null, - 'getOperationRequest' => GetOperationRequest::class, - 'cancelOperationRequest' => CancelOperationRequest::class, - 'deleteOperationRequest' => DeleteOperationRequest::class, - ]; - $this->operationReturnType = $options['operationReturnType']; - $this->metadataReturnType = $options['metadataReturnType']; - $this->lastProtoResponse = $options['lastProtoResponse']; - $this->getOperationMethod = $options['getOperationMethod']; - $this->cancelOperationMethod = $options['cancelOperationMethod']; - $this->deleteOperationMethod = $options['deleteOperationMethod']; - $this->additionalArgs = $options['additionalOperationArguments']; - $this->operationStatusMethod = $options['operationStatusMethod']; - $this->operationStatusDoneValue = $options['operationStatusDoneValue']; - $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; - $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; - $this->getOperationRequest = $options['getOperationRequest']; - $this->cancelOperationRequest = $options['cancelOperationRequest']; - $this->deleteOperationRequest = $options['deleteOperationRequest']; + $this->operationReturnType = $options['operationReturnType'] ?? null; + $this->metadataReturnType = $options['metadataReturnType'] ?? null; + + $lastProtoResponse = $options['lastProtoResponse'] ?? null; + if ($lastProtoResponse !== null && !$lastProtoResponse instanceof Operation) { + $customClient = $this->operationsClient instanceof CustomOperationsClient + ? $this->operationsClient + : new CustomOperationsClient($this->operationsClient, $options); + $lastProtoResponse = $customClient->toOperation($lastProtoResponse); + } + $this->lastProtoResponse = $lastProtoResponse; if (isset($options['initialPollDelayMillis'])) { $this->defaultPollSettings['initialPollDelayMillis'] = $options['initialPollDelayMillis']; @@ -177,16 +154,7 @@ public function __construct(?string $operationName, ?object $operationsClient, a */ public function isDone(): bool { - if (!$this->hasProtoResponse()) { - return false; - } - - $status = call_user_func([$this->lastProtoResponse, $this->operationStatusMethod]); - if (is_null($status)) { - return false; - } - - return $status === $this->operationStatusDoneValue; + return (bool) $this->lastProtoResponse?->getDone(); } /** @@ -197,17 +165,7 @@ public function isDone(): bool */ public function operationSucceeded(): bool { - if (!$this->hasProtoResponse()) { - return false; - } - - if (!$this->canHaveResult()) { - // For Operations which do not have a result, we consider a successful - // operation when the operation has completed without errors. - return $this->isDone() && !$this->hasErrors(); - } - - return !is_null($this->getResult()); + return $this->isDone() && !$this->operationFailed(); } /** @@ -218,15 +176,15 @@ public function operationSucceeded(): bool */ public function operationFailed(): bool { - return $this->hasErrors(); + return !is_null($this->lastProtoResponse?->getError()); } /** * Get the formatted name of the operation * - * @return string|null The formatted name of the operation + * @return string The formatted name of the operation */ - public function getName(): ?string + public function getName(): string { return $this->operationName; } @@ -276,10 +234,8 @@ public function reload(): void throw new ValidationException('Cannot call reload() on a deleted operation'); } - $this->lastProtoResponse = $this->operationsCall( - $this->getOperationMethod, - $this->getOperationRequest - ); + $request = GetOperationRequest::build($this->getName()); + $this->lastProtoResponse = $this->operationsClient->getOperation($request); } /** @@ -290,20 +246,12 @@ public function reload(): void */ public function getResult(): mixed { - if (!$this->hasProtoResponse()) { - return null; - } - - if (!$this->canHaveResult()) { - return null; - } - - if (!$this->isDone()) { + if (!$this->operationSucceeded()) { return null; } /** @var Any|null $anyResponse */ - $anyResponse = $this->lastProtoResponse->getResponse(); + $anyResponse = $this->lastProtoResponse?->getResponse(); if (is_null($anyResponse)) { return null; } @@ -320,32 +268,16 @@ public function getResult(): mixed /** * If the operation failed, return the status. If operationFailed() is false, return null. * - * @return Status|Message|null The status of the operation in case of failure, or null if + * @return Status|null The status of the operation in case of failure, or null if * operationFailed() is false. */ - public function getError(): ?Message + public function getError(): ?Status { - if (!$this->hasProtoResponse() || !$this->isDone()) { + if (!$this->isDone()) { return null; } - if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { - $errorCode = $this->operationErrorCodeMethod - ? call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]) - : null; - $errorMessage = $this->operationErrorMessageMethod - ? call_user_func([$this->lastProtoResponse, $this->operationErrorMessageMethod]) - : null; - return (new Status()) - ->setCode(ApiStatus::rpcCodeFromHttpStatusCode($errorCode)) - ->setMessage($errorMessage); - } - - if (method_exists($this->lastProtoResponse, 'getError')) { - return $this->lastProtoResponse->getError(); - } - - return null; + return $this->lastProtoResponse?->getError(); } /** @@ -365,18 +297,18 @@ public function getDescriptorOptions(): array } /** - * @return Operation|object|null The last Operation object received from the server. + * @return Operation|null The last Operation object received from the server. */ - public function getLastProtoResponse(): ?object + public function getLastProtoResponse(): ?Operation { return $this->lastProtoResponse; } /** - * @return ServiceInterface|object|null The OperationsClient object used to make + * @return OperationsClient|OperationsClientInterface The OperationsClient object used to make * requests to the operations API. */ - public function getOperationsClient(): ?object + public function getOperationsClient(): OperationsClient|OperationsClientInterface { return $this->operationsClient; } @@ -400,11 +332,8 @@ public function getOperationsClient(): ?object */ public function cancel(): void { - if (is_null($this->cancelOperationMethod)) { - throw new LogicException('The cancel operation is not supported by this API'); - } - - $this->operationsCall($this->cancelOperationMethod, $this->cancelOperationRequest); + $request = CancelOperationRequest::build($this->getName()); + $this->operationsClient->cancelOperation($request); } /** @@ -420,11 +349,8 @@ public function cancel(): void */ public function delete(): void { - if (is_null($this->deleteOperationMethod)) { - throw new LogicException('The delete operation is not supported by this API'); - } - - $this->operationsCall($this->deleteOperationMethod, $this->deleteOperationRequest); + $request = DeleteOperationRequest::build($this->getName()); + $this->operationsClient->deleteOperation($request); $this->deleted = true; } @@ -437,81 +363,15 @@ public function delete(): void */ public function getMetadata(): mixed { - if (!$this->hasProtoResponse()) { - return null; - } - - if (!method_exists($this->lastProtoResponse, 'getMetadata')) { - // The call to getMetadata is only for OnePlatform LROs, and is not - // supported by other LRO GAPIC clients (e.g. Compute) - return null; - } - /** @var Any|null $any */ - $any = $this->lastProtoResponse->getMetadata(); - if (is_null($this->metadataReturnType)) { + $any = $this->lastProtoResponse?->getMetadata(); + if (is_null($any) || is_null($this->metadataReturnType)) { return $any; } - if (is_null($any)) { - return null; - } $metadataReturnType = $this->metadataReturnType; /** @var Message $metadata */ $metadata = new $metadataReturnType(); $metadata->mergeFromString($any->getValue()); return $metadata; } - - /** - * Call the operations client to perform an operation. - * - * @param string $method The method to call on the operations client. - * @param string $requestClass The request class to use for the call. - * Will be null for legacy operations clients. - */ - private function operationsCall(string $method, string $requestClass): mixed - { - if (!method_exists($requestClass, 'build')) { - throw new LogicException('Request class must support the static build method'); - } - // In Compute, the Request "build" methods contain the operation ID last instead - // of first. Compute is the only API which uses $additionalArgs, so switching the order - // will not break anything. - $request = $requestClass::build(...array_merge( - array_values($this->additionalArgs), - [$this->getName()] - )); - return $this->operationsClient->$method($request); - } - - private function canHaveResult(): bool - { - // The call to getResponse is only for OnePlatform LROs, and is not - // supported by other LRO GAPIC clients (e.g. Compute) - return method_exists($this->lastProtoResponse, 'getResponse'); - } - - private function hasErrors(): bool - { - if (!$this->hasProtoResponse()) { - return false; - } - - if (method_exists($this->lastProtoResponse, 'getError')) { - return !empty($this->lastProtoResponse->getError()); - } - - if ($this->operationErrorCodeMethod) { - $errorCode = call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]); - return !empty($errorCode); - } - - // This should never happen unless an API is misconfigured - throw new LogicException('Unable to determine operation error status for this service'); - } - - private function hasProtoResponse(): bool - { - return !is_null($this->lastProtoResponse); - } } diff --git a/Gax/src/OperationsClientInterface.php b/Gax/src/OperationsClientInterface.php new file mode 100644 index 000000000000..914cf703f923 --- /dev/null +++ b/Gax/src/OperationsClientInterface.php @@ -0,0 +1,49 @@ +prophesize(CustomOperation::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledTimes(2) + ->shouldBeCalledOnce() ->willReturn('Yes, it is!'); $operation->getError() ->shouldBeCalledOnce() @@ -364,10 +364,10 @@ public function testCustomOperationError($operationClient) $operationName = 'test-123'; $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledTimes(2) + ->shouldBeCalledOnce() ->willReturn('Yes, it is!'); $operation->getTheErrorCode() - ->shouldBeCalledTimes(2) + ->shouldBeCalledOnce() ->willReturn(500); $operation->getTheErrorMessage() ->shouldBeCalledOnce() @@ -419,6 +419,9 @@ public function testEmptyCustomOperationErrorIsSuccessful($operationClient) */ public function testMisconfiguredCustomOperationThrowsException($operationClient) { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Unable to determine operation error status for this service'); + $operationName = 'test-123'; $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); $operation->isThisOperationDoneOrWhat() @@ -432,9 +435,6 @@ public function testMisconfiguredCustomOperationThrowsException($operationClient ]; $operationResponse = new OperationResponse($operationName, $operationClient, $options); - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Unable to determine operation error status for this service'); - $operationResponse->operationSucceeded(); } diff --git a/Spanner/tests/Unit/BackupTest.php b/Spanner/tests/Unit/BackupTest.php index d9615f6ea9a0..60f06af9aa82 100644 --- a/Spanner/tests/Unit/BackupTest.php +++ b/Spanner/tests/Unit/BackupTest.php @@ -86,6 +86,8 @@ public function setUp(): void $this->instance->database(Argument::any())->willReturn($this->database); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('operation-name'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); $this->expireTime = new DateTime('+7 hours'); $this->versionTime = new DateTime('-2 hours'); diff --git a/Spanner/tests/Unit/DatabaseTest.php b/Spanner/tests/Unit/DatabaseTest.php index c4e340cd2e90..a3628c9f016e 100644 --- a/Spanner/tests/Unit/DatabaseTest.php +++ b/Spanner/tests/Unit/DatabaseTest.php @@ -185,6 +185,8 @@ public function setUp(): void ); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('operation-name'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); } public function testName() diff --git a/Spanner/tests/Unit/InstanceConfigurationTest.php b/Spanner/tests/Unit/InstanceConfigurationTest.php index 9b5df8c3df95..f8fec13d324a 100644 --- a/Spanner/tests/Unit/InstanceConfigurationTest.php +++ b/Spanner/tests/Unit/InstanceConfigurationTest.php @@ -245,6 +245,9 @@ public function testUpdateWithChanges() 'displayName' => 'New Name', ]; + $operationResponse = $this->prophesize(OperationResponse::class); + $operationResponse->getName()->willReturn('operation-name'); + $operationResponse->getLastProtoResponse()->willReturn(null); $this->instanceAdminClient->updateInstanceConfig( Argument::that(function (UpdateInstanceConfigRequest $request) use ($config) { $instanceConfig = $request->getInstanceConfig()->serializeToJsonString(); @@ -253,7 +256,7 @@ public function testUpdateWithChanges() Argument::type('array') ) ->shouldBeCalledOnce() - ->willReturn($this->prophesize(OperationResponse::class)->reveal()); + ->willReturn($operationResponse->reveal()); $instanceConfig = new InstanceConfiguration( $this->instanceAdminClient->reveal(), diff --git a/Spanner/tests/Unit/InstanceTest.php b/Spanner/tests/Unit/InstanceTest.php index 253f04ffc22e..8afeeae2179f 100644 --- a/Spanner/tests/Unit/InstanceTest.php +++ b/Spanner/tests/Unit/InstanceTest.php @@ -99,6 +99,8 @@ public function setUp(): void $this->instanceAdminClient = $this->prophesize(InstanceAdminClient::class); $this->databaseAdminClient = $this->prophesize(DatabaseAdminClient::class); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('operation-name'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); $this->page = $this->prophesize(Page::class); $this->pagedListResponse = $this->prophesize(PagedListResponse::class); $this->pagedListResponse->getPage()->willReturn($this->page->reveal()); diff --git a/Spanner/tests/Unit/SpannerClientTest.php b/Spanner/tests/Unit/SpannerClientTest.php index 62e231cac99b..7d71d701855e 100644 --- a/Spanner/tests/Unit/SpannerClientTest.php +++ b/Spanner/tests/Unit/SpannerClientTest.php @@ -117,6 +117,8 @@ public function setUp(): void ]); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('operation-name'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); } public function testBatch() From 604f5ae506dd6afca5412f70695ee3ebb1155316 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 00:29:37 +0000 Subject: [PATCH 02/11] fix(Gax,Spanner): fix php-cs-fixer imports, DocFX @see FQCNs, and Spanner snippet mocks --- Gax/src/CustomOperationsClient.php | 4 ++-- Gax/src/Middleware/OperationsMiddleware.php | 2 -- Spanner/tests/Snippet/BackupTest.php | 1 + Spanner/tests/Snippet/DatabaseTest.php | 1 + Spanner/tests/Snippet/InstanceTest.php | 1 + 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php index 9cf111dd2164..c64bd07a7f31 100644 --- a/Gax/src/CustomOperationsClient.php +++ b/Gax/src/CustomOperationsClient.php @@ -44,8 +44,8 @@ /** * Adapter that wraps a custom operations client (e.g. Compute's ZoneOperationsClient) - * to implement {@see OperationsClientInterface} and normalize custom operation messages - * into {@see Operation}. + * to implement {@see \Google\ApiCore\OperationsClientInterface} and normalize custom operation messages + * into {@see \Google\LongRunning\Operation}. */ class CustomOperationsClient implements OperationsClientInterface { diff --git a/Gax/src/Middleware/OperationsMiddleware.php b/Gax/src/Middleware/OperationsMiddleware.php index 4637a8e31e62..13de084071e3 100644 --- a/Gax/src/Middleware/OperationsMiddleware.php +++ b/Gax/src/Middleware/OperationsMiddleware.php @@ -35,8 +35,6 @@ use Google\ApiCore\Call; use Google\ApiCore\OperationResponse; -use Google\ApiCore\OperationsClientInterface; -use Google\LongRunning\Client\OperationsClient; use Google\Protobuf\Internal\Message; use GuzzleHttp\Promise\PromiseInterface; diff --git a/Spanner/tests/Snippet/BackupTest.php b/Spanner/tests/Snippet/BackupTest.php index f5b065d0f777..13e14ed952fb 100644 --- a/Spanner/tests/Snippet/BackupTest.php +++ b/Spanner/tests/Snippet/BackupTest.php @@ -74,6 +74,7 @@ public function setUp(): void $this->serializer = new Serializer(); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('my-operation'); $this->expireTime = new \DateTime('+ 7 hours'); $database = $this->prophesize(Database::class); diff --git a/Spanner/tests/Snippet/DatabaseTest.php b/Spanner/tests/Snippet/DatabaseTest.php index eae38f0c9678..50e5907f44c6 100644 --- a/Spanner/tests/Snippet/DatabaseTest.php +++ b/Spanner/tests/Snippet/DatabaseTest.php @@ -100,6 +100,7 @@ public function setUp(): void $this->databaseAdminClient = $this->prophesize(DatabaseAdminClient::class); $this->instanceAdminClient = $this->prophesize(InstanceAdminClient::class); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('my-operation'); $this->serializer = new Serializer(); $session = $this->prophesize(SessionCache::class); diff --git a/Spanner/tests/Snippet/InstanceTest.php b/Spanner/tests/Snippet/InstanceTest.php index 6b04e6c55ade..c6aff32c56b8 100644 --- a/Spanner/tests/Snippet/InstanceTest.php +++ b/Spanner/tests/Snippet/InstanceTest.php @@ -88,6 +88,7 @@ public function setUp(): void $this->instanceAdminClient = $this->prophesize(InstanceAdminClient::class); $this->databaseAdminClient = $this->prophesize(DatabaseAdminClient::class); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('my-operation'); $this->page = $this->prophesize(Page::class); $this->page->getNextPageToken() From 953f7041a5152cfc5ee9e9da6e19bd2ae502561d Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 18:31:01 +0000 Subject: [PATCH 03/11] test(Gax): add unit tests for OperationsClientInterface and CustomOperationsClient --- Gax/tests/Unit/OperationResponseTest.php | 62 ++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 00d652b26a3d..b7291d6f9072 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -38,7 +38,9 @@ use Google\CustomOperation\CustomOperationWithErrorAnnotations; use Google\CustomOperation\DeleteOperationRequest as CustomDeleteOperationRequest; use Google\CustomOperation\GetOperationRequest as CustomGetOperationRequest; +use Google\ApiCore\CustomOperationsClient; use Google\ApiCore\OperationResponse; +use Google\ApiCore\OperationsClientInterface; use Google\LongRunning\CancelOperationRequest; use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\DeleteOperationRequest; @@ -515,6 +517,66 @@ public function testDeleteWithOperationsClient() $operationResponse->delete(); } + public function testOperationsClientInterface() + { + $operationClient = $this->prophesize(OperationsClientInterface::class); + $getRequest = new GetOperationRequest(['name' => 'test-123']); + $cancelRequest = new CancelOperationRequest(['name' => 'test-123']); + $deleteRequest = new DeleteOperationRequest(['name' => 'test-123']); + $protoOp = new Operation(['name' => 'test-123', 'done' => true]); + + $operationClient->getOperation($getRequest) + ->shouldBeCalledOnce() + ->willReturn($protoOp); + $operationClient->cancelOperation($cancelRequest) + ->shouldBeCalledOnce(); + $operationClient->deleteOperation($deleteRequest) + ->shouldBeCalledOnce(); + + $operationResponse = new OperationResponse('test-123', $operationClient->reveal()); + $this->assertSame($operationClient->reveal(), $operationResponse->getOperationsClient()); + + $operationResponse->reload(); + $this->assertTrue($operationResponse->isDone()); + $this->assertSame($protoOp, $operationResponse->getLastProtoResponse()); + + $operationResponse->cancel(); + $operationResponse->delete(); + } + + public function testCustomOperationsClientDirectly() + { + $operationName = 'test-123'; + $customOp = $this->prophesize(CustomOperation::class); + $customOp->isThisOperationDoneOrWhat() + ->shouldBeCalledOnce() + ->willReturn('Yes, it is!'); + $customOp->getError() + ->shouldBeCalledOnce() + ->willReturn(null); + + $rawClient = $this->prophesize(CustomOperationClient::class); + $rawClient->getMyOperationPlease(Argument::type(Message::class)) + ->shouldBeCalledOnce() + ->willReturn($customOp->reveal()); + + $adapter = new CustomOperationsClient($rawClient->reveal(), [ + 'getOperationMethod' => 'getMyOperationPlease', + 'operationStatusMethod' => 'isThisOperationDoneOrWhat', + 'operationStatusDoneValue' => 'Yes, it is!', + ]); + + $operationResponse = new OperationResponse($operationName, $adapter); + $this->assertSame($adapter, $operationResponse->getOperationsClient()); + $this->assertInstanceOf(OperationsClientInterface::class, $operationResponse->getOperationsClient()); + + $operationResponse->reload(); + $this->assertTrue($operationResponse->isDone()); + $this->assertTrue($operationResponse->operationSucceeded()); + $this->assertInstanceOf(Operation::class, $operationResponse->getLastProtoResponse()); + $this->assertTrue($operationResponse->getLastProtoResponse()->getDone()); + } + private function createOperationResponse($options, $reloadCount) { $opName = 'operations/opname'; From 6581d26cb2435d06578a137494bd9e0029f4e80b Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 21:18:58 +0000 Subject: [PATCH 04/11] test(Spanner): stub OperationResponse::getLastProtoResponse in snippet tests --- Spanner/tests/Snippet/BackupTest.php | 1 + Spanner/tests/Snippet/DatabaseTest.php | 1 + Spanner/tests/Snippet/InstanceConfigurationTest.php | 2 ++ Spanner/tests/Snippet/InstanceTest.php | 1 + Spanner/tests/Snippet/SpannerClientTest.php | 4 +++- 5 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Spanner/tests/Snippet/BackupTest.php b/Spanner/tests/Snippet/BackupTest.php index 13e14ed952fb..b195066fd577 100644 --- a/Spanner/tests/Snippet/BackupTest.php +++ b/Spanner/tests/Snippet/BackupTest.php @@ -75,6 +75,7 @@ public function setUp(): void $this->operationResponse = $this->prophesize(OperationResponse::class); $this->operationResponse->getName()->willReturn('my-operation'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); $this->expireTime = new \DateTime('+ 7 hours'); $database = $this->prophesize(Database::class); diff --git a/Spanner/tests/Snippet/DatabaseTest.php b/Spanner/tests/Snippet/DatabaseTest.php index 50e5907f44c6..899be42a8e87 100644 --- a/Spanner/tests/Snippet/DatabaseTest.php +++ b/Spanner/tests/Snippet/DatabaseTest.php @@ -101,6 +101,7 @@ public function setUp(): void $this->instanceAdminClient = $this->prophesize(InstanceAdminClient::class); $this->operationResponse = $this->prophesize(OperationResponse::class); $this->operationResponse->getName()->willReturn('my-operation'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); $this->serializer = new Serializer(); $session = $this->prophesize(SessionCache::class); diff --git a/Spanner/tests/Snippet/InstanceConfigurationTest.php b/Spanner/tests/Snippet/InstanceConfigurationTest.php index a38710c935e6..7d7091c1012b 100644 --- a/Spanner/tests/Snippet/InstanceConfigurationTest.php +++ b/Spanner/tests/Snippet/InstanceConfigurationTest.php @@ -56,6 +56,8 @@ public function setUp(): void $this->serializer = new Serializer(); $this->instanceAdminClient = $this->prophesize(InstanceAdminClient::class); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('my-operation'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); $this->config = new InstanceConfiguration( $this->instanceAdminClient->reveal(), diff --git a/Spanner/tests/Snippet/InstanceTest.php b/Spanner/tests/Snippet/InstanceTest.php index c6aff32c56b8..bfe8d8e47fd0 100644 --- a/Spanner/tests/Snippet/InstanceTest.php +++ b/Spanner/tests/Snippet/InstanceTest.php @@ -89,6 +89,7 @@ public function setUp(): void $this->databaseAdminClient = $this->prophesize(DatabaseAdminClient::class); $this->operationResponse = $this->prophesize(OperationResponse::class); $this->operationResponse->getName()->willReturn('my-operation'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); $this->page = $this->prophesize(Page::class); $this->page->getNextPageToken() diff --git a/Spanner/tests/Snippet/SpannerClientTest.php b/Spanner/tests/Snippet/SpannerClientTest.php index 9c643e272940..03f98cf10821 100644 --- a/Spanner/tests/Snippet/SpannerClientTest.php +++ b/Spanner/tests/Snippet/SpannerClientTest.php @@ -82,6 +82,8 @@ public function setUp(): void 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), ]); $this->operationResponse = $this->prophesize(OperationResponse::class); + $this->operationResponse->getName()->willReturn('my-operation'); + $this->operationResponse->getLastProtoResponse()->willReturn(null); } public function testClass() @@ -168,7 +170,7 @@ public function testCreateInstance() Argument::type('array') ) ->shouldBeCalledOnce() - ->willReturn($this->prophesize(OperationResponse::class)->reveal()); + ->willReturn($this->operationResponse->reveal()); $res = $snippet->invoke('operation'); $this->assertInstanceOf(LongRunningOperation::class, $res->returnVal()); From c2db3e5637d0a7ba3cc9e1f921012f3c7daa00c0 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 6 Nov 2026 19:00:26 +0000 Subject: [PATCH 05/11] chore(Gax): add TODO for removing OperationsClient check --- Gax/src/OperationResponse.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 85674952a0a1..8cfda473c2f6 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -115,6 +115,7 @@ public function __construct( array $options = [] ) { $this->operationName = $operationName; + // @TODO: Remove check for OperationsClient once support for google/longrunning:0.4 is dropped $isStandardClient = $operationsClient instanceof OperationsClient || $operationsClient instanceof OperationsClientInterface; if (!$isStandardClient || CustomOperationsClient::hasCustomOptions($options)) { From 387853c978aca33b877bf2f866c33b807f4ebdf4 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 6 Nov 2026 19:27:30 +0000 Subject: [PATCH 06/11] fix(Gax): preserve custom operation message in getLastProtoResponse Preserve the raw custom operation response (e.g. Compute's Operation) for custom operation clients: - Store the raw response in CustomOperationsClient - Return the raw response in OperationResponse::getLastProtoResponse() with ?object typehint - Update MIGRATING.md to document the return type --- Gax/MIGRATING.md | 2 +- Gax/src/CustomOperationsClient.php | 10 ++++++++++ Gax/src/OperationResponse.php | 11 ++++++++--- Gax/tests/Unit/OperationResponseTest.php | 3 +-- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 2ce02d51584f..51773dd2161f 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -58,7 +58,7 @@ Update your `google/gax` dependency to `^2.0`: - `__construct(string $operationName, object $operationsClient, array $options = [])` now requires non-null `$operationName` (`string`) and `$operationsClient` (`object`). - `getName()` now returns non-nullable `string`. - `getError()` now returns `?Google\Rpc\Status`. - - `getLastProtoResponse()` now returns `?Google\LongRunning\Operation`. + - `getLastProtoResponse()` now returns `?object` (annotated as `Operation|Message|null`), preserving the raw custom operation message (e.g. `Google\Cloud\Compute\V1\Operation`) for custom operation services such as Compute. - `getOperationsClient()` now returns `Google\LongRunning\Client\OperationsClient|Google\ApiCore\OperationsClientInterface`. - Custom operations clients (e.g., Compute's `ZoneOperationsClient`) and custom operation options are now encapsulated in `Google\ApiCore\CustomOperationsClient` (implementing `Google\ApiCore\OperationsClientInterface`), which normalizes custom operation proto responses into `Google\LongRunning\Operation`. diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php index c64bd07a7f31..e107485eecd2 100644 --- a/Gax/src/CustomOperationsClient.php +++ b/Gax/src/CustomOperationsClient.php @@ -77,6 +77,7 @@ class CustomOperationsClient implements OperationsClientInterface private mixed $operationStatusDoneValue; private ?string $operationErrorCodeMethod; private ?string $operationErrorMessageMethod; + private ?object $lastCustomResponse = null; public function __construct(object $client, array $options = []) { @@ -130,6 +131,8 @@ public function getOperation(GetOperationRequest $request, array $callOptions = $callOptions ); + $this->lastCustomResponse = is_object($response) ? $response : null; + return $this->toOperation($response); } @@ -167,6 +170,8 @@ public function toOperation(?object $response): Operation return new Operation(); } + $this->lastCustomResponse = $response; + if ($response instanceof Operation) { return $response; } @@ -215,6 +220,11 @@ public function toOperation(?object $response): Operation return $operation; } + public function getLastCustomResponse(): ?object + { + return $this->lastCustomResponse; + } + private function operationsCall( string $method, string $requestClass, diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 8cfda473c2f6..084cb885a655 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -82,6 +82,7 @@ class OperationResponse ]; private ?Operation $lastProtoResponse; + private ?object $lastCustomResponse = null; private bool $deleted = false; /** @@ -127,6 +128,7 @@ public function __construct( $lastProtoResponse = $options['lastProtoResponse'] ?? null; if ($lastProtoResponse !== null && !$lastProtoResponse instanceof Operation) { + $this->lastCustomResponse = $lastProtoResponse; $customClient = $this->operationsClient instanceof CustomOperationsClient ? $this->operationsClient : new CustomOperationsClient($this->operationsClient, $options); @@ -237,6 +239,9 @@ public function reload(): void $request = GetOperationRequest::build($this->getName()); $this->lastProtoResponse = $this->operationsClient->getOperation($request); + if ($this->operationsClient instanceof CustomOperationsClient) { + $this->lastCustomResponse = $this->operationsClient->getLastCustomResponse(); + } } /** @@ -298,11 +303,11 @@ public function getDescriptorOptions(): array } /** - * @return Operation|null The last Operation object received from the server. + * @return Operation|Message|null The last Operation object received from the server. */ - public function getLastProtoResponse(): ?Operation + public function getLastProtoResponse(): ?object { - return $this->lastProtoResponse; + return $this->lastCustomResponse ?? $this->lastProtoResponse; } /** diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index b7291d6f9072..0309578ae580 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -573,8 +573,7 @@ public function testCustomOperationsClientDirectly() $operationResponse->reload(); $this->assertTrue($operationResponse->isDone()); $this->assertTrue($operationResponse->operationSucceeded()); - $this->assertInstanceOf(Operation::class, $operationResponse->getLastProtoResponse()); - $this->assertTrue($operationResponse->getLastProtoResponse()->getDone()); + $this->assertSame($customOp->reveal(), $operationResponse->getLastProtoResponse()); } private function createOperationResponse($options, $reloadCount) From 57286bab46c318db82bd55be639624df777eeffd Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 6 Nov 2026 19:36:56 +0000 Subject: [PATCH 07/11] refactor(Gax): simplify lastProtoResponse in CustomOperationsClient - Use lastProtoResponse consistently instead of separate lastCustomResponse - Remove duplicate lastCustomResponse property from OperationResponse - Delegate to CustomOperationsClient::getLastProtoResponse() in OperationResponse --- Gax/src/CustomOperationsClient.php | 10 +++++----- Gax/src/OperationResponse.php | 11 +++++------ 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php index e107485eecd2..1ff2fcec98c8 100644 --- a/Gax/src/CustomOperationsClient.php +++ b/Gax/src/CustomOperationsClient.php @@ -77,7 +77,7 @@ class CustomOperationsClient implements OperationsClientInterface private mixed $operationStatusDoneValue; private ?string $operationErrorCodeMethod; private ?string $operationErrorMessageMethod; - private ?object $lastCustomResponse = null; + private ?object $lastProtoResponse = null; public function __construct(object $client, array $options = []) { @@ -131,7 +131,7 @@ public function getOperation(GetOperationRequest $request, array $callOptions = $callOptions ); - $this->lastCustomResponse = is_object($response) ? $response : null; + $this->lastProtoResponse = is_object($response) ? $response : null; return $this->toOperation($response); } @@ -170,7 +170,7 @@ public function toOperation(?object $response): Operation return new Operation(); } - $this->lastCustomResponse = $response; + $this->lastProtoResponse = $response; if ($response instanceof Operation) { return $response; @@ -220,9 +220,9 @@ public function toOperation(?object $response): Operation return $operation; } - public function getLastCustomResponse(): ?object + public function getLastProtoResponse(): ?object { - return $this->lastCustomResponse; + return $this->lastProtoResponse; } private function operationsCall( diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 084cb885a655..e3cd90fe55a3 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -82,7 +82,6 @@ class OperationResponse ]; private ?Operation $lastProtoResponse; - private ?object $lastCustomResponse = null; private bool $deleted = false; /** @@ -128,7 +127,6 @@ public function __construct( $lastProtoResponse = $options['lastProtoResponse'] ?? null; if ($lastProtoResponse !== null && !$lastProtoResponse instanceof Operation) { - $this->lastCustomResponse = $lastProtoResponse; $customClient = $this->operationsClient instanceof CustomOperationsClient ? $this->operationsClient : new CustomOperationsClient($this->operationsClient, $options); @@ -239,9 +237,6 @@ public function reload(): void $request = GetOperationRequest::build($this->getName()); $this->lastProtoResponse = $this->operationsClient->getOperation($request); - if ($this->operationsClient instanceof CustomOperationsClient) { - $this->lastCustomResponse = $this->operationsClient->getLastCustomResponse(); - } } /** @@ -307,7 +302,11 @@ public function getDescriptorOptions(): array */ public function getLastProtoResponse(): ?object { - return $this->lastCustomResponse ?? $this->lastProtoResponse; + if ($this->operationsClient instanceof CustomOperationsClient) { + return $this->operationsClient->getLastProtoResponse() ?? $this->lastProtoResponse; + } + + return $this->lastProtoResponse; } /** From 7c6551e269c5281c74fc3810d5e9c1e13788f858 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 6 Nov 2026 20:06:20 +0000 Subject: [PATCH 08/11] revert: remove CustomOperationsClient to preserve GAPIC LRO BC --- .../OperationResponseTraitTest.php | 112 +++----- Gax/MIGRATING.md | 4 +- Gax/src/CustomOperationsClient.php | 252 ------------------ Gax/src/OperationResponse.php | 218 ++++++++++++--- Gax/tests/Unit/OperationResponseTest.php | 39 +-- 5 files changed, 219 insertions(+), 406 deletions(-) delete mode 100644 Gax/src/CustomOperationsClient.php diff --git a/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php b/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php index b090f9eb5931..1bfd54709939 100644 --- a/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php +++ b/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php @@ -62,6 +62,26 @@ public function setUp(): void { $serializer = $this->prophesize(Serializer::class); $serializer->encodeMessage(Argument::any())->will(function ($arg) { + if ($arg[0] instanceof Operation) { + $result = [ + 'done' => $arg[0]->getDone(), + 'metadata' => [ + 'typeUrl' => $arg[0]->getMetadata()->getTypeUrl(), + 'value' => $arg[0]->getMetadata()->getValue(), + ], + ]; + if ($arg[0]->hasResponse()) { + $result['response'] = [ + 'typeUrl' => $arg[0]->getResponse()->getTypeUrl(), + 'value' => $arg[0]->getResponse()->getValue(), + ]; + } + if ($arg[0]->hasError()) { + $result['error'] = $arg[0]->getError(); + } + + return $result; + } $json = $arg[0]->serializeToJsonString(); return json_decode($json, true); }); @@ -79,7 +99,7 @@ public function testOperationWithResponse() $meta = new RequestMetadata([ 'caller_ip' => '127.8.9.10', // Sic(!) ]); - $response = new Response(self::METADATA_TYPE, $meta, self::RESULT_TYPE, $result); + $response = $this->createOperation(self::METADATA_TYPE, $meta, self::RESULT_TYPE, $result); $operation = new OperationResponse( self::OPERATION_NAME, $this->operationsClient, @@ -112,8 +132,8 @@ public function testOperationWithError() $meta = new RequestMetadata([ 'caller_ip' => '127.8.9.10', // Sic(!) ]); - $response = new Response(self::METADATA_TYPE, $meta); - $response->error = $error; + $response = $this->createOperation(self::METADATA_TYPE, $meta); + $response->setError($error); $operation = new OperationResponse( self::OPERATION_NAME, $this->operationsClient, @@ -153,7 +173,7 @@ public function testLroCallable() $meta = new RequestMetadata([ 'caller_ip' => '127.8.9.10', ]); - $response = new Response(self::METADATA_TYPE, $meta, self::RESULT_TYPE, $result); + $response = $this->createOperation(self::METADATA_TYPE, $meta, self::RESULT_TYPE, $result); $operation = new OperationResponse( self::OPERATION_NAME, $this->operationsClient, @@ -178,81 +198,23 @@ public function testLroCallable() $expected = 'any|all|1'; $this->assertEquals($expected, $got); } -} - -//@codingStandardsIgnoreStart - -class Value extends Any -{ - public $value; - - public function __construct($value = null) - { - $this->value = $value; - } - public function getValue(): string + private function createOperation($metaType, $metadata, $respType = null, $response = null): Operation { - return (string) $this->value; - } -} - -class Response extends Operation -{ - public $metadataType; - public $metadata; - public $responseType; - public $response = null; - public $error = null; - - public function __construct($metaType, $metadata, $respType = null, $response = null) - { - $this->metadataType = $metaType; - $this->metadata = $metadata->serializeToString(); - $this->responseType = $respType; - if (isset($response)) { - $this->response = $response->serializeToString(); - } - } - - public function getResponse(): ?Any - { - return new Value($this->response); - } - - public function getMetadata(): ?Any - { - return new Value($this->metadata); - } - - public function getDone(): bool - { - return (isset($this->response) or isset($this->error)); - } - - public function getError(): ?Status - { - return $this->error; - } - - public function serializeToJsonString($options = 0): string - { - $result = [ + $operation = new Operation([ 'done' => true, - 'metadata' => [ - 'typeUrl' => $this->metadataType, - 'value' => $this->metadata, - ], - ]; - if (isset($this->response)) { - $result['response'] = [ - 'typeUrl' => $this->responseType, - 'value' => $this->response, - ]; + 'metadata' => new Any([ + 'type_url' => $metaType, + 'value' => $metadata->serializeToString(), + ]), + ]); + if (isset($response)) { + $operation->setResponse(new Any([ + 'type_url' => $respType, + 'value' => $response->serializeToString(), + ])); } - return json_encode($result); + return $operation; } } - -//@codingStandardsIgnoreEnd diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 51773dd2161f..4e4371340b79 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -58,7 +58,5 @@ Update your `google/gax` dependency to `^2.0`: - `__construct(string $operationName, object $operationsClient, array $options = [])` now requires non-null `$operationName` (`string`) and `$operationsClient` (`object`). - `getName()` now returns non-nullable `string`. - `getError()` now returns `?Google\Rpc\Status`. - - `getLastProtoResponse()` now returns `?object` (annotated as `Operation|Message|null`), preserving the raw custom operation message (e.g. `Google\Cloud\Compute\V1\Operation`) for custom operation services such as Compute. - - `getOperationsClient()` now returns `Google\LongRunning\Client\OperationsClient|Google\ApiCore\OperationsClientInterface`. - - Custom operations clients (e.g., Compute's `ZoneOperationsClient`) and custom operation options are now encapsulated in `Google\ApiCore\CustomOperationsClient` (implementing `Google\ApiCore\OperationsClientInterface`), which normalizes custom operation proto responses into `Google\LongRunning\Operation`. + - `getOperationsClient()` now returns non-nullable `object`. diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php deleted file mode 100644 index 1ff2fcec98c8..000000000000 --- a/Gax/src/CustomOperationsClient.php +++ /dev/null @@ -1,252 +0,0 @@ -client = $client; - $options += [ - 'getOperationMethod' => 'getOperation', - 'cancelOperationMethod' => 'cancelOperation', - 'deleteOperationMethod' => 'deleteOperation', - 'getOperationRequest' => GetOperationRequest::class, - 'cancelOperationRequest' => CancelOperationRequest::class, - 'deleteOperationRequest' => DeleteOperationRequest::class, - 'additionalOperationArguments' => [], - 'operationNameMethod' => 'getName', - 'operationStatusMethod' => 'getDone', - 'operationStatusDoneValue' => true, - 'operationErrorCodeMethod' => null, - 'operationErrorMessageMethod' => null, - ]; - - $this->getOperationMethod = $options['getOperationMethod']; - $this->cancelOperationMethod = $options['cancelOperationMethod']; - $this->deleteOperationMethod = $options['deleteOperationMethod']; - $this->getOperationRequest = $options['getOperationRequest']; - $this->cancelOperationRequest = $options['cancelOperationRequest']; - $this->deleteOperationRequest = $options['deleteOperationRequest']; - $this->additionalArgs = $options['additionalOperationArguments']; - $this->operationNameMethod = $options['operationNameMethod']; - $this->operationStatusMethod = $options['operationStatusMethod']; - $this->operationStatusDoneValue = $options['operationStatusDoneValue']; - $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; - $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; - } - - public static function hasCustomOptions(array $options): bool - { - foreach (self::CUSTOM_OPTION_KEYS as $key) { - if (array_key_exists($key, $options)) { - return true; - } - } - - return false; - } - - public function getOperation(GetOperationRequest $request, array $callOptions = []): Operation - { - $response = $this->operationsCall( - $this->getOperationMethod, - $this->getOperationRequest, - $request->getName(), - $callOptions - ); - - $this->lastProtoResponse = is_object($response) ? $response : null; - - return $this->toOperation($response); - } - - public function cancelOperation(CancelOperationRequest $request, array $callOptions = []): void - { - if (is_null($this->cancelOperationMethod) || is_null($this->cancelOperationRequest)) { - throw new LogicException('The cancel operation is not supported by this API'); - } - - $this->operationsCall( - $this->cancelOperationMethod, - $this->cancelOperationRequest, - $request->getName(), - $callOptions - ); - } - - public function deleteOperation(DeleteOperationRequest $request, array $callOptions = []): void - { - if (is_null($this->deleteOperationMethod) || is_null($this->deleteOperationRequest)) { - throw new LogicException('The delete operation is not supported by this API'); - } - - $this->operationsCall( - $this->deleteOperationMethod, - $this->deleteOperationRequest, - $request->getName(), - $callOptions - ); - } - - public function toOperation(?object $response): Operation - { - if (is_null($response)) { - return new Operation(); - } - - $this->lastProtoResponse = $response; - - if ($response instanceof Operation) { - return $response; - } - - $operation = new Operation(); - if (method_exists($response, $this->operationNameMethod)) { - $name = $response->{$this->operationNameMethod}(); - if (is_string($name)) { - $operation->setName($name); - } - } - - if (!method_exists($response, $this->operationStatusMethod)) { - return $operation; - } - - $status = $response->{$this->operationStatusMethod}(); - $done = !is_null($status) && $status === $this->operationStatusDoneValue; - $operation->setDone($done); - - if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { - $errorCode = $this->operationErrorCodeMethod - ? $response->{$this->operationErrorCodeMethod}() - : null; - if (!empty($errorCode)) { - $errorMessage = $this->operationErrorMessageMethod - ? $response->{$this->operationErrorMessageMethod}() - : ''; - $operation->setError( - (new Status()) - ->setCode(ApiStatus::rpcCodeFromHttpStatusCode($errorCode)) - ->setMessage((string) $errorMessage) - ); - } - } elseif (method_exists($response, 'getError')) { - $error = $response->getError(); - if (!empty($error)) { - $operation->setError( - $error instanceof Status ? $error : (new Status())->setCode(Code::UNKNOWN) - ); - } - } elseif ($done) { - throw new LogicException('Unable to determine operation error status for this service'); - } - - return $operation; - } - - public function getLastProtoResponse(): ?object - { - return $this->lastProtoResponse; - } - - private function operationsCall( - string $method, - string $requestClass, - string $operationName, - array $callOptions = [] - ): mixed { - if (!method_exists($requestClass, 'build')) { - throw new LogicException('Request class must support the static build method'); - } - - // In Compute, the Request "build" methods contain the operation ID last instead - // of first. Compute is the only API which uses $additionalArgs, so switching the order - // will not break anything. - $request = $requestClass::build(...array_merge( - array_values($this->additionalArgs), - [$operationName] - )); - - if ($callOptions) { - return $this->client->$method($request, $callOptions); - } - - return $this->client->$method($request); - } -} diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index e3cd90fe55a3..57113071fd3f 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -70,7 +70,7 @@ class OperationResponse const DEFAULT_MAX_POLLING_DURATION = 0; private string $operationName; - private OperationsClient|OperationsClientInterface $operationsClient; + private object $operationsClient; private ?string $operationReturnType; private ?string $metadataReturnType; @@ -81,9 +81,21 @@ class OperationResponse 'totalPollTimeoutMillis' => self::DEFAULT_MAX_POLLING_DURATION, ]; - private ?Operation $lastProtoResponse; + private ?object $lastProtoResponse; private bool $deleted = false; + private array $additionalArgs; + private string $getOperationMethod; + private ?string $cancelOperationMethod; + private ?string $deleteOperationMethod; + private string $getOperationRequest; + private ?string $cancelOperationRequest; + private ?string $deleteOperationRequest; + private string $operationStatusMethod; + private mixed $operationStatusDoneValue; + private ?string $operationErrorCodeMethod; + private ?string $operationErrorMessageMethod; + /** * OperationResponse constructor. * @@ -115,24 +127,37 @@ public function __construct( array $options = [] ) { $this->operationName = $operationName; - // @TODO: Remove check for OperationsClient once support for google/longrunning:0.4 is dropped - $isStandardClient = $operationsClient instanceof OperationsClient - || $operationsClient instanceof OperationsClientInterface; - if (!$isStandardClient || CustomOperationsClient::hasCustomOptions($options)) { - $operationsClient = new CustomOperationsClient($operationsClient, $options); - } $this->operationsClient = $operationsClient; - $this->operationReturnType = $options['operationReturnType'] ?? null; - $this->metadataReturnType = $options['metadataReturnType'] ?? null; - - $lastProtoResponse = $options['lastProtoResponse'] ?? null; - if ($lastProtoResponse !== null && !$lastProtoResponse instanceof Operation) { - $customClient = $this->operationsClient instanceof CustomOperationsClient - ? $this->operationsClient - : new CustomOperationsClient($this->operationsClient, $options); - $lastProtoResponse = $customClient->toOperation($lastProtoResponse); - } - $this->lastProtoResponse = $lastProtoResponse; + $options += [ + 'operationReturnType' => null, + 'metadataReturnType' => null, + 'lastProtoResponse' => null, + 'getOperationMethod' => 'getOperation', + 'cancelOperationMethod' => 'cancelOperation', + 'deleteOperationMethod' => 'deleteOperation', + 'operationStatusMethod' => 'getDone', + 'operationStatusDoneValue' => true, + 'additionalOperationArguments' => [], + 'operationErrorCodeMethod' => null, + 'operationErrorMessageMethod' => null, + 'getOperationRequest' => GetOperationRequest::class, + 'cancelOperationRequest' => CancelOperationRequest::class, + 'deleteOperationRequest' => DeleteOperationRequest::class, + ]; + $this->operationReturnType = $options['operationReturnType']; + $this->metadataReturnType = $options['metadataReturnType']; + $this->lastProtoResponse = $options['lastProtoResponse']; + $this->getOperationMethod = $options['getOperationMethod']; + $this->cancelOperationMethod = $options['cancelOperationMethod']; + $this->deleteOperationMethod = $options['deleteOperationMethod']; + $this->additionalArgs = $options['additionalOperationArguments']; + $this->operationStatusMethod = $options['operationStatusMethod']; + $this->operationStatusDoneValue = $options['operationStatusDoneValue']; + $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; + $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; + $this->getOperationRequest = $options['getOperationRequest']; + $this->cancelOperationRequest = $options['cancelOperationRequest']; + $this->deleteOperationRequest = $options['deleteOperationRequest']; if (isset($options['initialPollDelayMillis'])) { $this->defaultPollSettings['initialPollDelayMillis'] = $options['initialPollDelayMillis']; @@ -155,7 +180,16 @@ public function __construct( */ public function isDone(): bool { - return (bool) $this->lastProtoResponse?->getDone(); + if (!$this->hasProtoResponse()) { + return false; + } + + $status = call_user_func([$this->lastProtoResponse, $this->operationStatusMethod]); + if (is_null($status)) { + return false; + } + + return $status === $this->operationStatusDoneValue; } /** @@ -166,7 +200,17 @@ public function isDone(): bool */ public function operationSucceeded(): bool { - return $this->isDone() && !$this->operationFailed(); + if (!$this->hasProtoResponse()) { + return false; + } + + if (!$this->canHaveResult()) { + // For Operations which do not have a result, we consider a successful + // operation when the operation has completed without errors. + return $this->isDone() && !$this->hasErrors(); + } + + return !is_null($this->getResult()); } /** @@ -177,7 +221,7 @@ public function operationSucceeded(): bool */ public function operationFailed(): bool { - return !is_null($this->lastProtoResponse?->getError()); + return $this->hasErrors(); } /** @@ -235,8 +279,10 @@ public function reload(): void throw new ValidationException('Cannot call reload() on a deleted operation'); } - $request = GetOperationRequest::build($this->getName()); - $this->lastProtoResponse = $this->operationsClient->getOperation($request); + $this->lastProtoResponse = $this->operationsCall( + $this->getOperationMethod, + $this->getOperationRequest + ); } /** @@ -247,12 +293,20 @@ public function reload(): void */ public function getResult(): mixed { - if (!$this->operationSucceeded()) { + if (!$this->hasProtoResponse()) { + return null; + } + + if (!$this->canHaveResult()) { + return null; + } + + if (!$this->isDone()) { return null; } /** @var Any|null $anyResponse */ - $anyResponse = $this->lastProtoResponse?->getResponse(); + $anyResponse = $this->lastProtoResponse->getResponse(); if (is_null($anyResponse)) { return null; } @@ -274,11 +328,27 @@ public function getResult(): mixed */ public function getError(): ?Status { - if (!$this->isDone()) { + if (!$this->hasProtoResponse() || !$this->isDone()) { return null; } - return $this->lastProtoResponse?->getError(); + if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { + $errorCode = $this->operationErrorCodeMethod + ? call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]) + : null; + $errorMessage = $this->operationErrorMessageMethod + ? call_user_func([$this->lastProtoResponse, $this->operationErrorMessageMethod]) + : null; + return (new Status()) + ->setCode(ApiStatus::rpcCodeFromHttpStatusCode((int) $errorCode)) + ->setMessage((string) $errorMessage); + } + + if (method_exists($this->lastProtoResponse, 'getError')) { + return $this->lastProtoResponse->getError(); + } + + return null; } /** @@ -302,18 +372,14 @@ public function getDescriptorOptions(): array */ public function getLastProtoResponse(): ?object { - if ($this->operationsClient instanceof CustomOperationsClient) { - return $this->operationsClient->getLastProtoResponse() ?? $this->lastProtoResponse; - } - return $this->lastProtoResponse; } /** - * @return OperationsClient|OperationsClientInterface The OperationsClient object used to make + * @return OperationsClient|OperationsClientInterface|object The OperationsClient object used to make * requests to the operations API. */ - public function getOperationsClient(): OperationsClient|OperationsClientInterface + public function getOperationsClient(): object { return $this->operationsClient; } @@ -337,8 +403,11 @@ public function getOperationsClient(): OperationsClient|OperationsClientInterfac */ public function cancel(): void { - $request = CancelOperationRequest::build($this->getName()); - $this->operationsClient->cancelOperation($request); + if (is_null($this->cancelOperationMethod)) { + throw new LogicException('The cancel operation is not supported by this API'); + } + + $this->operationsCall($this->cancelOperationMethod, $this->cancelOperationRequest); } /** @@ -354,8 +423,11 @@ public function cancel(): void */ public function delete(): void { - $request = DeleteOperationRequest::build($this->getName()); - $this->operationsClient->deleteOperation($request); + if (is_null($this->deleteOperationMethod)) { + throw new LogicException('The delete operation is not supported by this API'); + } + + $this->operationsCall($this->deleteOperationMethod, $this->deleteOperationRequest); $this->deleted = true; } @@ -368,15 +440,81 @@ public function delete(): void */ public function getMetadata(): mixed { + if (!$this->hasProtoResponse()) { + return null; + } + + if (!method_exists($this->lastProtoResponse, 'getMetadata')) { + // The call to getMetadata is only for OnePlatform LROs, and is not + // supported by other LRO GAPIC clients (e.g. Compute) + return null; + } + /** @var Any|null $any */ - $any = $this->lastProtoResponse?->getMetadata(); - if (is_null($any) || is_null($this->metadataReturnType)) { + $any = $this->lastProtoResponse->getMetadata(); + if (is_null($this->metadataReturnType)) { return $any; } + if (is_null($any)) { + return null; + } $metadataReturnType = $this->metadataReturnType; /** @var Message $metadata */ $metadata = new $metadataReturnType(); $metadata->mergeFromString($any->getValue()); return $metadata; } + + /** + * Call the operations client to perform an operation. + * + * @param string $method The method to call on the operations client. + * @param string $requestClass The request class to use for the call. + * Will be null for legacy operations clients. + */ + private function operationsCall(string $method, string $requestClass): mixed + { + if (!method_exists($requestClass, 'build')) { + throw new LogicException('Request class must support the static build method'); + } + // In Compute, the Request "build" methods contain the operation ID last instead + // of first. Compute is the only API which uses $additionalArgs, so switching the order + // will not break anything. + $request = $requestClass::build(...array_merge( + array_values($this->additionalArgs), + [$this->getName()] + )); + return $this->operationsClient->$method($request); + } + + private function canHaveResult(): bool + { + // The call to getResponse is only for OnePlatform LROs, and is not + // supported by other LRO GAPIC clients (e.g. Compute) + return method_exists($this->lastProtoResponse, 'getResponse'); + } + + private function hasErrors(): bool + { + if (!$this->hasProtoResponse()) { + return false; + } + + if (method_exists($this->lastProtoResponse, 'getError')) { + return !empty($this->lastProtoResponse->getError()); + } + + if ($this->operationErrorCodeMethod) { + $errorCode = call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]); + return !empty($errorCode); + } + + // This should never happen unless an API is misconfigured + throw new LogicException('Unable to determine operation error status for this service'); + } + + private function hasProtoResponse(): bool + { + return !is_null($this->lastProtoResponse); + } } diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 0309578ae580..de31e5357f9d 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -38,7 +38,6 @@ use Google\CustomOperation\CustomOperationWithErrorAnnotations; use Google\CustomOperation\DeleteOperationRequest as CustomDeleteOperationRequest; use Google\CustomOperation\GetOperationRequest as CustomGetOperationRequest; -use Google\ApiCore\CustomOperationsClient; use Google\ApiCore\OperationResponse; use Google\ApiCore\OperationsClientInterface; use Google\LongRunning\CancelOperationRequest; @@ -233,7 +232,7 @@ public function testCustomOperation() $operationName = 'test-123'; $operation = $this->prophesize(CustomOperation::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn('Yes, it is!'); $operation->getError() ->shouldBeCalledOnce() @@ -366,10 +365,10 @@ public function testCustomOperationError($operationClient) $operationName = 'test-123'; $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn('Yes, it is!'); $operation->getTheErrorCode() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn(500); $operation->getTheErrorMessage() ->shouldBeCalledOnce() @@ -544,38 +543,6 @@ public function testOperationsClientInterface() $operationResponse->delete(); } - public function testCustomOperationsClientDirectly() - { - $operationName = 'test-123'; - $customOp = $this->prophesize(CustomOperation::class); - $customOp->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() - ->willReturn('Yes, it is!'); - $customOp->getError() - ->shouldBeCalledOnce() - ->willReturn(null); - - $rawClient = $this->prophesize(CustomOperationClient::class); - $rawClient->getMyOperationPlease(Argument::type(Message::class)) - ->shouldBeCalledOnce() - ->willReturn($customOp->reveal()); - - $adapter = new CustomOperationsClient($rawClient->reveal(), [ - 'getOperationMethod' => 'getMyOperationPlease', - 'operationStatusMethod' => 'isThisOperationDoneOrWhat', - 'operationStatusDoneValue' => 'Yes, it is!', - ]); - - $operationResponse = new OperationResponse($operationName, $adapter); - $this->assertSame($adapter, $operationResponse->getOperationsClient()); - $this->assertInstanceOf(OperationsClientInterface::class, $operationResponse->getOperationsClient()); - - $operationResponse->reload(); - $this->assertTrue($operationResponse->isDone()); - $this->assertTrue($operationResponse->operationSucceeded()); - $this->assertSame($customOp->reveal(), $operationResponse->getLastProtoResponse()); - } - private function createOperationResponse($options, $reloadCount) { $opName = 'operations/opname'; From 3ca49f429e05651ca76ef7885134cd3bd1e81f0a Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 6 Nov 2026 21:26:23 +0000 Subject: [PATCH 09/11] feat(Gax): add OperationsClientWrapperInterface and restore CustomOperationsClient --- Gax/MIGRATING.md | 4 +- Gax/src/CustomOperationsClient.php | 257 +++++++++++++++++++ Gax/src/OperationResponse.php | 218 +++------------- Gax/src/OperationsClientWrapperInterface.php | 50 ++++ Gax/tests/Unit/OperationResponseTest.php | 40 ++- 5 files changed, 389 insertions(+), 180 deletions(-) create mode 100644 Gax/src/CustomOperationsClient.php create mode 100644 Gax/src/OperationsClientWrapperInterface.php diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 4e4371340b79..31476d193504 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -58,5 +58,7 @@ Update your `google/gax` dependency to `^2.0`: - `__construct(string $operationName, object $operationsClient, array $options = [])` now requires non-null `$operationName` (`string`) and `$operationsClient` (`object`). - `getName()` now returns non-nullable `string`. - `getError()` now returns `?Google\Rpc\Status`. - - `getOperationsClient()` now returns non-nullable `object`. + - `getLastProtoResponse()` now returns `?object` (annotated as `Operation|Message|null`), preserving the raw custom operation message (e.g. `Google\Cloud\Compute\V1\Operation`) for custom operation services such as Compute. + - `getOperationsClient()` now returns non-nullable `object` (annotated as `OperationsClient|OperationsClientInterface|object`), unwrapping `OperationsClientWrapperInterface` adapters so custom operation services still receive their underlying operations client. + - Custom operations clients (e.g., Compute's `ZoneOperationsClient`) and custom operation options are now encapsulated in `Google\ApiCore\CustomOperationsClient` (implementing `Google\ApiCore\OperationsClientWrapperInterface`). diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php new file mode 100644 index 000000000000..0ef413f51f84 --- /dev/null +++ b/Gax/src/CustomOperationsClient.php @@ -0,0 +1,257 @@ +client = $client; + $options += [ + 'getOperationMethod' => 'getOperation', + 'cancelOperationMethod' => 'cancelOperation', + 'deleteOperationMethod' => 'deleteOperation', + 'getOperationRequest' => GetOperationRequest::class, + 'cancelOperationRequest' => CancelOperationRequest::class, + 'deleteOperationRequest' => DeleteOperationRequest::class, + 'additionalOperationArguments' => [], + 'operationNameMethod' => 'getName', + 'operationStatusMethod' => 'getDone', + 'operationStatusDoneValue' => true, + 'operationErrorCodeMethod' => null, + 'operationErrorMessageMethod' => null, + ]; + + $this->getOperationMethod = $options['getOperationMethod']; + $this->cancelOperationMethod = $options['cancelOperationMethod']; + $this->deleteOperationMethod = $options['deleteOperationMethod']; + $this->getOperationRequest = $options['getOperationRequest']; + $this->cancelOperationRequest = $options['cancelOperationRequest']; + $this->deleteOperationRequest = $options['deleteOperationRequest']; + $this->additionalArgs = $options['additionalOperationArguments']; + $this->operationNameMethod = $options['operationNameMethod']; + $this->operationStatusMethod = $options['operationStatusMethod']; + $this->operationStatusDoneValue = $options['operationStatusDoneValue']; + $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; + $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; + } + + public static function hasCustomOptions(array $options): bool + { + foreach (self::CUSTOM_OPTION_KEYS as $key) { + if (array_key_exists($key, $options)) { + return true; + } + } + + return false; + } + + public function getOperation(GetOperationRequest $request, array $callOptions = []): Operation + { + $response = $this->operationsCall( + $this->getOperationMethod, + $this->getOperationRequest, + $request->getName(), + $callOptions + ); + + $this->lastProtoResponse = is_object($response) ? $response : null; + + return $this->toOperation($response); + } + + public function cancelOperation(CancelOperationRequest $request, array $callOptions = []): void + { + if (is_null($this->cancelOperationMethod) || is_null($this->cancelOperationRequest)) { + throw new LogicException('The cancel operation is not supported by this API'); + } + + $this->operationsCall( + $this->cancelOperationMethod, + $this->cancelOperationRequest, + $request->getName(), + $callOptions + ); + } + + public function deleteOperation(DeleteOperationRequest $request, array $callOptions = []): void + { + if (is_null($this->deleteOperationMethod) || is_null($this->deleteOperationRequest)) { + throw new LogicException('The delete operation is not supported by this API'); + } + + $this->operationsCall( + $this->deleteOperationMethod, + $this->deleteOperationRequest, + $request->getName(), + $callOptions + ); + } + + public function toOperation(?object $response): Operation + { + if (is_null($response)) { + return new Operation(); + } + + $this->lastProtoResponse = $response; + + if ($response instanceof Operation) { + return $response; + } + + $operation = new Operation(); + if (method_exists($response, $this->operationNameMethod)) { + $name = $response->{$this->operationNameMethod}(); + if (is_string($name)) { + $operation->setName($name); + } + } + + if (!method_exists($response, $this->operationStatusMethod)) { + return $operation; + } + + $status = $response->{$this->operationStatusMethod}(); + $done = !is_null($status) && $status === $this->operationStatusDoneValue; + $operation->setDone($done); + + if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { + $errorCode = $this->operationErrorCodeMethod + ? $response->{$this->operationErrorCodeMethod}() + : null; + if (!empty($errorCode)) { + $errorMessage = $this->operationErrorMessageMethod + ? $response->{$this->operationErrorMessageMethod}() + : ''; + $operation->setError( + (new Status()) + ->setCode(ApiStatus::rpcCodeFromHttpStatusCode($errorCode)) + ->setMessage((string) $errorMessage) + ); + } + } elseif (method_exists($response, 'getError')) { + $error = $response->getError(); + if (!empty($error)) { + $operation->setError( + $error instanceof Status ? $error : (new Status())->setCode(Code::UNKNOWN) + ); + } + } elseif ($done) { + throw new LogicException('Unable to determine operation error status for this service'); + } + + return $operation; + } + + public function getOperationsClient(): object + { + return $this->client; + } + + public function getLastProtoResponse(): ?object + { + return $this->lastProtoResponse; + } + + private function operationsCall( + string $method, + string $requestClass, + string $operationName, + array $callOptions = [] + ): mixed { + if (!method_exists($requestClass, 'build')) { + throw new LogicException('Request class must support the static build method'); + } + + // In Compute, the Request "build" methods contain the operation ID last instead + // of first. Compute is the only API which uses $additionalArgs, so switching the order + // will not break anything. + $request = $requestClass::build(...array_merge( + array_values($this->additionalArgs), + [$operationName] + )); + + if ($callOptions) { + return $this->client->$method($request, $callOptions); + } + + return $this->client->$method($request); + } +} diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 57113071fd3f..a3e71a1b62d2 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -70,7 +70,7 @@ class OperationResponse const DEFAULT_MAX_POLLING_DURATION = 0; private string $operationName; - private object $operationsClient; + private OperationsClient|OperationsClientInterface $operationsClient; private ?string $operationReturnType; private ?string $metadataReturnType; @@ -81,21 +81,9 @@ class OperationResponse 'totalPollTimeoutMillis' => self::DEFAULT_MAX_POLLING_DURATION, ]; - private ?object $lastProtoResponse; + private ?Operation $lastProtoResponse; private bool $deleted = false; - private array $additionalArgs; - private string $getOperationMethod; - private ?string $cancelOperationMethod; - private ?string $deleteOperationMethod; - private string $getOperationRequest; - private ?string $cancelOperationRequest; - private ?string $deleteOperationRequest; - private string $operationStatusMethod; - private mixed $operationStatusDoneValue; - private ?string $operationErrorCodeMethod; - private ?string $operationErrorMessageMethod; - /** * OperationResponse constructor. * @@ -127,37 +115,24 @@ public function __construct( array $options = [] ) { $this->operationName = $operationName; + // @TODO: Remove check for OperationsClient once support for google/longrunning:0.4 is dropped + $isStandardClient = $operationsClient instanceof OperationsClient + || $operationsClient instanceof OperationsClientInterface; + if (!$isStandardClient || CustomOperationsClient::hasCustomOptions($options)) { + $operationsClient = new CustomOperationsClient($operationsClient, $options); + } $this->operationsClient = $operationsClient; - $options += [ - 'operationReturnType' => null, - 'metadataReturnType' => null, - 'lastProtoResponse' => null, - 'getOperationMethod' => 'getOperation', - 'cancelOperationMethod' => 'cancelOperation', - 'deleteOperationMethod' => 'deleteOperation', - 'operationStatusMethod' => 'getDone', - 'operationStatusDoneValue' => true, - 'additionalOperationArguments' => [], - 'operationErrorCodeMethod' => null, - 'operationErrorMessageMethod' => null, - 'getOperationRequest' => GetOperationRequest::class, - 'cancelOperationRequest' => CancelOperationRequest::class, - 'deleteOperationRequest' => DeleteOperationRequest::class, - ]; - $this->operationReturnType = $options['operationReturnType']; - $this->metadataReturnType = $options['metadataReturnType']; - $this->lastProtoResponse = $options['lastProtoResponse']; - $this->getOperationMethod = $options['getOperationMethod']; - $this->cancelOperationMethod = $options['cancelOperationMethod']; - $this->deleteOperationMethod = $options['deleteOperationMethod']; - $this->additionalArgs = $options['additionalOperationArguments']; - $this->operationStatusMethod = $options['operationStatusMethod']; - $this->operationStatusDoneValue = $options['operationStatusDoneValue']; - $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; - $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; - $this->getOperationRequest = $options['getOperationRequest']; - $this->cancelOperationRequest = $options['cancelOperationRequest']; - $this->deleteOperationRequest = $options['deleteOperationRequest']; + $this->operationReturnType = $options['operationReturnType'] ?? null; + $this->metadataReturnType = $options['metadataReturnType'] ?? null; + + $lastProtoResponse = $options['lastProtoResponse'] ?? null; + if ($lastProtoResponse !== null && !$lastProtoResponse instanceof Operation) { + $wrapper = $this->operationsClient instanceof OperationsClientWrapperInterface + ? $this->operationsClient + : new CustomOperationsClient($this->operationsClient, $options); + $lastProtoResponse = $wrapper->toOperation($lastProtoResponse); + } + $this->lastProtoResponse = $lastProtoResponse; if (isset($options['initialPollDelayMillis'])) { $this->defaultPollSettings['initialPollDelayMillis'] = $options['initialPollDelayMillis']; @@ -180,16 +155,7 @@ public function __construct( */ public function isDone(): bool { - if (!$this->hasProtoResponse()) { - return false; - } - - $status = call_user_func([$this->lastProtoResponse, $this->operationStatusMethod]); - if (is_null($status)) { - return false; - } - - return $status === $this->operationStatusDoneValue; + return (bool) $this->lastProtoResponse?->getDone(); } /** @@ -200,17 +166,7 @@ public function isDone(): bool */ public function operationSucceeded(): bool { - if (!$this->hasProtoResponse()) { - return false; - } - - if (!$this->canHaveResult()) { - // For Operations which do not have a result, we consider a successful - // operation when the operation has completed without errors. - return $this->isDone() && !$this->hasErrors(); - } - - return !is_null($this->getResult()); + return $this->isDone() && !$this->operationFailed(); } /** @@ -221,7 +177,7 @@ public function operationSucceeded(): bool */ public function operationFailed(): bool { - return $this->hasErrors(); + return !is_null($this->lastProtoResponse?->getError()); } /** @@ -279,10 +235,8 @@ public function reload(): void throw new ValidationException('Cannot call reload() on a deleted operation'); } - $this->lastProtoResponse = $this->operationsCall( - $this->getOperationMethod, - $this->getOperationRequest - ); + $request = GetOperationRequest::build($this->getName()); + $this->lastProtoResponse = $this->operationsClient->getOperation($request); } /** @@ -293,20 +247,12 @@ public function reload(): void */ public function getResult(): mixed { - if (!$this->hasProtoResponse()) { - return null; - } - - if (!$this->canHaveResult()) { - return null; - } - - if (!$this->isDone()) { + if (!$this->operationSucceeded()) { return null; } /** @var Any|null $anyResponse */ - $anyResponse = $this->lastProtoResponse->getResponse(); + $anyResponse = $this->lastProtoResponse?->getResponse(); if (is_null($anyResponse)) { return null; } @@ -328,27 +274,11 @@ public function getResult(): mixed */ public function getError(): ?Status { - if (!$this->hasProtoResponse() || !$this->isDone()) { + if (!$this->isDone()) { return null; } - if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { - $errorCode = $this->operationErrorCodeMethod - ? call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]) - : null; - $errorMessage = $this->operationErrorMessageMethod - ? call_user_func([$this->lastProtoResponse, $this->operationErrorMessageMethod]) - : null; - return (new Status()) - ->setCode(ApiStatus::rpcCodeFromHttpStatusCode((int) $errorCode)) - ->setMessage((string) $errorMessage); - } - - if (method_exists($this->lastProtoResponse, 'getError')) { - return $this->lastProtoResponse->getError(); - } - - return null; + return $this->lastProtoResponse?->getError(); } /** @@ -372,6 +302,10 @@ public function getDescriptorOptions(): array */ public function getLastProtoResponse(): ?object { + if ($this->operationsClient instanceof OperationsClientWrapperInterface) { + return $this->operationsClient->getLastProtoResponse() ?? $this->lastProtoResponse; + } + return $this->lastProtoResponse; } @@ -381,6 +315,10 @@ public function getLastProtoResponse(): ?object */ public function getOperationsClient(): object { + if ($this->operationsClient instanceof OperationsClientWrapperInterface) { + return $this->operationsClient->getOperationsClient(); + } + return $this->operationsClient; } @@ -403,11 +341,8 @@ public function getOperationsClient(): object */ public function cancel(): void { - if (is_null($this->cancelOperationMethod)) { - throw new LogicException('The cancel operation is not supported by this API'); - } - - $this->operationsCall($this->cancelOperationMethod, $this->cancelOperationRequest); + $request = CancelOperationRequest::build($this->getName()); + $this->operationsClient->cancelOperation($request); } /** @@ -423,11 +358,8 @@ public function cancel(): void */ public function delete(): void { - if (is_null($this->deleteOperationMethod)) { - throw new LogicException('The delete operation is not supported by this API'); - } - - $this->operationsCall($this->deleteOperationMethod, $this->deleteOperationRequest); + $request = DeleteOperationRequest::build($this->getName()); + $this->operationsClient->deleteOperation($request); $this->deleted = true; } @@ -440,81 +372,15 @@ public function delete(): void */ public function getMetadata(): mixed { - if (!$this->hasProtoResponse()) { - return null; - } - - if (!method_exists($this->lastProtoResponse, 'getMetadata')) { - // The call to getMetadata is only for OnePlatform LROs, and is not - // supported by other LRO GAPIC clients (e.g. Compute) - return null; - } - /** @var Any|null $any */ - $any = $this->lastProtoResponse->getMetadata(); - if (is_null($this->metadataReturnType)) { + $any = $this->lastProtoResponse?->getMetadata(); + if (is_null($any) || is_null($this->metadataReturnType)) { return $any; } - if (is_null($any)) { - return null; - } $metadataReturnType = $this->metadataReturnType; /** @var Message $metadata */ $metadata = new $metadataReturnType(); $metadata->mergeFromString($any->getValue()); return $metadata; } - - /** - * Call the operations client to perform an operation. - * - * @param string $method The method to call on the operations client. - * @param string $requestClass The request class to use for the call. - * Will be null for legacy operations clients. - */ - private function operationsCall(string $method, string $requestClass): mixed - { - if (!method_exists($requestClass, 'build')) { - throw new LogicException('Request class must support the static build method'); - } - // In Compute, the Request "build" methods contain the operation ID last instead - // of first. Compute is the only API which uses $additionalArgs, so switching the order - // will not break anything. - $request = $requestClass::build(...array_merge( - array_values($this->additionalArgs), - [$this->getName()] - )); - return $this->operationsClient->$method($request); - } - - private function canHaveResult(): bool - { - // The call to getResponse is only for OnePlatform LROs, and is not - // supported by other LRO GAPIC clients (e.g. Compute) - return method_exists($this->lastProtoResponse, 'getResponse'); - } - - private function hasErrors(): bool - { - if (!$this->hasProtoResponse()) { - return false; - } - - if (method_exists($this->lastProtoResponse, 'getError')) { - return !empty($this->lastProtoResponse->getError()); - } - - if ($this->operationErrorCodeMethod) { - $errorCode = call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]); - return !empty($errorCode); - } - - // This should never happen unless an API is misconfigured - throw new LogicException('Unable to determine operation error status for this service'); - } - - private function hasProtoResponse(): bool - { - return !is_null($this->lastProtoResponse); - } } diff --git a/Gax/src/OperationsClientWrapperInterface.php b/Gax/src/OperationsClientWrapperInterface.php new file mode 100644 index 000000000000..4845b1f36fe4 --- /dev/null +++ b/Gax/src/OperationsClientWrapperInterface.php @@ -0,0 +1,50 @@ +prophesize(CustomOperation::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledTimes(2) + ->shouldBeCalledOnce() ->willReturn('Yes, it is!'); $operation->getError() ->shouldBeCalledOnce() @@ -365,10 +367,10 @@ public function testCustomOperationError($operationClient) $operationName = 'test-123'; $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledTimes(2) + ->shouldBeCalledOnce() ->willReturn('Yes, it is!'); $operation->getTheErrorCode() - ->shouldBeCalledTimes(2) + ->shouldBeCalledOnce() ->willReturn(500); $operation->getTheErrorMessage() ->shouldBeCalledOnce() @@ -543,6 +545,38 @@ public function testOperationsClientInterface() $operationResponse->delete(); } + public function testCustomOperationsClientDirectly() + { + $operationName = 'test-123'; + $customOp = $this->prophesize(CustomOperation::class); + $customOp->isThisOperationDoneOrWhat() + ->shouldBeCalledOnce() + ->willReturn('Yes, it is!'); + $customOp->getError() + ->shouldBeCalledOnce() + ->willReturn(null); + + $rawClient = $this->prophesize(CustomOperationClient::class); + $rawClient->getMyOperationPlease(Argument::type(Message::class)) + ->shouldBeCalledOnce() + ->willReturn($customOp->reveal()); + + $adapter = new CustomOperationsClient($rawClient->reveal(), [ + 'getOperationMethod' => 'getMyOperationPlease', + 'operationStatusMethod' => 'isThisOperationDoneOrWhat', + 'operationStatusDoneValue' => 'Yes, it is!', + ]); + $this->assertInstanceOf(OperationsClientWrapperInterface::class, $adapter); + + $operationResponse = new OperationResponse($operationName, $adapter); + $this->assertSame($rawClient->reveal(), $operationResponse->getOperationsClient()); + + $operationResponse->reload(); + $this->assertTrue($operationResponse->isDone()); + $this->assertTrue($operationResponse->operationSucceeded()); + $this->assertSame($customOp->reveal(), $operationResponse->getLastProtoResponse()); + } + private function createOperationResponse($options, $reloadCount) { $opName = 'operations/opname'; From 94be853882aa98deb4b494ec8d5ea3a9f0127468 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 6 Nov 2026 21:50:33 +0000 Subject: [PATCH 10/11] refactor(Gax): simplify OperationsClientWrapperInterface to getOperationsClient --- Gax/MIGRATING.md | 2 +- Gax/src/CustomOperationsClient.php | 96 +------------ Gax/src/OperationResponse.php | 143 +++++++++++++++---- Gax/src/OperationsClientInterface.php | 6 +- Gax/src/OperationsClientWrapperInterface.php | 10 -- Gax/tests/Unit/OperationResponseTest.php | 15 +- 6 files changed, 135 insertions(+), 137 deletions(-) diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 31476d193504..e2ce7dfafc51 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -60,5 +60,5 @@ Update your `google/gax` dependency to `^2.0`: - `getError()` now returns `?Google\Rpc\Status`. - `getLastProtoResponse()` now returns `?object` (annotated as `Operation|Message|null`), preserving the raw custom operation message (e.g. `Google\Cloud\Compute\V1\Operation`) for custom operation services such as Compute. - `getOperationsClient()` now returns non-nullable `object` (annotated as `OperationsClient|OperationsClientInterface|object`), unwrapping `OperationsClientWrapperInterface` adapters so custom operation services still receive their underlying operations client. - - Custom operations clients (e.g., Compute's `ZoneOperationsClient`) and custom operation options are now encapsulated in `Google\ApiCore\CustomOperationsClient` (implementing `Google\ApiCore\OperationsClientWrapperInterface`). + - Custom operations clients (e.g., Compute's `ZoneOperationsClient`) and custom operation RPC options are now encapsulated in `Google\ApiCore\CustomOperationsClient` (implementing `Google\ApiCore\OperationsClientWrapperInterface`). diff --git a/Gax/src/CustomOperationsClient.php b/Gax/src/CustomOperationsClient.php index 0ef413f51f84..a5562d3db231 100644 --- a/Gax/src/CustomOperationsClient.php +++ b/Gax/src/CustomOperationsClient.php @@ -37,15 +37,11 @@ use Google\LongRunning\CancelOperationRequest; use Google\LongRunning\DeleteOperationRequest; use Google\LongRunning\GetOperationRequest; -use Google\LongRunning\Operation; -use Google\Rpc\Code; -use Google\Rpc\Status; use LogicException; /** * Adapter that wraps a custom operations client (e.g. Compute's ZoneOperationsClient) - * to implement {@see \Google\ApiCore\OperationsClientWrapperInterface} and normalize custom operation messages - * into {@see \Google\LongRunning\Operation}. + * to implement {@see \Google\ApiCore\OperationsClientWrapperInterface}. */ class CustomOperationsClient implements OperationsClientWrapperInterface { @@ -57,11 +53,6 @@ class CustomOperationsClient implements OperationsClientWrapperInterface 'cancelOperationRequest', 'deleteOperationRequest', 'additionalOperationArguments', - 'operationNameMethod', - 'operationStatusMethod', - 'operationStatusDoneValue', - 'operationErrorCodeMethod', - 'operationErrorMessageMethod', ]; private object $client; @@ -72,12 +63,6 @@ class CustomOperationsClient implements OperationsClientWrapperInterface private string $getOperationRequest; private ?string $cancelOperationRequest; private ?string $deleteOperationRequest; - private string $operationNameMethod; - private string $operationStatusMethod; - private mixed $operationStatusDoneValue; - private ?string $operationErrorCodeMethod; - private ?string $operationErrorMessageMethod; - private ?object $lastProtoResponse = null; public function __construct(object $client, array $options = []) { @@ -90,11 +75,6 @@ public function __construct(object $client, array $options = []) 'cancelOperationRequest' => CancelOperationRequest::class, 'deleteOperationRequest' => DeleteOperationRequest::class, 'additionalOperationArguments' => [], - 'operationNameMethod' => 'getName', - 'operationStatusMethod' => 'getDone', - 'operationStatusDoneValue' => true, - 'operationErrorCodeMethod' => null, - 'operationErrorMessageMethod' => null, ]; $this->getOperationMethod = $options['getOperationMethod']; @@ -104,11 +84,6 @@ public function __construct(object $client, array $options = []) $this->cancelOperationRequest = $options['cancelOperationRequest']; $this->deleteOperationRequest = $options['deleteOperationRequest']; $this->additionalArgs = $options['additionalOperationArguments']; - $this->operationNameMethod = $options['operationNameMethod']; - $this->operationStatusMethod = $options['operationStatusMethod']; - $this->operationStatusDoneValue = $options['operationStatusDoneValue']; - $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; - $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; } public static function hasCustomOptions(array $options): bool @@ -122,18 +97,14 @@ public static function hasCustomOptions(array $options): bool return false; } - public function getOperation(GetOperationRequest $request, array $callOptions = []): Operation + public function getOperation(GetOperationRequest $request, array $callOptions = []): object { - $response = $this->operationsCall( + return $this->operationsCall( $this->getOperationMethod, $this->getOperationRequest, $request->getName(), $callOptions ); - - $this->lastProtoResponse = is_object($response) ? $response : null; - - return $this->toOperation($response); } public function cancelOperation(CancelOperationRequest $request, array $callOptions = []): void @@ -164,72 +135,11 @@ public function deleteOperation(DeleteOperationRequest $request, array $callOpti ); } - public function toOperation(?object $response): Operation - { - if (is_null($response)) { - return new Operation(); - } - - $this->lastProtoResponse = $response; - - if ($response instanceof Operation) { - return $response; - } - - $operation = new Operation(); - if (method_exists($response, $this->operationNameMethod)) { - $name = $response->{$this->operationNameMethod}(); - if (is_string($name)) { - $operation->setName($name); - } - } - - if (!method_exists($response, $this->operationStatusMethod)) { - return $operation; - } - - $status = $response->{$this->operationStatusMethod}(); - $done = !is_null($status) && $status === $this->operationStatusDoneValue; - $operation->setDone($done); - - if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { - $errorCode = $this->operationErrorCodeMethod - ? $response->{$this->operationErrorCodeMethod}() - : null; - if (!empty($errorCode)) { - $errorMessage = $this->operationErrorMessageMethod - ? $response->{$this->operationErrorMessageMethod}() - : ''; - $operation->setError( - (new Status()) - ->setCode(ApiStatus::rpcCodeFromHttpStatusCode($errorCode)) - ->setMessage((string) $errorMessage) - ); - } - } elseif (method_exists($response, 'getError')) { - $error = $response->getError(); - if (!empty($error)) { - $operation->setError( - $error instanceof Status ? $error : (new Status())->setCode(Code::UNKNOWN) - ); - } - } elseif ($done) { - throw new LogicException('Unable to determine operation error status for this service'); - } - - return $operation; - } - public function getOperationsClient(): object { return $this->client; } - public function getLastProtoResponse(): ?object - { - return $this->lastProtoResponse; - } - private function operationsCall( string $method, string $requestClass, diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index a3e71a1b62d2..b0f8e145d30d 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -81,9 +81,14 @@ class OperationResponse 'totalPollTimeoutMillis' => self::DEFAULT_MAX_POLLING_DURATION, ]; - private ?Operation $lastProtoResponse; + private ?object $lastProtoResponse; private bool $deleted = false; + private string $operationStatusMethod; + private mixed $operationStatusDoneValue; + private ?string $operationErrorCodeMethod; + private ?string $operationErrorMessageMethod; + /** * OperationResponse constructor. * @@ -122,17 +127,22 @@ public function __construct( $operationsClient = new CustomOperationsClient($operationsClient, $options); } $this->operationsClient = $operationsClient; - $this->operationReturnType = $options['operationReturnType'] ?? null; - $this->metadataReturnType = $options['metadataReturnType'] ?? null; - - $lastProtoResponse = $options['lastProtoResponse'] ?? null; - if ($lastProtoResponse !== null && !$lastProtoResponse instanceof Operation) { - $wrapper = $this->operationsClient instanceof OperationsClientWrapperInterface - ? $this->operationsClient - : new CustomOperationsClient($this->operationsClient, $options); - $lastProtoResponse = $wrapper->toOperation($lastProtoResponse); - } - $this->lastProtoResponse = $lastProtoResponse; + $options += [ + 'operationReturnType' => null, + 'metadataReturnType' => null, + 'lastProtoResponse' => null, + 'operationStatusMethod' => 'getDone', + 'operationStatusDoneValue' => true, + 'operationErrorCodeMethod' => null, + 'operationErrorMessageMethod' => null, + ]; + $this->operationReturnType = $options['operationReturnType']; + $this->metadataReturnType = $options['metadataReturnType']; + $this->lastProtoResponse = $options['lastProtoResponse']; + $this->operationStatusMethod = $options['operationStatusMethod']; + $this->operationStatusDoneValue = $options['operationStatusDoneValue']; + $this->operationErrorCodeMethod = $options['operationErrorCodeMethod']; + $this->operationErrorMessageMethod = $options['operationErrorMessageMethod']; if (isset($options['initialPollDelayMillis'])) { $this->defaultPollSettings['initialPollDelayMillis'] = $options['initialPollDelayMillis']; @@ -155,7 +165,16 @@ public function __construct( */ public function isDone(): bool { - return (bool) $this->lastProtoResponse?->getDone(); + if (!$this->hasProtoResponse()) { + return false; + } + + $status = call_user_func([$this->lastProtoResponse, $this->operationStatusMethod]); + if (is_null($status)) { + return false; + } + + return $status === $this->operationStatusDoneValue; } /** @@ -166,7 +185,17 @@ public function isDone(): bool */ public function operationSucceeded(): bool { - return $this->isDone() && !$this->operationFailed(); + if (!$this->hasProtoResponse()) { + return false; + } + + if (!$this->canHaveResult()) { + // For Operations which do not have a result, we consider a successful + // operation when the operation has completed without errors. + return $this->isDone() && !$this->hasErrors(); + } + + return !is_null($this->getResult()); } /** @@ -177,7 +206,7 @@ public function operationSucceeded(): bool */ public function operationFailed(): bool { - return !is_null($this->lastProtoResponse?->getError()); + return $this->hasErrors(); } /** @@ -247,12 +276,20 @@ public function reload(): void */ public function getResult(): mixed { - if (!$this->operationSucceeded()) { + if (!$this->hasProtoResponse()) { + return null; + } + + if (!$this->canHaveResult()) { + return null; + } + + if (!$this->isDone()) { return null; } /** @var Any|null $anyResponse */ - $anyResponse = $this->lastProtoResponse?->getResponse(); + $anyResponse = $this->lastProtoResponse->getResponse(); if (is_null($anyResponse)) { return null; } @@ -274,11 +311,27 @@ public function getResult(): mixed */ public function getError(): ?Status { - if (!$this->isDone()) { + if (!$this->hasProtoResponse() || !$this->isDone()) { return null; } - return $this->lastProtoResponse?->getError(); + if ($this->operationErrorCodeMethod || $this->operationErrorMessageMethod) { + $errorCode = $this->operationErrorCodeMethod + ? call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]) + : null; + $errorMessage = $this->operationErrorMessageMethod + ? call_user_func([$this->lastProtoResponse, $this->operationErrorMessageMethod]) + : null; + return (new Status()) + ->setCode(ApiStatus::rpcCodeFromHttpStatusCode((int) $errorCode)) + ->setMessage((string) $errorMessage); + } + + if (method_exists($this->lastProtoResponse, 'getError')) { + return $this->lastProtoResponse->getError(); + } + + return null; } /** @@ -302,10 +355,6 @@ public function getDescriptorOptions(): array */ public function getLastProtoResponse(): ?object { - if ($this->operationsClient instanceof OperationsClientWrapperInterface) { - return $this->operationsClient->getLastProtoResponse() ?? $this->lastProtoResponse; - } - return $this->lastProtoResponse; } @@ -372,15 +421,59 @@ public function delete(): void */ public function getMetadata(): mixed { + if (!$this->hasProtoResponse()) { + return null; + } + + if (!method_exists($this->lastProtoResponse, 'getMetadata')) { + // The call to getMetadata is only for OnePlatform LROs, and is not + // supported by other LRO GAPIC clients (e.g. Compute) + return null; + } + /** @var Any|null $any */ - $any = $this->lastProtoResponse?->getMetadata(); - if (is_null($any) || is_null($this->metadataReturnType)) { + $any = $this->lastProtoResponse->getMetadata(); + if (is_null($this->metadataReturnType)) { return $any; } + if (is_null($any)) { + return null; + } $metadataReturnType = $this->metadataReturnType; /** @var Message $metadata */ $metadata = new $metadataReturnType(); $metadata->mergeFromString($any->getValue()); return $metadata; } + + private function canHaveResult(): bool + { + // The call to getResponse is only for OnePlatform LROs, and is not + // supported by other LRO GAPIC clients (e.g. Compute) + return method_exists($this->lastProtoResponse, 'getResponse'); + } + + private function hasErrors(): bool + { + if (!$this->hasProtoResponse()) { + return false; + } + + if (method_exists($this->lastProtoResponse, 'getError')) { + return !empty($this->lastProtoResponse->getError()); + } + + if ($this->operationErrorCodeMethod) { + $errorCode = call_user_func([$this->lastProtoResponse, $this->operationErrorCodeMethod]); + return !empty($errorCode); + } + + // This should never happen unless an API is misconfigured + throw new LogicException('Unable to determine operation error status for this service'); + } + + private function hasProtoResponse(): bool + { + return !is_null($this->lastProtoResponse); + } } diff --git a/Gax/src/OperationsClientInterface.php b/Gax/src/OperationsClientInterface.php index 914cf703f923..95050c7f97b7 100644 --- a/Gax/src/OperationsClientInterface.php +++ b/Gax/src/OperationsClientInterface.php @@ -38,10 +38,14 @@ use Google\LongRunning\DeleteOperationRequest; use Google\LongRunning\GetOperationRequest; use Google\LongRunning\Operation; +use Google\Protobuf\Internal\Message; interface OperationsClientInterface { - public function getOperation(GetOperationRequest $request, array $callOptions = []): Operation; + /** + * @return Operation|Message + */ + public function getOperation(GetOperationRequest $request, array $callOptions = []): object; public function cancelOperation(CancelOperationRequest $request, array $callOptions = []): void; diff --git a/Gax/src/OperationsClientWrapperInterface.php b/Gax/src/OperationsClientWrapperInterface.php index 4845b1f36fe4..4cdfe142e6e5 100644 --- a/Gax/src/OperationsClientWrapperInterface.php +++ b/Gax/src/OperationsClientWrapperInterface.php @@ -34,17 +34,7 @@ namespace Google\ApiCore; -use Google\LongRunning\Operation; -use Google\Protobuf\Internal\Message; - interface OperationsClientWrapperInterface extends OperationsClientInterface { public function getOperationsClient(): object; - - /** - * @return Operation|Message|null - */ - public function getLastProtoResponse(): ?object; - - public function toOperation(?object $response): Operation; } diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index f1c220ed6c72..a04791c0c12b 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -234,7 +234,7 @@ public function testCustomOperation() $operationName = 'test-123'; $operation = $this->prophesize(CustomOperation::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn('Yes, it is!'); $operation->getError() ->shouldBeCalledOnce() @@ -367,10 +367,10 @@ public function testCustomOperationError($operationClient) $operationName = 'test-123'; $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn('Yes, it is!'); $operation->getTheErrorCode() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn(500); $operation->getTheErrorMessage() ->shouldBeCalledOnce() @@ -550,7 +550,7 @@ public function testCustomOperationsClientDirectly() $operationName = 'test-123'; $customOp = $this->prophesize(CustomOperation::class); $customOp->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() + ->shouldBeCalledTimes(2) ->willReturn('Yes, it is!'); $customOp->getError() ->shouldBeCalledOnce() @@ -563,12 +563,13 @@ public function testCustomOperationsClientDirectly() $adapter = new CustomOperationsClient($rawClient->reveal(), [ 'getOperationMethod' => 'getMyOperationPlease', - 'operationStatusMethod' => 'isThisOperationDoneOrWhat', - 'operationStatusDoneValue' => 'Yes, it is!', ]); $this->assertInstanceOf(OperationsClientWrapperInterface::class, $adapter); - $operationResponse = new OperationResponse($operationName, $adapter); + $operationResponse = new OperationResponse($operationName, $adapter, [ + 'operationStatusMethod' => 'isThisOperationDoneOrWhat', + 'operationStatusDoneValue' => 'Yes, it is!', + ]); $this->assertSame($rawClient->reveal(), $operationResponse->getOperationsClient()); $operationResponse->reload(); From 53ded2097a39d1abb1e54462f7b4359e8e17bc5f Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 12 Nov 2026 18:40:20 +0000 Subject: [PATCH 11/11] test(Gax): return Operation from getOperation mock in testAdditionalArgumentMethods --- Gax/tests/Unit/GapicClientTraitTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 79b83952fa3f..0dc5fd222f4e 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -906,7 +906,8 @@ public function testAdditionalArgumentMethods() $operationsClient->getOperation( \Google\CustomOperation\GetOperationRequest::build('abc', 100, 'test-123') ) - ->shouldBeCalledOnce(); + ->shouldBeCalledOnce() + ->willReturn($expectedOperation); $operationResponse = $client->startOperationsCall( 'method.name',