Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Core/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"guzzlehttp/psr7": "^2.6.3||^3.0",
"monolog/monolog": "^2.9||^3.0",
"psr/http-message": "^1.0||^2.0",
"google/gax": "^1.38.0"
"google/gax": "^1.38.0",
"open-telemetry/api": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0",
Expand Down
6 changes: 6 additions & 0 deletions Core/src/GrpcRequestWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ public function __construct(array $config = [])
];

$this->authHttpHandler = $config['authHttpHandler'] ?: HttpHandlerFactory::build();
if (isset($config['tracerProvider'])) {
$this->authHttpHandler = new \Google\Cloud\Core\Telemetry\AuthTracingMiddleware(
$this->authHttpHandler,
$config['tracerProvider']
);
}
$this->serializer = $config['serializer'];
$this->grpcOptions = $config['grpcOptions'];
}
Expand Down
8 changes: 8 additions & 0 deletions Core/src/RequestWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ public function __construct(array $config = [])
$this->calcDelayFunction = $config['restCalcDelayFunction'];
$this->httpHandler = $config['httpHandler'] ?: HttpHandlerFactory::build();
$this->authHttpHandler = $config['authHttpHandler'] ?: $this->httpHandler;

if (isset($config['tracerProvider'])) {
$this->authHttpHandler = new \Google\Cloud\Core\Telemetry\AuthTracingMiddleware(
$this->authHttpHandler,
$config['tracerProvider']
);
}

$this->asyncHttpHandler = $config['asyncHttpHandler'] ?: $this->buildDefaultAsyncHandler();
$this->universeDomain = $config['universeDomain'];

Expand Down
82 changes: 82 additions & 0 deletions Core/src/Telemetry/AuthTracingMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
namespace Google\Cloud\Core\Telemetry;

use GuzzleHttp\Promise\PromiseInterface;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerProviderInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
* Middleware for tracing authentication requests.
*/
class AuthTracingMiddleware
{
/**
* @var callable
*/
private $httpHandler;

private TracerProviderInterface $tracerProvider;

/**
* @param callable $httpHandler The HTTP handler to wrap.
* @param TracerProviderInterface $tracerProvider The tracer provider.
*/
public function __construct(callable $httpHandler, TracerProviderInterface $tracerProvider)
{
$this->httpHandler = $httpHandler;
$this->tracerProvider = $tracerProvider;
}

/**
* Can be used as a callable for google-auth-library-php
*
* @param RequestInterface $request
* @param array $options
* @return ResponseInterface|PromiseInterface
*/
public function __invoke(RequestInterface $request, array $options = [])
{
$span = $this->tracerProvider->getTracer('google-cloud-php', '')
->spanBuilder('AuthRequest')
->setSpanKind(SpanKind::KIND_CLIENT)
->setAttribute('rpc.system', 'http')
->setAttribute('rpc.service', 'auth')
->startSpan();

$scope = $span->activate();

try {
$handler = $this->httpHandler;
$response = $handler($request, $options);

if ($response instanceof PromiseInterface) {
return $response->then(
function (ResponseInterface $res) use ($span) {
$span->setStatus(StatusCode::STATUS_OK);
$span->end();
return $res;
},
function (\Throwable $e) use ($span) {
$span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
$span->end();
throw $e;
}
);
}

$span->setStatus(StatusCode::STATUS_OK);
return $response;
} catch (\Throwable $e) {
$span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
throw $e;
} finally {
$scope->detach();
if (!isset($response) || !($response instanceof PromiseInterface)) {
$span->end();
}
}
}
}
74 changes: 74 additions & 0 deletions Core/src/Telemetry/TelemetryConfiguration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

