diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCache.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCache.java index 59415d94c37d..9eb7c5dc8bfe 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCache.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCache.java @@ -23,9 +23,15 @@ import com.google.cloud.spanner.ErrorCode; import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.common.annotations.VisibleForTesting; +import io.grpc.ChannelCredentials; import io.grpc.ConnectivityState; +import io.grpc.Grpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.alts.AltsChannelCredentials; +import io.grpc.netty.shaded.io.grpc.netty.InternalNettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.InternalNettyChannelCredentials; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import java.io.IOException; import java.time.Duration; import java.util.Map; @@ -34,6 +40,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; @@ -42,8 +49,10 @@ * gRPC implementation of {@link ChannelEndpointCache}. * *

This cache creates and caches gRPC channels per address. It uses {@link - * InstantiatingGrpcChannelProvider#withEndpoint(String)} to create new channels with the same - * configuration but different endpoints, avoiding race conditions. + * InstantiatingGrpcChannelProvider#withEndpoint(String)} to create a provider for each address from + * the settings of the base provider, avoiding race conditions. Routed channels use their own + * keepalive settings and the authority of the default channel. When the base provider can use + * DirectPath, routed channels use ALTS. */ @InternalApi class GrpcChannelEndpointCache implements ChannelEndpointCache { @@ -61,6 +70,7 @@ class GrpcChannelEndpointCache implements ChannelEndpointCache { private final GrpcChannelEndpoint defaultEndpoint; private final String defaultAuthority; @Nullable private final GrpcGcpEndpointChannelConfigurator endpointChannelConfigurator; + private final Supplier directPathCredentials; private final AtomicBoolean isShutdown = new AtomicBoolean(false); /** @@ -79,8 +89,24 @@ public GrpcChannelEndpointCache( InstantiatingGrpcChannelProvider channelProvider, @Nullable GrpcGcpEndpointChannelConfigurator endpointChannelConfigurator) throws IOException { + this(channelProvider, endpointChannelConfigurator, AltsChannelCredentials::create); + } + + /** + * Creates a cache that builds routed DirectPath channels with {@code directPathCredentials}. The + * other constructors pass {@link AltsChannelCredentials#create()}. Tests pass their own + * credentials, so that they can point ALTS at a local handshaker service or connect to a + * plaintext test server. + */ + @VisibleForTesting + GrpcChannelEndpointCache( + InstantiatingGrpcChannelProvider channelProvider, + @Nullable GrpcGcpEndpointChannelConfigurator endpointChannelConfigurator, + Supplier directPathCredentials) + throws IOException { this.baseProvider = channelProvider; this.endpointChannelConfigurator = endpointChannelConfigurator; + this.directPathCredentials = directPathCredentials; String defaultEndpoint = channelProvider.getEndpoint(); this.defaultEndpoint = new GrpcChannelEndpoint(defaultEndpoint, channelProvider); this.defaultAuthority = this.defaultEndpoint.getChannel().authority(); @@ -103,7 +129,7 @@ public ChannelEndpoint get(String address) { address, addr -> { try { - // Create a new provider with the same config but different endpoint. + // Create a new provider for addr from the settings of the base provider. // This is thread-safe as withEndpoint() returns a new provider instance. InstantiatingGrpcChannelProvider newProvider = createProviderWithAuthorityOverride(addr); @@ -127,6 +153,10 @@ public ChannelEndpoint getIfPresent(String address) { @VisibleForTesting InstantiatingGrpcChannelProvider createProviderWithAuthorityOverride(String address) { + // Read DirectPath eligibility from baseProvider. canUseDirectPath() returns false when the + // endpoint does not contain googleapis.com, so the provider for a server address such as + // 10.0.0.1:443 would return false and its channel would never use ALTS. + final boolean useDirectPath = baseProvider.canUseDirectPath(); InstantiatingGrpcChannelProvider endpointProvider = (InstantiatingGrpcChannelProvider) baseProvider.withEndpoint(address); if (Objects.equals(defaultAuthority, address)) { @@ -137,12 +167,27 @@ InstantiatingGrpcChannelProvider createProviderWithAuthorityOverride(String addr builder.setKeepAliveTimeDuration(ROUTED_KEEPALIVE_TIME); builder.setKeepAliveTimeoutDuration(ROUTED_KEEPALIVE_TIMEOUT); builder.setKeepAliveWithoutCalls(Boolean.TRUE); + final Integer maxInboundMessageSize = builder.getMaxInboundMessageSize(); + final Integer maxInboundMetadataSize = builder.getMaxInboundMetadataSize(); final com.google.api.core.ApiFunction baseConfigurator = endpointChannelConfigurator == null ? builder.getChannelConfigurator() : null; builder.setChannelConfigurator( channelBuilder -> { ManagedChannelBuilder effectiveBuilder = channelBuilder; + if (useDirectPath) { + // Call useDirectPathCredentials before the configurators below. The grpc-gcp + // configurator wraps channelBuilder in a builder that is not a NettyChannelBuilder. + // useDirectPathCredentials would replace that builder, so the routed channel would + // lose grpc-gcp and the settings that gax set on channelBuilder. + effectiveBuilder = + useDirectPathCredentials( + channelBuilder, + address, + directPathCredentials.get(), + maxInboundMessageSize, + maxInboundMetadataSize); + } if (endpointChannelConfigurator != null) { effectiveBuilder = endpointChannelConfigurator.configure(effectiveBuilder); } else if (baseConfigurator != null) { @@ -153,6 +198,60 @@ InstantiatingGrpcChannelProvider createProviderWithAuthorityOverride(String addr return builder.build(); } + /** + * Returns a builder for channels to {@code address} that connect with {@code credentials}. + * + *

gax builds {@code channelBuilder} without DirectPath, because the address of a Spanner + * server does not contain googleapis.com. When {@code channelBuilder} is a {@link + * NettyChannelBuilder} that gax created without {@link ChannelCredentials}, this method sets + * {@code credentials} as the security of {@code channelBuilder} and returns {@code + * channelBuilder}. Its channels then keep the interceptors, header provider headers, user agent, + * executor, keepalive settings and size limits that gax set. + * + *

Otherwise this method leaves {@code channelBuilder} unchanged and returns a new builder with + * {@link #ROUTED_KEEPALIVE_TIME}, {@link #ROUTED_KEEPALIVE_TIMEOUT}, {@code + * maxInboundMessageSize} and {@code maxInboundMetadataSize}. The new builder does not get the + * other settings of {@code channelBuilder}, so its channels run without the interceptors and + * headers that gax added. + */ + @VisibleForTesting + static ManagedChannelBuilder useDirectPathCredentials( + ManagedChannelBuilder channelBuilder, + String address, + ChannelCredentials credentials, + @Nullable Integer maxInboundMessageSize, + @Nullable Integer maxInboundMetadataSize) { + if (channelBuilder instanceof NettyChannelBuilder) { + try { + // gRPC has no public API that changes the security of an existing builder. + InternalNettyChannelBuilder.setProtocolNegotiatorFactory( + (NettyChannelBuilder) channelBuilder, + InternalNettyChannelCredentials.toNegotiator(credentials)); + return channelBuilder; + } catch (IllegalStateException e) { + // setProtocolNegotiatorFactory throws IllegalStateException when channelBuilder was + // created with ChannelCredentials. gax creates channelBuilder that way for mTLS and S2A. + } + } + logger.log( + Level.FINE, + "Routed DirectPath channel for {0} does not get the interceptors and headers that gax adds", + address); + ManagedChannelBuilder replacement = + Grpc.newChannelBuilder(address, credentials) + .keepAliveTime(ROUTED_KEEPALIVE_TIME.toMillis(), TimeUnit.MILLISECONDS) + .keepAliveTimeout(ROUTED_KEEPALIVE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) + .keepAliveWithoutCalls(true) + .disableServiceConfigLookUp(); + if (maxInboundMessageSize != null) { + replacement.maxInboundMessageSize(maxInboundMessageSize); + } + if (maxInboundMetadataSize != null) { + replacement.maxInboundMetadataSize(maxInboundMetadataSize); + } + return replacement; + } + @Override public void evict(String address) { if (defaultEndpoint.getAddress().equals(address)) { diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCacheTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCacheTest.java index cca418a53f99..390f8f8d152a 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCacheTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GrpcChannelEndpointCacheTest.java @@ -17,17 +17,102 @@ package com.google.cloud.spanner.spi.v1; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.api.gax.rpc.FixedHeaderProvider; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.NoCredentials; +import com.google.cloud.spanner.MockSpannerServiceImpl; +import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; import com.google.cloud.spanner.SpannerException; +import com.google.cloud.spanner.SpannerOptions; +import com.google.cloud.spanner.Statement; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ListValue; +import com.google.protobuf.Value; +import com.google.spanner.v1.CreateSessionRequest; +import com.google.spanner.v1.ExecuteSqlRequest; +import com.google.spanner.v1.ResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import com.google.spanner.v1.Session; +import com.google.spanner.v1.SpannerGrpc; +import com.google.spanner.v1.SpannerGrpc.SpannerBlockingStub; +import com.google.spanner.v1.StructType; +import com.google.spanner.v1.StructType.Field; +import com.google.spanner.v1.Type; +import com.google.spanner.v1.TypeCode; +import io.grpc.BindableService; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ChannelCredentials; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.Grpc; +import io.grpc.HandlerRegistry; +import io.grpc.InsecureChannelCredentials; +import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerMethodDefinition; +import io.grpc.TlsChannelCredentials; +import io.grpc.alts.AltsChannelCredentials; +import io.grpc.internal.GrpcUtil; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.stub.MetadataUtils; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.annotation.Nullable; +import org.junit.After; import org.junit.Test; public class GrpcChannelEndpointCacheTest { private static final String DEFAULT_ENDPOINT = "default.invalid:1234"; private static final String ROUTED_ENDPOINT_A = "replica-a.invalid:1111"; private static final String ROUTED_ENDPOINT_B = "replica-b.invalid:2222"; + private static final String DIRECT_PATH_ENDPOINT = "spanner.googleapis.com:443"; + private static final String DATABASE = + "projects/test-project/instances/test-instance/databases/test-database"; + private static final String ALTS_HANDSHAKE_METHOD = "grpc.gcp.HandshakerService/DoHandshake"; + private static final long RPC_TIMEOUT_SECONDS = 30; + + /** + * Length of a query result value that is larger than gRPC's default inbound message limit, so + * that a routed channel without the provider's maxInboundMessageSize rejects the result. + */ + private static final int LARGE_VALUE_LENGTH = GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE + 1024 * 1024; + + /** + * Length of a response header value that is larger than gRPC's default inbound metadata limit, so + * that a routed channel without the provider's maxInboundMetadataSize rejects the response. + */ + private static final int LARGE_HEADER_LENGTH = GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE + 1024; + + private static final Metadata.Key API_CLIENT_KEY = + Metadata.Key.of("x-goog-api-client", Metadata.ASCII_STRING_MARSHALLER); + private static final String API_CLIENT = "gl-java/17.0.2 gccl/6.121.0 gax/2.92.0 grpc/1.86.0"; + + private static final Metadata.Key LARGE_HEADER_KEY = + Metadata.Key.of("x-large-header", Metadata.ASCII_STRING_MARSHALLER); private static InstantiatingGrpcChannelProvider createProvider(String endpoint) { return InstantiatingGrpcChannelProvider.newBuilder() @@ -36,6 +121,359 @@ private static InstantiatingGrpcChannelProvider createProvider(String endpoint) .build(); } + /** + * Returns a provider for which {@code canUseDirectPath()} is true on any machine. DirectPath over + * Interconnect skips the Compute Engine check in {@code canUseDirectPath()}, so tests that use + * this provider do not need to run on Google Cloud. + */ + private static InstantiatingGrpcChannelProvider createDirectPathProvider() { + InstantiatingGrpcChannelProvider provider = + InstantiatingGrpcChannelProvider.newBuilder() + .setEndpoint(DIRECT_PATH_ENDPOINT) + .setAttemptDirectPath(true) + .setAttemptDirectPathXdsOverInterconnect(true) + // canUseDirectPath() is false while the provider still needs credentials. + .setCredentials(GoogleCredentials.create(new AccessToken("token", null))) + .setMaxInboundMessageSize(2 * LARGE_VALUE_LENGTH) + .setMaxInboundMetadataSize(2 * LARGE_HEADER_LENGTH) + .build(); + assertTrue(provider.canUseDirectPath()); + return provider; + } + + private final List servers = new ArrayList<>(); + + @After + public void stopServers() throws InterruptedException { + for (Server server : servers) { + server.shutdownNow(); + } + for (Server server : servers) { + server.awaitTermination(5, TimeUnit.SECONDS); + } + } + + private Server startSpannerServer(BindableService spanner, ServerInterceptor... interceptors) + throws IOException { + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("localhost", 0)) + .addService(ServerInterceptors.intercept(spanner, interceptors)) + .build(); + servers.add(server); + return server.start(); + } + + private Server startHandshakerServer(RecordingHandshaker handshaker) throws IOException { + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("localhost", 0)) + .fallbackHandlerRegistry(handshaker) + .build(); + servers.add(server); + return server.start(); + } + + private static String addressOf(Server server) { + return "localhost:" + server.getPort(); + } + + private static SpannerBlockingStub spannerStub(ChannelEndpoint endpoint) { + return SpannerGrpc.newBlockingStub(endpoint.getChannel()) + .withDeadlineAfter(RPC_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + /** + * A fake ALTS handshaker service that records each method a client calls on it, so that a test + * can tell whether a channel started an ALTS handshake. + */ + private static final class RecordingHandshaker extends HandlerRegistry { + private final BlockingQueue calledMethods = new LinkedBlockingQueue<>(); + + @Override + @Nullable + public ServerMethodDefinition lookupMethod( + String methodName, @Nullable String authority) { + calledMethods.add(methodName); + // Returning no method definition makes the server answer UNIMPLEMENTED, which ends the + // handshake. The tests only check that the handshake started. + return null; + } + } + + private static ChannelCredentials altsCredentialsUsing(Server handshaker) { + return AltsChannelCredentials.newBuilder() + // Without enableUntrustedAltsForTesting(), ALTS refuses to connect outside Google Cloud + // and never calls the handshaker. + .enableUntrustedAltsForTesting() + .setHandshakerAddressForTesting(addressOf(handshaker)) + .build(); + } + + private static ClientInterceptor recordingMethodNames(BlockingQueue interceptedMethods) { + return new ClientInterceptor() { + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions callOptions, Channel next) { + interceptedMethods.add(method.getFullMethodName()); + return next.newCall(method, callOptions); + } + }; + } + + private static ServerInterceptor addingResponseHeader(Metadata.Key key, String value) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + return next.startCall( + new SimpleForwardingServerCall(call) { + @Override + public void sendHeaders(Metadata responseHeaders) { + responseHeaders.put(key, value); + super.sendHeaders(responseHeaders); + } + }, + headers); + } + }; + } + + private static ResultSet singleStringRow(String column, String value) { + return ResultSet.newBuilder() + .setMetadata( + ResultSetMetadata.newBuilder() + .setRowType( + StructType.newBuilder() + .addFields( + Field.newBuilder() + .setName(column) + .setType(Type.newBuilder().setCode(TypeCode.STRING))))) + .addRows(ListValue.newBuilder().addValues(Value.newBuilder().setStringValue(value))) + .build(); + } + + @Test + public void routedChannelUsesAltsWhenBaseProviderCanUseDirectPath() throws Exception { + RecordingHandshaker handshaker = new RecordingHandshaker(); + Server handshakerServer = startHandshakerServer(handshaker); + Server routedServer = startSpannerServer(new MockSpannerServiceImpl()); + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache( + createDirectPathProvider(), null, () -> altsCredentialsUsing(handshakerServer)); + try { + // getState(true) makes the channel connect, which starts the ALTS handshake. + cache.get(addressOf(routedServer)).getChannel().getState(true); + + assertEquals( + ALTS_HANDSHAKE_METHOD, + handshaker.calledMethods.poll(RPC_TIMEOUT_SECONDS, TimeUnit.SECONDS)); + } finally { + cache.shutdown(); + } + } + + @Test + public void routedChannelSkipsAltsWhenBaseProviderCannotUseDirectPath() throws Exception { + RecordingHandshaker handshaker = new RecordingHandshaker(); + Server handshakerServer = startHandshakerServer(handshaker); + Server routedServer = startSpannerServer(new MockSpannerServiceImpl()); + InstantiatingGrpcChannelProvider provider = createProvider(DEFAULT_ENDPOINT); + assertFalse(provider.canUseDirectPath()); + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache(provider, null, () -> altsCredentialsUsing(handshakerServer)); + try { + Session session = + spannerStub(cache.get(addressOf(routedServer))) + .createSession(CreateSessionRequest.newBuilder().setDatabase(DATABASE).build()); + + assertTrue(session.getName(), session.getName().startsWith(DATABASE + "/sessions/")); + assertEquals(ImmutableList.of(), ImmutableList.copyOf(handshaker.calledMethods)); + } finally { + cache.shutdown(); + } + } + + @Test + public void routedDirectPathChannelReusesDefaultAuthority() throws Exception { + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache( + createDirectPathProvider(), null, InsecureChannelCredentials::create); + try { + ChannelEndpoint routed = cache.get(ROUTED_ENDPOINT_A); + + assertEquals( + cache.defaultChannel().getChannel().authority(), routed.getChannel().authority()); + } finally { + cache.shutdown(); + } + } + + @Test + public void routedDirectPathChannelKeepsInboundMessageSizeLimit() throws Exception { + MockSpannerServiceImpl mockSpanner = new MockSpannerServiceImpl(); + Statement query = Statement.of("SELECT Bio FROM Singers WHERE SingerId = 1"); + String bio = Strings.repeat("x", LARGE_VALUE_LENGTH); + mockSpanner.putStatementResult(StatementResult.query(query, singleStringRow("Bio", bio))); + Server routedServer = startSpannerServer(mockSpanner); + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache( + createDirectPathProvider(), null, InsecureChannelCredentials::create); + try { + SpannerBlockingStub stub = spannerStub(cache.get(addressOf(routedServer))); + Session session = + stub.createSession(CreateSessionRequest.newBuilder().setDatabase(DATABASE).build()); + + ResultSet resultSet = + stub.executeSql( + ExecuteSqlRequest.newBuilder() + .setSession(session.getName()) + .setSql(query.getSql()) + .build()); + + assertEquals(LARGE_VALUE_LENGTH, resultSet.getRows(0).getValues(0).getStringValue().length()); + } finally { + cache.shutdown(); + } + } + + @Test + public void routedDirectPathChannelKeepsInboundMetadataSizeLimit() throws Exception { + String largeHeaderValue = Strings.repeat("x", LARGE_HEADER_LENGTH); + Server routedServer = + startSpannerServer( + new MockSpannerServiceImpl(), addingResponseHeader(LARGE_HEADER_KEY, largeHeaderValue)); + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache( + createDirectPathProvider(), null, InsecureChannelCredentials::create); + try { + AtomicReference responseHeaders = new AtomicReference<>(); + AtomicReference responseTrailers = new AtomicReference<>(); + spannerStub(cache.get(addressOf(routedServer))) + .withInterceptors( + MetadataUtils.newCaptureMetadataInterceptor(responseHeaders, responseTrailers)) + .createSession(CreateSessionRequest.newBuilder().setDatabase(DATABASE).build()); + + assertEquals(largeHeaderValue, responseHeaders.get().get(LARGE_HEADER_KEY)); + } finally { + cache.shutdown(); + } + } + + @Test + public void routedDirectPathChannelRunsBaseChannelConfigurator() throws Exception { + BlockingQueue interceptedMethods = new LinkedBlockingQueue<>(); + InstantiatingGrpcChannelProvider provider = + createDirectPathProvider().toBuilder() + .setChannelConfigurator( + channelBuilder -> + channelBuilder.intercept(recordingMethodNames(interceptedMethods))) + .build(); + Server routedServer = startSpannerServer(new MockSpannerServiceImpl()); + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache(provider, null, InsecureChannelCredentials::create); + try { + spannerStub(cache.get(addressOf(routedServer))) + .createSession(CreateSessionRequest.newBuilder().setDatabase(DATABASE).build()); + + assertEquals( + ImmutableList.of(SpannerGrpc.getCreateSessionMethod().getFullMethodName()), + ImmutableList.copyOf(interceptedMethods)); + } finally { + cache.shutdown(); + } + } + + @Test + public void routedDirectPathChannelRunsProviderInterceptorsAndSendsProviderHeaders() + throws Exception { + AtomicReference receivedApiClient = new AtomicReference<>(); + ServerInterceptor apiClientCapture = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + receivedApiClient.set(headers.get(API_CLIENT_KEY)); + return next.startCall(call, headers); + } + }; + Server routedServer = startSpannerServer(new MockSpannerServiceImpl(), apiClientCapture); + BlockingQueue interceptedMethods = new LinkedBlockingQueue<>(); + InstantiatingGrpcChannelProvider.Builder providerBuilder = + createDirectPathProvider().toBuilder() + .setInterceptorProvider( + () -> ImmutableList.of(recordingMethodNames(interceptedMethods))) + .setHeaderProvider(FixedHeaderProvider.create(API_CLIENT_KEY.name(), API_CLIENT)); + // GapicSpannerRpc passes this configurator to GrpcChannelEndpointCache when grpc-gcp is on, + // which is the default in SpannerOptions. + GrpcGcpEndpointChannelConfigurator grpcGcpConfigurator = + GapicSpannerRpc.createGrpcGcpEndpointChannelConfigurator( + providerBuilder, + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .build()); + GrpcChannelEndpointCache cache = + new GrpcChannelEndpointCache( + providerBuilder.build(), grpcGcpConfigurator, InsecureChannelCredentials::create); + try { + spannerStub(cache.get(addressOf(routedServer))) + .createSession(CreateSessionRequest.newBuilder().setDatabase(DATABASE).build()); + + assertEquals( + ImmutableList.of(SpannerGrpc.getCreateSessionMethod().getFullMethodName()), + ImmutableList.copyOf(interceptedMethods)); + assertEquals(API_CLIENT, receivedApiClient.get()); + } finally { + cache.shutdown(); + } + } + + @Test + public void directPathCredentialsReplaceBuilderCreatedWithChannelCredentials() throws Exception { + MockSpannerServiceImpl mockSpanner = new MockSpannerServiceImpl(); + Statement query = Statement.of("SELECT Bio FROM Singers WHERE SingerId = 1"); + String bio = Strings.repeat("x", LARGE_VALUE_LENGTH); + mockSpanner.putStatementResult(StatementResult.query(query, singleStringRow("Bio", bio))); + String largeHeaderValue = Strings.repeat("x", LARGE_HEADER_LENGTH); + Server routedServer = + startSpannerServer(mockSpanner, addingResponseHeader(LARGE_HEADER_KEY, largeHeaderValue)); + // gax creates its builder with ChannelCredentials for mTLS, as this test does with TLS + // credentials. gRPC does not let useDirectPathCredentials change the security of such a + // builder. + ManagedChannelBuilder mtlsBuilder = + Grpc.newChannelBuilder(addressOf(routedServer), TlsChannelCredentials.create()); + assertTrue(mtlsBuilder.getClass().getName(), mtlsBuilder instanceof NettyChannelBuilder); + ManagedChannel channel = + GrpcChannelEndpointCache.useDirectPathCredentials( + mtlsBuilder, + addressOf(routedServer), + InsecureChannelCredentials.create(), + 2 * LARGE_VALUE_LENGTH, + 2 * LARGE_HEADER_LENGTH) + .build(); + try { + AtomicReference responseHeaders = new AtomicReference<>(); + AtomicReference responseTrailers = new AtomicReference<>(); + SpannerBlockingStub stub = + SpannerGrpc.newBlockingStub(channel) + .withDeadlineAfter(RPC_TIMEOUT_SECONDS, TimeUnit.SECONDS) + .withInterceptors( + MetadataUtils.newCaptureMetadataInterceptor(responseHeaders, responseTrailers)); + Session session = + stub.createSession(CreateSessionRequest.newBuilder().setDatabase(DATABASE).build()); + ResultSet resultSet = + stub.executeSql( + ExecuteSqlRequest.newBuilder() + .setSession(session.getName()) + .setSql(query.getSql()) + .build()); + + assertEquals(largeHeaderValue, responseHeaders.get().get(LARGE_HEADER_KEY)); + assertEquals(LARGE_VALUE_LENGTH, resultSet.getRows(0).getValues(0).getStringValue().length()); + } finally { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + @Test public void defaultChannelIsCached() throws Exception { GrpcChannelEndpointCache cache = new GrpcChannelEndpointCache(createProvider(DEFAULT_ENDPOINT));