Skip to content

Commit

Permalink
remove TPC-specific logic
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer committed Sep 26, 2023
1 parent fa93022 commit 76478c9
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 144 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"license": "BSD-3-Clause",
"require": {
"php": ">=7.4",
"google/auth": "dev-add-universe-domain-phase1 as 1.31.0",
"google/auth": "^1.25.0",
"google/grpc-gcp": "^0.2||^0.3",
"grpc/grpc": "^1.13",
"google/protobuf": "^3.21.4",
Expand Down
12 changes: 1 addition & 11 deletions src/CredentialsWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
use Google\Auth\FetchAuthTokenCache;
use Google\Auth\FetchAuthTokenInterface;
use Google\Auth\GetQuotaProjectInterface;
use Google\Auth\GetUniverseDomainInterface;
use Google\Auth\HttpHandler\Guzzle6HttpHandler;
use Google\Auth\HttpHandler\Guzzle7HttpHandler;
use Google\Auth\HttpHandler\HttpHandlerFactory;
Expand All @@ -50,7 +49,7 @@
/**
* The CredentialsWrapper object provides a wrapper around a FetchAuthTokenInterface.
*/
class CredentialsWrapper implements GetUniverseDomainInterface
class CredentialsWrapper
{
use ValidationTrait;

Expand Down Expand Up @@ -307,13 +306,4 @@ private static function isExpired($token)
&& array_key_exists('expires_at', $token)
&& $token['expires_at'] > time() + self::$eagerRefreshThresholdSeconds);
}

public function getUniverseDomain(): string
{
if ($this->credentialsFetcher instanceof GetUniverseDomainInterface) {
return $this->credentialsFetcher->getUniverseDomain();
}

return GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN;
}
}
58 changes: 18 additions & 40 deletions src/GapicClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ trait GapicClientTrait

/** @var TransportInterface */
private $transport;
private Closure $apiEndpointFunction;
private Closure $transportFunction;
private $credentialsWrapper;

Expand Down Expand Up @@ -116,7 +115,7 @@ protected function getTransport()

private function buildTransport(): TransportInterface
{
return ($this->transportFunction)(($this->apiEndpointFunction)());
return ($this->transportFunction)();
}