/**
* Copyright 2026 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Core\Telemetry;

/**
* Parses and provides telemetry configuration from environment variables.
*
* @internal
*/
class TelemetryConfiguration
{
/**
* Determine if tracing is enabled based on the environment variables.
*
* @return bool
*/
public static function isTracingEnabled()
{
return self::resolveEnabled('GOOGLE_SDK_PHP_TRACING_ENABLED');
}

/**
* Determine if logging is enabled based on the environment variables.
*
* @return bool
*/
public static function isLoggingEnabled()
{
return self::resolveEnabled('GOOGLE_SDK_PHP_LOGGING_ENABLED');
}

/**
* Determine if metrics are enabled based on the environment variables.
*
* @return bool
*/
public static function isMetricsEnabled()
{
return self::resolveEnabled('GOOGLE_SDK_PHP_METRICS_ENABLED');
}

/**
* @param string $specificEnvVar
* @return bool
*/
private static function resolveEnabled($specificEnvVar)
{
$enabled = getenv($specificEnvVar);
if ($enabled !== false) {
return filter_var($enabled, FILTER_VALIDATE_BOOLEAN);
}
$legacyEnabled = getenv('GOOGLE_API_ENABLE_TELEMETRY');
if ($legacyEnabled !== false) {
return filter_var($legacyEnabled, FILTER_VALIDATE_BOOLEAN);
}
return false;
}
}
118 changes: 118 additions & 0 deletions Core/tests/Unit/Telemetry/TelemetryConfigurationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php
/**
* Copyright 2026 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Core\Tests\Unit\Telemetry;

use Google\Cloud\Core\Telemetry\TelemetryConfiguration;
use PHPUnit\Framework\TestCase;

/**
* @group core
* @group telemetry
*/
class TelemetryConfigurationTest extends TestCase
{
private $originalTracingEnabled;
private $originalLoggingEnabled;
private $originalMetricsEnabled;
private $originalLegacyTelemetry;

public function setUp(): void
{
$this->originalTracingEnabled = getenv('GOOGLE_SDK_PHP_TRACING_ENABLED');
$this->originalLoggingEnabled = getenv('GOOGLE_SDK_PHP_LOGGING_ENABLED');
$this->originalMetricsEnabled = getenv('GOOGLE_SDK_PHP_METRICS_ENABLED');
$this->originalLegacyTelemetry = getenv('GOOGLE_API_ENABLE_TELEMETRY');
putenv('GOOGLE_SDK_PHP_TRACING_ENABLED');
putenv('GOOGLE_SDK_PHP_LOGGING_ENABLED');
putenv('GOOGLE_SDK_PHP_METRICS_ENABLED');
putenv('GOOGLE_API_ENABLE_TELEMETRY');
}

public function tearDown(): void
{
if ($this->originalTracingEnabled !== false) {
putenv("GOOGLE_SDK_PHP_TRACING_ENABLED={$this->originalTracingEnabled}");
}
if ($this->originalLoggingEnabled !== false) {
putenv("GOOGLE_SDK_PHP_LOGGING_ENABLED={$this->originalLoggingEnabled}");
}
if ($this->originalMetricsEnabled !== false) {
putenv("GOOGLE_SDK_PHP_METRICS_ENABLED={$this->originalMetricsEnabled}");
}
if ($this->originalLegacyTelemetry !== false) {
putenv("GOOGLE_API_ENABLE_TELEMETRY={$this->originalLegacyTelemetry}");
}
}

public function testIsTracingEnabledDefaultFalse()
{
$this->assertFalse(TelemetryConfiguration::isTracingEnabled());
}

public function testIsTracingEnabledWithSpecificEnv()
{
putenv('GOOGLE_SDK_PHP_TRACING_ENABLED=true');
$this->assertTrue(TelemetryConfiguration::isTracingEnabled());

putenv('GOOGLE_SDK_PHP_TRACING_ENABLED=false');
$this->assertFalse(TelemetryConfiguration::isTracingEnabled());
}

public function testIsTracingEnabledWithLegacyEnv()
{
putenv('GOOGLE_API_ENABLE_TELEMETRY=true');
$this->assertTrue(TelemetryConfiguration::isTracingEnabled());

putenv('GOOGLE_API_ENABLE_TELEMETRY=false');
$this->assertFalse(TelemetryConfiguration::isTracingEnabled());
}

public function testIsTracingEnabledPrecedence()
{
// Specific flag takes precedence over legacy flag
putenv('GOOGLE_SDK_PHP_TRACING_ENABLED=false');
putenv('GOOGLE_API_ENABLE_TELEMETRY=true');
$this->assertFalse(TelemetryConfiguration::isTracingEnabled());

putenv('GOOGLE_SDK_PHP_TRACING_ENABLED=true');
putenv('GOOGLE_API_ENABLE_TELEMETRY=false');
$this->assertTrue(TelemetryConfiguration::isTracingEnabled());
}

public function testIsLoggingEnabledPrecedence()
{
putenv('GOOGLE_SDK_PHP_LOGGING_ENABLED=false');
putenv('GOOGLE_API_ENABLE_TELEMETRY=true');
$this->assertFalse(TelemetryConfiguration::isLoggingEnabled());

putenv('GOOGLE_SDK_PHP_LOGGING_ENABLED=true');
putenv('GOOGLE_API_ENABLE_TELEMETRY=false');
$this->assertTrue(TelemetryConfiguration::isLoggingEnabled());
}

public function testIsMetricsEnabledPrecedence()
{
putenv('GOOGLE_SDK_PHP_METRICS_ENABLED=false');
putenv('GOOGLE_API_ENABLE_TELEMETRY=true');
$this->assertFalse(TelemetryConfiguration::isMetricsEnabled());

putenv('GOOGLE_SDK_PHP_METRICS_ENABLED=true');
putenv('GOOGLE_API_ENABLE_TELEMETRY=false');
$this->assertTrue(TelemetryConfiguration::isMetricsEnabled());
}
}
3 changes: 2 additions & 1 deletion Gax/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"guzzlehttp/psr7": "^2.6.3||^3.0",
"google/common-protos": "^4.9",
"google/longrunning": "~0.4",
"ramsey/uuid": "^4.0"
"ramsey/uuid": "^4.0",
"open-telemetry/api": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^9.6",
Expand Down
14 changes: 12 additions & 2 deletions Gax/src/GapicClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,13 @@ private function setClientOptions(array $options)
);
}

$telemetryOptions = [
'tracerProvider' => $options['tracerProvider'] ?? null,
'loggerProvider' => $options['loggerProvider'] ?? null,
'gcp.client.service' => $this->serviceName,
'gcp.client.version' => $options['libVersion'] ?? null,
];

$transport = $options['transport'] ?: self::defaultTransport();
$this->transport = $transport instanceof TransportInterface
? $transport
Expand All @@ -378,7 +385,8 @@ private function setClientOptions(array $options)
$transport,
$options['transportConfig'],
$options['clientCertSource'],
$hasEmulator
$hasEmulator,
$telemetryOptions
);
}

Expand All @@ -396,7 +404,8 @@ private function createTransport(
$transport,
$transportConfig,
?callable $clientCertSource = null,
bool $hasEmulator = false
bool $hasEmulator = false,
array $telemetryOptions = []
) {
if (!is_string($transport)) {
throw new ValidationException(
Expand All @@ -419,6 +428,7 @@ private function createTransport(
$configForSpecifiedTransport->setClientCertSource($clientCertSource);
$configForSpecifiedTransport = $configForSpecifiedTransport->toArray();
}
$configForSpecifiedTransport += $telemetryOptions;
switch ($transport) {
case 'grpc':
// Setting the user agent for gRPC requires special handling
Expand Down
Loading
Loading