This repository was archived by the owner on Apr 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 141
chore: handle unary gRPC call ordering in KeyAwareChannel #4336
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b9e5d4e
chore: handle unary gRPC call ordering in KeyAwareChannel
rahul2393 a4fb7f8
incorporate suggestions
rahul2393 4bab789
test: add tests for location API
olavloite d719633
fix test
rahul2393 33175a5
add more tests
rahul2393 7e2d482
add test for executesSql update cache
rahul2393 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -245,6 +245,12 @@ static final class KeyAwareClientCall<RequestT, ResponseT> | |
| @Nullable private ChannelEndpoint selectedEndpoint; | ||
| @Nullable private ByteString transactionIdToClear; | ||
| private boolean allowDefaultAffinity; | ||
| private long pendingRequests; | ||
| private boolean pendingHalfClose; | ||
| @Nullable private Boolean pendingMessageCompression; | ||
| private boolean cancelled; | ||
| @Nullable private String cancelMessage; | ||
| @Nullable private Throwable cancelCause; | ||
|
rahul2393 marked this conversation as resolved.
Outdated
|
||
|
|
||
| KeyAwareClientCall( | ||
| KeyAwareChannel parentChannel, | ||
|
|
@@ -268,11 +274,22 @@ protected ClientCall<RequestT, ResponseT> delegate() { | |
| public void start(Listener<ResponseT> responseListener, Metadata headers) { | ||
| this.responseListener = new KeyAwareClientCallListener<>(responseListener, this); | ||
| this.headers = headers; | ||
| if (cancelled) { | ||
| this.responseListener.onClose( | ||
| io.grpc.Status.CANCELLED.withDescription(cancelMessage).withCause(cancelCause), | ||
| new Metadata()); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| @SuppressWarnings("unchecked") | ||
| public void sendMessage(RequestT message) { | ||
| if (cancelled) { | ||
| return; | ||
| } | ||
| if (responseListener == null || headers == null) { | ||
| throw new IllegalStateException("start must be called before sendMessage"); | ||
| } | ||
| ChannelEndpoint endpoint = null; | ||
| ChannelFinder finder = null; | ||
|
|
||
|
|
@@ -326,26 +343,81 @@ public void sendMessage(RequestT message) { | |
| this.channelFinder = finder; | ||
|
|
||
| delegate = endpoint.getChannel().newCall(methodDescriptor, callOptions); | ||
| if (pendingMessageCompression != null) { | ||
| delegate.setMessageCompression(pendingMessageCompression); | ||
| } | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated to set it to null |
||
| delegate.start(responseListener, headers); | ||
| drainPendingRequests(); | ||
| delegate.sendMessage(message); | ||
| if (pendingHalfClose) { | ||
| delegate.halfClose(); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void halfClose() { | ||
| if (delegate != null) { | ||
| delegate.halfClose(); | ||
| } else { | ||
| throw new IllegalStateException("halfClose called before sendMessage"); | ||
| pendingHalfClose = true; | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void cancel(@Nullable String message, @Nullable Throwable cause) { | ||
| if (delegate != null) { | ||
| delegate.cancel(message, cause); | ||
| } else if (responseListener != null) { | ||
| responseListener.onClose( | ||
| io.grpc.Status.CANCELLED.withDescription(message).withCause(cause), new Metadata()); | ||
| } else { | ||
| cancelled = true; | ||
| cancelMessage = message; | ||
| cancelCause = cause; | ||
| if (responseListener != null) { | ||
| responseListener.onClose( | ||
| io.grpc.Status.CANCELLED.withDescription(message).withCause(cause), new Metadata()); | ||
| } | ||
|
rahul2393 marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void request(int numMessages) { | ||
| if (delegate != null) { | ||
|
rahul2393 marked this conversation as resolved.
Outdated
|
||
| delegate.request(numMessages); | ||
| return; | ||
| } | ||
| if (numMessages <= 0) { | ||
| return; | ||
| } | ||
| long updated = pendingRequests + numMessages; | ||
| if (updated < 0L) { | ||
| updated = Long.MAX_VALUE; | ||
| } | ||
| pendingRequests = updated; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isReady() { | ||
| if (delegate == null) { | ||
| return false; | ||
| } | ||
| return delegate.isReady(); | ||
| } | ||
|
|
||
| @Override | ||
| public void setMessageCompression(boolean enabled) { | ||
| if (delegate != null) { | ||
| delegate.setMessageCompression(enabled); | ||
| } else { | ||
| pendingMessageCompression = enabled; | ||
| } | ||
| } | ||
|
|
||
| private void drainPendingRequests() { | ||
| long requests = pendingRequests; | ||
| pendingRequests = 0L; | ||
| while (requests > 0) { | ||
| int batch = requests > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) requests; | ||
| delegate.request(batch); | ||
| requests -= batch; | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -419,6 +491,9 @@ public void onMessage(ResponseT message) { | |
| transactionId = transactionIdFromMetadata(response); | ||
| } else if (message instanceof ResultSet) { | ||
| ResultSet response = (ResultSet) message; | ||
| if (response.hasCacheUpdate() && call.channelFinder != null) { | ||
| call.channelFinder.update(response.getCacheUpdate()); | ||
| } | ||
|
rahul2393 marked this conversation as resolved.
|
||
| transactionId = transactionIdFromMetadata(response); | ||
| } else if (message instanceof Transaction) { | ||
| Transaction response = (Transaction) message; | ||
|
|
||
140 changes: 140 additions & 0 deletions
140
google-cloud-spanner/src/test/java/com/google/cloud/spanner/LocationAwareTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| /* | ||
| * Copyright 2026 Google LLC | ||
| * | ||
| * 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. | ||
| */ | ||
|
|
||
| package com.google.cloud.spanner; | ||
|
|
||
| import static org.junit.Assert.assertEquals; | ||
|
|
||
| import com.google.cloud.NoCredentials; | ||
| import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; | ||
| import com.google.cloud.spanner.connection.AbstractMockServerTest; | ||
| import com.google.cloud.spanner.connection.RandomResultSetGenerator; | ||
| import com.google.common.util.concurrent.Futures; | ||
| import com.google.common.util.concurrent.ListenableFuture; | ||
| import com.google.common.util.concurrent.ListeningExecutorService; | ||
| import com.google.common.util.concurrent.MoreExecutors; | ||
| import io.grpc.ManagedChannelBuilder; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.ThreadLocalRandom; | ||
| import org.junit.AfterClass; | ||
| import org.junit.BeforeClass; | ||
| import org.junit.Test; | ||
| import org.junit.runner.RunWith; | ||
| import org.junit.runners.JUnit4; | ||
|
|
||
| @RunWith(JUnit4.class) | ||
| public class LocationAwareTest extends AbstractMockServerTest { | ||
| private static final Statement SELECT_RANDOM_STATEMENT = Statement.of("select * from random"); | ||
| private static final int RANDOM_RESULT_ROW_COUNT = 20; | ||
| private static Spanner spanner; | ||
| private static DatabaseClient client; | ||
|
|
||
| @BeforeClass | ||
| public static void enableLocationApiAndSetupClient() { | ||
| SpannerOptions.useEnvironment( | ||
| new SpannerOptions.SpannerEnvironment() { | ||
| @Override | ||
| public boolean isEnableLocationApi() { | ||
| return true; | ||
| } | ||
| }); | ||
| spanner = | ||
| SpannerOptions.newBuilder() | ||
| .setProjectId("my-project") | ||
| .setHost(String.format("http://localhost:%d", getPort())) | ||
| .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) | ||
| .setCredentials(NoCredentials.getInstance()) | ||
| .build() | ||
| .getService(); | ||
| client = spanner.getDatabaseClient(DatabaseId.of("my-project", "my-instance", "my-database")); | ||
|
|
||
| RandomResultSetGenerator generator = new RandomResultSetGenerator(RANDOM_RESULT_ROW_COUNT); | ||
| mockSpanner.putStatementResult( | ||
| StatementResult.query(SELECT_RANDOM_STATEMENT, generator.generate())); | ||
| } | ||
|
|
||
| @AfterClass | ||
| public static void cleanup() { | ||
| SpannerOptions.useDefaultEnvironment(); | ||
| if (spanner != null) { | ||
| spanner.close(); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| public void testSingleQuery() { | ||
| int rowCount = 0; | ||
| try (ResultSet resultSet = client.singleUse().executeQuery(SELECT_RANDOM_STATEMENT)) { | ||
| while (resultSet.next()) { | ||
| rowCount++; | ||
| } | ||
| } | ||
| assertEquals(RANDOM_RESULT_ROW_COUNT, rowCount); | ||
| } | ||
|
|
||
| @Test | ||
| public void testParallelQueries() throws Exception { | ||
| int numThreads = 10; | ||
| ListeningExecutorService executor = | ||
| MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numThreads)); | ||
| List<ListenableFuture<Void>> results = new ArrayList<>(); | ||
| for (int i = 0; i < numThreads; i++) { | ||
| results.add( | ||
| executor.submit( | ||
| () -> { | ||
| try (ResultSet resultSet = | ||
| client.singleUse().executeQuery(SELECT_RANDOM_STATEMENT)) { | ||
| while (resultSet.next()) { | ||
| // Randomly stop consuming results somewhere halfway the results (sometimes). | ||
| if (ThreadLocalRandom.current().nextInt(RANDOM_RESULT_ROW_COUNT * 2) == 5) { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| return null; | ||
| })); | ||
| } | ||
| executor.shutdown(); | ||
| Futures.allAsList(results).get(); | ||
| } | ||
|
|
||
| @Test | ||
| public void testSingleReadWriteTransaction() { | ||
| client.readWriteTransaction().run(transaction -> transaction.executeUpdate(INSERT_STATEMENT)); | ||
| } | ||
|
|
||
| @Test | ||
| public void testParallelReadWriteTransactions() throws Exception { | ||
| int numThreads = 10; | ||
| ListeningExecutorService executor = | ||
| MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numThreads)); | ||
| List<ListenableFuture<Void>> results = new ArrayList<>(); | ||
| for (int i = 0; i < numThreads; i++) { | ||
| results.add( | ||
| executor.submit( | ||
| () -> { | ||
| client | ||
| .readWriteTransaction() | ||
| .run(transaction -> transaction.executeUpdate(INSERT_STATEMENT)); | ||
| return null; | ||
| })); | ||
| } | ||
| executor.shutdown(); | ||
| Futures.allAsList(results).get(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.