From 7b827e3e27080879faee9e89192e11de6fb70c20 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 7 Oct 2026 19:45:44 +0000 Subject: [PATCH 1/6] test(Gax): add OpenTelemetry tracing test plan and Showcase conformance tests --- Gax/composer.json | 3 +- Gax/tests/Conformance/OtelTracingTest.php | 572 +++++++++ .../Unit/Telemetry/TracingTestPlanTest.php | 1132 +++++++++++++++++ 3 files changed, 1706 insertions(+), 1 deletion(-) create mode 100644 Gax/tests/Conformance/OtelTracingTest.php create mode 100644 Gax/tests/Unit/Telemetry/TracingTestPlanTest.php diff --git a/Gax/composer.json b/Gax/composer.json index 4789cecff58f..07313bf2520b 100644 --- a/Gax/composer.json +++ b/Gax/composer.json @@ -25,7 +25,8 @@ "phpspec/prophecy-phpunit": "^2.1", "phpstan/phpstan": "^2.0", "google/cloud-tools": "^0.16.1", - "webmozart/assert": "^1.11.0" + "webmozart/assert": "^1.11.0", + "open-telemetry/sdk": "^1.13" }, "extra": { "component": { diff --git a/Gax/tests/Conformance/OtelTracingTest.php b/Gax/tests/Conformance/OtelTracingTest.php new file mode 100644 index 000000000000..b25c5e73db44 --- /dev/null +++ b/Gax/tests/Conformance/OtelTracingTest.php @@ -0,0 +1,572 @@ +exporter = new InMemoryExporter(); + $this->tracerProvider = new TracerProvider(new SimpleSpanProcessor($this->exporter)); + } + + protected function tearDown(): void + { + $this->tracerProvider->shutdown(); + parent::tearDown(); + } + + public function provideTransportType(): array + { + return [ + 'grpc' => ['grpc'], + 'rest' => ['rest'], + ]; + } + + /** + * @dataProvider provideTransportType + */ + public function testTracingDisabledEmitsOnlyAppSpan(string $transportType): void + { + $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, null); + $echoClient = new EchoClient([ + 'credentials' => new InsecureCredentialsWrapper(), + 'transport' => $transport, + ]); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $response = $echoClient->echo(new EchoRequest(['content' => 'trace disabled'])); + $this->assertSame('trace disabled', $response->getContent()); + } finally { + $appScope->detach(); + $appSpan->end(); + $echoClient->close(); + } + + $spans = $this->exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + /** + * @dataProvider provideTransportType + */ + public function testTracingSuccessfulEcho(string $transportType): void + { + $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, $this->tracerProvider); + $echoClient = new EchoClient([ + 'credentials' => new InsecureCredentialsWrapper(), + 'transport' => $transport, + 'openTelemetryTracerProvider' => $this->tracerProvider, + ]); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $response = $echoClient->echo(new EchoRequest(['content' => 'hello tracing'])); + $this->assertSame('hello tracing', $response->getContent()); + } finally { + $appScope->detach(); + $appSpan->end(); + $echoClient->close(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $expectedMethod = 'google.showcase.v1beta1.Echo/Echo'; + + if ($transportType === 'grpc') { + $this->assertCount(3, $spans); + $t4Span = $spans[0]; + $t3Span = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($t3Span->getSpanId(), $t4Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); + $this->assertSame($expectedMethod, $t4Span->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t4Span->getStatus()->getCode()); + $this->assertSame('google-cloud-php', $t4Span->getInstrumentationScope()->getName()); + + $t4Attrs = $t4Span->getAttributes()->toArray(); + $this->assertSame('grpc', $t4Attrs[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame($expectedMethod, $t4Attrs[SpanAttributes::RPC_METHOD]); + $this->assertSame('OK', $t4Attrs[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame(self::SERVER_ADDRESS, $t4Attrs[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(self::SERVER_PORT, $t4Attrs[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $t4Attrs); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $t4Attrs); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $t4Attrs); + } else { + $this->assertCount(2, $spans); + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + } + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame($expectedMethod, $t3Span->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); + $this->assertSame('google-cloud-php', $t3Span->getInstrumentationScope()->getName()); + + $t3Attrs = $t3Span->getAttributes()->toArray(); + $this->assertSame($transportType === 'grpc' ? 'grpc' : 'http', $t3Attrs[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame($expectedMethod, $t3Attrs[SpanAttributes::RPC_METHOD]); + $this->assertSame(self::SERVER_ADDRESS, $t3Attrs[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(self::SERVER_PORT, $t3Attrs[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $t3Attrs); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $t3Attrs); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $t3Attrs); + } + + /** + * @dataProvider provideTransportType + */ + public function testTracingIdentityGetUserFailure(string $transportType): void + { + $transport = $this->buildTransport($transportType, self::IDENTITY_REST_CONFIG, $this->tracerProvider); + $identityClient = new IdentityClient([ + 'credentials' => new InsecureCredentialsWrapper(), + 'transport' => $transport, + 'openTelemetryTracerProvider' => $this->tracerProvider, + ]); + + try { + $request = new GetUserRequest([ + 'name' => IdentityClient::userName('nonexistent-user'), + ]); + try { + $identityClient->getUser($request); + $this->fail('Expected ApiException for nonexistent user'); + } catch (ApiException $e) { + $this->assertSame('NOT_FOUND', $e->getStatus()); + } + } finally { + $identityClient->close(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $expectedMethod = 'google.showcase.v1beta1.Identity/GetUser'; + + if ($transportType === 'grpc') { + $this->assertCount(2, $spans); + $t4Span = $spans[0]; + $t3Span = $spans[1]; + + $this->assertSame($t3Span->getSpanId(), $t4Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); + $this->assertSame($expectedMethod, $t4Span->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Span->getStatus()->getCode()); + $this->assertSame('NOT_FOUND', $t4Span->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertSame('NOT_FOUND', $t4Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame(ApiException::class, $t4Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } else { + $this->assertCount(1, $spans); + $t3Span = $spans[0]; + } + + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame($expectedMethod, $t3Span->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); + $this->assertSame('NOT_FOUND', $t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame(ApiException::class, $t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + $this->assertNotEmpty($t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + $this->assertSame(self::SERVER_ADDRESS, $t3Span->getAttributes()->get(SpanAttributes::SERVER_ADDRESS)); + $this->assertSame(self::SERVER_PORT, $t3Span->getAttributes()->get(SpanAttributes::SERVER_PORT)); + } + + /** + * @dataProvider provideTransportType + */ + public function testTracingRetrySucceedsWithSequenceService(string $transportType): void + { + $transport = $this->buildTransport($transportType, self::SEQUENCE_REST_CONFIG, $this->tracerProvider); + $sequenceClient = new SequenceServiceClient([ + 'credentials' => new InsecureCredentialsWrapper(), + 'transport' => $transport, + 'openTelemetryTracerProvider' => $this->tracerProvider, + ]); + + try { + $sequence = new Sequence([ + 'responses' => [ + new Response([ + 'status' => new Status([ + 'code' => Code::UNAVAILABLE, + 'message' => 'Temporary failure on attempt 1', + ]), + ]), + new Response([ + 'status' => new Status([ + 'code' => Code::OK, + ]), + ]), + ], + ]); + + $createdSequence = $sequenceClient->createSequence( + new CreateSequenceRequest(['sequence' => $sequence]) + ); + $this->exporter->getStorage()->exchangeArray([]); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $sequenceClient->attemptSequence( + new AttemptSequenceRequest(['name' => $createdSequence->getName()]) + ); + } finally { + $appScope->detach(); + $appSpan->end(); + } + } finally { + $sequenceClient->close(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $expectedMethod = 'google.showcase.v1beta1.SequenceService/AttemptSequence'; + + if ($transportType === 'grpc') { + $this->assertCount(4, $spans); + $t4Attempt1 = $spans[0]; + $t4Attempt2 = $spans[1]; + $t3Span = $spans[2]; + $exportedAppSpan = $spans[3]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame($t3Span->getSpanId(), $t4Attempt1->getParentSpanId()); + $this->assertSame($t3Span->getSpanId(), $t4Attempt2->getParentSpanId()); + + $this->assertSame(SpanKind::KIND_CLIENT, $t4Attempt1->getKind()); + $this->assertSame($expectedMethod, $t4Attempt1->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Attempt1->getStatus()->getCode()); + $this->assertSame( + 'UNAVAILABLE', + $t4Attempt1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE) + ); + $this->assertSame('UNAVAILABLE', $t4Attempt1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + + $this->assertSame(SpanKind::KIND_CLIENT, $t4Attempt2->getKind()); + $this->assertSame($expectedMethod, $t4Attempt2->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t4Attempt2->getStatus()->getCode()); + $this->assertSame('OK', $t4Attempt2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertNull($t4Attempt2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + } else { + $this->assertCount(2, $spans); + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + } + + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame($expectedMethod, $t3Span->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); + $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } + + /** + * @dataProvider provideTransportType + */ + public function testTracingRetriesExhausted(string $transportType): void + { + $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, $this->tracerProvider); + $echoClient = new EchoClient([ + 'credentials' => new InsecureCredentialsWrapper(), + 'transport' => $transport, + 'openTelemetryTracerProvider' => $this->tracerProvider, + ]); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'maxRetries' => 4, + 'initialRetryDelayMillis' => 10, + 'maxRetryDelayMillis' => 50, + ]); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $request = new EchoRequest([ + 'error' => new Status([ + 'code' => Code::UNAVAILABLE, + 'message' => 'Test error', + ]), + ]); + + try { + $echoClient->echo($request, ['retrySettings' => $retrySettings]); + $this->fail('Expected ApiException after exhausting retries'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + $echoClient->close(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $expectedMethod = 'google.showcase.v1beta1.Echo/Echo'; + + if ($transportType === 'grpc') { + // 5 T4 attempt spans (1 initial + 4 retries) + 1 T3 span + 1 APP span = 7 spans + $this->assertCount(7, $spans); + $t3Span = $spans[5]; + $exportedAppSpan = $spans[6]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + for ($i = 0; $i < 5; $i++) { + $t4Span = $spans[$i]; + $this->assertSame($t3Span->getSpanId(), $t4Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); + $this->assertSame($expectedMethod, $t4Span->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Span->getStatus()->getCode()); + $this->assertSame( + 'UNAVAILABLE', + $t4Span->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE) + ); + $this->assertSame('UNAVAILABLE', $t4Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame('Test error', $t4Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + } + } else { + $this->assertCount(2, $spans); + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + } + + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame($expectedMethod, $t3Span->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame('Test error', $t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + $this->assertSame(ApiException::class, $t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } + + /** + * @dataProvider provideTransportType + */ + public function testTracingErrorInfoReasonAndStatusCodes(string $transportType): void + { + $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, $this->tracerProvider); + $echoClient = new EchoClient([ + 'credentials' => new InsecureCredentialsWrapper(), + 'transport' => $transport, + 'openTelemetryTracerProvider' => $this->tracerProvider, + ]); + + try { + // 1. Successful Echo (OK) + $echoClient->echo(new EchoRequest(['content' => 'success'])); + + // 2. Echo with ErrorInfo detail (verifies ErrorInfo reason is used for error.type) + $errorInfo = new ErrorInfo([ + 'reason' => 'CUSTOM_SHOWCASE_ERROR_REASON', + 'domain' => 'showcase.googleapis.com', + 'metadata' => ['key' => 'value'], + ]); + $anyDetail = new Any(); + $anyDetail->pack($errorInfo); + + try { + $echoClient->echo(new EchoRequest([ + 'error' => new Status([ + 'code' => Code::INVALID_ARGUMENT, + 'message' => 'Invalid argument with ErrorInfo', + 'details' => [$anyDetail], + ]), + ])); + $this->fail('Expected ApiException'); + } catch (ApiException $e) { + $this->assertSame('INVALID_ARGUMENT', $e->getStatus()); + } + + // 3. FailEchoWithDetails (standard Showcase error details RPC) + try { + $echoClient->failEchoWithDetails(new FailEchoWithDetailsRequest([ + 'message' => 'Failed echo with details', + ])); + $this->fail('Expected ApiException from failEchoWithDetails'); + } catch (ApiException $e) { + $this->assertNotEmpty($e->getErrorDetails()); + } + } finally { + $echoClient->close(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + + if ($transportType === 'grpc') { + $this->assertCount(6, $spans); + $okT4Span = $spans[0]; + $okT3Span = $spans[1]; + $errInfoT4Span = $spans[2]; + $errInfoT3Span = $spans[3]; + $failDetailsT4Span = $spans[4]; + $failDetailsT3Span = $spans[5]; + + $this->assertSame('OK', $okT4Span->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertNull($okT4Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertNull($okT3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + + $this->assertSame( + 'INVALID_ARGUMENT', + $errInfoT4Span->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE) + ); + $this->assertSame( + 'CUSTOM_SHOWCASE_ERROR_REASON', + $errInfoT4Span->getAttributes()->get(SpanAttributes::ERROR_TYPE) + ); + $this->assertSame( + 'CUSTOM_SHOWCASE_ERROR_REASON', + $errInfoT3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE) + ); + + $this->assertSame( + 'google.showcase.v1beta1.Echo/FailEchoWithDetails', + $failDetailsT4Span->getName() + ); + $this->assertSame(StatusCode::STATUS_ERROR, $failDetailsT4Span->getStatus()->getCode()); + $this->assertSame(StatusCode::STATUS_ERROR, $failDetailsT3Span->getStatus()->getCode()); + $this->assertSame( + ApiException::class, + $failDetailsT3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE) + ); + } else { + $this->assertCount(3, $spans); + $okT3Span = $spans[0]; + $errInfoT3Span = $spans[1]; + $failDetailsT3Span = $spans[2]; + + $this->assertSame(StatusCode::STATUS_OK, $okT3Span->getStatus()->getCode()); + $this->assertNull($okT3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + + $this->assertSame(StatusCode::STATUS_ERROR, $errInfoT3Span->getStatus()->getCode()); + $this->assertSame( + 'CUSTOM_SHOWCASE_ERROR_REASON', + $errInfoT3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE) + ); + + $this->assertSame( + 'google.showcase.v1beta1.Echo/FailEchoWithDetails', + $failDetailsT3Span->getName() + ); + $this->assertSame(StatusCode::STATUS_ERROR, $failDetailsT3Span->getStatus()->getCode()); + $this->assertSame( + ApiException::class, + $failDetailsT3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE) + ); + } + } + + private function buildTransport( + string $transportType, + string $restConfigPath, + ?TracerProviderInterface $tracerProvider + ): TransportInterface { + if (file_exists(self::PEM_PATH)) { + $pemContents = file_get_contents(self::PEM_PATH); + $grpcCredentials = ChannelCredentials::createSsl($pemContents); + $requestBuilder = new RequestBuilder(self::HOST, $restConfigPath); + $guzzleClient = new Client(['verify' => self::PEM_PATH]); + } else { + $grpcCredentials = ChannelCredentials::createInsecure(); + $requestBuilder = new InsecureRequestBuilder(self::HOST, $restConfigPath); + $guzzleClient = null; + } + + if ($transportType === 'grpc') { + return GrpcTransport::build( + self::HOST, + [ + 'stubOpts' => [ + 'credentials' => $grpcCredentials, + ], + 'openTelemetryTracerProvider' => $tracerProvider, + ] + ); + } + + $httpHandler = HttpHandlerFactory::build($guzzleClient); + return new RestTransport($requestBuilder, [$httpHandler, 'async']); + } +} diff --git a/Gax/tests/Unit/Telemetry/TracingTestPlanTest.php b/Gax/tests/Unit/Telemetry/TracingTestPlanTest.php new file mode 100644 index 000000000000..fb133433feea --- /dev/null +++ b/Gax/tests/Unit/Telemetry/TracingTestPlanTest.php @@ -0,0 +1,1132 @@ +exporter = new InMemoryExporter(); + $this->tracerProvider = new TracerProvider(new SimpleSpanProcessor($this->exporter)); + } + + protected function tearDown(): void + { + $this->tracerProvider->shutdown(); + parent::tearDown(); + } + + /** + * F1.1: HTTP no traces emitted unless enabled. + */ + public function testF1_1_HttpNoTracesEmittedUnlessEnabled(): void + { + $response = new Status(['code' => Code::OK]); + $restTransport = $this->prophesize(RestTransport::class); + $restTransport->startUnaryCall(\Prophecy\Argument::type(Call::class), \Prophecy\Argument::type('array')) + ->shouldBeCalledOnce() + ->willReturn(Create::promiseFor($response)); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $restTransport->reveal()->startUnaryCall($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + $spans = $this->exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + /** + * F1.6: gRPC no traces emitted unless enabled. + */ + public function testF1_6_GrpcNoTracesEmittedUnlessEnabled(): void + { + $response = new Status(['code' => Code::OK]); + $status = new stdClass(); + $status->code = Code::OK; + + $unaryCall = $this->prophesize(UnaryCall::class); + $unaryCall->wait()->shouldBeCalledOnce()->willReturn([$response, $status]); + + $transport = $this->createGrpcTransport([$unaryCall->reveal()]); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $transport->startUnaryCall($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + $spans = $this->exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + /** + * F1.7: gRPC T4 success case name and attributes conform to requirements. + */ + public function testF1_7_GrpcT4Success(): void + { + $response = new Status(['code' => Code::OK]); + $status = new stdClass(); + $status->code = Code::OK; + + $unaryCall = $this->prophesize(UnaryCall::class); + $unaryCall->wait()->shouldBeCalledOnce()->willReturn([$response, $status]); + + $transport = $this->createGrpcTransport([$unaryCall->reveal()], [ + 'openTelemetryTracerProvider' => $this->tracerProvider, + 'clientVersion' => self::CLIENT_VERSION, + ]); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $transport->startUnaryCall($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(2, $spans); + + $t4Span = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t4Span->getParentSpanId()); + $this->assertSame($exportedAppSpan->getTraceId(), $t4Span->getTraceId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); + $this->assertSame(self::RPC_METHOD, $t4Span->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t4Span->getStatus()->getCode()); + $this->assertSame('google-cloud-php', $t4Span->getInstrumentationScope()->getName()); + $this->assertSame(self::CLIENT_VERSION, $t4Span->getInstrumentationScope()->getVersion()); + + $attributes = $t4Span->getAttributes()->toArray(); + $this->assertSame('grpc', $attributes[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame(self::RPC_METHOD, $attributes[SpanAttributes::RPC_METHOD]); + $this->assertSame('OK', $attributes[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame(self::SERVER_ADDRESS, $attributes[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(self::SERVER_PORT, $attributes[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attributes); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attributes); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attributes); + } + + /** + * F1.8: gRPC T4 server failures case name and attributes conform to requirements + * (testing both standard gRPC status code and ErrorInfo reason). + */ + public function testF1_8_GrpcT4ServerFailures(): void + { + // Case 1: Server failure without ErrorInfo (uses status code string) + $statusWithoutErrorInfo = new stdClass(); + $statusWithoutErrorInfo->code = Code::UNAVAILABLE; + $statusWithoutErrorInfo->details = 'Service unavailable'; + + // Case 2: Server failure with ErrorInfo (uses ErrorInfo reason) + $errorInfo = new ErrorInfo([ + 'reason' => 'IAM_PERMISSION_DENIED', + 'domain' => 'googleapis.com', + ]); + $statusWithErrorInfo = new stdClass(); + $statusWithErrorInfo->code = Code::PERMISSION_DENIED; + $statusWithErrorInfo->details = 'Permission denied on resource'; + $statusWithErrorInfo->metadata = [ + 'google.rpc.errorinfo-bin' => [$errorInfo->serializeToString()], + ]; + + $unaryCall1 = $this->prophesize(UnaryCall::class); + $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $statusWithoutErrorInfo]); + + $unaryCall2 = $this->prophesize(UnaryCall::class); + $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([null, $statusWithErrorInfo]); + + $transport = $this->createGrpcTransport( + [$unaryCall1->reveal(), $unaryCall2->reveal()], + ['openTelemetryTracerProvider' => $this->tracerProvider] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + + try { + $transport->startUnaryCall($call, [])->wait(); + $this->fail('Expected ApiException for call 1'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + + try { + $transport->startUnaryCall($call, [])->wait(); + $this->fail('Expected ApiException for call 2'); + } catch (ApiException $e) { + $this->assertSame('PERMISSION_DENIED', $e->getStatus()); + $this->assertSame('IAM_PERMISSION_DENIED', $e->getReason()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(3, $spans); + + $t4Span1 = $spans[0]; + $t4Span2 = $spans[1]; + $exportedAppSpan = $spans[2]; + + // Verify T4 span 1 (without ErrorInfo) + $this->assertSame($exportedAppSpan->getSpanId(), $t4Span1->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span1->getKind()); + $this->assertSame(self::RPC_METHOD, $t4Span1->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Span1->getStatus()->getCode()); + $this->assertSame('Service unavailable', $t4Span1->getStatus()->getDescription()); + $attrs1 = $t4Span1->getAttributes()->toArray(); + $this->assertSame('grpc', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame(self::RPC_METHOD, $attrs1[SpanAttributes::RPC_METHOD]); + $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Service unavailable', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame(self::SERVER_ADDRESS, $attrs1[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(self::SERVER_PORT, $attrs1[SpanAttributes::SERVER_PORT]); + + // Verify T4 span 2 (with ErrorInfo) + $this->assertSame($exportedAppSpan->getSpanId(), $t4Span2->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span2->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Span2->getStatus()->getCode()); + $this->assertSame('Permission denied on resource', $t4Span2->getStatus()->getDescription()); + $attrs2 = $t4Span2->getAttributes()->toArray(); + $this->assertSame('PERMISSION_DENIED', $attrs2[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame('IAM_PERMISSION_DENIED', $attrs2[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Permission denied on resource', $attrs2[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs2[SpanAttributes::EXCEPTION_TYPE]); + } + + /** + * F1.9: gRPC T4 client failures case name and attributes conform to requirements + * (testing both client-side exception before response and client cancellation). + */ + public function testF1_9_GrpcT4ClientFailures(): void + { + $unaryCallForCancel = $this->prophesize(UnaryCall::class); + $unaryCallForCancel->cancel()->shouldBeCalledOnce(); + + $callCount = 0; + $transport = new class( + self::SERVER_ADDRESS . ':' . self::SERVER_PORT, + function () use (&$callCount, $unaryCallForCancel) { + $callCount++; + if ($callCount === 1) { + throw new RuntimeException('Client deadline exceeded before sending request'); + } + return $unaryCallForCancel->reveal(); + }, + ['openTelemetryTracerProvider' => $this->tracerProvider] + ) extends GrpcTransport { + /** @var callable */ + private $factory; + + public function __construct(string $hostname, callable $factory, array $telemetryOptions) + { + $this->factory = $factory; + parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); + $this->setTelemetryOptions($telemetryOptions); + } + + // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore + protected function _simpleRequest( + $method, + $arguments, + $deserialize, + array $metadata = [], + array $options = [] + ) { + return ($this->factory)(); + } + }; + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + + // Case 1: Client-side exception thrown before receiving response + try { + $transport->startUnaryCall($call, []); + $this->fail('Expected RuntimeException'); + } catch (RuntimeException $e) { + $this->assertSame('Client deadline exceeded before sending request', $e->getMessage()); + } + + // Case 2: Client cancels the in-flight RPC promise + $promise = $transport->startUnaryCall($call, []); + $promise->cancel(); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(3, $spans); + + $t4ExceptionSpan = $spans[0]; + $t4CancelledSpan = $spans[1]; + $exportedAppSpan = $spans[2]; + + // Verify client exception span + $this->assertSame($exportedAppSpan->getSpanId(), $t4ExceptionSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4ExceptionSpan->getKind()); + $this->assertSame(self::RPC_METHOD, $t4ExceptionSpan->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4ExceptionSpan->getStatus()->getCode()); + $attrs1 = $t4ExceptionSpan->getAttributes()->toArray(); + $this->assertSame(RuntimeException::class, $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame(RuntimeException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame('Client deadline exceeded before sending request', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs1); + + // Verify client cancellation span + $this->assertSame($exportedAppSpan->getSpanId(), $t4CancelledSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4CancelledSpan->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4CancelledSpan->getStatus()->getCode()); + $attrs2 = $t4CancelledSpan->getAttributes()->toArray(); + $this->assertSame('CANCELLED', $attrs2[SpanAttributes::ERROR_TYPE]); + $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs2); + } + + /** + * F1.10: gRPC T4 retries. + */ + public function testF1_10_GrpcT4Retries(): void + { + $failStatus = new stdClass(); + $failStatus->code = Code::UNAVAILABLE; + $failStatus->details = 'Temporary backend error'; + + $okResponse = new Status(['code' => Code::OK]); + $okStatus = new stdClass(); + $okStatus->code = Code::OK; + + $unaryCall1 = $this->prophesize(UnaryCall::class); + $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); + + $unaryCall2 = $this->prophesize(UnaryCall::class); + $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([$okResponse, $okStatus]); + + $transport = $this->createGrpcTransport( + [$unaryCall1->reveal(), $unaryCall2->reveal()], + ['openTelemetryTracerProvider' => $this->tracerProvider] + ); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'initialRetryDelayMillis' => 1, + 'maxRetryDelayMillis' => 5, + ]); + + $retryMiddleware = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $retryMiddleware($call, [])->wait(); + $this->assertSame($okResponse, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(3, $spans); + + $t4Attempt1 = $spans[0]; + $t4Attempt2 = $spans[1]; + $exportedAppSpan = $spans[2]; + + // First attempt fails + $this->assertSame($exportedAppSpan->getSpanId(), $t4Attempt1->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Attempt1->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Attempt1->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $t4Attempt1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertSame('UNAVAILABLE', $t4Attempt1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + + // Second attempt succeeds + $this->assertSame($exportedAppSpan->getSpanId(), $t4Attempt2->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Attempt2->getKind()); + $this->assertSame(StatusCode::STATUS_OK, $t4Attempt2->getStatus()->getCode()); + $this->assertSame('OK', $t4Attempt2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertNull($t4Attempt2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + } + + /** + * F2.1: HTTP no traces emitted unless enabled. + */ + public function testF2_1_HttpNoTracesEmittedUnlessEnabled(): void + { + $response = new Status(['code' => Code::OK]); + $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'http', + ['openTelemetryTracerProvider' => null] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $middleware($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + $spans = $this->exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + /** + * F2.2: HTTP T3 case name and attributes conform to requirements. + */ + public function testF2_2_HttpT3Success(): void + { + $response = new Status(['code' => Code::OK]); + $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'http', + [ + 'openTelemetryTracerProvider' => $this->tracerProvider, + 'clientVersion' => self::CLIENT_VERSION, + ] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $middleware($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(2, $spans); + + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame($exportedAppSpan->getTraceId(), $t3Span->getTraceId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame(self::RPC_METHOD, $t3Span->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); + $this->assertSame('google-cloud-php', $t3Span->getInstrumentationScope()->getName()); + $this->assertSame(self::CLIENT_VERSION, $t3Span->getInstrumentationScope()->getVersion()); + + $attrs = $t3Span->getAttributes()->toArray(); + $this->assertSame('http', $attrs[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame(self::RPC_METHOD, $attrs[SpanAttributes::RPC_METHOD]); + $this->assertSame(self::SERVER_ADDRESS, $attrs[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(self::SERVER_PORT, $attrs[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attrs); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attrs); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attrs); + } + + /** + * F2.3: HTTP T3 server failures case name and attributes conform to requirements. + */ + public function testF2_3_HttpT3ServerFailures(): void + { + $apiException1 = ApiException::createFromRestApiResponse( + 'Service unavailable', + Code::UNAVAILABLE + ); + $apiException2 = ApiException::createFromRestApiResponse( + 'API disabled in project', + Code::PERMISSION_DENIED, + [ + [ + '@type' => 'type.googleapis.com/google.rpc.ErrorInfo', + 'reason' => 'SERVICE_DISABLED', + 'domain' => 'googleapis.com', + 'metadata' => [], + ], + ] + ); + + $exceptions = [$apiException1, $apiException2]; + $nextHandler = function () use (&$exceptions) { + return Create::rejectionFor(array_shift($exceptions)); + }; + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'http', + ['openTelemetryTracerProvider' => $this->tracerProvider] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + + try { + $middleware($call, [])->wait(); + $this->fail('Expected ApiException 1'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + + try { + $middleware($call, [])->wait(); + $this->fail('Expected ApiException 2'); + } catch (ApiException $e) { + $this->assertSame('SERVICE_DISABLED', $e->getReason()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(3, $spans); + + $t3Span1 = $spans[0]; + $t3Span2 = $spans[1]; + $exportedAppSpan = $spans[2]; + + // Span 1: status code fallback + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span1->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span1->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span1->getStatus()->getCode()); + $attrs1 = $t3Span1->getAttributes()->toArray(); + $this->assertSame('http', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Service unavailable', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + + // Span 2: ErrorInfo reason + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span2->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span2->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span2->getStatus()->getCode()); + $attrs2 = $t3Span2->getAttributes()->toArray(); + $this->assertSame('SERVICE_DISABLED', $attrs2[SpanAttributes::ERROR_TYPE]); + $this->assertSame('API disabled in project', $attrs2[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs2[SpanAttributes::EXCEPTION_TYPE]); + } + + /** + * F2.4: HTTP T3 client failures case name and attributes conform to requirements. + */ + public function testF2_4_HttpT3ClientFailures(): void + { + $callIndex = 0; + $nextHandler = function () use (&$callIndex) { + $callIndex++; + if ($callIndex === 1) { + throw new InvalidArgumentException('Client request validation failed'); + } + $pending = new Promise(function () { + }, function () { + }); + return $pending; + }; + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'http', + ['openTelemetryTracerProvider' => $this->tracerProvider] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + + try { + $middleware($call, []); + $this->fail('Expected InvalidArgumentException'); + } catch (InvalidArgumentException $e) { + $this->assertSame('Client request validation failed', $e->getMessage()); + } + + $promise = $middleware($call, []); + $promise->cancel(); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(3, $spans); + + $t3ExceptionSpan = $spans[0]; + $t3CancelSpan = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3ExceptionSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3ExceptionSpan->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3ExceptionSpan->getStatus()->getCode()); + $attrs1 = $t3ExceptionSpan->getAttributes()->toArray(); + $this->assertSame('http', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame(InvalidArgumentException::class, $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame(InvalidArgumentException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame('Client request validation failed', $attrs1[SpanAttributes::STATUS_MESSAGE]); + + $this->assertSame($exportedAppSpan->getSpanId(), $t3CancelSpan->getParentSpanId()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3CancelSpan->getStatus()->getCode()); + $attrs2 = $t3CancelSpan->getAttributes()->toArray(); + $this->assertSame('CANCELLED', $attrs2[SpanAttributes::ERROR_TYPE]); + } + + /** + * F2.5: gRPC no traces emitted unless enabled. + */ + public function testF2_5_GrpcNoTracesEmittedUnlessEnabled(): void + { + $response = new Status(['code' => Code::OK]); + $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'grpc', + ['openTelemetryTracerProvider' => null] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $middleware($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + $spans = $this->exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + /** + * F2.6: gRPC T3 success case name and attributes conform to requirements. + */ + public function testF2_6_GrpcT3Success(): void + { + $response = new Status(['code' => Code::OK]); + $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'grpc', + [ + 'openTelemetryTracerProvider' => $this->tracerProvider, + 'clientVersion' => self::CLIENT_VERSION, + ] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $middleware($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(2, $spans); + + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame($exportedAppSpan->getTraceId(), $t3Span->getTraceId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame(self::RPC_METHOD, $t3Span->getName()); + $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); + + $attrs = $t3Span->getAttributes()->toArray(); + $this->assertSame('grpc', $attrs[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame(self::RPC_METHOD, $attrs[SpanAttributes::RPC_METHOD]); + $this->assertSame(self::SERVER_ADDRESS, $attrs[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(self::SERVER_PORT, $attrs[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attrs); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attrs); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attrs); + } + + /** + * F2.7: gRPC T3 server failures case name and attributes conform to requirements. + */ + public function testF2_7_GrpcT3ServerFailures(): void + { + $errorInfo = new ErrorInfo([ + 'reason' => 'RESOURCE_MISSING', + 'domain' => 'googleapis.com', + ]); + $status = new stdClass(); + $status->code = Code::NOT_FOUND; + $status->details = 'Secret version not found'; + $status->metadata = [ + 'google.rpc.errorinfo-bin' => [$errorInfo->serializeToString()], + ]; + $apiException = ApiException::createFromStdClass($status); + + $nextHandler = fn () => Create::rejectionFor($apiException); + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'grpc', + ['openTelemetryTracerProvider' => $this->tracerProvider] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + try { + $middleware($call, [])->wait(); + $this->fail('Expected ApiException'); + } catch (ApiException $e) { + $this->assertSame('RESOURCE_MISSING', $e->getReason()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(2, $spans); + + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); + $this->assertSame('Secret version not found', $t3Span->getStatus()->getDescription()); + + $attrs = $t3Span->getAttributes()->toArray(); + $this->assertSame('grpc', $attrs[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame('RESOURCE_MISSING', $attrs[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Secret version not found', $attrs[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs[SpanAttributes::EXCEPTION_TYPE]); + } + + /** + * F2.8: gRPC T3 client failures case name and attributes conform to requirements. + */ + public function testF2_8_GrpcT3ClientFailures(): void + { + $nextHandler = function () { + throw new RuntimeException('Client connection setup error'); + }; + + $middleware = new TracingMiddleware( + $nextHandler, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'grpc', + ['openTelemetryTracerProvider' => $this->tracerProvider] + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + try { + $middleware($call, []); + $this->fail('Expected RuntimeException'); + } catch (RuntimeException $e) { + $this->assertSame('Client connection setup error', $e->getMessage()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(2, $spans); + + $t3Span = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); + $attrs = $t3Span->getAttributes()->toArray(); + $this->assertSame(RuntimeException::class, $attrs[SpanAttributes::ERROR_TYPE]); + $this->assertSame(RuntimeException::class, $attrs[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame('Client connection setup error', $attrs[SpanAttributes::STATUS_MESSAGE]); + $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs); + } + + /** + * F3.3: gRPC T3/T4 retry succeeds. + */ + public function testF3_3_GrpcT3T4RetrySucceeds(): void + { + $failStatus = new stdClass(); + $failStatus->code = Code::UNAVAILABLE; + $failStatus->details = 'Transient error on attempt 1'; + + $okResponse = new Status(['code' => Code::OK]); + $okStatus = new stdClass(); + $okStatus->code = Code::OK; + + $unaryCall1 = $this->prophesize(UnaryCall::class); + $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); + + $unaryCall2 = $this->prophesize(UnaryCall::class); + $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([$okResponse, $okStatus]); + + $telemetryOptions = [ + 'openTelemetryTracerProvider' => $this->tracerProvider, + 'clientVersion' => self::CLIENT_VERSION, + ]; + + $transport = $this->createGrpcTransport( + [$unaryCall1->reveal(), $unaryCall2->reveal()], + $telemetryOptions + ); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'initialRetryDelayMillis' => 1, + 'maxRetryDelayMillis' => 5, + ]); + + $callStack = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); + $callStack = new TracingMiddleware( + $callStack, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'grpc', + $telemetryOptions + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + $result = $callStack($call, [])->wait(); + $this->assertSame($okResponse, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(4, $spans); + + $t4Span1 = $spans[0]; + $t4Span2 = $spans[1]; + $t3Span = $spans[2]; + $exportedAppSpan = $spans[3]; + + // Verify parent-child hierarchy: APP -> T3 -> (T4_1, T4_2) + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + $this->assertSame($t3Span->getSpanId(), $t4Span1->getParentSpanId()); + $this->assertSame($t3Span->getSpanId(), $t4Span2->getParentSpanId()); + + // Verify T4_1 matches failure requirements (F1.8) + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span1->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Span1->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $t4Span1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertSame('UNAVAILABLE', $t4Span1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame( + 'Transient error on attempt 1', + $t4Span1->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) + ); + + // Verify T4_2 matches success requirements (F1.7) + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span2->getKind()); + $this->assertSame(StatusCode::STATUS_OK, $t4Span2->getStatus()->getCode()); + $this->assertSame('OK', $t4Span2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertNull($t4Span2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertNull($t4Span2->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + + // Verify T3 matches success requirements (F2.6) + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); + $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } + + /** + * F3.4: gRPC T3/T4 retries exhausted. + */ + public function testF3_4_GrpcT3T4RetriesExhausted(): void + { + $failStatus = new stdClass(); + $failStatus->code = Code::UNAVAILABLE; + $failStatus->details = 'Persistent backend outage'; + + $unaryCalls = []; + for ($i = 0; $i < 3; $i++) { + $call = $this->prophesize(UnaryCall::class); + $call->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); + $unaryCalls[] = $call->reveal(); + } + + $telemetryOptions = [ + 'openTelemetryTracerProvider' => $this->tracerProvider, + 'clientVersion' => self::CLIENT_VERSION, + ]; + + $transport = $this->createGrpcTransport($unaryCalls, $telemetryOptions); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'maxRetries' => 2, + 'initialRetryDelayMillis' => 1, + 'maxRetryDelayMillis' => 5, + ]); + + $callStack = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); + $callStack = new TracingMiddleware( + $callStack, + self::SERVER_ADDRESS, + self::SERVER_PORT, + 'grpc', + $telemetryOptions + ); + + $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); + try { + $callStack($call, [])->wait(); + $this->fail('Expected ApiException after exhausting retries'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $this->exporter->getSpans(); + $this->assertCount(5, $spans); + + $t4Spans = [$spans[0], $spans[1], $spans[2]]; + $t3Span = $spans[3]; + $exportedAppSpan = $spans[4]; + + $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); + + foreach ($t4Spans as $t4Span) { + $this->assertSame($t3Span->getSpanId(), $t4Span->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t4Span->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $t4Span->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertSame('UNAVAILABLE', $t4Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame( + 'Persistent backend outage', + $t4Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) + ); + } + + // Verify T3 span matches failure requirements (F2.7) + $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame('Persistent backend outage', $t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + $this->assertSame(ApiException::class, $t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } + + /** + * @param UnaryCall[] $unaryCalls + * @param array $telemetryOptions + */ + private function createGrpcTransport(array $unaryCalls, array $telemetryOptions = []): GrpcTransport + { + return new class( + self::SERVER_ADDRESS . ':' . self::SERVER_PORT, + $unaryCalls, + $telemetryOptions + ) extends GrpcTransport { + /** @var UnaryCall[] */ + private array $unaryCalls; + + /** + * @param UnaryCall[] $unaryCalls + * @param array $telemetryOptions + */ + public function __construct(string $hostname, array $unaryCalls, array $telemetryOptions) + { + $this->unaryCalls = $unaryCalls; + parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); + $this->setTelemetryOptions($telemetryOptions); + } + + // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore + protected function _simpleRequest( + $method, + $arguments, + $deserialize, + array $metadata = [], + array $options = [] + ) { + return array_shift($this->unaryCalls); + } + }; + } +} From 73b2a92702a145a339c0c7c3630f7ad086024dab Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 7 Oct 2026 22:17:08 +0000 Subject: [PATCH 2/6] test(Gax): pass apiEndpoint in OtelTracingTest until gapic-generator-php#889 is merged --- Gax/tests/Conformance/OtelTracingTest.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Gax/tests/Conformance/OtelTracingTest.php b/Gax/tests/Conformance/OtelTracingTest.php index b25c5e73db44..d6bd85f3b478 100644 --- a/Gax/tests/Conformance/OtelTracingTest.php +++ b/Gax/tests/Conformance/OtelTracingTest.php @@ -96,6 +96,9 @@ public function testTracingDisabledEmitsOnlyAppSpan(string $transportType): void { $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, null); $echoClient = new EchoClient([ + // @TODO: Remove apiEndpoint once https://github.com/googleapis/gapic-generator-php/pull/889 is merged + // and the Showcase client is regenerated. + 'apiEndpoint' => self::HOST, 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport, ]); @@ -124,6 +127,9 @@ public function testTracingSuccessfulEcho(string $transportType): void { $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, $this->tracerProvider); $echoClient = new EchoClient([ + // @TODO: Remove apiEndpoint once https://github.com/googleapis/gapic-generator-php/pull/889 is merged + // and the Showcase client is regenerated. + 'apiEndpoint' => self::HOST, 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport, 'openTelemetryTracerProvider' => $this->tracerProvider, @@ -195,6 +201,9 @@ public function testTracingIdentityGetUserFailure(string $transportType): void { $transport = $this->buildTransport($transportType, self::IDENTITY_REST_CONFIG, $this->tracerProvider); $identityClient = new IdentityClient([ + // @TODO: Remove apiEndpoint once https://github.com/googleapis/gapic-generator-php/pull/889 is merged + // and the Showcase client is regenerated. + 'apiEndpoint' => self::HOST, 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport, 'openTelemetryTracerProvider' => $this->tracerProvider, @@ -252,6 +261,9 @@ public function testTracingRetrySucceedsWithSequenceService(string $transportTyp { $transport = $this->buildTransport($transportType, self::SEQUENCE_REST_CONFIG, $this->tracerProvider); $sequenceClient = new SequenceServiceClient([ + // @TODO: Remove apiEndpoint once https://github.com/googleapis/gapic-generator-php/pull/889 is merged + // and the Showcase client is regenerated. + 'apiEndpoint' => self::HOST, 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport, 'openTelemetryTracerProvider' => $this->tracerProvider, @@ -345,6 +357,9 @@ public function testTracingRetriesExhausted(string $transportType): void { $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, $this->tracerProvider); $echoClient = new EchoClient([ + // @TODO: Remove apiEndpoint once https://github.com/googleapis/gapic-generator-php/pull/889 is merged + // and the Showcase client is regenerated. + 'apiEndpoint' => self::HOST, 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport, 'openTelemetryTracerProvider' => $this->tracerProvider, @@ -428,6 +443,9 @@ public function testTracingErrorInfoReasonAndStatusCodes(string $transportType): { $transport = $this->buildTransport($transportType, self::ECHO_REST_CONFIG, $this->tracerProvider); $echoClient = new EchoClient([ + // @TODO: Remove apiEndpoint once https://github.com/googleapis/gapic-generator-php/pull/889 is merged + // and the Showcase client is regenerated. + 'apiEndpoint' => self::HOST, 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport, 'openTelemetryTracerProvider' => $this->tracerProvider, From 0b3970ad7bdae410627595cd689d574520a0663e Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 7 Oct 2026 22:52:27 +0000 Subject: [PATCH 3/6] test: move tracing tests from TracingTestPlanTest into class-based unit tests --- .../Unit/Middleware/TracingMiddlewareTest.php | 548 ++++++++ .../Unit/Telemetry/TracingTestPlanTest.php | 1132 ----------------- .../Unit/Transport/GrpcTransportTest.php | 391 ++++++ .../Unit/Transport/RestTransportTest.php | 31 + 4 files changed, 970 insertions(+), 1132 deletions(-) delete mode 100644 Gax/tests/Unit/Telemetry/TracingTestPlanTest.php diff --git a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php index 12d5a5572506..a01b65db00b3 100644 --- a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php @@ -33,13 +33,26 @@ namespace Google\ApiCore\Tests\Unit\Middleware; use Google\ApiCore\ApiException; +use Google\ApiCore\ApiStatus; use Google\ApiCore\Call; +use Google\ApiCore\Middleware\RetryMiddleware; use Google\ApiCore\Middleware\TracingMiddleware; +use Google\ApiCore\RetrySettings; use Google\ApiCore\Telemetry\SpanAttributes; +use Google\ApiCore\Testing\MockRequest; +use Google\ApiCore\Tests\Unit\TestTrait; +use Google\ApiCore\Transport\GrpcTransport; use Google\ApiCore\ValidationException; +use Google\Rpc\Code; +use Google\Rpc\ErrorInfo; +use Google\Rpc\Status; +use Grpc\ChannelCredentials; +use Grpc\UnaryCall; +use GuzzleHttp\Promise\Create; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\RejectedPromise; +use InvalidArgumentException; use OpenTelemetry\API\Trace\SpanBuilderInterface; use OpenTelemetry\API\Trace\SpanInterface; use OpenTelemetry\API\Trace\SpanKind; @@ -47,11 +60,19 @@ use OpenTelemetry\API\Trace\TracerInterface; use OpenTelemetry\API\Trace\TracerProviderInterface; use OpenTelemetry\Context\ScopeInterface; +use OpenTelemetry\SDK\Trace\SpanDataInterface; +use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; +use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; +use OpenTelemetry\SDK\Trace\TracerProvider; use PHPUnit\Framework\TestCase; +use Prophecy\PhpUnit\ProphecyTrait; +use RuntimeException; use stdClass; class TracingMiddlewareTest extends TestCase { + use ProphecyTrait; + use TestTrait; public function testTracingDisabledReturnsHandlerResult(): void { $call = new Call('test/method'); @@ -622,4 +643,531 @@ function () use ($innerPromise) { $this->assertTrue($cancelled); $this->assertSame('CANCELLED', $recordedAttributes[SpanAttributes::ERROR_TYPE]); } + + /** + * @dataProvider transportNameProvider + */ + public function testTracingDisabledDoesNotEmitSpanToExporter(string $transportName): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + + $response = new Status(['code' => Code::OK]); + $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); + + $middleware = new TracingMiddleware( + $nextHandler, + 'secretmanager.googleapis.com', + 443, + $transportName, + ['openTelemetryTracerProvider' => null] + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call( + 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion', + Status::class, + new MockRequest() + ); + $result = $middleware($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + $spans = $exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + /** + * @dataProvider transportNameProvider + */ + public function testUnaryCallEmitsSpanAsChildOfActiveSpan(string $transportName): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $response = new Status(['code' => Code::OK]); + $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); + + $middleware = new TracingMiddleware( + $nextHandler, + 'secretmanager.googleapis.com', + 443, + $transportName, + [ + 'openTelemetryTracerProvider' => $tracerProvider, + 'clientVersion' => '1.2.3', + ] + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + $result = $middleware($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(2, $spans); + + $middlewareSpan = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $middlewareSpan->getParentSpanId()); + $this->assertSame($exportedAppSpan->getTraceId(), $middlewareSpan->getTraceId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $middlewareSpan->getKind()); + $this->assertSame($method, $middlewareSpan->getName()); + $this->assertSame(StatusCode::STATUS_OK, $middlewareSpan->getStatus()->getCode()); + $this->assertSame('google-cloud-php', $middlewareSpan->getInstrumentationScope()->getName()); + $this->assertSame('1.2.3', $middlewareSpan->getInstrumentationScope()->getVersion()); + + $attrs = $middlewareSpan->getAttributes()->toArray(); + $this->assertSame($transportName, $attrs[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame($method, $attrs[SpanAttributes::RPC_METHOD]); + $this->assertSame('secretmanager.googleapis.com', $attrs[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(443, $attrs[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attrs); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attrs); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attrs); + } + + /** + * @dataProvider transportNameProvider + */ + public function testUnaryCallServerFailureAttributesWithInMemoryExporter(string $transportName): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + if ($transportName === 'http') { + $apiException1 = ApiException::createFromRestApiResponse( + 'Service unavailable', + Code::UNAVAILABLE + ); + $apiException2 = ApiException::createFromRestApiResponse( + 'API disabled in project', + Code::PERMISSION_DENIED, + [ + [ + '@type' => 'type.googleapis.com/google.rpc.ErrorInfo', + 'reason' => 'SERVICE_DISABLED', + 'domain' => 'googleapis.com', + 'metadata' => [], + ], + ] + ); + } else { + $status1 = new stdClass(); + $status1->code = Code::UNAVAILABLE; + $status1->details = 'Service unavailable'; + $apiException1 = ApiException::createFromStdClass($status1); + + $errorInfo = new ErrorInfo([ + 'reason' => 'SERVICE_DISABLED', + 'domain' => 'googleapis.com', + ]); + $status2 = new stdClass(); + $status2->code = Code::PERMISSION_DENIED; + $status2->details = 'API disabled in project'; + $status2->metadata = [ + 'google.rpc.errorinfo-bin' => [$errorInfo->serializeToString()], + ]; + $apiException2 = ApiException::createFromStdClass($status2); + } + + $exceptions = [$apiException1, $apiException2]; + $nextHandler = function () use (&$exceptions) { + return Create::rejectionFor(array_shift($exceptions)); + }; + + $middleware = new TracingMiddleware( + $nextHandler, + 'secretmanager.googleapis.com', + 443, + $transportName, + ['openTelemetryTracerProvider' => $tracerProvider] + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + + try { + $middleware($call, [])->wait(); + $this->fail('Expected ApiException 1'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + + try { + $middleware($call, [])->wait(); + $this->fail('Expected ApiException 2'); + } catch (ApiException $e) { + $this->assertSame('SERVICE_DISABLED', $e->getReason()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(3, $spans); + + $span1 = $spans[0]; + $span2 = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($exportedAppSpan->getSpanId(), $span1->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $span1->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $span1->getStatus()->getCode()); + $attrs1 = $span1->getAttributes()->toArray(); + $this->assertSame($transportName, $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Service unavailable', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + + $this->assertSame($exportedAppSpan->getSpanId(), $span2->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $span2->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $span2->getStatus()->getCode()); + $attrs2 = $span2->getAttributes()->toArray(); + $this->assertSame($transportName, $attrs2[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame('SERVICE_DISABLED', $attrs2[SpanAttributes::ERROR_TYPE]); + $this->assertSame('API disabled in project', $attrs2[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs2[SpanAttributes::EXCEPTION_TYPE]); + } + + /** + * @dataProvider transportNameProvider + */ + public function testUnaryCallClientFailureAndCancellationWithInMemoryExporter(string $transportName): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $callIndex = 0; + $nextHandler = function () use (&$callIndex) { + $callIndex++; + if ($callIndex === 1) { + throw new InvalidArgumentException('Client request validation failed'); + } + return new Promise(function () { + }, function () { + }); + }; + + $middleware = new TracingMiddleware( + $nextHandler, + 'secretmanager.googleapis.com', + 443, + $transportName, + ['openTelemetryTracerProvider' => $tracerProvider] + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + + try { + $middleware($call, []); + $this->fail('Expected InvalidArgumentException'); + } catch (InvalidArgumentException $e) { + $this->assertSame('Client request validation failed', $e->getMessage()); + } + + $promise = $middleware($call, []); + $promise->cancel(); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(3, $spans); + + $exceptionSpan = $spans[0]; + $cancelSpan = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($exportedAppSpan->getSpanId(), $exceptionSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_INTERNAL, $exceptionSpan->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $exceptionSpan->getStatus()->getCode()); + $attrs1 = $exceptionSpan->getAttributes()->toArray(); + $this->assertSame($transportName, $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame(InvalidArgumentException::class, $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame(InvalidArgumentException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame('Client request validation failed', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs1); + + $this->assertSame($exportedAppSpan->getSpanId(), $cancelSpan->getParentSpanId()); + $this->assertSame(StatusCode::STATUS_ERROR, $cancelSpan->getStatus()->getCode()); + $attrs2 = $cancelSpan->getAttributes()->toArray(); + $this->assertSame('CANCELLED', $attrs2[SpanAttributes::ERROR_TYPE]); + } + + /** + * @return array + */ + public function transportNameProvider(): array + { + return [ + ['http'], + ['grpc'], + ]; + } + + public function testRetrySucceedsLinksAttemptSpansToParentMiddlewareSpan(): void + { + self::requiresGrpcExtension(); + + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $failStatus = new stdClass(); + $failStatus->code = Code::UNAVAILABLE; + $failStatus->details = 'Transient error on attempt 1'; + + $okResponse = new Status(['code' => Code::OK]); + $okStatus = new stdClass(); + $okStatus->code = Code::OK; + + $unaryCall1 = $this->prophesize(UnaryCall::class); + $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); + + $unaryCall2 = $this->prophesize(UnaryCall::class); + $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([$okResponse, $okStatus]); + + $telemetryOptions = [ + 'openTelemetryTracerProvider' => $tracerProvider, + 'clientVersion' => '1.2.3', + ]; + + $transport = $this->createGrpcTransport( + [$unaryCall1->reveal(), $unaryCall2->reveal()], + $telemetryOptions + ); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'initialRetryDelayMillis' => 1, + 'maxRetryDelayMillis' => 5, + ]); + + $callStack = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); + $callStack = new TracingMiddleware( + $callStack, + 'secretmanager.googleapis.com', + 443, + 'grpc', + $telemetryOptions + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + $result = $callStack($call, [])->wait(); + $this->assertSame($okResponse, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(4, $spans); + + $attemptSpan1 = $spans[0]; + $attemptSpan2 = $spans[1]; + $middlewareSpan = $spans[2]; + $exportedAppSpan = $spans[3]; + + $this->assertSame($exportedAppSpan->getSpanId(), $middlewareSpan->getParentSpanId()); + $this->assertSame($middlewareSpan->getSpanId(), $attemptSpan1->getParentSpanId()); + $this->assertSame($middlewareSpan->getSpanId(), $attemptSpan2->getParentSpanId()); + + $this->assertSame(SpanKind::KIND_CLIENT, $attemptSpan1->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $attemptSpan1->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $attemptSpan1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertSame('UNAVAILABLE', $attemptSpan1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame( + 'Transient error on attempt 1', + $attemptSpan1->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) + ); + + $this->assertSame(SpanKind::KIND_CLIENT, $attemptSpan2->getKind()); + $this->assertSame(StatusCode::STATUS_OK, $attemptSpan2->getStatus()->getCode()); + $this->assertSame('OK', $attemptSpan2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertNull($attemptSpan2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertNull($attemptSpan2->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + + $this->assertSame(SpanKind::KIND_INTERNAL, $middlewareSpan->getKind()); + $this->assertSame(StatusCode::STATUS_OK, $middlewareSpan->getStatus()->getCode()); + $this->assertNull($middlewareSpan->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertNull($middlewareSpan->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); + $this->assertNull($middlewareSpan->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } + + public function testRetriesExhaustedLinksAllAttemptSpansAndMarksParentSpanAsError(): void + { + self::requiresGrpcExtension(); + + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $failStatus = new stdClass(); + $failStatus->code = Code::UNAVAILABLE; + $failStatus->details = 'Persistent backend outage'; + + $unaryCalls = []; + for ($i = 0; $i < 3; $i++) { + $call = $this->prophesize(UnaryCall::class); + $call->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); + $unaryCalls[] = $call->reveal(); + } + + $telemetryOptions = [ + 'openTelemetryTracerProvider' => $tracerProvider, + 'clientVersion' => '1.2.3', + ]; + + $transport = $this->createGrpcTransport($unaryCalls, $telemetryOptions); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'maxRetries' => 2, + 'initialRetryDelayMillis' => 1, + 'maxRetryDelayMillis' => 5, + ]); + + $callStack = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); + $callStack = new TracingMiddleware( + $callStack, + 'secretmanager.googleapis.com', + 443, + 'grpc', + $telemetryOptions + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + try { + $callStack($call, [])->wait(); + $this->fail('Expected ApiException after exhausting retries'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(5, $spans); + + $attemptSpans = [$spans[0], $spans[1], $spans[2]]; + $middlewareSpan = $spans[3]; + $exportedAppSpan = $spans[4]; + + $this->assertSame($exportedAppSpan->getSpanId(), $middlewareSpan->getParentSpanId()); + + foreach ($attemptSpans as $attemptSpan) { + $this->assertSame($middlewareSpan->getSpanId(), $attemptSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $attemptSpan->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $attemptSpan->getStatus()->getCode()); + $this->assertSame( + 'UNAVAILABLE', + $attemptSpan->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE) + ); + $this->assertSame('UNAVAILABLE', $attemptSpan->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame( + 'Persistent backend outage', + $attemptSpan->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) + ); + } + + $this->assertSame(SpanKind::KIND_INTERNAL, $middlewareSpan->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $middlewareSpan->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $middlewareSpan->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + $this->assertSame( + 'Persistent backend outage', + $middlewareSpan->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) + ); + $this->assertSame(ApiException::class, $middlewareSpan->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); + } + + /** + * @param UnaryCall[] $unaryCalls + * @param array $telemetryOptions + */ + private function createGrpcTransport(array $unaryCalls, array $telemetryOptions = []): GrpcTransport + { + return new class( + 'secretmanager.googleapis.com:443', + $unaryCalls, + $telemetryOptions + ) extends GrpcTransport { + /** @var UnaryCall[] */ + private array $unaryCalls; + + /** + * @param UnaryCall[] $unaryCalls + * @param array $telemetryOptions + */ + public function __construct(string $hostname, array $unaryCalls, array $telemetryOptions) + { + $this->unaryCalls = $unaryCalls; + parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); + $this->setTelemetryOptions($telemetryOptions); + } + + // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore + protected function _simpleRequest( + $method, + $arguments, + $deserialize, + array $metadata = [], + array $options = [] + ) { + return array_shift($this->unaryCalls); + } + }; + } } diff --git a/Gax/tests/Unit/Telemetry/TracingTestPlanTest.php b/Gax/tests/Unit/Telemetry/TracingTestPlanTest.php deleted file mode 100644 index fb133433feea..000000000000 --- a/Gax/tests/Unit/Telemetry/TracingTestPlanTest.php +++ /dev/null @@ -1,1132 +0,0 @@ -exporter = new InMemoryExporter(); - $this->tracerProvider = new TracerProvider(new SimpleSpanProcessor($this->exporter)); - } - - protected function tearDown(): void - { - $this->tracerProvider->shutdown(); - parent::tearDown(); - } - - /** - * F1.1: HTTP no traces emitted unless enabled. - */ - public function testF1_1_HttpNoTracesEmittedUnlessEnabled(): void - { - $response = new Status(['code' => Code::OK]); - $restTransport = $this->prophesize(RestTransport::class); - $restTransport->startUnaryCall(\Prophecy\Argument::type(Call::class), \Prophecy\Argument::type('array')) - ->shouldBeCalledOnce() - ->willReturn(Create::promiseFor($response)); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $restTransport->reveal()->startUnaryCall($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - $spans = $this->exporter->getSpans(); - $this->assertCount(1, $spans); - $this->assertSame('app-operation', $spans[0]->getName()); - } - - /** - * F1.6: gRPC no traces emitted unless enabled. - */ - public function testF1_6_GrpcNoTracesEmittedUnlessEnabled(): void - { - $response = new Status(['code' => Code::OK]); - $status = new stdClass(); - $status->code = Code::OK; - - $unaryCall = $this->prophesize(UnaryCall::class); - $unaryCall->wait()->shouldBeCalledOnce()->willReturn([$response, $status]); - - $transport = $this->createGrpcTransport([$unaryCall->reveal()]); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $transport->startUnaryCall($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - $spans = $this->exporter->getSpans(); - $this->assertCount(1, $spans); - $this->assertSame('app-operation', $spans[0]->getName()); - } - - /** - * F1.7: gRPC T4 success case name and attributes conform to requirements. - */ - public function testF1_7_GrpcT4Success(): void - { - $response = new Status(['code' => Code::OK]); - $status = new stdClass(); - $status->code = Code::OK; - - $unaryCall = $this->prophesize(UnaryCall::class); - $unaryCall->wait()->shouldBeCalledOnce()->willReturn([$response, $status]); - - $transport = $this->createGrpcTransport([$unaryCall->reveal()], [ - 'openTelemetryTracerProvider' => $this->tracerProvider, - 'clientVersion' => self::CLIENT_VERSION, - ]); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $transport->startUnaryCall($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(2, $spans); - - $t4Span = $spans[0]; - $exportedAppSpan = $spans[1]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t4Span->getParentSpanId()); - $this->assertSame($exportedAppSpan->getTraceId(), $t4Span->getTraceId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); - $this->assertSame(self::RPC_METHOD, $t4Span->getName()); - $this->assertSame(StatusCode::STATUS_OK, $t4Span->getStatus()->getCode()); - $this->assertSame('google-cloud-php', $t4Span->getInstrumentationScope()->getName()); - $this->assertSame(self::CLIENT_VERSION, $t4Span->getInstrumentationScope()->getVersion()); - - $attributes = $t4Span->getAttributes()->toArray(); - $this->assertSame('grpc', $attributes[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame(self::RPC_METHOD, $attributes[SpanAttributes::RPC_METHOD]); - $this->assertSame('OK', $attributes[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); - $this->assertSame(self::SERVER_ADDRESS, $attributes[SpanAttributes::SERVER_ADDRESS]); - $this->assertSame(self::SERVER_PORT, $attributes[SpanAttributes::SERVER_PORT]); - $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attributes); - $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attributes); - $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attributes); - } - - /** - * F1.8: gRPC T4 server failures case name and attributes conform to requirements - * (testing both standard gRPC status code and ErrorInfo reason). - */ - public function testF1_8_GrpcT4ServerFailures(): void - { - // Case 1: Server failure without ErrorInfo (uses status code string) - $statusWithoutErrorInfo = new stdClass(); - $statusWithoutErrorInfo->code = Code::UNAVAILABLE; - $statusWithoutErrorInfo->details = 'Service unavailable'; - - // Case 2: Server failure with ErrorInfo (uses ErrorInfo reason) - $errorInfo = new ErrorInfo([ - 'reason' => 'IAM_PERMISSION_DENIED', - 'domain' => 'googleapis.com', - ]); - $statusWithErrorInfo = new stdClass(); - $statusWithErrorInfo->code = Code::PERMISSION_DENIED; - $statusWithErrorInfo->details = 'Permission denied on resource'; - $statusWithErrorInfo->metadata = [ - 'google.rpc.errorinfo-bin' => [$errorInfo->serializeToString()], - ]; - - $unaryCall1 = $this->prophesize(UnaryCall::class); - $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $statusWithoutErrorInfo]); - - $unaryCall2 = $this->prophesize(UnaryCall::class); - $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([null, $statusWithErrorInfo]); - - $transport = $this->createGrpcTransport( - [$unaryCall1->reveal(), $unaryCall2->reveal()], - ['openTelemetryTracerProvider' => $this->tracerProvider] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - - try { - $transport->startUnaryCall($call, [])->wait(); - $this->fail('Expected ApiException for call 1'); - } catch (ApiException $e) { - $this->assertSame('UNAVAILABLE', $e->getStatus()); - } - - try { - $transport->startUnaryCall($call, [])->wait(); - $this->fail('Expected ApiException for call 2'); - } catch (ApiException $e) { - $this->assertSame('PERMISSION_DENIED', $e->getStatus()); - $this->assertSame('IAM_PERMISSION_DENIED', $e->getReason()); - } - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(3, $spans); - - $t4Span1 = $spans[0]; - $t4Span2 = $spans[1]; - $exportedAppSpan = $spans[2]; - - // Verify T4 span 1 (without ErrorInfo) - $this->assertSame($exportedAppSpan->getSpanId(), $t4Span1->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4Span1->getKind()); - $this->assertSame(self::RPC_METHOD, $t4Span1->getName()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4Span1->getStatus()->getCode()); - $this->assertSame('Service unavailable', $t4Span1->getStatus()->getDescription()); - $attrs1 = $t4Span1->getAttributes()->toArray(); - $this->assertSame('grpc', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame(self::RPC_METHOD, $attrs1[SpanAttributes::RPC_METHOD]); - $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); - $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::ERROR_TYPE]); - $this->assertSame('Service unavailable', $attrs1[SpanAttributes::STATUS_MESSAGE]); - $this->assertSame(ApiException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); - $this->assertSame(self::SERVER_ADDRESS, $attrs1[SpanAttributes::SERVER_ADDRESS]); - $this->assertSame(self::SERVER_PORT, $attrs1[SpanAttributes::SERVER_PORT]); - - // Verify T4 span 2 (with ErrorInfo) - $this->assertSame($exportedAppSpan->getSpanId(), $t4Span2->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4Span2->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4Span2->getStatus()->getCode()); - $this->assertSame('Permission denied on resource', $t4Span2->getStatus()->getDescription()); - $attrs2 = $t4Span2->getAttributes()->toArray(); - $this->assertSame('PERMISSION_DENIED', $attrs2[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); - $this->assertSame('IAM_PERMISSION_DENIED', $attrs2[SpanAttributes::ERROR_TYPE]); - $this->assertSame('Permission denied on resource', $attrs2[SpanAttributes::STATUS_MESSAGE]); - $this->assertSame(ApiException::class, $attrs2[SpanAttributes::EXCEPTION_TYPE]); - } - - /** - * F1.9: gRPC T4 client failures case name and attributes conform to requirements - * (testing both client-side exception before response and client cancellation). - */ - public function testF1_9_GrpcT4ClientFailures(): void - { - $unaryCallForCancel = $this->prophesize(UnaryCall::class); - $unaryCallForCancel->cancel()->shouldBeCalledOnce(); - - $callCount = 0; - $transport = new class( - self::SERVER_ADDRESS . ':' . self::SERVER_PORT, - function () use (&$callCount, $unaryCallForCancel) { - $callCount++; - if ($callCount === 1) { - throw new RuntimeException('Client deadline exceeded before sending request'); - } - return $unaryCallForCancel->reveal(); - }, - ['openTelemetryTracerProvider' => $this->tracerProvider] - ) extends GrpcTransport { - /** @var callable */ - private $factory; - - public function __construct(string $hostname, callable $factory, array $telemetryOptions) - { - $this->factory = $factory; - parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); - $this->setTelemetryOptions($telemetryOptions); - } - - // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore - protected function _simpleRequest( - $method, - $arguments, - $deserialize, - array $metadata = [], - array $options = [] - ) { - return ($this->factory)(); - } - }; - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - - // Case 1: Client-side exception thrown before receiving response - try { - $transport->startUnaryCall($call, []); - $this->fail('Expected RuntimeException'); - } catch (RuntimeException $e) { - $this->assertSame('Client deadline exceeded before sending request', $e->getMessage()); - } - - // Case 2: Client cancels the in-flight RPC promise - $promise = $transport->startUnaryCall($call, []); - $promise->cancel(); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(3, $spans); - - $t4ExceptionSpan = $spans[0]; - $t4CancelledSpan = $spans[1]; - $exportedAppSpan = $spans[2]; - - // Verify client exception span - $this->assertSame($exportedAppSpan->getSpanId(), $t4ExceptionSpan->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4ExceptionSpan->getKind()); - $this->assertSame(self::RPC_METHOD, $t4ExceptionSpan->getName()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4ExceptionSpan->getStatus()->getCode()); - $attrs1 = $t4ExceptionSpan->getAttributes()->toArray(); - $this->assertSame(RuntimeException::class, $attrs1[SpanAttributes::ERROR_TYPE]); - $this->assertSame(RuntimeException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); - $this->assertSame('Client deadline exceeded before sending request', $attrs1[SpanAttributes::STATUS_MESSAGE]); - $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs1); - - // Verify client cancellation span - $this->assertSame($exportedAppSpan->getSpanId(), $t4CancelledSpan->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4CancelledSpan->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4CancelledSpan->getStatus()->getCode()); - $attrs2 = $t4CancelledSpan->getAttributes()->toArray(); - $this->assertSame('CANCELLED', $attrs2[SpanAttributes::ERROR_TYPE]); - $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs2); - } - - /** - * F1.10: gRPC T4 retries. - */ - public function testF1_10_GrpcT4Retries(): void - { - $failStatus = new stdClass(); - $failStatus->code = Code::UNAVAILABLE; - $failStatus->details = 'Temporary backend error'; - - $okResponse = new Status(['code' => Code::OK]); - $okStatus = new stdClass(); - $okStatus->code = Code::OK; - - $unaryCall1 = $this->prophesize(UnaryCall::class); - $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); - - $unaryCall2 = $this->prophesize(UnaryCall::class); - $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([$okResponse, $okStatus]); - - $transport = $this->createGrpcTransport( - [$unaryCall1->reveal(), $unaryCall2->reveal()], - ['openTelemetryTracerProvider' => $this->tracerProvider] - ); - - $retrySettings = RetrySettings::constructDefault() - ->with([ - 'retriesEnabled' => true, - 'retryableCodes' => [ApiStatus::UNAVAILABLE], - 'initialRetryDelayMillis' => 1, - 'maxRetryDelayMillis' => 5, - ]); - - $retryMiddleware = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $retryMiddleware($call, [])->wait(); - $this->assertSame($okResponse, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(3, $spans); - - $t4Attempt1 = $spans[0]; - $t4Attempt2 = $spans[1]; - $exportedAppSpan = $spans[2]; - - // First attempt fails - $this->assertSame($exportedAppSpan->getSpanId(), $t4Attempt1->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4Attempt1->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4Attempt1->getStatus()->getCode()); - $this->assertSame('UNAVAILABLE', $t4Attempt1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); - $this->assertSame('UNAVAILABLE', $t4Attempt1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - - // Second attempt succeeds - $this->assertSame($exportedAppSpan->getSpanId(), $t4Attempt2->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4Attempt2->getKind()); - $this->assertSame(StatusCode::STATUS_OK, $t4Attempt2->getStatus()->getCode()); - $this->assertSame('OK', $t4Attempt2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); - $this->assertNull($t4Attempt2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - } - - /** - * F2.1: HTTP no traces emitted unless enabled. - */ - public function testF2_1_HttpNoTracesEmittedUnlessEnabled(): void - { - $response = new Status(['code' => Code::OK]); - $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'http', - ['openTelemetryTracerProvider' => null] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $middleware($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - $spans = $this->exporter->getSpans(); - $this->assertCount(1, $spans); - $this->assertSame('app-operation', $spans[0]->getName()); - } - - /** - * F2.2: HTTP T3 case name and attributes conform to requirements. - */ - public function testF2_2_HttpT3Success(): void - { - $response = new Status(['code' => Code::OK]); - $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'http', - [ - 'openTelemetryTracerProvider' => $this->tracerProvider, - 'clientVersion' => self::CLIENT_VERSION, - ] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $middleware($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(2, $spans); - - $t3Span = $spans[0]; - $exportedAppSpan = $spans[1]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); - $this->assertSame($exportedAppSpan->getTraceId(), $t3Span->getTraceId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); - $this->assertSame(self::RPC_METHOD, $t3Span->getName()); - $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); - $this->assertSame('google-cloud-php', $t3Span->getInstrumentationScope()->getName()); - $this->assertSame(self::CLIENT_VERSION, $t3Span->getInstrumentationScope()->getVersion()); - - $attrs = $t3Span->getAttributes()->toArray(); - $this->assertSame('http', $attrs[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame(self::RPC_METHOD, $attrs[SpanAttributes::RPC_METHOD]); - $this->assertSame(self::SERVER_ADDRESS, $attrs[SpanAttributes::SERVER_ADDRESS]); - $this->assertSame(self::SERVER_PORT, $attrs[SpanAttributes::SERVER_PORT]); - $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attrs); - $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attrs); - $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attrs); - } - - /** - * F2.3: HTTP T3 server failures case name and attributes conform to requirements. - */ - public function testF2_3_HttpT3ServerFailures(): void - { - $apiException1 = ApiException::createFromRestApiResponse( - 'Service unavailable', - Code::UNAVAILABLE - ); - $apiException2 = ApiException::createFromRestApiResponse( - 'API disabled in project', - Code::PERMISSION_DENIED, - [ - [ - '@type' => 'type.googleapis.com/google.rpc.ErrorInfo', - 'reason' => 'SERVICE_DISABLED', - 'domain' => 'googleapis.com', - 'metadata' => [], - ], - ] - ); - - $exceptions = [$apiException1, $apiException2]; - $nextHandler = function () use (&$exceptions) { - return Create::rejectionFor(array_shift($exceptions)); - }; - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'http', - ['openTelemetryTracerProvider' => $this->tracerProvider] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - - try { - $middleware($call, [])->wait(); - $this->fail('Expected ApiException 1'); - } catch (ApiException $e) { - $this->assertSame('UNAVAILABLE', $e->getStatus()); - } - - try { - $middleware($call, [])->wait(); - $this->fail('Expected ApiException 2'); - } catch (ApiException $e) { - $this->assertSame('SERVICE_DISABLED', $e->getReason()); - } - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(3, $spans); - - $t3Span1 = $spans[0]; - $t3Span2 = $spans[1]; - $exportedAppSpan = $spans[2]; - - // Span 1: status code fallback - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span1->getParentSpanId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span1->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3Span1->getStatus()->getCode()); - $attrs1 = $t3Span1->getAttributes()->toArray(); - $this->assertSame('http', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::ERROR_TYPE]); - $this->assertSame('Service unavailable', $attrs1[SpanAttributes::STATUS_MESSAGE]); - $this->assertSame(ApiException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); - - // Span 2: ErrorInfo reason - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span2->getParentSpanId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span2->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3Span2->getStatus()->getCode()); - $attrs2 = $t3Span2->getAttributes()->toArray(); - $this->assertSame('SERVICE_DISABLED', $attrs2[SpanAttributes::ERROR_TYPE]); - $this->assertSame('API disabled in project', $attrs2[SpanAttributes::STATUS_MESSAGE]); - $this->assertSame(ApiException::class, $attrs2[SpanAttributes::EXCEPTION_TYPE]); - } - - /** - * F2.4: HTTP T3 client failures case name and attributes conform to requirements. - */ - public function testF2_4_HttpT3ClientFailures(): void - { - $callIndex = 0; - $nextHandler = function () use (&$callIndex) { - $callIndex++; - if ($callIndex === 1) { - throw new InvalidArgumentException('Client request validation failed'); - } - $pending = new Promise(function () { - }, function () { - }); - return $pending; - }; - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'http', - ['openTelemetryTracerProvider' => $this->tracerProvider] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - - try { - $middleware($call, []); - $this->fail('Expected InvalidArgumentException'); - } catch (InvalidArgumentException $e) { - $this->assertSame('Client request validation failed', $e->getMessage()); - } - - $promise = $middleware($call, []); - $promise->cancel(); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(3, $spans); - - $t3ExceptionSpan = $spans[0]; - $t3CancelSpan = $spans[1]; - $exportedAppSpan = $spans[2]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t3ExceptionSpan->getParentSpanId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3ExceptionSpan->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3ExceptionSpan->getStatus()->getCode()); - $attrs1 = $t3ExceptionSpan->getAttributes()->toArray(); - $this->assertSame('http', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame(InvalidArgumentException::class, $attrs1[SpanAttributes::ERROR_TYPE]); - $this->assertSame(InvalidArgumentException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); - $this->assertSame('Client request validation failed', $attrs1[SpanAttributes::STATUS_MESSAGE]); - - $this->assertSame($exportedAppSpan->getSpanId(), $t3CancelSpan->getParentSpanId()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3CancelSpan->getStatus()->getCode()); - $attrs2 = $t3CancelSpan->getAttributes()->toArray(); - $this->assertSame('CANCELLED', $attrs2[SpanAttributes::ERROR_TYPE]); - } - - /** - * F2.5: gRPC no traces emitted unless enabled. - */ - public function testF2_5_GrpcNoTracesEmittedUnlessEnabled(): void - { - $response = new Status(['code' => Code::OK]); - $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'grpc', - ['openTelemetryTracerProvider' => null] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $middleware($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - $spans = $this->exporter->getSpans(); - $this->assertCount(1, $spans); - $this->assertSame('app-operation', $spans[0]->getName()); - } - - /** - * F2.6: gRPC T3 success case name and attributes conform to requirements. - */ - public function testF2_6_GrpcT3Success(): void - { - $response = new Status(['code' => Code::OK]); - $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'grpc', - [ - 'openTelemetryTracerProvider' => $this->tracerProvider, - 'clientVersion' => self::CLIENT_VERSION, - ] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $middleware($call, [])->wait(); - $this->assertSame($response, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(2, $spans); - - $t3Span = $spans[0]; - $exportedAppSpan = $spans[1]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); - $this->assertSame($exportedAppSpan->getTraceId(), $t3Span->getTraceId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); - $this->assertSame(self::RPC_METHOD, $t3Span->getName()); - $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); - - $attrs = $t3Span->getAttributes()->toArray(); - $this->assertSame('grpc', $attrs[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame(self::RPC_METHOD, $attrs[SpanAttributes::RPC_METHOD]); - $this->assertSame(self::SERVER_ADDRESS, $attrs[SpanAttributes::SERVER_ADDRESS]); - $this->assertSame(self::SERVER_PORT, $attrs[SpanAttributes::SERVER_PORT]); - $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attrs); - $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attrs); - $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attrs); - } - - /** - * F2.7: gRPC T3 server failures case name and attributes conform to requirements. - */ - public function testF2_7_GrpcT3ServerFailures(): void - { - $errorInfo = new ErrorInfo([ - 'reason' => 'RESOURCE_MISSING', - 'domain' => 'googleapis.com', - ]); - $status = new stdClass(); - $status->code = Code::NOT_FOUND; - $status->details = 'Secret version not found'; - $status->metadata = [ - 'google.rpc.errorinfo-bin' => [$errorInfo->serializeToString()], - ]; - $apiException = ApiException::createFromStdClass($status); - - $nextHandler = fn () => Create::rejectionFor($apiException); - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'grpc', - ['openTelemetryTracerProvider' => $this->tracerProvider] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - try { - $middleware($call, [])->wait(); - $this->fail('Expected ApiException'); - } catch (ApiException $e) { - $this->assertSame('RESOURCE_MISSING', $e->getReason()); - } - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(2, $spans); - - $t3Span = $spans[0]; - $exportedAppSpan = $spans[1]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); - $this->assertSame('Secret version not found', $t3Span->getStatus()->getDescription()); - - $attrs = $t3Span->getAttributes()->toArray(); - $this->assertSame('grpc', $attrs[SpanAttributes::RPC_SYSTEM_NAME]); - $this->assertSame('RESOURCE_MISSING', $attrs[SpanAttributes::ERROR_TYPE]); - $this->assertSame('Secret version not found', $attrs[SpanAttributes::STATUS_MESSAGE]); - $this->assertSame(ApiException::class, $attrs[SpanAttributes::EXCEPTION_TYPE]); - } - - /** - * F2.8: gRPC T3 client failures case name and attributes conform to requirements. - */ - public function testF2_8_GrpcT3ClientFailures(): void - { - $nextHandler = function () { - throw new RuntimeException('Client connection setup error'); - }; - - $middleware = new TracingMiddleware( - $nextHandler, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'grpc', - ['openTelemetryTracerProvider' => $this->tracerProvider] - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - try { - $middleware($call, []); - $this->fail('Expected RuntimeException'); - } catch (RuntimeException $e) { - $this->assertSame('Client connection setup error', $e->getMessage()); - } - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(2, $spans); - - $t3Span = $spans[0]; - $exportedAppSpan = $spans[1]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); - $attrs = $t3Span->getAttributes()->toArray(); - $this->assertSame(RuntimeException::class, $attrs[SpanAttributes::ERROR_TYPE]); - $this->assertSame(RuntimeException::class, $attrs[SpanAttributes::EXCEPTION_TYPE]); - $this->assertSame('Client connection setup error', $attrs[SpanAttributes::STATUS_MESSAGE]); - $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs); - } - - /** - * F3.3: gRPC T3/T4 retry succeeds. - */ - public function testF3_3_GrpcT3T4RetrySucceeds(): void - { - $failStatus = new stdClass(); - $failStatus->code = Code::UNAVAILABLE; - $failStatus->details = 'Transient error on attempt 1'; - - $okResponse = new Status(['code' => Code::OK]); - $okStatus = new stdClass(); - $okStatus->code = Code::OK; - - $unaryCall1 = $this->prophesize(UnaryCall::class); - $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); - - $unaryCall2 = $this->prophesize(UnaryCall::class); - $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([$okResponse, $okStatus]); - - $telemetryOptions = [ - 'openTelemetryTracerProvider' => $this->tracerProvider, - 'clientVersion' => self::CLIENT_VERSION, - ]; - - $transport = $this->createGrpcTransport( - [$unaryCall1->reveal(), $unaryCall2->reveal()], - $telemetryOptions - ); - - $retrySettings = RetrySettings::constructDefault() - ->with([ - 'retriesEnabled' => true, - 'retryableCodes' => [ApiStatus::UNAVAILABLE], - 'initialRetryDelayMillis' => 1, - 'maxRetryDelayMillis' => 5, - ]); - - $callStack = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); - $callStack = new TracingMiddleware( - $callStack, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'grpc', - $telemetryOptions - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - $result = $callStack($call, [])->wait(); - $this->assertSame($okResponse, $result); - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(4, $spans); - - $t4Span1 = $spans[0]; - $t4Span2 = $spans[1]; - $t3Span = $spans[2]; - $exportedAppSpan = $spans[3]; - - // Verify parent-child hierarchy: APP -> T3 -> (T4_1, T4_2) - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); - $this->assertSame($t3Span->getSpanId(), $t4Span1->getParentSpanId()); - $this->assertSame($t3Span->getSpanId(), $t4Span2->getParentSpanId()); - - // Verify T4_1 matches failure requirements (F1.8) - $this->assertSame(SpanKind::KIND_CLIENT, $t4Span1->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4Span1->getStatus()->getCode()); - $this->assertSame('UNAVAILABLE', $t4Span1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); - $this->assertSame('UNAVAILABLE', $t4Span1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - $this->assertSame( - 'Transient error on attempt 1', - $t4Span1->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) - ); - - // Verify T4_2 matches success requirements (F1.7) - $this->assertSame(SpanKind::KIND_CLIENT, $t4Span2->getKind()); - $this->assertSame(StatusCode::STATUS_OK, $t4Span2->getStatus()->getCode()); - $this->assertSame('OK', $t4Span2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); - $this->assertNull($t4Span2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - $this->assertNull($t4Span2->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); - - // Verify T3 matches success requirements (F2.6) - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); - $this->assertSame(StatusCode::STATUS_OK, $t3Span->getStatus()->getCode()); - $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); - $this->assertNull($t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); - } - - /** - * F3.4: gRPC T3/T4 retries exhausted. - */ - public function testF3_4_GrpcT3T4RetriesExhausted(): void - { - $failStatus = new stdClass(); - $failStatus->code = Code::UNAVAILABLE; - $failStatus->details = 'Persistent backend outage'; - - $unaryCalls = []; - for ($i = 0; $i < 3; $i++) { - $call = $this->prophesize(UnaryCall::class); - $call->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); - $unaryCalls[] = $call->reveal(); - } - - $telemetryOptions = [ - 'openTelemetryTracerProvider' => $this->tracerProvider, - 'clientVersion' => self::CLIENT_VERSION, - ]; - - $transport = $this->createGrpcTransport($unaryCalls, $telemetryOptions); - - $retrySettings = RetrySettings::constructDefault() - ->with([ - 'retriesEnabled' => true, - 'retryableCodes' => [ApiStatus::UNAVAILABLE], - 'maxRetries' => 2, - 'initialRetryDelayMillis' => 1, - 'maxRetryDelayMillis' => 5, - ]); - - $callStack = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); - $callStack = new TracingMiddleware( - $callStack, - self::SERVER_ADDRESS, - self::SERVER_PORT, - 'grpc', - $telemetryOptions - ); - - $appSpan = $this->tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); - $appScope = $appSpan->activate(); - - try { - $call = new Call(self::RPC_METHOD, Status::class, new MockRequest()); - try { - $callStack($call, [])->wait(); - $this->fail('Expected ApiException after exhausting retries'); - } catch (ApiException $e) { - $this->assertSame('UNAVAILABLE', $e->getStatus()); - } - } finally { - $appScope->detach(); - $appSpan->end(); - } - - /** @var SpanDataInterface[] $spans */ - $spans = $this->exporter->getSpans(); - $this->assertCount(5, $spans); - - $t4Spans = [$spans[0], $spans[1], $spans[2]]; - $t3Span = $spans[3]; - $exportedAppSpan = $spans[4]; - - $this->assertSame($exportedAppSpan->getSpanId(), $t3Span->getParentSpanId()); - - foreach ($t4Spans as $t4Span) { - $this->assertSame($t3Span->getSpanId(), $t4Span->getParentSpanId()); - $this->assertSame(SpanKind::KIND_CLIENT, $t4Span->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t4Span->getStatus()->getCode()); - $this->assertSame('UNAVAILABLE', $t4Span->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); - $this->assertSame('UNAVAILABLE', $t4Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - $this->assertSame( - 'Persistent backend outage', - $t4Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE) - ); - } - - // Verify T3 span matches failure requirements (F2.7) - $this->assertSame(SpanKind::KIND_INTERNAL, $t3Span->getKind()); - $this->assertSame(StatusCode::STATUS_ERROR, $t3Span->getStatus()->getCode()); - $this->assertSame('UNAVAILABLE', $t3Span->getAttributes()->get(SpanAttributes::ERROR_TYPE)); - $this->assertSame('Persistent backend outage', $t3Span->getAttributes()->get(SpanAttributes::STATUS_MESSAGE)); - $this->assertSame(ApiException::class, $t3Span->getAttributes()->get(SpanAttributes::EXCEPTION_TYPE)); - } - - /** - * @param UnaryCall[] $unaryCalls - * @param array $telemetryOptions - */ - private function createGrpcTransport(array $unaryCalls, array $telemetryOptions = []): GrpcTransport - { - return new class( - self::SERVER_ADDRESS . ':' . self::SERVER_PORT, - $unaryCalls, - $telemetryOptions - ) extends GrpcTransport { - /** @var UnaryCall[] */ - private array $unaryCalls; - - /** - * @param UnaryCall[] $unaryCalls - * @param array $telemetryOptions - */ - public function __construct(string $hostname, array $unaryCalls, array $telemetryOptions) - { - $this->unaryCalls = $unaryCalls; - parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); - $this->setTelemetryOptions($telemetryOptions); - } - - // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore - protected function _simpleRequest( - $method, - $arguments, - $deserialize, - array $metadata = [], - array $options = [] - ) { - return array_shift($this->unaryCalls); - } - }; - } -} diff --git a/Gax/tests/Unit/Transport/GrpcTransportTest.php b/Gax/tests/Unit/Transport/GrpcTransportTest.php index 72dfa4b0c164..267fc59780d9 100644 --- a/Gax/tests/Unit/Transport/GrpcTransportTest.php +++ b/Gax/tests/Unit/Transport/GrpcTransportTest.php @@ -33,8 +33,11 @@ namespace Google\ApiCore\Tests\Unit\Transport; use Google\ApiCore\ApiException; +use Google\ApiCore\ApiStatus; use Google\ApiCore\Call; use Google\ApiCore\CredentialsWrapper; +use Google\ApiCore\Middleware\RetryMiddleware; +use Google\ApiCore\RetrySettings; use Google\ApiCore\Testing\MockGrpcTransport; use Google\ApiCore\Testing\MockRequest; use Google\ApiCore\Telemetry\SpanAttributes; @@ -46,6 +49,7 @@ use Google\Protobuf\Internal\Message; use Google\Protobuf\RepeatedField; use Google\Rpc\Code; +use Google\Rpc\ErrorInfo; use Google\Rpc\Status; use Grpc\BaseStub; use Grpc\CallInvoker; @@ -61,11 +65,16 @@ use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\API\Trace\TracerInterface; use OpenTelemetry\API\Trace\TracerProviderInterface; +use OpenTelemetry\SDK\Trace\SpanDataInterface; +use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; +use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; +use OpenTelemetry\SDK\Trace\TracerProvider; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; use Psr\Log\LoggerInterface; use ReflectionClass; +use RuntimeException; use stdClass; use TypeError; @@ -920,4 +929,386 @@ public function testBuildSetsTelemetryOptions(): void $portProp = $ref->getProperty('serverPort'); $this->assertSame(443, $portProp->getValue($transport)); } + + public function testStartUnaryCallDoesNotEmitSpanWhenTracingDisabled(): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + + $response = new Status(['code' => Code::OK]); + $status = new stdClass(); + $status->code = Code::OK; + + $unaryCall = $this->prophesize(UnaryCall::class); + $unaryCall->wait()->shouldBeCalledOnce()->willReturn([$response, $status]); + + $transport = $this->createTracedGrpcTransport([$unaryCall->reveal()]); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call( + 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion', + Status::class, + new MockRequest() + ); + $result = $transport->startUnaryCall($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + $spans = $exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } + + public function testStartUnaryCallRecordsParentSpanAndServerAttributes(): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $response = new Status(['code' => Code::OK]); + $status = new stdClass(); + $status->code = Code::OK; + + $unaryCall = $this->prophesize(UnaryCall::class); + $unaryCall->wait()->shouldBeCalledOnce()->willReturn([$response, $status]); + + $transport = $this->createTracedGrpcTransport([$unaryCall->reveal()], [ + 'openTelemetryTracerProvider' => $tracerProvider, + 'clientVersion' => '1.2.3', + ]); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + $result = $transport->startUnaryCall($call, [])->wait(); + $this->assertSame($response, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(2, $spans); + + $transportSpan = $spans[0]; + $exportedAppSpan = $spans[1]; + + $this->assertSame($exportedAppSpan->getSpanId(), $transportSpan->getParentSpanId()); + $this->assertSame($exportedAppSpan->getTraceId(), $transportSpan->getTraceId()); + $this->assertSame(SpanKind::KIND_CLIENT, $transportSpan->getKind()); + $this->assertSame($method, $transportSpan->getName()); + $this->assertSame(StatusCode::STATUS_OK, $transportSpan->getStatus()->getCode()); + $this->assertSame('google-cloud-php', $transportSpan->getInstrumentationScope()->getName()); + $this->assertSame('1.2.3', $transportSpan->getInstrumentationScope()->getVersion()); + + $attributes = $transportSpan->getAttributes()->toArray(); + $this->assertSame('grpc', $attributes[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame($method, $attributes[SpanAttributes::RPC_METHOD]); + $this->assertSame('OK', $attributes[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame('secretmanager.googleapis.com', $attributes[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(443, $attributes[SpanAttributes::SERVER_PORT]); + $this->assertArrayNotHasKey(SpanAttributes::STATUS_MESSAGE, $attributes); + $this->assertArrayNotHasKey(SpanAttributes::ERROR_TYPE, $attributes); + $this->assertArrayNotHasKey(SpanAttributes::EXCEPTION_TYPE, $attributes); + } + + public function testStartUnaryCallRecordsErrorInfoReasonAndServerFailureAttributes(): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $statusWithoutErrorInfo = new stdClass(); + $statusWithoutErrorInfo->code = Code::UNAVAILABLE; + $statusWithoutErrorInfo->details = 'Service unavailable'; + + $errorInfo = new ErrorInfo([ + 'reason' => 'IAM_PERMISSION_DENIED', + 'domain' => 'googleapis.com', + ]); + $statusWithErrorInfo = new stdClass(); + $statusWithErrorInfo->code = Code::PERMISSION_DENIED; + $statusWithErrorInfo->details = 'Permission denied on resource'; + $statusWithErrorInfo->metadata = [ + 'google.rpc.errorinfo-bin' => [$errorInfo->serializeToString()], + ]; + + $unaryCall1 = $this->prophesize(UnaryCall::class); + $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $statusWithoutErrorInfo]); + + $unaryCall2 = $this->prophesize(UnaryCall::class); + $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([null, $statusWithErrorInfo]); + + $transport = $this->createTracedGrpcTransport( + [$unaryCall1->reveal(), $unaryCall2->reveal()], + ['openTelemetryTracerProvider' => $tracerProvider] + ); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + + try { + $transport->startUnaryCall($call, [])->wait(); + $this->fail('Expected ApiException for call 1'); + } catch (ApiException $e) { + $this->assertSame('UNAVAILABLE', $e->getStatus()); + } + + try { + $transport->startUnaryCall($call, [])->wait(); + $this->fail('Expected ApiException for call 2'); + } catch (ApiException $e) { + $this->assertSame('PERMISSION_DENIED', $e->getStatus()); + $this->assertSame('IAM_PERMISSION_DENIED', $e->getReason()); + } + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(3, $spans); + + $span1 = $spans[0]; + $span2 = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($exportedAppSpan->getSpanId(), $span1->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $span1->getKind()); + $this->assertSame($method, $span1->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $span1->getStatus()->getCode()); + $this->assertSame('Service unavailable', $span1->getStatus()->getDescription()); + $attrs1 = $span1->getAttributes()->toArray(); + $this->assertSame('grpc', $attrs1[SpanAttributes::RPC_SYSTEM_NAME]); + $this->assertSame($method, $attrs1[SpanAttributes::RPC_METHOD]); + $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame('UNAVAILABLE', $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Service unavailable', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame('secretmanager.googleapis.com', $attrs1[SpanAttributes::SERVER_ADDRESS]); + $this->assertSame(443, $attrs1[SpanAttributes::SERVER_PORT]); + + $this->assertSame($exportedAppSpan->getSpanId(), $span2->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $span2->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $span2->getStatus()->getCode()); + $this->assertSame('Permission denied on resource', $span2->getStatus()->getDescription()); + $attrs2 = $span2->getAttributes()->toArray(); + $this->assertSame('PERMISSION_DENIED', $attrs2[SpanAttributes::RPC_RESPONSE_STATUS_CODE]); + $this->assertSame('IAM_PERMISSION_DENIED', $attrs2[SpanAttributes::ERROR_TYPE]); + $this->assertSame('Permission denied on resource', $attrs2[SpanAttributes::STATUS_MESSAGE]); + $this->assertSame(ApiException::class, $attrs2[SpanAttributes::EXCEPTION_TYPE]); + } + + public function testStartUnaryCallRecordsClientFailureAndCancellationOnSpan(): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $unaryCallForCancel = $this->prophesize(UnaryCall::class); + $unaryCallForCancel->cancel()->shouldBeCalledOnce(); + + $callCount = 0; + $transport = new class( + 'secretmanager.googleapis.com:443', + function () use (&$callCount, $unaryCallForCancel) { + $callCount++; + if ($callCount === 1) { + throw new RuntimeException('Client deadline exceeded before sending request'); + } + return $unaryCallForCancel->reveal(); + }, + ['openTelemetryTracerProvider' => $tracerProvider] + ) extends GrpcTransport { + /** @var callable */ + private $factory; + + public function __construct(string $hostname, callable $factory, array $telemetryOptions) + { + $this->factory = $factory; + parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); + $this->setTelemetryOptions($telemetryOptions); + } + + // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore + protected function _simpleRequest( + $method, + $arguments, + $deserialize, + array $metadata = [], + array $options = [] + ) { + return ($this->factory)(); + } + }; + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + + try { + $transport->startUnaryCall($call, []); + $this->fail('Expected RuntimeException'); + } catch (RuntimeException $e) { + $this->assertSame('Client deadline exceeded before sending request', $e->getMessage()); + } + + $promise = $transport->startUnaryCall($call, []); + $promise->cancel(); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(3, $spans); + + $exceptionSpan = $spans[0]; + $cancelledSpan = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($exportedAppSpan->getSpanId(), $exceptionSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $exceptionSpan->getKind()); + $this->assertSame($method, $exceptionSpan->getName()); + $this->assertSame(StatusCode::STATUS_ERROR, $exceptionSpan->getStatus()->getCode()); + $attrs1 = $exceptionSpan->getAttributes()->toArray(); + $this->assertSame(RuntimeException::class, $attrs1[SpanAttributes::ERROR_TYPE]); + $this->assertSame(RuntimeException::class, $attrs1[SpanAttributes::EXCEPTION_TYPE]); + $this->assertSame('Client deadline exceeded before sending request', $attrs1[SpanAttributes::STATUS_MESSAGE]); + $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs1); + + $this->assertSame($exportedAppSpan->getSpanId(), $cancelledSpan->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $cancelledSpan->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $cancelledSpan->getStatus()->getCode()); + $attrs2 = $cancelledSpan->getAttributes()->toArray(); + $this->assertSame('CANCELLED', $attrs2[SpanAttributes::ERROR_TYPE]); + $this->assertArrayNotHasKey(SpanAttributes::RPC_RESPONSE_STATUS_CODE, $attrs2); + } + + public function testStartUnaryCallWithRetryMiddlewareEmitsSpanPerAttempt(): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; + + $failStatus = new stdClass(); + $failStatus->code = Code::UNAVAILABLE; + $failStatus->details = 'Temporary backend error'; + + $okResponse = new Status(['code' => Code::OK]); + $okStatus = new stdClass(); + $okStatus->code = Code::OK; + + $unaryCall1 = $this->prophesize(UnaryCall::class); + $unaryCall1->wait()->shouldBeCalledOnce()->willReturn([null, $failStatus]); + + $unaryCall2 = $this->prophesize(UnaryCall::class); + $unaryCall2->wait()->shouldBeCalledOnce()->willReturn([$okResponse, $okStatus]); + + $transport = $this->createTracedGrpcTransport( + [$unaryCall1->reveal(), $unaryCall2->reveal()], + ['openTelemetryTracerProvider' => $tracerProvider] + ); + + $retrySettings = RetrySettings::constructDefault() + ->with([ + 'retriesEnabled' => true, + 'retryableCodes' => [ApiStatus::UNAVAILABLE], + 'initialRetryDelayMillis' => 1, + 'maxRetryDelayMillis' => 5, + ]); + + $retryMiddleware = new RetryMiddleware([$transport, 'startUnaryCall'], $retrySettings); + + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $call = new Call($method, Status::class, new MockRequest()); + $result = $retryMiddleware($call, [])->wait(); + $this->assertSame($okResponse, $result); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + /** @var SpanDataInterface[] $spans */ + $spans = $exporter->getSpans(); + $this->assertCount(3, $spans); + + $attempt1 = $spans[0]; + $attempt2 = $spans[1]; + $exportedAppSpan = $spans[2]; + + $this->assertSame($exportedAppSpan->getSpanId(), $attempt1->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $attempt1->getKind()); + $this->assertSame(StatusCode::STATUS_ERROR, $attempt1->getStatus()->getCode()); + $this->assertSame('UNAVAILABLE', $attempt1->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertSame('UNAVAILABLE', $attempt1->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + + $this->assertSame($exportedAppSpan->getSpanId(), $attempt2->getParentSpanId()); + $this->assertSame(SpanKind::KIND_CLIENT, $attempt2->getKind()); + $this->assertSame(StatusCode::STATUS_OK, $attempt2->getStatus()->getCode()); + $this->assertSame('OK', $attempt2->getAttributes()->get(SpanAttributes::RPC_RESPONSE_STATUS_CODE)); + $this->assertNull($attempt2->getAttributes()->get(SpanAttributes::ERROR_TYPE)); + } + + /** + * @param UnaryCall[] $unaryCalls + * @param array $telemetryOptions + */ + private function createTracedGrpcTransport(array $unaryCalls, array $telemetryOptions = []): GrpcTransport + { + return new class( + 'secretmanager.googleapis.com:443', + $unaryCalls, + $telemetryOptions + ) extends GrpcTransport { + /** @var UnaryCall[] */ + private array $unaryCalls; + + /** + * @param UnaryCall[] $unaryCalls + * @param array $telemetryOptions + */ + public function __construct(string $hostname, array $unaryCalls, array $telemetryOptions) + { + $this->unaryCalls = $unaryCalls; + parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); + $this->setTelemetryOptions($telemetryOptions); + } + + // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore + protected function _simpleRequest( + $method, + $arguments, + $deserialize, + array $metadata = [], + array $options = [] + ) { + return array_shift($this->unaryCalls); + } + }; + } } diff --git a/Gax/tests/Unit/Transport/RestTransportTest.php b/Gax/tests/Unit/Transport/RestTransportTest.php index fb0de054d360..eebc6bc567a9 100644 --- a/Gax/tests/Unit/Transport/RestTransportTest.php +++ b/Gax/tests/Unit/Transport/RestTransportTest.php @@ -54,6 +54,9 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use InvalidArgumentException; +use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; +use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; +use OpenTelemetry\SDK\Trace\TracerProvider; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; use Prophecy\Argument; @@ -681,4 +684,32 @@ public function testBuildRequestWithDefaultHeaders() $actualRequest = $transport->buildRequest($method, $message); $this->assertSame($expectedRequest, $actualRequest); } + + public function testStartUnaryCallDoesNotEmitSpan(): void + { + $exporter = new InMemoryExporter(); + $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + + $body = ['name' => 'hello', 'number' => 15]; + $httpHandler = fn (RequestInterface $request, array $options = []) => Create::promiseFor( + new Response(200, [], json_encode($body)) + ); + + $transport = $this->getTransport($httpHandler); + $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); + $appScope = $appSpan->activate(); + + try { + $response = $transport->startUnaryCall($this->call, [])->wait(); + $this->assertSame('hello', $response->getName()); + } finally { + $appScope->detach(); + $appSpan->end(); + $tracerProvider->shutdown(); + } + + $spans = $exporter->getSpans(); + $this->assertCount(1, $spans); + $this->assertSame('app-operation', $spans[0]->getName()); + } } From e70541d828132b5845abd3e6078e6ae513dc0281 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 7 Oct 2026 23:06:28 +0000 Subject: [PATCH 4/6] test(gax): use empty ResourceInfo in TracerProvider for lowest dependency compatibility --- Gax/tests/Conformance/OtelTracingTest.php | 7 +++- .../Unit/Middleware/TracingMiddlewareTest.php | 37 ++++++++++++++++--- .../Unit/Transport/GrpcTransportTest.php | 31 +++++++++++++--- .../Unit/Transport/RestTransportTest.php | 7 +++- 4 files changed, 69 insertions(+), 13 deletions(-) diff --git a/Gax/tests/Conformance/OtelTracingTest.php b/Gax/tests/Conformance/OtelTracingTest.php index d6bd85f3b478..cadf6a30718d 100644 --- a/Gax/tests/Conformance/OtelTracingTest.php +++ b/Gax/tests/Conformance/OtelTracingTest.php @@ -48,6 +48,7 @@ use OpenTelemetry\API\Trace\SpanKind; use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\API\Trace\TracerProviderInterface; +use OpenTelemetry\SDK\Resource\ResourceInfoFactory; use OpenTelemetry\SDK\Trace\SpanDataInterface; use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; @@ -72,7 +73,11 @@ protected function setUp(): void { parent::setUp(); $this->exporter = new InMemoryExporter(); - $this->tracerProvider = new TracerProvider(new SimpleSpanProcessor($this->exporter)); + $this->tracerProvider = new TracerProvider( + new SimpleSpanProcessor($this->exporter), + null, + ResourceInfoFactory::emptyResource() + ); } protected function tearDown(): void diff --git a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php index a01b65db00b3..d35ca63262f1 100644 --- a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php @@ -60,6 +60,7 @@ use OpenTelemetry\API\Trace\TracerInterface; use OpenTelemetry\API\Trace\TracerProviderInterface; use OpenTelemetry\Context\ScopeInterface; +use OpenTelemetry\SDK\Resource\ResourceInfoFactory; use OpenTelemetry\SDK\Trace\SpanDataInterface; use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; @@ -650,7 +651,11 @@ function () use ($innerPromise) { public function testTracingDisabledDoesNotEmitSpanToExporter(string $transportName): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $response = new Status(['code' => Code::OK]); $nextHandler = fn (Call $call, array $options) => Create::promiseFor($response); @@ -691,7 +696,11 @@ public function testTracingDisabledDoesNotEmitSpanToExporter(string $transportNa public function testUnaryCallEmitsSpanAsChildOfActiveSpan(string $transportName): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $response = new Status(['code' => Code::OK]); @@ -752,7 +761,11 @@ public function testUnaryCallEmitsSpanAsChildOfActiveSpan(string $transportName) public function testUnaryCallServerFailureAttributesWithInMemoryExporter(string $transportName): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; if ($transportName === 'http') { @@ -862,7 +875,11 @@ public function testUnaryCallServerFailureAttributesWithInMemoryExporter(string public function testUnaryCallClientFailureAndCancellationWithInMemoryExporter(string $transportName): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $callIndex = 0; @@ -945,7 +962,11 @@ public function testRetrySucceedsLinksAttemptSpansToParentMiddlewareSpan(): void self::requiresGrpcExtension(); $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $failStatus = new stdClass(); @@ -1042,7 +1063,11 @@ public function testRetriesExhaustedLinksAllAttemptSpansAndMarksParentSpanAsErro self::requiresGrpcExtension(); $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $failStatus = new stdClass(); diff --git a/Gax/tests/Unit/Transport/GrpcTransportTest.php b/Gax/tests/Unit/Transport/GrpcTransportTest.php index 267fc59780d9..4bea9a9b5637 100644 --- a/Gax/tests/Unit/Transport/GrpcTransportTest.php +++ b/Gax/tests/Unit/Transport/GrpcTransportTest.php @@ -65,6 +65,7 @@ use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\API\Trace\TracerInterface; use OpenTelemetry\API\Trace\TracerProviderInterface; +use OpenTelemetry\SDK\Resource\ResourceInfoFactory; use OpenTelemetry\SDK\Trace\SpanDataInterface; use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; @@ -933,7 +934,11 @@ public function testBuildSetsTelemetryOptions(): void public function testStartUnaryCallDoesNotEmitSpanWhenTracingDisabled(): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $response = new Status(['code' => Code::OK]); $status = new stdClass(); @@ -969,7 +974,11 @@ public function testStartUnaryCallDoesNotEmitSpanWhenTracingDisabled(): void public function testStartUnaryCallRecordsParentSpanAndServerAttributes(): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $response = new Status(['code' => Code::OK]); @@ -1026,7 +1035,11 @@ public function testStartUnaryCallRecordsParentSpanAndServerAttributes(): void public function testStartUnaryCallRecordsErrorInfoReasonAndServerFailureAttributes(): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $statusWithoutErrorInfo = new stdClass(); @@ -1118,7 +1131,11 @@ public function testStartUnaryCallRecordsErrorInfoReasonAndServerFailureAttribut public function testStartUnaryCallRecordsClientFailureAndCancellationOnSpan(): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $unaryCallForCancel = $this->prophesize(UnaryCall::class); @@ -1208,7 +1225,11 @@ protected function _simpleRequest( public function testStartUnaryCallWithRetryMiddlewareEmitsSpanPerAttempt(): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $method = 'google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion'; $failStatus = new stdClass(); diff --git a/Gax/tests/Unit/Transport/RestTransportTest.php b/Gax/tests/Unit/Transport/RestTransportTest.php index eebc6bc567a9..fcb51bf1b042 100644 --- a/Gax/tests/Unit/Transport/RestTransportTest.php +++ b/Gax/tests/Unit/Transport/RestTransportTest.php @@ -54,6 +54,7 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use InvalidArgumentException; +use OpenTelemetry\SDK\Resource\ResourceInfoFactory; use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; use OpenTelemetry\SDK\Trace\TracerProvider; @@ -688,7 +689,11 @@ public function testBuildRequestWithDefaultHeaders() public function testStartUnaryCallDoesNotEmitSpan(): void { $exporter = new InMemoryExporter(); - $tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter)); + $tracerProvider = new TracerProvider( + new SimpleSpanProcessor($exporter), + null, + ResourceInfoFactory::emptyResource() + ); $body = ['name' => 'hello', 'number' => 15]; $httpHandler = fn (RequestInterface $request, array $options = []) => Create::promiseFor( From dce32d1e9de67f0c63189ff4ad02922d7ee0a264 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 8 Oct 2026 20:15:39 +0000 Subject: [PATCH 5/6] test(Gax): use non-empty associative array for ErrorInfo metadata with ext-protobuf --- Gax/tests/Unit/Middleware/TracingMiddlewareTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php index d35ca63262f1..869f54298b5a 100644 --- a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php @@ -781,7 +781,7 @@ public function testUnaryCallServerFailureAttributesWithInMemoryExporter(string '@type' => 'type.googleapis.com/google.rpc.ErrorInfo', 'reason' => 'SERVICE_DISABLED', 'domain' => 'googleapis.com', - 'metadata' => [], + 'metadata' => ['service' => 'secretmanager.googleapis.com'], ], ] ); From ed30fadcaa7e127c7241735b84561abd43ad0ea3 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 8 Oct 2026 21:37:12 +0000 Subject: [PATCH 6/6] test(Gax): use ReflectionClass for private setTelemetryOptions on GrpcTransport subclasses --- .../Unit/Middleware/TracingMiddlewareTest.php | 14 +++++++----- .../Unit/Transport/GrpcTransportTest.php | 22 ++++++++++--------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php index 869f54298b5a..15a935bc7d70 100644 --- a/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/TracingMiddlewareTest.php @@ -67,6 +67,7 @@ use OpenTelemetry\SDK\Trace\TracerProvider; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; +use ReflectionClass; use RuntimeException; use stdClass; @@ -1164,23 +1165,20 @@ public function testRetriesExhaustedLinksAllAttemptSpansAndMarksParentSpanAsErro */ private function createGrpcTransport(array $unaryCalls, array $telemetryOptions = []): GrpcTransport { - return new class( + $transport = new class( 'secretmanager.googleapis.com:443', - $unaryCalls, - $telemetryOptions + $unaryCalls ) extends GrpcTransport { /** @var UnaryCall[] */ private array $unaryCalls; /** * @param UnaryCall[] $unaryCalls - * @param array $telemetryOptions */ - public function __construct(string $hostname, array $unaryCalls, array $telemetryOptions) + public function __construct(string $hostname, array $unaryCalls) { $this->unaryCalls = $unaryCalls; parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); - $this->setTelemetryOptions($telemetryOptions); } // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore @@ -1194,5 +1192,9 @@ protected function _simpleRequest( return array_shift($this->unaryCalls); } }; + (new ReflectionClass(GrpcTransport::class)) + ->getMethod('setTelemetryOptions') + ->invoke($transport, $telemetryOptions, 'secretmanager.googleapis.com:443'); + return $transport; } } diff --git a/Gax/tests/Unit/Transport/GrpcTransportTest.php b/Gax/tests/Unit/Transport/GrpcTransportTest.php index 57043e8b8e2b..f12b97a0740b 100644 --- a/Gax/tests/Unit/Transport/GrpcTransportTest.php +++ b/Gax/tests/Unit/Transport/GrpcTransportTest.php @@ -1150,17 +1150,15 @@ function () use (&$callCount, $unaryCallForCancel) { throw new RuntimeException('Client deadline exceeded before sending request'); } return $unaryCallForCancel->reveal(); - }, - ['openTelemetryTracerProvider' => $tracerProvider] + } ) extends GrpcTransport { /** @var callable */ private $factory; - public function __construct(string $hostname, callable $factory, array $telemetryOptions) + public function __construct(string $hostname, callable $factory) { $this->factory = $factory; parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); - $this->setTelemetryOptions($telemetryOptions); } // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore @@ -1174,6 +1172,11 @@ protected function _simpleRequest( return ($this->factory)(); } }; + $this->setTelemetryOptions( + $transport, + ['openTelemetryTracerProvider' => $tracerProvider], + 'secretmanager.googleapis.com:443' + ); $appSpan = $tracerProvider->getTracer('test-app')->spanBuilder('app-operation')->startSpan(); $appScope = $appSpan->activate(); @@ -1329,23 +1332,20 @@ private function setTelemetryOptions( */ private function createTracedGrpcTransport(array $unaryCalls, array $telemetryOptions = []): GrpcTransport { - return new class( + $transport = new class( 'secretmanager.googleapis.com:443', - $unaryCalls, - $telemetryOptions + $unaryCalls ) extends GrpcTransport { /** @var UnaryCall[] */ private array $unaryCalls; /** * @param UnaryCall[] $unaryCalls - * @param array $telemetryOptions */ - public function __construct(string $hostname, array $unaryCalls, array $telemetryOptions) + public function __construct(string $hostname, array $unaryCalls) { $this->unaryCalls = $unaryCalls; parent::__construct($hostname, ['credentials' => ChannelCredentials::createSsl()]); - $this->setTelemetryOptions($telemetryOptions); } // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore @@ -1359,5 +1359,7 @@ protected function _simpleRequest( return array_shift($this->unaryCalls); } }; + $this->setTelemetryOptions($transport, $telemetryOptions, 'secretmanager.googleapis.com:443'); + return $transport; } }