/**
Expand Down Expand Up @@ -194,9 +193,6 @@ private function buildClientOptions(array $options)
];
}

// user-supplied API endpoint
$apiEndpoint = $options['apiEndpoint'] ?? null;

// Merge defaults into $options starting from top level
// variables, then going into deeper nesting, so that
// we will not encounter missing keys
Expand All @@ -215,7 +211,7 @@ private function buildClientOptions(array $options)

// serviceAddress is now deprecated and acts as an alias for apiEndpoint
if (isset($options['serviceAddress'])) {
$apiEndpoint = $this->pluck('serviceAddress', $options, false);
$options['apiEndpoint'] = $this->pluck('serviceAddress', $options, false);
}

// If an API endpoint is set, ensure the "audience" does not conflict
Expand Down Expand Up @@ -264,37 +260,12 @@ private function buildClientOptions(array $options)

// mTLS: If no apiEndpoint has been supplied by the user, and either
// GOOGLE_API_USE_MTLS_ENDPOINT tells us to, or mTLS is available, use the mTLS endpoint.
if (is_null($apiEndpoint) && $this->shouldUseMtlsEndpoint($options)) {
$apiEndpoint = self::determineMtlsEndpoint($defaultOptions['apiEndpoint']);
if ($options['apiEndpoint'] === $defaultOptions['apiEndpoint']
&& $this->shouldUseMtlsEndpoint($options)
) {
$options['apiEndpoint'] = self::determineMtlsEndpoint($options['apiEndpoint']);
}

$this->apiEndpointFunction = Closure::fromCallable(function () use ($apiEndpoint, $defaultOptions) {
// If a custom endpoint is set, or we are using an MTLS endpoint, return it
if ($apiEndpoint) {
return $apiEndpoint;
}

// If no API endpoint is set, derive the endpoint from the service address template and the
// universe domain fetched from the credentials.
if (defined('self::SERVICE_ADDRESS_TEMPLATE')) {
$universeDomain = $this->credentialsWrapper->getUniverseDomain();
if (!$universeDomain) {
throw new ValidationException('Credentials provided do not contain universe information');
}
return str_replace(
'UNIVERSE_DOMAIN',
$universeDomain,
self::SERVICE_ADDRESS_TEMPLATE
);
}

// If no serviceAddressTemplate exsts, use the default endpoint
return $defaultOptions['apiEndpoint'];
});

// For backwards compatibility
$options['apiEndpoint'] = $apiEndpoint ?: $defaultOptions['apiEndpoint'];

return $options;
}

Expand Down Expand Up @@ -385,6 +356,10 @@ private static function determineMtlsEndpoint(string $apiEndpoint)
*/
private function setClientOptions(array $options)
{
// serviceAddress is now deprecated and acts as an alias for apiEndpoint
if (isset($options['serviceAddress'])) {
$options['apiEndpoint'] = $this->pluck('serviceAddress', $options, false);
}
$this->validateNotNull($options, [
'apiEndpoint',
'serviceName',
Expand Down Expand Up @@ -458,12 +433,14 @@ private function setClientOptions(array $options)
);

if ($transport instanceof TransportInterface) {
// User-provided transport class
$this->transport = $transport;
} else {
$this->transportFunction = $this->createTransportFunction(
$transport,
$options['transportConfig'],
$options['clientCertSource']
$options['apiEndpoint'],
$options['clientCertSource'],
);
}
}
Expand Down Expand Up @@ -504,6 +481,7 @@ private function createCredentialsWrapper($credentials, array $credentialsConfig
private function createTransportFunction(
$transport,
$transportConfig,
string $apiEndpoint,
callable $clientCertSource = null
): Closure {
if (!is_string($transport)) {
Expand Down Expand Up @@ -538,12 +516,12 @@ private function createTransportFunction(
$configForSpecifiedTransport['stubOpts']['grpc.primary_user_agent'] .=
$this->agentHeader['User-Agent'][0];
}
$transportFunction = function (string $apiEndpoint) use ($configForSpecifiedTransport) {
$transportFunction = function () use ($apiEndpoint, $configForSpecifiedTransport) {
return GrpcTransport::build($apiEndpoint, $configForSpecifiedTransport);
};
break;
case 'grpc-fallback':
$transportFunction = function (string $apiEndpoint) use ($configForSpecifiedTransport) {
$transportFunction = function () use ($apiEndpoint, $configForSpecifiedTransport) {
return GrpcFallbackTransport::build($apiEndpoint, $configForSpecifiedTransport);
};
break;
Expand All @@ -553,7 +531,7 @@ private function createTransportFunction(
"The 'restClientConfigPath' config is required for 'rest' transport."
);
}
$transportFunction = function (string $apiEndpoint) use ($configForSpecifiedTransport) {
$transportFunction = function () use ($apiEndpoint, $configForSpecifiedTransport) {
return RestTransport::build(
$apiEndpoint,
$configForSpecifiedTransport['restClientConfigPath'],
Expand Down Expand Up @@ -833,7 +811,7 @@ private function createCallStack(array $callConstructionOptions)
$callStack = function (Call $call, array $options) {
$startCallMethod = $this->transportCallMethods[$call->getCallType()];
if (!$this->transport) {
// Create transport at call-time in order to delay checking universe domain
// Create transport at call-time to allow for lazy initialization
$this->transport = $this->buildTransport();
}
return $this->transport->$startCallMethod($call, $options);
Expand Down
100 changes: 8 additions & 92 deletions tests/Tests/Unit/GapicClientTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -706,19 +706,20 @@ public function testCreateTransport($apiEndpoint, $transport, $transportConfig,
$client = new GapicClientTraitStub();
$callable = $client->call('createTransportFunction', [
$transport,
$transportConfig
$transportConfig,
$apiEndpoint
]);
$transport = $callable($apiEndpoint);
$transport = $callable();

$this->assertEquals($expectedTransportClass, get_class($transport));
}

/**
* @dataProvider provideCreateTransportDefaultEndpoint
*/
public function testCreateTransportDefaultEndpoint(array $options, string $expectedEndpoint, $client = null)
public function testCreateTransportDefaultEndpoint(array $options, string $expectedEndpoint)
{
$client = $client ?: new GapicClientTraitStub();
$client = new GapicClientTraitStub();
$updatedOptions = $client->call('buildClientOptions', [$options]);

$client->call('setClientOptions', [$updatedOptions]);
Expand All @@ -739,10 +740,6 @@ public function testCreateTransportDefaultEndpoint(array $options, string $expec

public function provideCreateTransportDefaultEndpoint()
{
$credentialsWrapper = $this->prophesize(CredentialsWrapper::class);
$credentialsWrapper->getUniverseDomain()
->willReturn('universe-domain.com');

return [
[
['transport' => 'rest'],
Expand All @@ -752,63 +749,9 @@ public function provideCreateTransportDefaultEndpoint()
['transport' => 'rest', 'apiEndpoint' => 'new.test.address.com:123'],
'new.test.address.com:123', // explicitly set
],
[
[],
'stub.googleapis.com:443',
new GapicClientTraitTpcStub(), // service address template used by new clients
],
[
['credentials' => $credentialsWrapper->reveal()],
'stub.universe-domain.com:443',
new GapicClientTraitTpcStub(), // universe domain used by new clients
],
[
['transport' => 'rest', 'credentials' => $credentialsWrapper->reveal()],
'test.address.com:443', // universe domain has no effect on older clients
]
];
}

public function testApiEndpointLateBinding()
{
$called = false;
$credentialsWrapper = $this->prophesize(CredentialsWrapper::class);
$credentialsWrapper->getUniverseDomain()
->shouldBeCalledOnce()
->will(function () use (&$called) {
$called = true;
return 'universe-domain.com';
});
$credentialsWrapper->getQuotaProject()->shouldBeCalledOnce();
$credentialsWrapper->getAuthorizationHeaderCallback(null)
->shouldBeCalledOnce()
->willReturn(function() { return []; });

$client = new GapicClientTraitTpcStub();
$options = ['credentials' => $credentialsWrapper->reveal()];
$updatedOptions = $client->call('buildClientOptions', [$options]);
$client->call('setClientOptions', [$updatedOptions]);

// CredentialsWrapper::getUniverseDomain has not been called
$this->assertFalse($called);

$callStack = $client->call('createCallStack', [
['retrySettings' => RetrySettings::constructDefault()]
]);

// CredentialsWrapper::getUniverseDomain has still not been called
$this->assertFalse($called);

$call = $this->prophesize(Call::class);
$call->getCallType()->shouldBeCalledOnce()->willReturn(Call::UNARY_CALL);
$call->getMethod()->shouldBeCalledOnce()->willReturn('test.interface.v1.api/MethodWithBody');
$call->getMessage()->shouldBeCalledOnce()->willReturn(new MockRequest());

// CredentialsWrapper::getUniverseDomain is called at call time
$callStack($call->reveal(), []);
$this->assertTrue($called);
}

public function createTransportData()
{
$defaultTransportClass = extension_loaded('grpc')
Expand Down Expand Up @@ -842,9 +785,10 @@ public function testCreateTransportInvalid($apiEndpoint, $transport, $transportC

$callable = $client->call('createTransportFunction', [
$transport,
$transportConfig
$transportConfig,
$apiEndpoint
]);
$transport = $callable($apiEndpoint);
$transport = $callable();
}

public function createTransportDataInvalid()
Expand Down Expand Up @@ -1963,34 +1907,6 @@ public static function getClientDefaults()
}
}

class GapicClientTraitTpcStub
{
use GapicClientTrait;
use GapicClientStubTrait;

private const SERVICE_ADDRESS_TEMPLATE = 'stub.UNIVERSE_DOMAIN';

public static function getClientDefaults()
{
return [
'apiEndpoint' => 'test.address.com:443',
'serviceName' => 'test.interface.v1.api',
'clientConfig' => __DIR__ . '/testdata/test_service_client_config.json',
'descriptorsConfigPath' => __DIR__.'/testdata/test_service_descriptor_config.php',
'gcpApiConfigPath' => __DIR__.'/testdata/test_service_grpc_config.json',
'disableRetries' => false,
'auth' => null,
'authConfig' => null,
'transport' => 'rest',
'transportConfig' => [
'rest' => [
'restClientConfigPath' => __DIR__.'/testdata/test_service_rest_client_config.php',
]
],
];
}
}

trait GapicClientStubTrait
{
public function call($fn, array $args = [])
Expand Down

0 comments on commit 76478c9

Please sign in to comment.